diff --git a/cms/djangoapps/contentstore/management/commands/migrate_to_split.py b/cms/djangoapps/contentstore/management/commands/migrate_to_split.py deleted file mode 100644 index 38fed6265c..0000000000 --- a/cms/djangoapps/contentstore/management/commands/migrate_to_split.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -Django management command to migrate a course from the old Mongo modulestore -to the new split-Mongo modulestore. -""" - - -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user -from django.core.management.base import BaseCommand, CommandError -from opaque_keys import InvalidKeyError -from opaque_keys.edx.keys import CourseKey - -from cms.djangoapps.contentstore.management.commands.utils import user_from_str -from xmodule.modulestore import ModuleStoreEnum # lint-amnesty, pylint: disable=wrong-import-order -from xmodule.modulestore.django import modulestore # lint-amnesty, pylint: disable=wrong-import-order -from xmodule.modulestore.split_migrator import SplitMigrator # lint-amnesty, pylint: disable=wrong-import-order - - -class Command(BaseCommand): - """ - Migrate a course from old-Mongo to split-Mongo. It reuses the old course id except where overridden. - """ - - help = "Migrate a course from old-Mongo to split-Mongo. The new org, course, and run will " \ - "default to the old one unless overridden." - - def add_arguments(self, parser): - parser.add_argument('course_key') - parser.add_argument('email') - parser.add_argument('--org', help='New org to migrate to.') - parser.add_argument('--course', help='New course key to migrate to.') - parser.add_argument('--run', help='New run to migrate to.') - - def parse_args(self, **options): - """ - Return a 5-tuple of passed in values for (course_key, user, org, course, run). - """ - try: - course_key = CourseKey.from_string(options['course_key']) - except InvalidKeyError: - raise CommandError("Invalid location string") # lint-amnesty, pylint: disable=raise-missing-from - - try: - user = user_from_str(options['email']) - except User.DoesNotExist: - raise CommandError("No user found identified by {}".format(options['email'])) # lint-amnesty, pylint: disable=raise-missing-from - - return course_key, user.id, options['org'], options['course'], options['run'] - - def handle(self, *args, **options): - course_key, user, org, course, run = self.parse_args(**options) - - migrator = SplitMigrator( - source_modulestore=modulestore(), - split_modulestore=modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split), # lint-amnesty, pylint: disable=protected-access - ) - - migrator.migrate_mongo_course(course_key, user, org, course, run) diff --git a/cms/djangoapps/contentstore/management/commands/tests/test_migrate_to_split.py b/cms/djangoapps/contentstore/management/commands/tests/test_migrate_to_split.py deleted file mode 100644 index ba67bf28a3..0000000000 --- a/cms/djangoapps/contentstore/management/commands/tests/test_migrate_to_split.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -Unittests for migrating a course to split mongo -""" - - -from django.core.management import CommandError, call_command -from django.test import TestCase - -from xmodule.modulestore import ModuleStoreEnum -from xmodule.modulestore.django import modulestore -from xmodule.modulestore.exceptions import ItemNotFoundError -from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase -from xmodule.modulestore.tests.factories import CourseFactory - - -class TestArgParsing(TestCase): - """ - Tests for parsing arguments for the `migrate_to_split` management command - """ - def setUp(self): # lint-amnesty, pylint: disable=useless-super-delegation - super().setUp() - - def test_no_args(self): - """ - Test the arg length error - """ - errstring = "Error: the following arguments are required: course_key, email" - with self.assertRaisesRegex(CommandError, errstring): - call_command("migrate_to_split") - - def test_invalid_location(self): - """ - Test passing an unparsable course id - """ - errstring = "Invalid location string" - with self.assertRaisesRegex(CommandError, errstring): - call_command("migrate_to_split", "foo", "bar") - - def test_nonexistent_user_id(self): - """ - Test error for using an unknown user primary key - """ - errstring = "No user found identified by 99" - with self.assertRaisesRegex(CommandError, errstring): - call_command("migrate_to_split", "org/course/name", "99") - - def test_nonexistent_user_email(self): - """ - Test error for using an unknown user email - """ - errstring = "No user found identified by fake@example.com" - with self.assertRaisesRegex(CommandError, errstring): - call_command("migrate_to_split", "org/course/name", "fake@example.com") - - -# pylint: disable=protected-access -class TestMigrateToSplit(ModuleStoreTestCase): - """ - Unit tests for migrating a course from old mongo to split mongo - """ - - def setUp(self): - super().setUp() - self.course = CourseFactory(default_store=ModuleStoreEnum.Type.mongo) - - def test_user_email(self): - """ - Test migration for real as well as testing using an email addr to id the user - """ - call_command( - "migrate_to_split", - str(self.course.id), # lint-amnesty, pylint: disable=no-member - str(self.user.email), - ) - split_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split) - new_key = split_store.make_course_key(self.course.id.org, self.course.id.course, self.course.id.run) # lint-amnesty, pylint: disable=no-member - self.assertTrue( - split_store.has_course(new_key), - "Could not find course" - ) - - def test_user_id(self): - """ - Test that the command accepts the user's primary key - """ - # lack of error implies success - call_command( - "migrate_to_split", - str(self.course.id), # lint-amnesty, pylint: disable=no-member - str(self.user.id), - ) - - def test_locator_string(self): - """ - Test importing to a different course id - """ - call_command( - "migrate_to_split", - str(self.course.id), # lint-amnesty, pylint: disable=no-member - str(self.user.id), - org="org.dept", - course="name", - run="run", - ) - split_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.split) - locator = split_store.make_course_key("org.dept", "name", "run") - course_from_split = split_store.get_course(locator) - self.assertIsNotNone(course_from_split) - - # Getting the original course with mongo course_id - mongo_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.mongo) - mongo_locator = mongo_store.make_course_key(self.course.id.org, self.course.id.course, self.course.id.run) # lint-amnesty, pylint: disable=no-member - course_from_mongo = mongo_store.get_course(mongo_locator) - self.assertIsNotNone(course_from_mongo) - - # Throws ItemNotFoundError when try to access original course with split course_id - split_locator = split_store.make_course_key(self.course.id.org, self.course.id.course, self.course.id.run) # lint-amnesty, pylint: disable=no-member - with self.assertRaises(ItemNotFoundError): - mongo_store.get_course(split_locator) diff --git a/cms/djangoapps/contentstore/tasks.py b/cms/djangoapps/contentstore/tasks.py index 20146caf1f..eea41c3a43 100644 --- a/cms/djangoapps/contentstore/tasks.py +++ b/cms/djangoapps/contentstore/tasks.py @@ -51,6 +51,7 @@ from common.djangoapps.course_action_state.models import CourseRerunState from common.djangoapps.student.auth import has_course_author_access from common.djangoapps.util.monitoring import monitor_import_failure from openedx.core.djangoapps.content.learning_sequences.api import key_supports_outlines +from openedx.core.djangoapps.discussions.tasks import update_unit_discussion_state_from_discussion_blocks from openedx.core.djangoapps.embargo.models import CountryAccessRule, RestrictedCourse from openedx.core.lib.extract_tar import safetar_extractall from xmodule.contentstore.django import contentstore # lint-amnesty, pylint: disable=wrong-import-order @@ -119,6 +120,7 @@ def rerun_course(source_course_key_string, destination_course_key_string, user_i store = modulestore() with store.default_store('split'): store.clone_course(source_course_key, destination_course_key, user_id, fields=fields) + update_unit_discussion_state_from_discussion_blocks(destination_course_key, user_id) # set initial permissions for the user to access the course. initialize_permissions(destination_course_key, User.objects.get(id=user_id)) diff --git a/cms/djangoapps/contentstore/tests/test_clone_course.py b/cms/djangoapps/contentstore/tests/test_clone_course.py index 1c84055a11..6d45ae5469 100644 --- a/cms/djangoapps/contentstore/tests/test_clone_course.py +++ b/cms/djangoapps/contentstore/tests/test_clone_course.py @@ -27,25 +27,17 @@ class CloneCourseTest(CourseTestCase): Unit tests for cloning a course """ def test_clone_course(self): - """Tests cloning of a course as follows: XML -> Mongo (+ data) -> Mongo -> Split -> Split""" - # 1. import and populate test toy course - mongo_course1_id = self.import_and_populate_course() - mongo_course2_id = mongo_course1_id + """ + Tests cloning of a course: Split -> Split + """ - # 3. clone course (mongo -> split) with self.store.default_store(ModuleStoreEnum.Type.split): - split_course3_id = CourseLocator( - org="edx3", course="split3", run="2013_Fall" - ) - self.store.clone_course(mongo_course2_id, split_course3_id, self.user.id) - self.assertCoursesEqual(mongo_course2_id, split_course3_id) - - # 4. clone course (split -> split) - split_course4_id = CourseLocator( + split_course1_id = CourseFactory().id + split_course2_id = CourseLocator( org="edx4", course="split4", run="2013_Fall" ) - self.store.clone_course(split_course3_id, split_course4_id, self.user.id) - self.assertCoursesEqual(split_course3_id, split_course4_id) + self.store.clone_course(split_course1_id, split_course2_id, self.user.id) + self.assertCoursesEqual(split_course1_id, split_course2_id) def test_space_in_asset_name_for_rerun_course(self): """ @@ -99,16 +91,28 @@ class CloneCourseTest(CourseTestCase): """ Unit tests for :meth: `contentstore.tasks.rerun_course` """ - mongo_course1_id = self.import_and_populate_course() + org = 'edX' + course_number = 'CS101' + course_run = '2015_Q1' + display_name = 'rerun' + fields = {'display_name': display_name} + + # Create a course using split modulestore + split_course = CourseFactory.create( + org=org, + number=course_number, + run=course_run, + display_name=display_name, + default_store=ModuleStoreEnum.Type.split + ) - # rerun from mongo into split split_course3_id = CourseLocator( org="edx3", course="split3", run="rerun_test" ) # Mark the action as initiated fields = {'display_name': 'rerun'} - CourseRerunState.objects.initiated(mongo_course1_id, split_course3_id, self.user, fields['display_name']) - result = rerun_course.delay(str(mongo_course1_id), str(split_course3_id), self.user.id, + CourseRerunState.objects.initiated(split_course.id, split_course3_id, self.user, fields['display_name']) + result = rerun_course.delay(str(split_course.id), str(split_course3_id), self.user.id, json.dumps(fields, cls=EdxJSONEncoder)) self.assertEqual(result.get(), "succeeded") self.assertTrue(has_course_author_access(self.user, split_course3_id), "Didn't grant access") @@ -116,7 +120,7 @@ class CloneCourseTest(CourseTestCase): self.assertEqual(rerun_state.state, CourseRerunUIStateManager.State.SUCCEEDED) # try creating rerunning again to same name and ensure it generates error - result = rerun_course.delay(str(mongo_course1_id), str(split_course3_id), self.user.id) + result = rerun_course.delay(str(split_course.id), str(split_course3_id), self.user.id) self.assertEqual(result.get(), "duplicate course") # the below will raise an exception if the record doesn't exist CourseRerunState.objects.find_first( diff --git a/cms/djangoapps/contentstore/tests/test_contentstore.py b/cms/djangoapps/contentstore/tests/test_contentstore.py index 7d36753472..507ac7ebe1 100644 --- a/cms/djangoapps/contentstore/tests/test_contentstore.py +++ b/cms/djangoapps/contentstore/tests/test_contentstore.py @@ -1951,7 +1951,7 @@ class RerunCourseTest(ContentStoreTestCase): """ Test when rerunning a course with no videos, VAL copies nothing """ - source_course = CourseFactory.create() + source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split) destination_course_key = self.post_rerun_request(source_course.id) self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name']) videos, __ = get_videos_for_course(str(destination_course_key)) @@ -1964,7 +1964,10 @@ class RerunCourseTest(ContentStoreTestCase): Test when rerunning a course with video upload token, video upload token is not copied to new course. """ # Create a course with video upload token. - source_course = CourseFactory.create(video_upload_pipeline={"course_video_upload_token": 'test-token'}) + source_course = CourseFactory.create( + video_upload_pipeline={"course_video_upload_token": 'test-token'}, + default_store=ModuleStoreEnum.Type.split + ) destination_course_key = self.post_rerun_request(source_course.id) self.verify_rerun_course(source_course.id, destination_course_key, self.destination_course_data['display_name']) @@ -1977,7 +1980,7 @@ class RerunCourseTest(ContentStoreTestCase): self.assertEqual(new_course.video_upload_pipeline, {}) def test_rerun_course_success(self): - source_course = CourseFactory.create() + source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split) create_video( dict( edx_video_id="tree-hugger", @@ -2003,14 +2006,17 @@ class RerunCourseTest(ContentStoreTestCase): self.assertEqual(new_course.video_upload_pipeline, {}) def test_rerun_course_resets_advertised_date(self): - source_course = CourseFactory.create(advertised_start="01-12-2015") + source_course = CourseFactory.create( + advertised_start="01-12-2015", + default_store=ModuleStoreEnum.Type.split + ) destination_course_key = self.post_rerun_request(source_course.id) destination_course = self.store.get_course(destination_course_key) self.assertEqual(None, destination_course.advertised_start) def test_rerun_of_rerun(self): - source_course = CourseFactory.create() + source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split) rerun_course_key = self.post_rerun_request(source_course.id) rerun_of_rerun_data = { 'org': rerun_course_key.org, @@ -2022,7 +2028,7 @@ class RerunCourseTest(ContentStoreTestCase): self.verify_rerun_course(rerun_course_key, rerun_of_rerun_course_key, rerun_of_rerun_data['display_name']) def test_rerun_course_fail_no_source_course(self): - existent_course_key = CourseFactory.create().id + existent_course_key = CourseFactory.create(default_store=ModuleStoreEnum.Type.split).id non_existent_course_key = CourseLocator("org", "non_existent_course", "non_existent_run") destination_course_key = self.post_rerun_request(non_existent_course_key) @@ -2061,7 +2067,7 @@ class RerunCourseTest(ContentStoreTestCase): def test_rerun_with_permission_denied(self): with mock.patch.dict('django.conf.settings.FEATURES', {"ENABLE_CREATOR_GROUP": True}): - source_course = CourseFactory.create() + source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split) auth.add_users(self.user, CourseCreatorRole(), self.user) self.user.is_staff = False self.user.save() @@ -2090,7 +2096,7 @@ class RerunCourseTest(ContentStoreTestCase): 'xmodule.modulestore.mixed.MixedModuleStore.clone_course', mock.Mock(side_effect=Exception()), ): - source_course = CourseFactory.create() + source_course = CourseFactory.create(default_store=ModuleStoreEnum.Type.split) message_too_long = "traceback".rjust(CourseRerunState.MAX_MESSAGE_LENGTH * 2, '-') with mock.patch('traceback.format_exc', return_value=message_too_long): destination_course_key = self.post_rerun_request(source_course.id) @@ -2103,37 +2109,38 @@ class RerunCourseTest(ContentStoreTestCase): """ Test that unique wiki_slug is assigned to rerun course. """ - course_data = { - 'org': 'edX', - 'number': '123', - 'display_name': 'Rerun Course', - 'run': '2013' - } + with self.store.default_store(ModuleStoreEnum.Type.split): + course_data = { + 'org': 'edX', + 'number': '123', + 'display_name': 'Rerun Course', + 'run': '2013' + } - source_wiki_slug = '{}.{}.{}'.format(course_data['org'], course_data['number'], course_data['run']) + source_wiki_slug = '{}.{}.{}'.format(course_data['org'], course_data['number'], course_data['run']) - source_course_key = _get_course_id(self.store, course_data) - _create_course(self, source_course_key, course_data) - source_course = self.store.get_course(source_course_key) + source_course_key = _get_course_id(self.store, course_data) + _create_course(self, source_course_key, course_data) + source_course = self.store.get_course(source_course_key) - # Verify created course's wiki_slug. - self.assertEqual(source_course.wiki_slug, source_wiki_slug) + # Verify created course's wiki_slug. + self.assertEqual(source_course.wiki_slug, source_wiki_slug) - destination_course_data = course_data - destination_course_data['run'] = '2013_Rerun' + destination_course_data = course_data + destination_course_data['run'] = '2013_Rerun' - destination_course_key = self.post_rerun_request( - source_course.id, destination_course_data=destination_course_data - ) - self.verify_rerun_course(source_course.id, destination_course_key, destination_course_data['display_name']) - destination_course = self.store.get_course(destination_course_key) + destination_course_key = self.post_rerun_request( + source_course.id, destination_course_data=destination_course_data + ) + self.verify_rerun_course(source_course.id, destination_course_key, destination_course_data['display_name']) + destination_course = self.store.get_course(destination_course_key) - destination_wiki_slug = '{}.{}.{}'.format( - destination_course.id.org, destination_course.id.course, destination_course.id.run - ) + destination_wiki_slug = '{}.{}.{}'.format( + destination_course.id.org, destination_course.id.course, destination_course.id.run + ) - # Verify rerun course's wiki_slug. - self.assertEqual(destination_course.wiki_slug, destination_wiki_slug) + # Verify rerun course's wiki_slug. + self.assertEqual(destination_course.wiki_slug, destination_wiki_slug) class ContentLicenseTest(ContentStoreTestCase): diff --git a/cms/djangoapps/contentstore/tests/test_tasks.py b/cms/djangoapps/contentstore/tests/test_tasks.py index ad904e3e4b..d037f1d99c 100644 --- a/cms/djangoapps/contentstore/tests/test_tasks.py +++ b/cms/djangoapps/contentstore/tests/test_tasks.py @@ -23,6 +23,7 @@ from common.djangoapps.course_action_state.models import CourseRerunState from common.djangoapps.student.tests.factories import UserFactory from openedx.core.djangoapps.embargo.models import Country, CountryAccessRule, RestrictedCourse from xmodule.modulestore.django import modulestore # lint-amnesty, pylint: disable=wrong-import-order +from xmodule.modulestore.tests.django_utils import TEST_DATA_SPLIT_MODULESTORE TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE) TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex @@ -117,6 +118,9 @@ class ExportLibraryTestCase(LibraryTestCase): @override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE) class RerunCourseTaskTestCase(CourseTestCase): # lint-amnesty, pylint: disable=missing-class-docstring + + MODULESTORE = TEST_DATA_SPLIT_MODULESTORE + def _rerun_course(self, old_course_key, new_course_key): CourseRerunState.objects.initiated(old_course_key, new_course_key, self.user, 'Test Re-run') rerun_course(str(old_course_key), str(new_course_key), self.user.id) diff --git a/cms/envs/common.py b/cms/envs/common.py index bfae118aff..1e3bfbe4bc 100644 --- a/cms/envs/common.py +++ b/cms/envs/common.py @@ -1295,14 +1295,14 @@ PIPELINE['STYLESHEETS'] = { 'style-vendor-tinymce-content': { 'source_filenames': [ 'css/tinymce-studio-content-fonts.css', - 'js/vendor/tinymce/js/tinymce/skins/studio-tmce4/content.min.css', + 'js/vendor/tinymce/js/tinymce/skins/ui/studio-tmce5/content.min.css', 'css/tinymce-studio-content.css' ], 'output_filename': 'css/cms-style-vendor-tinymce-content.css', }, 'style-vendor-tinymce-skin': { 'source_filenames': [ - 'js/vendor/tinymce/js/tinymce/skins/studio-tmce4/skin.min.css' + 'js/vendor/tinymce/js/tinymce/skins/ui/studio-tmce5/skin.min.css' ], 'output_filename': 'css/cms-style-vendor-tinymce-skin.css', }, diff --git a/cms/envs/devstack.py b/cms/envs/devstack.py index fddaca9661..c76c24bac8 100644 --- a/cms/envs/devstack.py +++ b/cms/envs/devstack.py @@ -298,6 +298,7 @@ CREDENTIALS_PUBLIC_SERVICE_URL = 'http://localhost:18150' #################### Event bus backend ######################## EVENT_BUS_KAFKA_SCHEMA_REGISTRY_URL = 'http://edx.devstack.schema-registry:8081' EVENT_BUS_KAFKA_BOOTSTRAP_SERVERS = 'edx.devstack.kafka:29092' +EVENT_BUS_TOPIC_PREFIX = 'dev' ################# New settings must go ABOVE this line ################# ######################################################################## diff --git a/cms/templates/maintenance/_announcement_edit.html b/cms/templates/maintenance/_announcement_edit.html index f920db46b0..a9bee1c6fc 100644 --- a/cms/templates/maintenance/_announcement_edit.html +++ b/cms/templates/maintenance/_announcement_edit.html @@ -36,13 +36,15 @@ from openedx.core.djangolib.markup import HTML, Text %block> diff --git a/common/djangoapps/util/tests/test_db.py b/common/djangoapps/util/tests/test_db.py index f51941737e..4a16c2a20a 100644 --- a/common/djangoapps/util/tests/test_db.py +++ b/common/djangoapps/util/tests/test_db.py @@ -1,7 +1,6 @@ """Tests for util.db module.""" from io import StringIO -from unittest import skip import ddt from django.core.management import call_command @@ -121,7 +120,6 @@ class MigrationTests(TestCase): Tests for migrations. """ - @skip @override_settings(MIGRATION_MODULES={}) def test_migrations_are_in_sync(self): """ diff --git a/common/static/images/ico-tinymce-code.png b/common/static/images/ico-tinymce-code.png deleted file mode 100644 index e311c583af..0000000000 Binary files a/common/static/images/ico-tinymce-code.png and /dev/null differ diff --git a/common/static/js/vendor/tinymce/BUILD_README.md b/common/static/js/vendor/tinymce/BUILD_README.md new file mode 100644 index 0000000000..8adde977e2 --- /dev/null +++ b/common/static/js/vendor/tinymce/BUILD_README.md @@ -0,0 +1,53 @@ +# Instructions for updating tinymce to a newer version: + +1. Download the desired version from https://github.com/tinymce/tinymce/tags +2. If it’s a major update, follow the official migration doc and update the codebase as needed. +3. Setup the codemirror-plugin as per the instruction below. +4. Find all the EDX specific changes in the currently used version of tinymce by searching for the string "EDX" in the vendor/js/tinymce dir. +5. Merge the EDX specific changes with the newly downloaded version. +6. Follow the instructions given below to create the new version of js/tinymce.full.min.js + +# Instruction for setting codemirror-plugin + +1. Download the tinymce-codemirror-plugin from https://gitlab.com/tinymce-plugins/tinymce-codemirror +2. Open terminal in the downloaded plugin directory and run the following commands: + ``` + npm install + npm run prepublish (This command will generate the minified file in the plugin directory) + ``` +3. Remove the tinymce-codemirror/plugins/codemirror/codemirror-4.8 directory +4. Move the tinymce-codemirror/plugins directory to `common/static/js/vendor/tinymce/js/plugins/` directory. +5. Apply EDX specific changes in the existing code to the `plugin.js` and `source.html` files. +6. Install [uglify-js](https://www.npmjs.com/package/uglify-js) and generate `plugin.min.js` + ``` + cd common/static/js/vendor/tinymce/js/plugins/codemirror/ + uglify plugin.js -m -o plugin.min.js + ``` +**IMPORTANT NOTE:** Regenerate the `tinymce.full.min.js` bundle everytime the code-mirror `plugin.min.js` is regenerated to ensure the latest changes are added to the bundle. + +# Instructions for creating js/tinymce.full.min.js + +The following uses the version 5.5.1 as a reference. Change your filenames depending the version you have downloaded. + +1. Unzip the zip file downloaded from Github. + ``` + unzip tinymce-5.5.1.zip + ``` +2. Open terminal and change directory to the newly downloaded tinymce. + ``` + cd tinymce-5.5.1 + ``` +3. Build TinyMCE using Yarn. this will create multiple zip files in the `dist` directory. + ``` + yarn && yarn build + ``` +4. Unzip the dev bundle to the edx-platform's vendor directory. + ``` + unzip dist/tinymce_5.5.1_dev.zip -d /path/to/edx-platform/common/static/js/vendor/ + ``` +5. Remove the unnecessary files in `/path/to/edx-platform/common/static/js/vendor/tinymce` like `package.json`, `yarn.lock`...etc., +6. Generate a bundled version of the TinyMCE with all the plugins using the following command + ``` + cd common/static/js/vendor/tinymce/js/tinymce + LC_ALL=C cat tinymce.min.js */*/*.min.js plugins/emoticons/js/emojis.min.js > tinymce.full.min.js + ``` diff --git a/common/static/js/vendor/tinymce/BUILD_README.txt b/common/static/js/vendor/tinymce/BUILD_README.txt deleted file mode 100644 index e5ae62162c..0000000000 --- a/common/static/js/vendor/tinymce/BUILD_README.txt +++ /dev/null @@ -1,20 +0,0 @@ -Instructions for creating js/tinymce.full.min.js - -1. Ensure that the dependencies (NodeJS, Jake, and other dependencies) are installed. If necessary, - install them per the directions on https://github.com/tinymce/tinymce/tree/4.0.20. -2. Unzip edx-platform/vendor_extra/tinymce/JakePackage.zip into this directory (so that Jakefile.js resides in this directory). -3. Clean install the dependencies that were unzipped - npm ci -4. Run the following command in the tinymce directory: - npx jake clean-js -5. Run the following command in the tinymce directory: - npx jake minify bundle[themes:*,plugins:*] -6. Cleanup by deleting the Unversioned files that were created from unzipping jake_package.zip. - -Instructions for updating tinymce to a newer version: - -1. Download the desired version from https://github.com/tinymce/tinymce/releases -2. Find all the EDX specific changes that were made to the currently used version of tinymce by searching for - the string "EDX" in this directory. -3. Merge the EDX specific changes with the new version. -4. Follow the instructions above for creating the new version of js/tinymce.full.min.js diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/AddOnManager.js b/common/static/js/vendor/tinymce/js/tinymce/classes/AddOnManager.js deleted file mode 100755 index 02ae2d9bdd..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/AddOnManager.js +++ /dev/null @@ -1,256 +0,0 @@ -/** - * AddOnManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the loading of themes/plugins or other add-ons and their language packs. - * - * @class tinymce.AddOnManager - */ -define("tinymce/AddOnManager", [ - "tinymce/dom/ScriptLoader", - "tinymce/util/Tools" -], function(ScriptLoader, Tools) { - var each = Tools.each; - - function AddOnManager() { - var self = this; - - self.items = []; - self.urls = {}; - self.lookup = {}; - } - - AddOnManager.prototype = { - /** - * Returns the specified add on by the short name. - * - * @method get - * @param {String} name Add-on to look for. - * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. - */ - get: function(name) { - if (this.lookup[name]) { - return this.lookup[name].instance; - } else { - return undefined; - } - }, - - dependencies: function(name) { - var result; - - if (this.lookup[name]) { - result = this.lookup[name].dependencies; - } - - return result || []; - }, - - /** - * Loads a language pack for the specified add-on. - * - * @method requireLangPack - * @param {String} name Short name of the add-on. - * @param {String} languages Optional comma or space separated list of languages to check if it matches the name. - */ - requireLangPack: function(name, languages) { - if (AddOnManager.language && AddOnManager.languageLoad !== false) { - if (languages && new RegExp('([, ]|\\b)' + AddOnManager.language + '([, ]|\\b)').test(languages) === false) { - return; - } - - ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + AddOnManager.language + '.js'); - } - }, - - /** - * Adds a instance of the add-on by it's short name. - * - * @method add - * @param {String} id Short name/id for the add-on. - * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. - * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. - * @example - * // Create a simple plugin - * tinymce.create('tinymce.plugins.TestPlugin', { - * TestPlugin: function(ed, url) { - * ed.on('click', function(e) { - * ed.windowManager.alert('Hello World!'); - * }); - * } - * }); - * - * // Register plugin using the add method - * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-test' // Init the plugin but don't try to load it - * }); - */ - add: function(id, addOn, dependencies) { - this.items.push(addOn); - this.lookup[id] = {instance: addOn, dependencies: dependencies}; - - return addOn; - }, - - createUrl: function(baseUrl, dep) { - if (typeof dep === "object") { - return dep; - } else { - return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; - } - }, - - /** - * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. - * This should be used in development mode. A new compressor/javascript munger process will ensure that the - * components are put together into the plugin.js file and compressed correctly. - * - * @method addComponents - * @param {String} pluginName name of the plugin to load scripts from (will be used to get the base url for the plugins). - * @param {Array} scripts Array containing the names of the scripts to load. - */ - addComponents: function(pluginName, scripts) { - var pluginUrl = this.urls[pluginName]; - - each(scripts, function(script) { - ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); - }); - }, - - /** - * Loads an add-on from a specific url. - * - * @method load - * @param {String} name Short name of the add-on that gets loaded. - * @param {String} addOnUrl URL to the add-on that will get loaded. - * @param {function} callback Optional callback to execute ones the add-on is loaded. - * @param {Object} scope Optional scope to execute the callback in. - * @example - * // Loads a plugin from an external URL - * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-myplugin' // Don't try to load it again - * }); - */ - load: function(name, addOnUrl, callback, scope) { - var self = this, url = addOnUrl; - - function loadDependencies() { - var dependencies = self.dependencies(name); - - each(dependencies, function(dep) { - var newUrl = self.createUrl(addOnUrl, dep); - - self.load(newUrl.resource, newUrl, undefined, undefined); - }); - - if (callback) { - if (scope) { - callback.call(scope); - } else { - callback.call(ScriptLoader); - } - } - } - - if (self.urls[name]) { - return; - } - - if (typeof addOnUrl === "object") { - url = addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix; - } - - if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) { - url = AddOnManager.baseURL + '/' + url; - } - - self.urls[name] = url.substring(0, url.lastIndexOf('/')); - - if (self.lookup[name]) { - loadDependencies(); - } else { - ScriptLoader.ScriptLoader.add(url, loadDependencies, scope); - } - } - }; - - AddOnManager.PluginManager = new AddOnManager(); - AddOnManager.ThemeManager = new AddOnManager(); - - return AddOnManager; -}); - -/** - * TinyMCE theme class. - * - * @class tinymce.Theme - */ - -/** - * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. - * - * @method renderUI - * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. - * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. - */ - -/** - * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. - * - * @class tinymce.Plugin - * @example - * tinymce.PluginManager.add('example', function(editor, url) { - * // Add a button that opens a window - * editor.addButton('example', { - * text: 'My button', - * icon: false, - * onclick: function() { - * // Open window - * editor.windowManager.open({ - * title: 'Example plugin', - * body: [ - * {type: 'textbox', name: 'title', label: 'Title'} - * ], - * onsubmit: function(e) { - * // Insert content when the window form is submitted - * editor.insertContent('Title: ' + e.data.title); - * } - * }); - * } - * }); - * - * // Adds a menu item to the tools menu - * editor.addMenuItem('example', { - * text: 'Example plugin', - * context: 'tools', - * onclick: function() { - * // Open window with a specific url - * editor.windowManager.open({ - * title: 'TinyMCE site', - * url: 'http://www.tinymce.com', - * width: 800, - * height: 600, - * buttons: [{ - * text: 'Close', - * onclick: 'close' - * }] - * }); - * } - * }); - * }); - */ diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/Compat.js b/common/static/js/vendor/tinymce/js/tinymce/classes/Compat.js deleted file mode 100755 index eacc64c9cf..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/Compat.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Compat.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * TinyMCE core class. - * - * @static - * @class tinymce - * @borrow-members tinymce.EditorManager - * @borrow-members tinymce.util.Tools - */ -define("tinymce/Compat", [ - "tinymce/dom/DOMUtils", - "tinymce/dom/EventUtils", - "tinymce/dom/ScriptLoader", - "tinymce/AddOnManager", - "tinymce/util/Tools", - "tinymce/Env" -], function(DOMUtils, EventUtils, ScriptLoader, AddOnManager, Tools, Env) { - var tinymce = window.tinymce; - - /** - * @property {tinymce.dom.DOMUtils} DOM Global DOM instance. - * @property {tinymce.dom.ScriptLoader} ScriptLoader Global ScriptLoader instance. - * @property {tinymce.AddOnManager} PluginManager Global PluginManager instance. - * @property {tinymce.AddOnManager} ThemeManager Global ThemeManager instance. - */ - tinymce.DOM = DOMUtils.DOM; - tinymce.ScriptLoader = ScriptLoader.ScriptLoader; - tinymce.PluginManager = AddOnManager.PluginManager; - tinymce.ThemeManager = AddOnManager.ThemeManager; - - tinymce.dom = tinymce.dom || {}; - tinymce.dom.Event = EventUtils.Event; - - Tools.each(Tools, function(func, key) { - tinymce[key] = func; - }); - - Tools.each('isOpera isWebKit isIE isGecko isMac'.split(' '), function(name) { - tinymce[name] = Env[name.substr(2).toLowerCase()]; - }); - - return {}; -}); - -// Describe the different namespaces - -/** - * Root level namespace this contains classes directly releated to the TinyMCE editor. - * - * @namespace tinymce - */ - -/** - * Contains classes for handling the browsers DOM. - * - * @namespace tinymce.dom - */ - -/** - * Contains html parser and serializer logic. - * - * @namespace tinymce.html - */ - -/** - * Contains the different UI types such as buttons, listboxes etc. - * - * @namespace tinymce.ui - */ - -/** - * Contains various utility classes such as json parser, cookies etc. - * - * @namespace tinymce.util - */ diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/Editor.js b/common/static/js/vendor/tinymce/js/tinymce/classes/Editor.js deleted file mode 100755 index 571c4fa32d..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/Editor.js +++ /dev/null @@ -1,2168 +0,0 @@ -/** - * Editor.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*jshint scripturl:true */ - -/** - * Include the base event class documentation. - * - * @include ../../../tools/docs/tinymce.Event.js - */ - -/** - * This class contains the core logic for a TinyMCE editor. - * - * @class tinymce.Editor - * @mixes tinymce.util.Observable - * @example - * // Add a class to all paragraphs in the editor. - * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass'); - * - * // Gets the current editors selection as text - * tinymce.activeEditor.selection.getContent({format: 'text'}); - * - * // Creates a new editor instance - * var ed = new tinymce.Editor('textareaid', { - * some_setting: 1 - * }, tinymce.EditorManager); - * - * // Select each item the user clicks on - * ed.on('click', function(e) { - * ed.selection.select(e.target); - * }); - * - * ed.render(); - */ -define("tinymce/Editor", [ - "tinymce/dom/DOMUtils", - "tinymce/AddOnManager", - "tinymce/html/Node", - "tinymce/dom/Serializer", - "tinymce/html/Serializer", - "tinymce/dom/Selection", - "tinymce/Formatter", - "tinymce/UndoManager", - "tinymce/EnterKey", - "tinymce/ForceBlocks", - "tinymce/EditorCommands", - "tinymce/util/URI", - "tinymce/dom/ScriptLoader", - "tinymce/dom/EventUtils", - "tinymce/WindowManager", - "tinymce/html/Schema", - "tinymce/html/DomParser", - "tinymce/util/Quirks", - "tinymce/Env", - "tinymce/util/Tools", - "tinymce/util/Observable", - "tinymce/Shortcuts" -], function( - DOMUtils, AddOnManager, Node, DomSerializer, Serializer, - Selection, Formatter, UndoManager, EnterKey, ForceBlocks, EditorCommands, - URI, ScriptLoader, EventUtils, WindowManager, - Schema, DomParser, Quirks, Env, Tools, Observable, Shortcuts -) { - // Shorten these names - var DOM = DOMUtils.DOM, ThemeManager = AddOnManager.ThemeManager, PluginManager = AddOnManager.PluginManager; - var extend = Tools.extend, each = Tools.each, explode = Tools.explode; - var inArray = Tools.inArray, trim = Tools.trim, resolve = Tools.resolve; - var Event = EventUtils.Event; - var isGecko = Env.gecko, ie = Env.ie; - - function getEventTarget(editor, eventName) { - if (eventName == 'selectionchange') { - return editor.getDoc(); - } - - // Need to bind mousedown/mouseup etc to document not body in iframe mode - // Since the user might click on the HTML element not the BODY - if (!editor.inline && /^mouse|click|contextmenu|drop/.test(eventName)) { - return editor.getDoc(); - } - - return editor.getBody(); - } - - /** - * Include documentation for all the events. - * - * @include ../../../tools/docs/tinymce.Editor.js - */ - - /** - * Constructs a editor instance by id. - * - * @constructor - * @method Editor - * @param {String} id Unique id for the editor. - * @param {Object} settings Settings for the editor. - * @param {tinymce.EditorManager} editorManager EditorManager instance. - * @author Moxiecode - */ - function Editor(id, settings, editorManager) { - var self = this, documentBaseUrl, baseUri; - - documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL; - baseUri = editorManager.baseURI; - - /** - * Name/value collection with editor settings. - * - * @property settings - * @type Object - * @example - * // Get the value of the theme setting - * tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme"); - */ - self.settings = settings = extend({ - id: id, - theme: 'modern', - delta_width: 0, - delta_height: 0, - popup_css: '', - plugins: '', - document_base_url: documentBaseUrl, - add_form_submit_trigger: true, - submit_patch: true, - add_unload_trigger: true, - convert_urls: true, - relative_urls: true, - remove_script_host: true, - object_resizing: true, - doctype: '', - visual: true, - font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large', - - // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size - font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%', - forced_root_block: 'p', - hidden_input: true, - padd_empty_editor: true, - render_ui: true, - indentation: '30px', - inline_styles: true, - convert_fonts_to_spans: true, - indent: 'simple', - indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,' + - 'tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist', - indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,' + - 'tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist', - validate: true, - entity_encoding: 'named', - url_converter: self.convertURL, - url_converter_scope: self, - ie7_compat: true - }, settings); - - AddOnManager.language = settings.language || 'en'; - AddOnManager.languageLoad = settings.language_load; - - AddOnManager.baseURL = editorManager.baseURL; - - /** - * Editor instance id, normally the same as the div/textarea that was replaced. - * - * @property id - * @type String - */ - self.id = settings.id = id; - - /** - * State to force the editor to return false on a isDirty call. - * - * @property isNotDirty - * @type Boolean - * @example - * function ajaxSave() { - * var ed = tinymce.get('elm1'); - * - * // Save contents using some XHR call - * alert(ed.getContent()); - * - * ed.isNotDirty = true; // Force not dirty state - * } - */ - self.isNotDirty = true; - - /** - * Name/Value object containting plugin instances. - * - * @property plugins - * @type Object - * @example - * // Execute a method inside a plugin directly - * tinymce.activeEditor.plugins.someplugin.someMethod(); - */ - self.plugins = {}; - - /** - * URI object to document configured for the TinyMCE instance. - * - * @property documentBaseURI - * @type tinymce.util.URI - * @example - * // Get relative URL from the location of document_base_url - * tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm'); - * - * // Get absolute URL from the location of document_base_url - * tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm'); - */ - self.documentBaseURI = new URI(settings.document_base_url || documentBaseUrl, { - base_uri: baseUri - }); - - /** - * URI object to current document that holds the TinyMCE editor instance. - * - * @property baseURI - * @type tinymce.util.URI - * @example - * // Get relative URL from the location of the API - * tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm'); - * - * // Get absolute URL from the location of the API - * tinymce.activeEditor.baseURI.toAbsolute('somefile.htm'); - */ - self.baseURI = baseUri; - - /** - * Array with CSS files to load into the iframe. - * - * @property contentCSS - * @type Array - */ - self.contentCSS = []; - - /** - * Array of CSS styles to add to head of document when the editor loads. - * - * @property contentStyles - * @type Array - */ - self.contentStyles = []; - - // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic - self.shortcuts = new Shortcuts(self); - - // Internal command handler objects - self.execCommands = {}; - self.queryStateCommands = {}; - self.queryValueCommands = {}; - self.loadedCSS = {}; - - self.suffix = editorManager.suffix; - self.editorManager = editorManager; - self.inline = settings.inline; - - // Call setup - editorManager.fire('SetupEditor', self); - self.execCallback('setup', self); - } - - Editor.prototype = { - /** - * Renderes the editor/adds it to the page. - * - * @method render - */ - render: function() { - var self = this, settings = self.settings, id = self.id, suffix = self.suffix; - - function readyHandler() { - DOM.unbind(window, 'ready', readyHandler); - self.render(); - } - - // Page is not loaded yet, wait for it - if (!Event.domLoaded) { - DOM.bind(window, 'ready', readyHandler); - return; - } - - // Element not found, then skip initialization - if (!self.getElement()) { - return; - } - - // No editable support old iOS versions etc - if (!Env.contentEditable) { - return; - } - - // Hide target element early to prevent content flashing - if (!settings.inline) { - self.orgVisibility = self.getElement().style.visibility; - self.getElement().style.visibility = 'hidden'; - } else { - self.inline = true; - } - - var form = self.getElement().form || DOM.getParent(id, 'form'); - if (form) { - self.formElement = form; - - // Add hidden input for non input elements inside form elements - if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(self.getElement().nodeName)) { - DOM.insertAfter(DOM.create('input', {type: 'hidden', name: id}), id); - self.hasHiddenInput = true; - } - - // Pass submit/reset from form to editor instance - self.formEventDelegate = function(e) { - self.fire(e.type, e); - }; - - DOM.bind(form, 'submit reset', self.formEventDelegate); - - // Reset contents in editor when the form is reset - self.on('reset', function() { - self.setContent(self.startContent, {format: 'raw'}); - }); - - // Check page uses id="submit" or name="submit" for it's submit button - if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) { - form._mceOldSubmit = form.submit; - form.submit = function() { - self.editorManager.triggerSave(); - self.isNotDirty = true; - - return form._mceOldSubmit(form); - }; - } - } - - /** - * Window manager reference, use this to open new windows and dialogs. - * - * @property windowManager - * @type tinymce.WindowManager - * @example - * // Shows an alert message - * tinymce.activeEditor.windowManager.alert('Hello world!'); - * - * // Opens a new dialog with the file.htm file and the size 320x240 - * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog. - * tinymce.activeEditor.windowManager.open({ - * url: 'file.htm', - * width: 320, - * height: 240 - * }, { - * custom_param: 1 - * }); - */ - self.windowManager = new WindowManager(self); - - if (settings.encoding == 'xml') { - self.on('GetContent', function(e) { - if (e.save) { - e.content = DOM.encode(e.content); - } - }); - } - - if (settings.add_form_submit_trigger) { - self.on('submit', function() { - if (self.initialized) { - self.save(); - } - }); - } - - if (settings.add_unload_trigger) { - self._beforeUnload = function() { - if (self.initialized && !self.destroyed && !self.isHidden()) { - self.save({format: 'raw', no_events: true, set_dirty: false}); - } - }; - - self.editorManager.on('BeforeUnload', self._beforeUnload); - } - - // Load scripts - function loadScripts() { - var scriptLoader = ScriptLoader.ScriptLoader; - - if (settings.language && settings.language != 'en' && !settings.language_url) { - settings.language_url = self.editorManager.baseURL + '/langs/' + settings.language + '.js'; - } - - if (settings.language_url) { - scriptLoader.add(settings.language_url); - } - - if (settings.theme && typeof settings.theme != "function" && - settings.theme.charAt(0) != '-' && !ThemeManager.urls[settings.theme]) { - var themeUrl = settings.theme_url; - - if (themeUrl) { - themeUrl = self.documentBaseURI.toAbsolute(themeUrl); - } else { - themeUrl = 'themes/' + settings.theme + '/theme' + suffix + '.js'; - } - - ThemeManager.load(settings.theme, themeUrl); - } - - if (Tools.isArray(settings.plugins)) { - settings.plugins = settings.plugins.join(' '); - } - - each(settings.external_plugins, function(url, name) { - PluginManager.load(name, url); - settings.plugins += ' ' + name; - }); - - each(settings.plugins.split(/[ ,]/), function(plugin) { - plugin = trim(plugin); - - if (plugin && !PluginManager.urls[plugin]) { - if (plugin.charAt(0) == '-') { - plugin = plugin.substr(1, plugin.length); - - var dependencies = PluginManager.dependencies(plugin); - - each(dependencies, function(dep) { - var defaultSettings = { - prefix:'plugins/', - resource: dep, - suffix:'/plugin' + suffix + '.js' - }; - - dep = PluginManager.createUrl(defaultSettings, dep); - PluginManager.load(dep.resource, dep); - }); - } else { - PluginManager.load(plugin, { - prefix: 'plugins/', - resource: plugin, - suffix: '/plugin' + suffix + '.js' - }); - } - } - }); - - scriptLoader.loadQueue(function() { - if (!self.removed) { - self.init(); - } - }); - } - - loadScripts(); - }, - - /** - * Initializes the editor this will be called automatically when - * all plugins/themes and language packs are loaded by the rendered method. - * This method will setup the iframe and create the theme and plugin instances. - * - * @method init - */ - init: function() { - var self = this, settings = self.settings, elm = self.getElement(); - var w, h, minHeight, n, o, Theme, url, bodyId, bodyClass, re, i, initializedPlugins = []; - - self.rtl = this.editorManager.i18n.rtl; - self.editorManager.add(self); - - settings.aria_label = settings.aria_label || DOM.getAttrib(elm, 'aria-label', self.getLang('aria.rich_text_area')); - - /** - * Reference to the theme instance that was used to generate the UI. - * - * @property theme - * @type tinymce.Theme - * @example - * // Executes a method on the theme directly - * tinymce.activeEditor.theme.someMethod(); - */ - if (settings.theme) { - if (typeof settings.theme != "function") { - settings.theme = settings.theme.replace(/-/, ''); - Theme = ThemeManager.get(settings.theme); - self.theme = new Theme(self, ThemeManager.urls[settings.theme]); - - if (self.theme.init) { - self.theme.init(self, ThemeManager.urls[settings.theme] || self.documentBaseUrl.replace(/\/$/, '')); - } - } else { - self.theme = settings.theme; - } - } - - function initPlugin(plugin) { - var Plugin = PluginManager.get(plugin), pluginUrl, pluginInstance; - - pluginUrl = PluginManager.urls[plugin] || self.documentBaseUrl.replace(/\/$/, ''); - plugin = trim(plugin); - if (Plugin && inArray(initializedPlugins, plugin) === -1) { - each(PluginManager.dependencies(plugin), function(dep){ - initPlugin(dep); - }); - - pluginInstance = new Plugin(self, pluginUrl); - - self.plugins[plugin] = pluginInstance; - - if (pluginInstance.init) { - pluginInstance.init(self, pluginUrl); - initializedPlugins.push(plugin); - } - } - } - - // Create all plugins - each(settings.plugins.replace(/\-/g, '').split(/[ ,]/), initPlugin); - - // Measure box - if (settings.render_ui && self.theme) { - self.orgDisplay = elm.style.display; - - if (typeof settings.theme != "function") { - w = settings.width || elm.style.width || elm.offsetWidth; - h = settings.height || elm.style.height || elm.offsetHeight; - minHeight = settings.min_height || 100; - re = /^[0-9\.]+(|px)$/i; - - if (re.test('' + w)) { - w = Math.max(parseInt(w, 10), 100); - } - - if (re.test('' + h)) { - h = Math.max(parseInt(h, 10), minHeight); - } - - // Render UI - o = self.theme.renderUI({ - targetNode: elm, - width: w, - height: h, - deltaWidth: settings.delta_width, - deltaHeight: settings.delta_height - }); - - // Resize editor - if (!settings.content_editable) { - DOM.setStyles(o.sizeContainer || o.editorContainer, { - wi2dth: w, - // TODO: Fix this - h2eight: h - }); - - h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : ''); - if (h < minHeight) { - h = minHeight; - } - } - } else { - o = settings.theme(self, elm); - - // Convert element type to id:s - if (o.editorContainer.nodeType) { - o.editorContainer = o.editorContainer.id = o.editorContainer.id || self.id + "_parent"; - } - - // Convert element type to id:s - if (o.iframeContainer.nodeType) { - o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || self.id + "_iframecontainer"; - } - - // Use specified iframe height or the targets offsetHeight - h = o.iframeHeight || elm.offsetHeight; - } - - self.editorContainer = o.editorContainer; - } - - // Load specified content CSS last - if (settings.content_css) { - each(explode(settings.content_css), function(u) { - self.contentCSS.push(self.documentBaseURI.toAbsolute(u)); - }); - } - - // Load specified content CSS last - if (settings.content_style) { - self.contentStyles.push(settings.content_style); - } - - // Content editable mode ends here - if (settings.content_editable) { - elm = n = o = null; // Fix IE leak - return self.initContentBody(); - } - - self.iframeHTML = settings.doctype + '
'; - - // We only need to override paths if we have to - // IE has a bug where it remove site absolute urls to relative ones if this is specified - if (settings.document_base_url != self.documentBaseUrl) { - self.iframeHTML += ']*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/, '');
- });
- }
-
- self.load({initial: true, format: 'html'});
- self.startContent = self.getContent({format: 'raw'});
-
- /**
- * Is set to true after the editor instance has been initialized
- *
- * @property initialized
- * @type Boolean
- * @example
- * function isEditorInitialized(editor) {
- * return editor && editor.initialized;
- * }
- */
- self.initialized = true;
-
- each(self._pendingNativeEvents, function(name) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(e.type, e);
- });
- });
-
- self.fire('init');
- self.focus(true);
- self.nodeChanged({initial: true});
- self.execCallback('init_instance_callback', self);
-
- // Add editor specific CSS styles
- if (self.contentStyles.length > 0) {
- contentCssText = '';
-
- each(self.contentStyles, function(style) {
- contentCssText += style + "\r\n";
- });
-
- self.dom.addStyle(contentCssText);
- }
-
- // Load specified content CSS last
- each(self.contentCSS, function(cssUrl) {
- if (!self.loadedCSS[cssUrl]) {
- self.dom.loadCSS(cssUrl);
- self.loadedCSS[cssUrl] = true;
- }
- });
-
- // Handle auto focus
- if (settings.auto_focus) {
- setTimeout(function () {
- var ed = self.editorManager.get(settings.auto_focus);
-
- ed.selection.select(ed.getBody(), 1);
- ed.selection.collapse(1);
- ed.getBody().focus();
- ed.getWin().focus();
- }, 100);
- }
-
- // Clean up references for IE
- targetElm = doc = body = null;
- },
-
- /**
- * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
- * it will also place DOM focus inside the editor.
- *
- * @method focus
- * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
- */
- focus: function(skip_focus) {
- var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
- var controlElm, doc = self.getDoc(), body;
-
- if (!skip_focus) {
- // Get selected control element
- rng = selection.getRng();
- if (rng.item) {
- controlElm = rng.item(0);
- }
-
- self._refreshContentEditable();
-
- // Focus the window iframe
- if (!contentEditable) {
- // WebKit needs this call to fire focusin event properly see #5948
- // But Opera pre Blink engine will produce an empty selection so skip Opera
- if (!Env.opera) {
- self.getBody().focus();
- }
-
- self.getWin().focus();
- }
-
- // Focus the body as well since it's contentEditable
- if (isGecko || contentEditable) {
- body = self.getBody();
-
- // Check for setActive since it doesn't scroll to the element
- if (body.setActive && Env.ie < 11) {
- body.setActive();
- } else {
- body.focus();
- }
-
- if (contentEditable) {
- selection.normalize();
- }
- }
-
- // Restore selected control element
- // This is needed when for example an image is selected within a
- // layer a call to focus will then remove the control selection
- if (controlElm && controlElm.ownerDocument == doc) {
- rng = doc.body.createControlRange();
- rng.addElement(controlElm);
- rng.select();
- }
- }
-
- if (self.editorManager.activeEditor != self) {
- if ((oed = self.editorManager.activeEditor)) {
- oed.fire('deactivate', {relatedTarget: self});
- }
-
- self.fire('activate', {relatedTarget: oed});
- }
-
- self.editorManager.activeEditor = self;
- },
-
- /**
- * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
- * There new event model is a better way to add callback so this method might be removed in the future.
- *
- * @method execCallback
- * @param {String} name Name of the callback to execute.
- * @return {Object} Return value passed from callback function.
- */
- execCallback: function(name) {
- var self = this, callback = self.settings[name], scope;
-
- if (!callback) {
- return;
- }
-
- // Look through lookup
- if (self.callbackLookup && (scope = self.callbackLookup[name])) {
- callback = scope.func;
- scope = scope.scope;
- }
-
- if (typeof(callback) === 'string') {
- scope = callback.replace(/\.\w+$/, '');
- scope = scope ? resolve(scope) : 0;
- callback = resolve(callback);
- self.callbackLookup = self.callbackLookup || {};
- self.callbackLookup[name] = {func: callback, scope: scope};
- }
-
- return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
- },
-
- /**
- * Translates the specified string by replacing variables with language pack items it will also check if there is
- * a key mathcin the input.
- *
- * @method translate
- * @param {String} text String to translate by the language pack data.
- * @return {String} Translated string.
- */
- translate: function(text) {
- var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
-
- if (!text) {
- return '';
- }
-
- return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
- return i18n.data[lang + '.' + b] || '{#' + b + '}';
- });
- },
-
- /**
- * Returns a language pack item by name/key.
- *
- * @method getLang
- * @param {String} name Name/key to get from the language pack.
- * @param {String} defaultVal Optional default value to retrive.
- */
- getLang: function(name, defaultVal) {
- return (
- this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
- (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
- );
- },
-
- /**
- * Returns a configuration parameter by name.
- *
- * @method getParam
- * @param {String} name Configruation parameter to retrive.
- * @param {String} defaultVal Optional default value to return.
- * @param {String} type Optional type parameter.
- * @return {String} Configuration parameter value or default value.
- * @example
- * // Returns a specific config value from the currently active editor
- * var someval = tinymce.activeEditor.getParam('myvalue');
- *
- * // Returns a specific config value from a specific editor instance by id
- * var someval2 = tinymce.get('my_editor').getParam('myvalue');
- */
- getParam: function(name, defaultVal, type) {
- var value = name in this.settings ? this.settings[name] : defaultVal, output;
-
- if (type === 'hash') {
- output = {};
-
- if (typeof(value) === 'string') {
- each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
- value = value.split('=');
-
- if (value.length > 1) {
- output[trim(value[0])] = trim(value[1]);
- } else {
- output[trim(value[0])] = trim(value);
- }
- });
- } else {
- output = value;
- }
-
- return output;
- }
-
- return value;
- },
-
- /**
- * Distpaches out a onNodeChange event to all observers. This method should be called when you
- * need to update the UI states or element path etc.
- *
- * @method nodeChanged
- */
- nodeChanged: function() {
- var self = this, selection = self.selection, node, parents, root;
-
- // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
- if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
- // Get start node
- root = self.getBody();
- node = selection.getStart() || root;
- node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
-
- // Edge case for
|
|
- rng = selection.getRng(); - var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); - var body = editor.getBody(); - if (caretElement === body && selection.isCollapsed()) { - if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { - rng = dom.createRng(); - rng.setStart(body.firstChild, 0); - rng.setEnd(body.firstChild, 0); - selection.setRng(rng); - } - } - - // Insert node maker where we will insert the new HTML and get it's parent - if (!selection.isCollapsed()) { - editor.getDoc().execCommand('Delete', false, null); - } - - parentNode = selection.getNode(); - - // Parse the fragment within the context of the parent node - var parserArgs = {context: parentNode.nodeName.toLowerCase()}; - fragment = parser.parse(value, parserArgs); - - // Move the caret to a more suitable location - node = fragment.lastChild; - if (node.attr('id') == 'mce_marker') { - marker = node; - - for (node = node.prev; node; node = node.walk(true)) { - if (node.type == 3 || !dom.isBlock(node.name)) { - node.parent.insert(marker, node, node.name === 'br'); - break; - } - } - } - - // If parser says valid we can insert the contents into that parent - if (!parserArgs.invalid) { - value = serializer.serialize(fragment); - - // Check if parent is empty or only has one BR element then set the innerHTML of that parent - node = parentNode.firstChild; - node2 = parentNode.lastChild; - if (!node || (node === node2 && node.nodeName === 'BR')) { - dom.setHTML(parentNode, value); - } else { - selection.setContent(value); - } - } else { - // If the fragment was invalid within that context then we need - // to parse and process the parent it's inserted into - - // Insert bookmark node and get the parent - selection.setContent(bookmarkHtml); - parentNode = selection.getNode(); - rootNode = editor.getBody(); - - // Opera will return the document node when selection is in root - if (parentNode.nodeType == 9) { - parentNode = node = rootNode; - } else { - node = parentNode; - } - - // Find the ancestor just before the root element - while (node !== rootNode) { - parentNode = node; - node = node.parentNode; - } - - // Get the outer/inner HTML depending on if we are in the root and parser and serialize that - value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); - value = serializer.serialize( - parser.parse( - // Need to replace by using a function since $ in the contents would otherwise be a problem - value.replace(//i, function() { - return serializer.serialize(fragment); - }) - ) - ); - - // Set the inner/outer HTML depending on if we are in the root or not - if (parentNode == rootNode) { - dom.setHTML(rootNode, value); - } else { - dom.setOuterHTML(parentNode, value); - } - } - - marker = dom.get('mce_marker'); - selection.scrollIntoView(marker); - - // Move selection before marker and remove it - rng = dom.createRng(); - - // If previous sibling is a text node set the selection to the end of that node - node = marker.previousSibling; - if (node && node.nodeType == 3) { - rng.setStart(node, node.nodeValue.length); - - // TODO: Why can't we normalize on IE - if (!isIE) { - node2 = marker.nextSibling; - if (node2 && node2.nodeType == 3) { - node.appendData(node2.data); - node2.parentNode.removeChild(node2); - } - } - } else { - // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node - rng.setStartBefore(marker); - rng.setEndBefore(marker); - } - - // Remove the marker node and set the new range - dom.remove(marker); - selection.setRng(rng); - - // Dispatch after event and add any visual elements needed - editor.fire('SetContent', args); - editor.addVisual(); - }, - - mceInsertRawHTML: function(command, ui, value) { - selection.setContent('tiny_mce_marker'); - editor.setContent( - editor.getContent().replace(/tiny_mce_marker/g, function() { - return value; - }) - ); - }, - - mceToggleFormat: function(command, ui, value) { - toggleFormat(value); - }, - - mceSetContent: function(command, ui, value) { - editor.setContent(value); - }, - - 'Indent,Outdent': function(command) { - var intentValue, indentUnit, value; - - // Setup indent level - intentValue = settings.indentation; - indentUnit = /[a-z%]+$/i.exec(intentValue); - intentValue = parseInt(intentValue, 10); - - if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { - // If forced_root_blocks is set to false we don't have a block to indent so lets create a div - if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { - formatter.apply('div'); - } - - each(selection.getSelectedBlocks(), function(element) { - if (element.nodeName != "LI") { - var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; - - indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; - - if (command == 'outdent') { - value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); - dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); - } else { - value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; - dom.setStyle(element, indentStyleName, value); - } - } - }); - } else { - execNativeCommand(command); - } - }, - - mceRepaint: function() { - if (isGecko) { - try { - storeSelection(TRUE); - - if (selection.getSel()) { - selection.getSel().selectAllChildren(editor.getBody()); - } - - selection.collapse(TRUE); - restoreSelection(); - } catch (ex) { - // Ignore - } - } - }, - - InsertHorizontalRule: function() { - editor.execCommand('mceInsertContent', false, '|
- rng = selection.getRng(); - if (!rng.item) { - rng.moveToElementText(root); - rng.select(); - } - } - }, - - "delete": function() { - execNativeCommand("Delete"); - - // Check if body is empty after the delete call if so then set the contents - // to an empty string and move the caret to any block produced by that operation - // this fixes the issue with root blocks not being properly produced after a delete call on IE - var body = editor.getBody(); - - if (dom.isEmpty(body)) { - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - } - }, - - mceNewDocument: function() { - editor.setContent(''); - } - }); - - // Add queryCommandState overrides - addCommands({ - // Override justify commands - 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { - var name = 'align' + command.substring(7); - var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); - var matches = map(nodes, function(node) { - return !!formatter.matchNode(node, name); - }); - return inArray(matches, TRUE) !== -1; - }, - - 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { - return isFormatMatch(command); - }, - - mceBlockQuote: function() { - return isFormatMatch('blockquote'); - }, - - Outdent: function() { - var node; - - if (settings.inline_styles) { - if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - - if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - } - - return ( - queryCommandState('InsertUnorderedList') || - queryCommandState('InsertOrderedList') || - (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) - ); - }, - - 'InsertUnorderedList,InsertOrderedList': function(command) { - var list = dom.getParent(selection.getNode(), 'ul,ol'); - - return list && - ( - command === 'insertunorderedlist' && list.tagName === 'UL' || - command === 'insertorderedlist' && list.tagName === 'OL' - ); - } - }, 'state'); - - // Add queryCommandValue overrides - addCommands({ - 'FontSize,FontName': function(command) { - var value = 0, parent; - - if ((parent = dom.getParent(selection.getNode(), 'span'))) { - if (command == 'fontsize') { - value = parent.style.fontSize; - } else { - value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); - } - } - - return value; - } - }, 'value'); - - // Add undo manager logic - addCommands({ - Undo: function() { - editor.undoManager.undo(); - }, - - Redo: function() { - editor.undoManager.redo(); - } - }); - }; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/EditorManager.js b/common/static/js/vendor/tinymce/js/tinymce/classes/EditorManager.js deleted file mode 100755 index bc3294c976..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/EditorManager.js +++ /dev/null @@ -1,574 +0,0 @@ -/** - * EditorManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class used as a factory for manager for tinymce.Editor instances. - * - * @example - * tinymce.EditorManager.init({}); - * - * @class tinymce.EditorManager - * @mixes tinymce.util.Observable - * @static - */ -define("tinymce/EditorManager", [ - "tinymce/Editor", - "tinymce/dom/DOMUtils", - "tinymce/util/URI", - "tinymce/Env", - "tinymce/util/Tools", - "tinymce/util/Observable", - "tinymce/util/I18n", - "tinymce/FocusManager" -], function(Editor, DOMUtils, URI, Env, Tools, Observable, I18n, FocusManager) { - var DOM = DOMUtils.DOM; - var explode = Tools.explode, each = Tools.each, extend = Tools.extend; - var instanceCounter = 0, beforeUnloadDelegate; - - var EditorManager = { - /** - * Major version of TinyMCE build. - * - * @property majorVersion - * @type String - */ - majorVersion : '@@majorVersion@@', - - /** - * Minor version of TinyMCE build. - * - * @property minorVersion - * @type String - */ - minorVersion : '@@minorVersion@@', - - /** - * Release date of TinyMCE build. - * - * @property releaseDate - * @type String - */ - releaseDate: '@@releaseDate@@', - - /** - * Collection of editor instances. - * - * @property editors - * @type Object - * @example - * for (edId in tinymce.editors) - * tinymce.editors[edId].save(); - */ - editors: [], - - /** - * Collection of language pack data. - * - * @property i18n - * @type Object - */ - i18n: I18n, - - /** - * Currently active editor instance. - * - * @property activeEditor - * @type tinymce.Editor - * @example - * tinyMCE.activeEditor.selection.getContent(); - * tinymce.EditorManager.activeEditor.selection.getContent(); - */ - activeEditor: null, - - setup: function() { - var self = this, baseURL, documentBaseURL, suffix = "", preInit; - - // Get base URL for the current document - documentBaseURL = document.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, ''); - if (!/[\/\\]$/.test(documentBaseURL)) { - documentBaseURL += '/'; - } - - // If tinymce is defined and has a base use that or use the old tinyMCEPreInit - preInit = window.tinymce || window.tinyMCEPreInit; - if (preInit) { - baseURL = preInit.base || preInit.baseURL; - suffix = preInit.suffix; - } else { - // Get base where the tinymce script is located - var scripts = document.getElementsByTagName('script'); - for (var i = 0; i < scripts.length; i++) { - var src = scripts[i].src; - - // Script types supported: - // tinymce.js tinymce.min.js tinymce.dev.js - // tinymce.jquery.js tinymce.jquery.min.js tinymce.jquery.dev.js - // tinymce.full.js tinymce.full.min.js tinymce.full.dev.js - if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) { - if (src.indexOf('.min') != -1) { - suffix = '.min'; - } - - baseURL = src.substring(0, src.lastIndexOf('/')); - break; - } - } - } - - /** - * Base URL where the root directory if TinyMCE is located. - * - * @property baseURL - * @type String - */ - self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL); - - /** - * Document base URL where the current document is located. - * - * @property documentBaseURL - * @type String - */ - self.documentBaseURL = documentBaseURL; - - /** - * Absolute baseURI for the installation path of TinyMCE. - * - * @property baseURI - * @type tinymce.util.URI - */ - self.baseURI = new URI(self.baseURL); - - /** - * Current suffix to add to each plugin/theme that gets loaded for example ".min". - * - * @property suffix - * @type String - */ - self.suffix = suffix; - - self.focusManager = new FocusManager(self); - }, - - /** - * Initializes a set of editors. This method will create editors based on various settings. - * - * @method init - * @param {Object} settings Settings object to be passed to each editor instance. - * @example - * // Initializes a editor using the longer method - * tinymce.EditorManager.init({ - * some_settings : 'some value' - * }); - * - * // Initializes a editor instance using the shorter version - * tinyMCE.init({ - * some_settings : 'some value' - * }); - */ - init: function(settings) { - var self = this, editors = [], editor; - - function createId(elm) { - var id = elm.id; - - // Use element id, or unique name or generate a unique id - if (!id) { - id = elm.name; - - if (id && !DOM.get(id)) { - id = elm.name; - } else { - // Generate unique name - id = DOM.uniqueId(); - } - - elm.setAttribute('id', id); - } - - return id; - } - - function execCallback(se, n, s) { - var f = se[n]; - - if (!f) { - return; - } - - return f.apply(s || this, Array.prototype.slice.call(arguments, 2)); - } - - function hasClass(n, c) { - return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c); - } - - function readyHandler() { - var l, co; - - DOM.unbind(window, 'ready', readyHandler); - - execCallback(settings, 'onpageload'); - - if (settings.types) { - // Process type specific selector - each(settings.types, function(type) { - each(DOM.select(type.selector), function(elm) { - var editor = new Editor(createId(elm), extend({}, settings, type), self); - editors.push(editor); - editor.render(1); - }); - }); - - return; - } else if (settings.selector) { - // Process global selector - each(DOM.select(settings.selector), function(elm) { - var editor = new Editor(createId(elm), settings, self); - editors.push(editor); - editor.render(1); - }); - - return; - } - - // Fallback to old setting - switch (settings.mode) { - case "exact": - l = settings.elements || ''; - - if(l.length > 0) { - each(explode(l), function(v) { - if (DOM.get(v)) { - editor = new Editor(v, settings, self); - editors.push(editor); - editor.render(true); - } else { - each(document.forms, function(f) { - each(f.elements, function(e) { - if (e.name === v) { - v = 'mce_editor_' + instanceCounter++; - DOM.setAttrib(e, 'id', v); - - editor = new Editor(v, settings, self); - editors.push(editor); - editor.render(1); - } - }); - }); - } - }); - } - break; - - case "textareas": - case "specific_textareas": - each(DOM.select('textarea'), function(elm) { - if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) { - return; - } - - if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) { - editor = new Editor(createId(elm), settings, self); - editors.push(editor); - editor.render(true); - } - }); - break; - } - - // Call onInit when all editors are initialized - if (settings.oninit) { - l = co = 0; - - each(editors, function(ed) { - co++; - - if (!ed.initialized) { - // Wait for it - ed.on('init', function() { - l++; - - // All done - if (l == co) { - execCallback(settings, 'oninit'); - } - }); - } else { - l++; - } - - // All done - if (l == co) { - execCallback(settings, 'oninit'); - } - }); - } - } - - self.settings = settings; - - DOM.bind(window, 'ready', readyHandler); - }, - - /** - * Returns a editor instance by id. - * - * @method get - * @param {String/Number} id Editor instance id or index to return. - * @return {tinymce.Editor} Editor instance to return. - * @example - * // Adds an onclick event to an editor by id (shorter version) - * tinymce.get('mytextbox').on('click', function(e) { - * ed.windowManager.alert('Hello world!'); - * }); - * - * // Adds an onclick event to an editor by id (longer version) - * tinymce.EditorManager.get('mytextbox').on('click', function(e) { - * ed.windowManager.alert('Hello world!'); - * }); - */ - get: function(id) { - if (id === undefined) { - return this.editors; - } - - return this.editors[id]; - }, - - /** - * Adds an editor instance to the editor collection. This will also set it as the active editor. - * - * @method add - * @param {tinymce.Editor} editor Editor instance to add to the collection. - * @return {tinymce.Editor} The same instance that got passed in. - */ - add: function(editor) { - var self = this, editors = self.editors; - - // Add named and index editor instance - editors[editor.id] = editor; - editors.push(editor); - - self.activeEditor = editor; - - /** - * Fires when an editor is added to the EditorManager collection. - * - * @event AddEditor - * @param {Object} e Event arguments. - */ - self.fire('AddEditor', {editor: editor}); - - if (!beforeUnloadDelegate) { - beforeUnloadDelegate = function() { - self.fire('BeforeUnload'); - }; - - DOM.bind(window, 'beforeunload', beforeUnloadDelegate); - } - - return editor; - }, - - /** - * Creates an editor instance and adds it to the EditorManager collection. - * - * @method createEditor - * @param {String} id Instance id to use for editor. - * @param {Object} settings Editor instance settings. - * @return {tinymce.Editor} Editor instance that got created. - */ - createEditor: function(id, settings) { - return this.add(new Editor(id, settings, this)); - }, - - /** - * Removes a editor or editors form page. - * - * @example - * // Remove all editors bound to divs - * tinymce.remove('div'); - * - * // Remove all editors bound to textareas - * tinymce.remove('textarea'); - * - * // Remove all editors - * tinymce.remove(); - * - * // Remove specific instance by id - * tinymce.remove('#id'); - * - * @method remove - * @param {tinymce.Editor/String/Object} [selector] CSS selector or editor instance to remove. - * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null. - */ - remove: function(selector) { - var self = this, i, editors = self.editors, editor, removedFromList; - - // Remove all editors - if (!selector) { - for (i = editors.length - 1; i >= 0; i--) { - self.remove(editors[i]); - } - - return; - } - - // Remove editors by selector - if (typeof(selector) == "string") { - selector = selector.selector || selector; - - each(DOM.select(selector), function(elm) { - self.remove(editors[elm.id]); - }); - - return; - } - - // Remove specific editor - editor = selector; - - // Not in the collection - if (!editors[editor.id]) { - return null; - } - - delete editors[editor.id]; - - for (i = 0; i < editors.length; i++) { - if (editors[i] == editor) { - editors.splice(i, 1); - removedFromList = true; - break; - } - } - - // Select another editor since the active one was removed - if (self.activeEditor == editor) { - self.activeEditor = editors[0]; - } - - /** - * Fires when an editor is removed from EditorManager collection. - * - * @event RemoveEditor - * @param {Object} e Event arguments. - */ - if (removedFromList) { - self.fire('RemoveEditor', {editor: editor}); - } - - if (!editors.length) { - DOM.unbind(window, 'beforeunload', beforeUnloadDelegate); - } - - editor.remove(); - - return editor; - }, - - /** - * Executes a specific command on the currently active editor. - * - * @method execCommand - * @param {String} c Command to perform for example Bold. - * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not. - * @param {String} v Optional value parameter like for example an URL to a link. - * @return {Boolean} true/false if the command was executed or not. - */ - execCommand: function(cmd, ui, value) { - var self = this, editor = self.get(value); - - // Manager commands - switch (cmd) { - case "mceAddEditor": - if (!self.get(value)) { - new Editor(value, self.settings, self).render(); - } - - return true; - - case "mceRemoveEditor": - if (editor) { - editor.remove(); - } - - return true; - - case 'mceToggleEditor': - if (!editor) { - self.execCommand('mceAddEditor', 0, value); - return true; - } - - if (editor.isHidden()) { - editor.show(); - } else { - editor.hide(); - } - - return true; - } - - // Run command on active editor - if (self.activeEditor) { - return self.activeEditor.execCommand(cmd, ui, value); - } - - return false; - }, - - /** - * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted. - * - * @method triggerSave - * @example - * // Saves all contents - * tinyMCE.triggerSave(); - */ - triggerSave: function() { - each(this.editors, function(editor) { - editor.save(); - }); - }, - - /** - * Adds a language pack, this gets called by the loaded language files like en.js. - * - * @method addI18n - * @param {String} code Optional language code. - * @param {Object} items Name/value object with translations. - */ - addI18n: function(code, items) { - I18n.add(code, items); - }, - - /** - * Translates the specified string using the language pack items. - * - * @method translate - * @param {String/Array/Object} text String to translate - * @return {String} Translated string. - */ - translate: function(text) { - return I18n.translate(text); - } - }; - - extend(EditorManager, Observable); - - EditorManager.setup(); - - // Export EditorManager as tinymce/tinymce in global namespace - window.tinymce = window.tinyMCE = EditorManager; - - return EditorManager; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/EnterKey.js b/common/static/js/vendor/tinymce/js/tinymce/classes/EnterKey.js deleted file mode 100755 index 325ab28c00..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/EnterKey.js +++ /dev/null @@ -1,670 +0,0 @@ -/** - * EnterKey.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Contains logic for handling the enter key to split/generate block elements. - */ -define("tinymce/EnterKey", [ - "tinymce/dom/TreeWalker", - "tinymce/dom/RangeUtils", - "tinymce/Env" -], function(TreeWalker, RangeUtils, Env) { - var isIE = Env.ie && Env.ie < 11; - - return function(editor) { - var dom = editor.dom, selection = editor.selection, settings = editor.settings; - var undoManager = editor.undoManager, schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements(); - - function handleEnterKey(evt) { - var rng, tmpRng, editableRoot, container, offset, parentBlock, documentMode, shiftKey, - newBlock, fragment, containerBlock, parentBlockName, containerBlockName, newBlockName, isAfterLastNodeInContainer; - - // Returns true if the block can be split into two blocks or not - function canSplitBlock(node) { - return node && - dom.isBlock(node) && - !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && - !/^(fixed|absolute)/i.test(node.style.position) && - dom.getContentEditable(node) !== "true"; - } - - // Renders empty block on IE - function renderBlockOnIE(block) { - var oldRng; - - if (dom.isBlock(block)) { - oldRng = selection.getRng(); - block.appendChild(dom.create('span', null, '\u00a0')); - selection.select(block); - block.lastChild.outerHTML = ''; - selection.setRng(oldRng); - } - } - - // Remove the first empty inline element of the block so this:x
becomes this:x
- function trimInlineElementsOnLeftSideOfBlock(block) { - var node = block, firstChilds = [], i; - - // Find inner most first child ex:*
- while ((node = node.firstChild)) { - if (dom.isBlock(node)) { - return; - } - - if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { - firstChilds.push(node); - } - } - - i = firstChilds.length; - while (i--) { - node = firstChilds[i]; - if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { - dom.remove(node); - } else { - // Remove see #5381 - if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { - dom.remove(node); - } - } - } - } - - // Moves the caret to a suitable position within the root for example in the first non - // pure whitespace text node or before an image - function moveToCaretPosition(root) { - var walker, node, rng, lastNode = root, tempElm; - - function firstNonWhiteSpaceNodeSibling(node) { - while (node) { - if (node.nodeType == 1 || (node.nodeType == 3 && node.data && /[\r\n\s]/.test(node.data))) { - return node; - } - - node = node.nextSibling; - } - } - - // Old IE versions doesn't properly render blocks with br elements in them - // For exampletext|
text|text2
*texttext*
! - // This will reduce the number of wrapper elements that needs to be created - // Move start point up the tree - if (format[0].inline || format[0].block_expand) { - if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { - startContainer = findParentContainer(true); - } - - if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { - endContainer = findParentContainer(); - } - } - - // Expand start/end container to matching selector - if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { - // Find new startContainer/endContainer if there is better one - startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); - endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); - } - - // Expand start/end container to matching block element or text node - if (format[0].block || format[0].selector) { - // Find new startContainer/endContainer if there is better one - startContainer = findBlockEndPoint(startContainer, 'previousSibling'); - endContainer = findBlockEndPoint(endContainer, 'nextSibling'); - - // Non block element then try to expand up the leaf - if (format[0].block) { - if (!isBlock(startContainer)) { - startContainer = findParentContainer(true); - } - - if (!isBlock(endContainer)) { - endContainer = findParentContainer(); - } - } - } - - // Setup index for startContainer - if (startContainer.nodeType == 1) { - startOffset = nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - - // Setup index for endContainer - if (endContainer.nodeType == 1) { - endOffset = nodeIndex(endContainer) + 1; - endContainer = endContainer.parentNode; - } - - // Return new range like object - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - } - - /** - * Removes the specified format for the specified node. It will also remove the node if it doesn't have - * any attributes if the format specifies it to do so. - * - * @private - * @param {Object} format Format object with items to remove from node. - * @param {Object} vars Name/value object with variables to apply to format. - * @param {Node} node Node to remove the format styles on. - * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. - * @return {Boolean} True/false if the node was removed or not. - */ - function removeFormat(format, vars, node, compare_node) { - var i, attrs, stylesModified; - - // Check if node matches format - if (!matchName(node, format)) { - return FALSE; - } - - // Should we compare with format attribs and styles - if (format.remove != 'all') { - // Remove styles - each(format.styles, function(value, name) { - value = normalizeStyleValue(replaceVars(value, vars), name); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(getStyle(compare_node, name), value)) { - dom.setStyle(node, name, ''); - } - - stylesModified = 1; - }); - - // Remove style attribute if it's empty - if (stylesModified && dom.getAttrib(node, 'style') === '') { - node.removeAttribute('style'); - node.removeAttribute('data-mce-style'); - } - - // Remove attributes - each(format.attributes, function(value, name) { - var valueOut; - - value = replaceVars(value, vars); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { - // Keep internal classes - if (name == 'class') { - value = dom.getAttrib(node, name); - if (value) { - // Build new class value where everything is removed except the internal prefixed classes - valueOut = ''; - each(value.split(/\s+/), function(cls) { - if (/mce\w+/.test(cls)) { - valueOut += (valueOut ? ' ' : '') + cls; - } - }); - - // We got some internal classes left - if (valueOut) { - dom.setAttrib(node, name, valueOut); - return; - } - } - } - - // IE6 has a bug where the attribute doesn't get removed correctly - if (name == "class") { - node.removeAttribute('className'); - } - - // Remove mce prefixed attributes - if (MCE_ATTR_RE.test(name)) { - node.removeAttribute('data-mce-' + name); - } - - node.removeAttribute(name); - } - }); - - // Remove classes - each(format.classes, function(value) { - value = replaceVars(value, vars); - - if (!compare_node || dom.hasClass(compare_node, value)) { - dom.removeClass(node, value); - } - }); - - // Check for non internal attributes - attrs = dom.getAttribs(node); - for (i = 0; i < attrs.length; i++) { - if (attrs[i].nodeName.indexOf('_') !== 0) { - return FALSE; - } - } - } - - // Remove the inline child if it's empty for example or - if (format.remove != 'none') { - removeNode(node, format); - return TRUE; - } - } - - /** - * Removes the node and wrap it's children in paragraphs before doing so or - * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. - * - * If the div in the node below gets removed: - * text|
- formatNode.parentNode.replaceChild(caretContainer, formatNode); - } else { - // Insert caret container after the formated node - dom.insertAfter(caretContainer, formatNode); - } - - // Move selection to text node - selection.setCursorLocation(node, 1); - - // If the formatNode is empty, we can remove it safely. - if (dom.isEmpty(formatNode)) { - dom.remove(formatNode); - } - } - } - - // Checks if the parent caret container node isn't empty if that is the case it - // will remove the bogus state on all children that isn't empty - function unmarkBogusCaretParents() { - var caretContainer; - - caretContainer = getParentCaretContainer(selection.getStart()); - if (caretContainer && !dom.isEmpty(caretContainer)) { - walk(caretContainer, function(node) { - if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { - dom.setAttrib(node, 'data-mce-bogus', null); - } - }, 'childNodes'); - } - } - - // Only bind the caret events once - if (!ed._hasCaretEvents) { - // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements - markCaretContainersBogus = function() { - var nodes = [], i; - - if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { - // Mark children - i = nodes.length; - while (i--) { - dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); - } - } - }; - - disableCaretContainer = function(e) { - var keyCode = e.keyCode; - - removeCaretContainer(); - - // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys - if (keyCode == 8 || keyCode == 37 || keyCode == 39) { - removeCaretContainer(getParentCaretContainer(selection.getStart())); - } - - unmarkBogusCaretParents(); - }; - - // Remove bogus state if they got filled by contents using editor.selection.setContent - ed.on('SetContent', function(e) { - if (e.selection) { - unmarkBogusCaretParents(); - } - }); - ed._hasCaretEvents = true; - } - - // Do apply or remove caret format - if (type == "apply") { - applyCaretFormat(); - } else { - removeCaretFormat(); - } - } - - /** - * Moves the start to the first suitable text node. - */ - function moveStart(rng) { - var container = rng.startContainer, - offset = rng.startOffset, isAtEndOfText, - walker, node, nodes, tmpNode; - - // Convert text node into index if possible - if (container.nodeType == 3 && offset >= container.nodeValue.length) { - // Get the parent container location and walk from there - offset = nodeIndex(container); - container = container.parentNode; - isAtEndOfText = true; - } - - // Move startContainer/startOffset in to a suitable node - if (container.nodeType == 1) { - nodes = container.childNodes; - container = nodes[Math.min(offset, nodes.length - 1)]; - walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); - - // If offset is at end of the parent node walk to the next one - if (offset > nodes.length - 1 || isAtEndOfText) { - walker.next(); - } - - for (node = walker.current(); node; node = walker.next()) { - if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { - // IE has a "neat" feature where it moves the start node into the closest element - // we can avoid this by inserting an element before it and then remove it after we set the selection - tmpNode = dom.create('a', null, INVISIBLE_CHAR); - node.parentNode.insertBefore(tmpNode, node); - - // Set selection and remove tmpNode - rng.setStart(node, 0); - selection.setRng(rng); - dom.remove(tmpNode); - - return; - } - } - } - } - }; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/LegacyInput.js b/common/static/js/vendor/tinymce/js/tinymce/classes/LegacyInput.js deleted file mode 100755 index 2f3f55985c..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/LegacyInput.js +++ /dev/null @@ -1,73 +0,0 @@ -/** - * LegacyInput.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -define("tinymce/LegacyInput", [ - "tinymce/EditorManager", - "tinymce/util/Tools" -], function(EditorManager, Tools) { - var each = Tools.each, explode = Tools.explode; - - EditorManager.on('AddEditor', function(e) { - var editor = e.editor; - - editor.on('preInit', function() { - var filters, fontSizes, dom, settings = editor.settings; - - function replaceWithSpan(node, styles) { - each(styles, function(value, name) { - if (value) { - dom.setStyle(node, name, value); - } - }); - - dom.rename(node, 'span'); - } - - function convert(e) { - dom = editor.dom; - - if (settings.convert_fonts_to_spans) { - each(dom.select('font,u,strike', e.node), function(node) { - filters[node.nodeName.toLowerCase()](dom, node); - }); - } - } - - if (settings.inline_styles) { - fontSizes = explode(settings.font_size_legacy_values); - - filters = { - font: function(dom, node) { - replaceWithSpan(node, { - backgroundColor: node.style.backgroundColor, - color: node.color, - fontFamily: node.face, - fontSize: fontSizes[parseInt(node.size, 10) - 1] - }); - }, - - u: function(dom, node) { - replaceWithSpan(node, { - textDecoration: 'underline' - }); - }, - - strike: function(dom, node) { - replaceWithSpan(node, { - textDecoration: 'line-through' - }); - } - }; - - editor.on('PreProcess SetContent', convert); - } - }); - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/Shortcuts.js b/common/static/js/vendor/tinymce/js/tinymce/classes/Shortcuts.js deleted file mode 100755 index 03051d8e5e..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/Shortcuts.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Shortcuts.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Contains all logic for handling of keyboard shortcuts. - */ -define("tinymce/Shortcuts", [ - "tinymce/util/Tools", - "tinymce/Env" -], function(Tools, Env) { - var each = Tools.each, explode = Tools.explode; - - var keyCodeLookup = { - "f9": 120, - "f10": 121, - "f11": 122 - }; - - return function(editor) { - var self = this, shortcuts = {}; - - editor.on('keyup keypress keydown', function(e) { - if (e.altKey || e.ctrlKey || e.metaKey) { - each(shortcuts, function(shortcut) { - var ctrlKey = Env.mac ? e.metaKey : e.ctrlKey; - - if (shortcut.ctrl != ctrlKey || shortcut.alt != e.altKey || shortcut.shift != e.shiftKey) { - return; - } - - if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) { - e.preventDefault(); - - if (e.type == "keydown") { - shortcut.func.call(shortcut.scope); - } - - return true; - } - }); - } - }); - - /** - * Adds a keyboard shortcut for some command or function. - * - * @method addShortcut - * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o. - * @param {String} desc Text description for the command. - * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed. - * @param {Object} sc Optional scope to execute the function in. - * @return {Boolean} true/false state if the shortcut was added or not. - */ - self.add = function(pattern, desc, cmdFunc, scope) { - var cmd; - - cmd = cmdFunc; - - if (typeof(cmdFunc) === 'string') { - cmdFunc = function() { - editor.execCommand(cmd, false, null); - }; - } else if (Tools.isArray(cmd)) { - cmdFunc = function() { - editor.execCommand(cmd[0], cmd[1], cmd[2]); - }; - } - - each(explode(pattern.toLowerCase()), function(pattern) { - var shortcut = { - func: cmdFunc, - scope: scope || editor, - desc: editor.translate(desc), - alt: false, - ctrl: false, - shift: false - }; - - each(explode(pattern, '+'), function(value) { - switch (value) { - case 'alt': - case 'ctrl': - case 'shift': - shortcut[value] = true; - break; - - default: - shortcut.charCode = value.charCodeAt(0); - shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0); - } - }); - - shortcuts[ - (shortcut.ctrl ? 'ctrl' : '') + ',' + - (shortcut.alt ? 'alt' : '') + ',' + - (shortcut.shift ? 'shift' : '') + ',' + - shortcut.keyCode - ] = shortcut; - }); - - return true; - }; - }; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/UndoManager.js b/common/static/js/vendor/tinymce/js/tinymce/classes/UndoManager.js deleted file mode 100755 index ebe43b4b83..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/UndoManager.js +++ /dev/null @@ -1,337 +0,0 @@ -/** - * UndoManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. - * - * @class tinymce.UndoManager - */ -define("tinymce/UndoManager", [ - "tinymce/Env", - "tinymce/util/Tools" -], function(Env, Tools) { - var trim = Tools.trim, trimContentRegExp; - - trimContentRegExp = new RegExp([ - ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers - 'abcabc123
would produceabc
abc123
. - * - * @method split - * @param {Element} parentElm Parent element to split. - * @param {Element} splitElm Element to split at. - * @param {Element} replacementElm Optional replacement element to replace the split element with. - * @return {Element} Returns the split element or the replacement element if that is specified. - */ - split: function(parentElm, splitElm, replacementElm) { - var self = this, r = self.createRng(), bef, aft, pa; - - // W3C valid browsers tend to leave empty nodes to the left/right side of the contents - this makes sense - // but we don't want that in our code since it serves no purpose for the end user - // For example splitting this html at the bold element: - //text 1CHOPtext 2
- // would produce: - //text 1
CHOPtext 2
- // this function will then trim off empty edges and produce: - //text 1
CHOPtext 2
- function trimNode(node) { - var i, children = node.childNodes, type = node.nodeType; - - function surroundedBySpans(node) { - var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; - var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; - return previousIsSpan && nextIsSpan; - } - - if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') { - return; - } - - for (i = children.length - 1; i >= 0; i--) { - trimNode(children[i]); - } - - if (type != 9) { - // Keep non whitespace text nodes - if (type == 3 && node.nodeValue.length > 0) { - // If parent element isn't a block or there isn't any useful contents for example "" - // Also keep text nodes with only spaces if surrounded by spans. - // eg. "
a b
" should keep space between a and b - var trimmedLength = trim(node.nodeValue).length; - if (!self.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) { - return; - } - } else if (type == 1) { - // If the only child is a bookmark then move it up - children = node.childNodes; - - // TODO fix this complex if - if (children.length == 1 && children[0] && children[0].nodeType == 1 && - children[0].getAttribute('data-mce-type') == 'bookmark') { - node.parentNode.insertBefore(children[0], node); - } - - // Keep non empty elements or img, hr etc - if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) { - return; - } - } - - self.remove(node); - } - - return node; - } - - if (parentElm && splitElm) { - // Get before chunk - r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); - r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); - bef = r.extractContents(); - - // Get after chunk - r = self.createRng(); - r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); - r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); - aft = r.extractContents(); - - // Insert before chunk - pa = parentElm.parentNode; - pa.insertBefore(trimNode(bef), parentElm); - - // Insert middle chunk - if (replacementElm) { - pa.replaceChild(replacementElm, splitElm); - } else { - pa.insertBefore(splitElm, parentElm); - } - - // Insert after chunk - pa.insertBefore(trimNode(aft), parentElm); - self.remove(parentElm); - - return replacementElm || splitElm; - } - }, - - /** - * Adds an event handler to the specified object. - * - * @method bind - * @param {Element/Document/Window/Array} target Target element to bind events to. - * handler to or an array of elements/ids/documents. - * @param {String} name Name of event handler to add, for example: click. - * @param {function} func Function to execute when the event occurs. - * @param {Object} scope Optional scope to execute the function in. - * @return {function} Function callback handler the same as the one passed in. - */ - bind: function(target, name, func, scope) { - var self = this; - - if (Tools.isArray(target)) { - var i = target.length; - - while (i--) { - target[i] = self.bind(target[i], name, func, scope); - } - - return target; - } - - // Collect all window/document events bound by editor instance - if (self.settings.collect && (target === self.doc || target === self.win)) { - self.boundEvents.push([target, name, func, scope]); - } - - return self.events.bind(target, name, func, scope || self); - }, - - /** - * Removes the specified event handler by name and function from an element or collection of elements. - * - * @method unbind - * @param {Element/Document/Window/Array} target Target element to unbind events on. - * @param {String} name Event handler name, for example: "click" - * @param {function} func Function to remove. - * @return {bool/Array} Bool state of true if the handler was removed, or an array of states if multiple input elements - * were passed in. - */ - unbind: function(target, name, func) { - var self = this, i; - - if (Tools.isArray(target)) { - i = target.length; - - while (i--) { - target[i] = self.unbind(target[i], name, func); - } - - return target; - } - - // Remove any bound events matching the input - if (self.boundEvents && (target === self.doc || target === self.win)) { - i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - - if (target == item[0] && (!name || name == item[1]) && (!func || func == item[2])) { - this.events.unbind(item[0], item[1], item[2]); - } - } - } - - return this.events.unbind(target, name, func); - }, - - /** - * Fires the specified event name with object on target. - * - * @method fire - * @param {Node/Document/Window} target Target element or object to fire event on. - * @param {String} name Name of the event to fire. - * @param {Object} evt Event object to send. - * @return {Event} Event object. - */ - fire: function(target, name, evt) { - return this.events.fire(target, name, evt); - }, - - // Returns the content editable state of a node - getContentEditable: function(node) { - var contentEditable; - - // Check type - if (node.nodeType != 1) { - return null; - } - - // Check for fake content editable - contentEditable = node.getAttribute("data-mce-contenteditable"); - if (contentEditable && contentEditable !== "inherit") { - return contentEditable; - } - - // Check for real content editable - return node.contentEditable !== "inherit" ? node.contentEditable : null; - }, - - /** - * Destroys all internal references to the DOM to solve IE leak issues. - * - * @method destroy - */ - destroy: function() { - var self = this; - - // Unbind all events bound to window/document by editor instance - if (self.boundEvents) { - var i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - this.events.unbind(item[0], item[1], item[2]); - } - - self.boundEvents = null; - } - - // Restore sizzle document to window.document - // Since the current document might be removed producing "Permission denied" on IE see #6325 - if (Sizzle.setDocument) { - Sizzle.setDocument(); - } - - self.win = self.doc = self.root = self.events = self.frag = null; - }, - - // #ifdef debug - - dumpRng: function(r) { - return ( - 'startContainer: ' + r.startContainer.nodeName + - ', startOffset: ' + r.startOffset + - ', endContainer: ' + r.endContainer.nodeName + - ', endOffset: ' + r.endOffset - ); - }, - - // #endif - - _findSib: function(node, selector, name) { - var self = this, func = selector; - - if (node) { - // If expression make a function of it using is - if (typeof(func) == 'string') { - func = function(node) { - return self.is(node, selector); - }; - } - - // Loop all siblings - for (node = node[name]; node; node = node[name]) { - if (func(node)) { - return node; - } - } - } - - return null; - } - }; - - /** - * Instance of DOMUtils for the current document. - * - * @static - * @property DOM - * @type tinymce.dom.DOMUtils - * @example - * // Example of how to add a class to some element by id - * tinymce.DOM.addClass('someid', 'someclass'); - */ - DOMUtils.DOM = new DOMUtils(document); - - return DOMUtils; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/DomQuery.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/DomQuery.js deleted file mode 100755 index 838c98256f..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/DomQuery.js +++ /dev/null @@ -1,730 +0,0 @@ -/** - * DomQuery.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - * - * Some of this logic is based on jQuery code that is released under - * MIT license that grants us to sublicense it under LGPL. - * - * @ignore-file - */ - -/** - * @class tinymce.dom.DomQuery - */ -define("tinymce/dom/DomQuery", [ - "tinymce/dom/EventUtils", - "tinymce/dom/Sizzle" -], function(EventUtils, Sizzle) { - var doc = document, push = Array.prototype.push, slice = Array.prototype.slice; - var rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/; - var Event = EventUtils.Event; - - function isDefined(obj) { - return typeof obj !== "undefined"; - } - - function isString(obj) { - return typeof obj === "string"; - } - - function createFragment(html) { - var frag, node, container; - - container = doc.createElement("div"); - frag = doc.createDocumentFragment(); - container.innerHTML = html; - - while ((node = container.firstChild)) { - frag.appendChild(node); - } - - return frag; - } - - function domManipulate(targetNodes, sourceItem, callback) { - var i; - - if (typeof sourceItem === "string") { - sourceItem = createFragment(sourceItem); - } else if (sourceItem.length) { - for (i = 0; i < sourceItem.length; i++) { - domManipulate(targetNodes, sourceItem[i], callback); - } - - return targetNodes; - } - - i = targetNodes.length; - while (i--) { - callback.call(targetNodes[i], sourceItem.parentNode ? sourceItem : sourceItem); - } - - return targetNodes; - } - - function hasClass(node, className) { - return node && className && (' ' + node.className + ' ').indexOf(' ' + className + ' ') !== -1; - } - - /** - * Makes a map object out of a string that gets separated by a delimiter. - * - * @method makeMap - * @param {String} items Item string to split. - * @param {Object} map Optional object to add items to. - * @return {Object} name/value object with items as keys. - */ - function makeMap(items, map) { - var i; - - items = items || []; - - if (typeof(items) == "string") { - items = items.split(' '); - } - - map = map || {}; - - i = items.length; - while (i--) { - map[items[i]] = {}; - } - - return map; - } - - var numericCssMap = makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom'); - - function DomQuery(selector, context) { - /*eslint new-cap:0 */ - return new DomQuery.fn.init(selector, context); - } - - /** - * Extends the specified object with another object. - * - * @method extend - * @param {Object} target Object to extend. - * @param {Object..} obj Multiple objects to extend with. - * @return {Object} Same as target, the extended object. - */ - function extend(target) { - var args = arguments, arg, i, key; - - for (i = 1; i < args.length; i++) { - arg = args[i]; - - for (key in arg) { - target[key] = arg[key]; - } - } - - return target; - } - - /** - * Converts the specified object into a real JavaScript array. - * - * @method toArray - * @param {Object} obj Object to convert into array. - * @return {Array} Array object based in input. - */ - function toArray(obj) { - var array = [], i, l; - - for (i = 0, l = obj.length; i < l; i++) { - array[i] = obj[i]; - } - - return array; - } - - /** - * Returns the index of the specified item inside the array. - * - * @method inArray - * @param {Object} item Item to look for. - * @param {Array} array Array to look for item in. - * @return {Number} Index of the item or -1. - */ - function inArray(item, array) { - var i; - - if (array.indexOf) { - return array.indexOf(item); - } - - i = array.length; - while (i--) { - if (array[i] === item) { - return i; - } - } - - return -1; - } - - /** - * Returns true/false if the specified object is an array. - * - * @method isArray - * @param {Object} obj Object to check if it's an array. - * @return {Boolean} true/false if the input object is array or not. - */ - var isArray = Array.isArray || function(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; - - var whiteSpaceRegExp = /^\s*|\s*$/g; - - function trim(str) { - return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, ''); - } - - /** - * Executes the callback function for each item in array/object. If you return false in the - * callback it will break the loop. - * - * @method each - * @param {Object} obj Object to iterate. - * @param {function} callback Callback function to execute for each item. - */ - function each(obj, callback) { - var length, key, i, undef, value; - - if (obj) { - length = obj.length; - - if (length === undef) { - // Loop object items - for (key in obj) { - if (obj.hasOwnProperty(key)) { - value = obj[key]; - if (callback.call(value, value, key) === false) { - break; - } - } - } - } else { - // Loop array items - for (i = 0; i < length; i++) { - value = obj[i]; - if (callback.call(value, value, key) === false) { - break; - } - } - } - } - - return obj; - } - - DomQuery.fn = DomQuery.prototype = { - constructor: DomQuery, - selector: "", - length: 0, - - init: function(selector, context) { - var self = this, match, node; - - if (!selector) { - return self; - } - - if (selector.nodeType) { - self.context = self[0] = selector; - self.length = 1; - - return self; - } - - if (isString(selector)) { - if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) { - match = [null, selector, null]; - } else { - match = rquickExpr.exec(selector); - } - - if (match) { - if (match[1]) { - node = createFragment(selector).firstChild; - while (node) { - this.add(node); - node = node.nextSibling; - } - } else { - node = doc.getElementById(match[2]); - - if (node.id !== match[2]) { - return self.find(selector); - } - - self.length = 1; - self[0] = node; - } - } else { - return DomQuery(context || document).find(selector); - } - } else { - this.add(selector); - } - - return self; - }, - - toArray: function() { - return toArray(this); - }, - - add: function(items) { - var self = this; - - // Force single item into array - if (!isArray(items)) { - if (items instanceof DomQuery) { - self.add(items.toArray()); - } else { - push.call(self, items); - } - } else { - push.apply(self, items); - } - - return self; - }, - - attr: function(name, value) { - var self = this; - - if (typeof name === "object") { - each(name, function(value, name) { - self.attr(name, value); - }); - } else if (isDefined(value)) { - this.each(function() { - if (this.nodeType === 1) { - this.setAttribute(name, value); - } - }); - } else { - return self[0] && self[0].nodeType === 1 ? self[0].getAttribute(name) : undefined; - } - - return self; - }, - - css: function(name, value) { - var self = this; - - if (typeof name === "object") { - each(name, function(value, name) { - self.css(name, value); - }); - } else { - // Camelcase it, if needed - name = name.replace(/-(\D)/g, function(a, b) { - return b.toUpperCase(); - }); - - if (isDefined(value)) { - // Default px suffix on these - if (typeof(value) === 'number' && !numericCssMap[name]) { - value += 'px'; - } - - self.each(function() { - var style = this.style; - - // IE specific opacity - if (name === "opacity" && this.runtimeStyle && typeof(this.runtimeStyle.opacity) === "undefined") { - style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")"; - } - - try { - style[name] = value; - } catch (ex) { - // Ignore - } - }); - } else { - return self[0] ? self[0].style[name] : undefined; - } - } - - return self; - }, - - remove: function() { - var self = this, node, i = this.length; - - while (i--) { - node = self[i]; - Event.clean(node); - - if (node.parentNode) { - node.parentNode.removeChild(node); - } - } - - return this; - }, - - empty: function() { - var self = this, node, i = this.length; - - while (i--) { - node = self[i]; - while (node.firstChild) { - node.removeChild(node.firstChild); - } - } - - return this; - }, - - html: function(value) { - var self = this, i; - - if (isDefined(value)) { - i = self.length; - while (i--) { - self[i].innerHTML = value; - } - - return self; - } - - return self[0] ? self[0].innerHTML : ''; - }, - - text: function(value) { - var self = this, i; - - if (isDefined(value)) { - i = self.length; - while (i--) { - self[i].innerText = self[0].textContent = value; - } - - return self; - } - - return self[0] ? self[0].innerText || self[0].textContent : ''; - }, - - append: function() { - return domManipulate(this, arguments, function(node) { - if (this.nodeType === 1) { - this.appendChild(node); - } - }); - }, - - prepend: function() { - return domManipulate(this, arguments, function(node) { - if (this.nodeType === 1) { - this.insertBefore(node, this.firstChild); - } - }); - }, - - before: function() { - var self = this; - - if (self[0] && self[0].parentNode) { - return domManipulate(self, arguments, function(node) { - this.parentNode.insertBefore(node, this.nextSibling); - }); - } - - return self; - }, - - after: function() { - var self = this; - - if (self[0] && self[0].parentNode) { - return domManipulate(self, arguments, function(node) { - this.parentNode.insertBefore(node, this); - }); - } - - return self; - }, - - appendTo: function(val) { - DomQuery(val).append(this); - - return this; - }, - - addClass: function(className) { - return this.toggleClass(className, true); - }, - - removeClass: function(className) { - return this.toggleClass(className, false); - }, - - toggleClass: function(className, state) { - var self = this; - - if (className.indexOf(' ') !== -1) { - each(className.split(' '), function() { - self.toggleClass(this, state); - }); - } else { - self.each(function(node) { - var existingClassName; - - if (hasClass(node, className) !== state) { - existingClassName = node.className; - - if (state) { - node.className += existingClassName ? ' ' + className : className; - } else { - node.className = trim((" " + existingClassName + " ").replace(' ' + className + ' ', ' ')); - } - } - }); - } - - return self; - }, - - hasClass: function(className) { - return hasClass(this[0], className); - }, - - each: function(callback) { - return each(this, callback); - }, - - on: function(name, callback) { - return this.each(function() { - Event.bind(this, name, callback); - }); - }, - - off: function(name, callback) { - return this.each(function() { - Event.unbind(this, name, callback); - }); - }, - - show: function() { - return this.css('display', ''); - }, - - hide: function() { - return this.css('display', 'none'); - }, - - slice: function() { - return new DomQuery(slice.apply(this, arguments)); - }, - - eq: function(index) { - return index === -1 ? this.slice(index) : this.slice(index, +index + 1); - }, - - first: function() { - return this.eq(0); - }, - - last: function() { - return this.eq(-1); - }, - - replaceWith: function(content) { - var self = this; - - if (self[0]) { - self[0].parentNode.replaceChild(DomQuery(content)[0], self[0]); - } - - return self; - }, - - wrap: function(wrapper) { - wrapper = DomQuery(wrapper)[0]; - - return this.each(function() { - var self = this, newWrapper = wrapper.cloneNode(false); - self.parentNode.insertBefore(newWrapper, self); - newWrapper.appendChild(self); - }); - }, - - unwrap: function() { - return this.each(function() { - var self = this, node = self.firstChild, currentNode; - - while (node) { - currentNode = node; - node = node.nextSibling; - self.parentNode.insertBefore(currentNode, self); - } - }); - }, - - clone: function() { - var result = []; - - this.each(function() { - result.push(this.cloneNode(true)); - }); - - return DomQuery(result); - }, - - find: function(selector) { - var i, l, ret = []; - - for (i = 0, l = this.length; i < l; i++) { - DomQuery.find(selector, this[i], ret); - } - - return DomQuery(ret); - }, - - push: push, - sort: [].sort, - splice: [].splice - }; - - // Static members - extend(DomQuery, { - extend: extend, - toArray: toArray, - inArray: inArray, - isArray: isArray, - each: each, - trim: trim, - makeMap: makeMap, - - // Sizzle - find: Sizzle, - expr: Sizzle.selectors, - unique: Sizzle.uniqueSort, - text: Sizzle.getText, - isXMLDoc: Sizzle.isXML, - contains: Sizzle.contains, - filter: function(expr, elems, not) { - if (not) { - expr = ":not(" + expr + ")"; - } - - if (elems.length === 1) { - elems = DomQuery.find.matchesSelector(elems[0], expr) ? [elems[0]] : []; - } else { - elems = DomQuery.find.matches(expr, elems); - } - - return elems; - } - }); - - function dir(el, prop, until) { - var matched = [], cur = el[prop]; - - while (cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !DomQuery(cur).is(until))) { - if (cur.nodeType === 1) { - matched.push(cur); - } - - cur = cur[prop]; - } - - return matched; - } - - function sibling(n, el, siblingName, nodeType) { - var r = []; - - for(; n; n = n[siblingName]) { - if ((!nodeType || n.nodeType === nodeType) && n !== el) { - r.push(n); - } - } - - return r; - } - - each({ - parent: function(node) { - var parent = node.parentNode; - - return parent && parent.nodeType !== 11 ? parent : null; - }, - - parents: function(node) { - return dir(node, "parentNode"); - }, - - parentsUntil: function(node, until) { - return dir(node, "parentNode", until); - }, - - next: function(node) { - return sibling(node, 'nextSibling', 1); - }, - - prev: function(node) { - return sibling(node, 'previousSibling', 1); - }, - - nextNodes: function(node) { - return sibling(node, 'nextSibling'); - }, - - prevNodes: function(node) { - return sibling(node, 'previousSibling'); - }, - - children: function(node) { - return sibling(node.firstChild, 'nextSibling', 1); - }, - - contents: function(node) { - return toArray((node.nodeName === "iframe" ? node.contentDocument || node.contentWindow.document : node).childNodes); - } - }, function(name, fn){ - DomQuery.fn[name] = function(selector) { - var self = this, result; - - if (self.length > 1) { - throw new Error("DomQuery only supports traverse functions on a single node."); - } - - if (self[0]) { - result = fn(self[0], selector); - } - - result = DomQuery(result); - - if (selector && name !== "parentsUntil") { - return result.filter(selector); - } - - return result; - }; - }); - - DomQuery.fn.filter = function(selector) { - return DomQuery.filter(selector); - }; - - DomQuery.fn.is = function(selector) { - return !!selector && this.filter(selector).length > 0; - }; - - DomQuery.fn.init.prototype = DomQuery.fn; - - return DomQuery; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/EventUtils.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/EventUtils.js deleted file mode 100755 index e3a21cdd88..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/EventUtils.js +++ /dev/null @@ -1,557 +0,0 @@ -/** - * EventUtils.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*jshint loopfunc:true*/ -/*eslint no-loop-func:0 */ - -define("tinymce/dom/EventUtils", [], function() { - "use strict"; - - var eventExpandoPrefix = "mce-data-"; - var mouseEventRe = /^(?:mouse|contextmenu)|click/; - var deprecated = {keyLocation: 1, layerX: 1, layerY: 1, returnValue: 1}; - - /** - * Binds a native event to a callback on the speified target. - */ - function addEvent(target, name, callback, capture) { - if (target.addEventListener) { - target.addEventListener(name, callback, capture || false); - } else if (target.attachEvent) { - target.attachEvent('on' + name, callback); - } - } - - /** - * Unbinds a native event callback on the specified target. - */ - function removeEvent(target, name, callback, capture) { - if (target.removeEventListener) { - target.removeEventListener(name, callback, capture || false); - } else if (target.detachEvent) { - target.detachEvent('on' + name, callback); - } - } - - /** - * Normalizes a native event object or just adds the event specific methods on a custom event. - */ - function fix(originalEvent, data) { - var name, event = data || {}, undef; - - // Dummy function that gets replaced on the delegation state functions - function returnFalse() { - return false; - } - - // Dummy function that gets replaced on the delegation state functions - function returnTrue() { - return true; - } - - // Copy all properties from the original event - for (name in originalEvent) { - // layerX/layerY is deprecated in Chrome and produces a warning - if (!deprecated[name]) { - event[name] = originalEvent[name]; - } - } - - // Normalize target IE uses srcElement - if (!event.target) { - event.target = event.srcElement || document; - } - - // Calculate pageX/Y if missing and clientX/Y available - if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undef && originalEvent.clientX !== undef) { - var eventDoc = event.target.ownerDocument || document; - var doc = eventDoc.documentElement; - var body = eventDoc.body; - - event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - - ( doc && doc.clientLeft || body && body.clientLeft || 0); - - event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0 ) - - ( doc && doc.clientTop || body && body.clientTop || 0); - } - - // Add preventDefault method - event.preventDefault = function() { - event.isDefaultPrevented = returnTrue; - - // Execute preventDefault on the original event object - if (originalEvent) { - if (originalEvent.preventDefault) { - originalEvent.preventDefault(); - } else { - originalEvent.returnValue = false; // IE - } - } - }; - - // Add stopPropagation - event.stopPropagation = function() { - event.isPropagationStopped = returnTrue; - - // Execute stopPropagation on the original event object - if (originalEvent) { - if (originalEvent.stopPropagation) { - originalEvent.stopPropagation(); - } else { - originalEvent.cancelBubble = true; // IE - } - } - }; - - // Add stopImmediatePropagation - event.stopImmediatePropagation = function() { - event.isImmediatePropagationStopped = returnTrue; - event.stopPropagation(); - }; - - // Add event delegation states - if (!event.isDefaultPrevented) { - event.isDefaultPrevented = returnFalse; - event.isPropagationStopped = returnFalse; - event.isImmediatePropagationStopped = returnFalse; - } - - return event; - } - - /** - * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized. - * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times. - */ - function bindOnReady(win, callback, eventUtils) { - var doc = win.document, event = {type: 'ready'}; - - if (eventUtils.domLoaded) { - callback(event); - return; - } - - // Gets called when the DOM is ready - function readyHandler() { - if (!eventUtils.domLoaded) { - eventUtils.domLoaded = true; - callback(event); - } - } - - function waitForDomLoaded() { - // Check complete or interactive state if there is a body - // element on some iframes IE 8 will produce a null body - if (doc.readyState === "complete" || (doc.readyState === "interactive" && doc.body)) { - removeEvent(doc, "readystatechange", waitForDomLoaded); - readyHandler(); - } - } - - function tryScroll() { - try { - // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author. - // http://javascript.nwbox.com/IEContentLoaded/ - doc.documentElement.doScroll("left"); - } catch (ex) { - setTimeout(tryScroll, 0); - return; - } - - readyHandler(); - } - - // Use W3C method - if (doc.addEventListener) { - if (doc.readyState === "complete") { - readyHandler(); - } else { - addEvent(win, 'DOMContentLoaded', readyHandler); - } - } else { - // Use IE method - addEvent(doc, "readystatechange", waitForDomLoaded); - - // Wait until we can scroll, when we can the DOM is initialized - if (doc.documentElement.doScroll && win.self === win.top) { - tryScroll(); - } - } - - // Fallback if any of the above methods should fail for some odd reason - addEvent(win, 'load', readyHandler); - } - - /** - * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers. - */ - function EventUtils() { - var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave; - - expando = eventExpandoPrefix + (+new Date()).toString(32); - hasMouseEnterLeave = "onmouseenter" in document.documentElement; - hasFocusIn = "onfocusin" in document.documentElement; - mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'}; - count = 1; - - // State if the DOMContentLoaded was executed or not - self.domLoaded = false; - self.events = events; - - /** - * Executes all event handler callbacks for a specific event. - * - * @private - * @param {Event} evt Event object. - * @param {String} id Expando id value to look for. - */ - function executeHandlers(evt, id) { - var callbackList, i, l, callback, container = events[id]; - - callbackList = container && container[evt.type]; - if (callbackList) { - for (i = 0, l = callbackList.length; i < l; i++) { - callback = callbackList[i]; - - // Check if callback exists might be removed if a unbind is called inside the callback - if (callback && callback.func.call(callback.scope, evt) === false) { - evt.preventDefault(); - } - - // Should we stop propagation to immediate listeners - if (evt.isImmediatePropagationStopped()) { - return; - } - } - } - } - - /** - * Binds a callback to an event on the specified target. - * - * @method bind - * @param {Object} target Target node/window or custom object. - * @param {String} names Name of the event to bind. - * @param {function} callback Callback function to execute when the event occurs. - * @param {Object} scope Scope to call the callback function on, defaults to target. - * @return {function} Callback function that got bound. - */ - self.bind = function(target, names, callback, scope) { - var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window; - - // Native event handler function patches the event and executes the callbacks for the expando - function defaultNativeHandler(evt) { - executeHandlers(fix(evt || win.event), id); - } - - // Don't bind to text nodes or comments - if (!target || target.nodeType === 3 || target.nodeType === 8) { - return; - } - - // Create or get events id for the target - if (!target[expando]) { - id = count++; - target[expando] = id; - events[id] = {}; - } else { - id = target[expando]; - } - - // Setup the specified scope or use the target as a default - scope = scope || target; - - // Split names and bind each event, enables you to bind multiple events with one call - names = names.split(' '); - i = names.length; - while (i--) { - name = names[i]; - nativeHandler = defaultNativeHandler; - fakeName = capture = false; - - // Use ready instead of DOMContentLoaded - if (name === "DOMContentLoaded") { - name = "ready"; - } - - // DOM is already ready - if (self.domLoaded && name === "ready" && target.readyState == 'complete') { - callback.call(scope, fix({type: name})); - continue; - } - - // Handle mouseenter/mouseleaver - if (!hasMouseEnterLeave) { - fakeName = mouseEnterLeave[name]; - - if (fakeName) { - nativeHandler = function(evt) { - var current, related; - - current = evt.currentTarget; - related = evt.relatedTarget; - - // Check if related is inside the current target if it's not then the event should - // be ignored since it's a mouseover/mouseout inside the element - if (related && current.contains) { - // Use contains for performance - related = current.contains(related); - } else { - while (related && related !== current) { - related = related.parentNode; - } - } - - // Fire fake event - if (!related) { - evt = fix(evt || win.event); - evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter'; - evt.target = current; - executeHandlers(evt, id); - } - }; - } - } - - // Fake bubbeling of focusin/focusout - if (!hasFocusIn && (name === "focusin" || name === "focusout")) { - capture = true; - fakeName = name === "focusin" ? "focus" : "blur"; - nativeHandler = function(evt) { - evt = fix(evt || win.event); - evt.type = evt.type === 'focus' ? 'focusin' : 'focusout'; - executeHandlers(evt, id); - }; - } - - // Setup callback list and bind native event - callbackList = events[id][name]; - if (!callbackList) { - events[id][name] = callbackList = [{func: callback, scope: scope}]; - callbackList.fakeName = fakeName; - callbackList.capture = capture; - - // Add the nativeHandler to the callback list so that we can later unbind it - callbackList.nativeHandler = nativeHandler; - - // Check if the target has native events support - - if (name === "ready") { - bindOnReady(target, nativeHandler, self); - } else { - addEvent(target, fakeName || name, nativeHandler, capture); - } - } else { - if (name === "ready" && self.domLoaded) { - callback({type: name}); - } else { - // If it already has an native handler then just push the callback - callbackList.push({func: callback, scope: scope}); - } - } - } - - target = callbackList = 0; // Clean memory for IE - - return callback; - }; - - /** - * Unbinds the specified event by name, name and callback or all events on the target. - * - * @method unbind - * @param {Object} target Target node/window or custom object. - * @param {String} names Optional event name to unbind. - * @param {function} callback Optional callback function to unbind. - * @return {EventUtils} Event utils instance. - */ - self.unbind = function(target, names, callback) { - var id, callbackList, i, ci, name, eventMap; - - // Don't bind to text nodes or comments - if (!target || target.nodeType === 3 || target.nodeType === 8) { - return self; - } - - // Unbind event or events if the target has the expando - id = target[expando]; - if (id) { - eventMap = events[id]; - - // Specific callback - if (names) { - names = names.split(' '); - i = names.length; - while (i--) { - name = names[i]; - callbackList = eventMap[name]; - - // Unbind the event if it exists in the map - if (callbackList) { - // Remove specified callback - if (callback) { - ci = callbackList.length; - while (ci--) { - if (callbackList[ci].func === callback) { - var nativeHandler = callbackList.nativeHandler; - var fakeName = callbackList.fakeName, capture = callbackList.capture; - - // Clone callbackList since unbind inside a callback would otherwise break the handlers loop - callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1)); - callbackList.nativeHandler = nativeHandler; - callbackList.fakeName = fakeName; - callbackList.capture = capture; - - eventMap[name] = callbackList; - } - } - } - - // Remove all callbacks if there isn't a specified callback or there is no callbacks left - if (!callback || callbackList.length === 0) { - delete eventMap[name]; - removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture); - } - } - } - } else { - // All events for a specific element - for (name in eventMap) { - callbackList = eventMap[name]; - removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture); - } - - eventMap = {}; - } - - // Check if object is empty, if it isn't then we won't remove the expando map - for (name in eventMap) { - return self; - } - - // Delete event object - delete events[id]; - - // Remove expando from target - try { - // IE will fail here since it can't delete properties from window - delete target[expando]; - } catch (ex) { - // IE will set it to null - target[expando] = null; - } - } - - return self; - }; - - /** - * Fires the specified event on the specified target. - * - * @method fire - * @param {Object} target Target node/window or custom object. - * @param {String} name Event name to fire. - * @param {Object} args Optional arguments to send to the observers. - * @return {EventUtils} Event utils instance. - */ - self.fire = function(target, name, args) { - var id; - - // Don't bind to text nodes or comments - if (!target || target.nodeType === 3 || target.nodeType === 8) { - return self; - } - - // Build event object by patching the args - args = fix(null, args); - args.type = name; - args.target = target; - - do { - // Found an expando that means there is listeners to execute - id = target[expando]; - if (id) { - executeHandlers(args, id); - } - - // Walk up the DOM - target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow; - } while (target && !args.isPropagationStopped()); - - return self; - }; - - /** - * Removes all bound event listeners for the specified target. This will also remove any bound - * listeners to child nodes within that target. - * - * @method clean - * @param {Object} target Target node/window object. - * @return {EventUtils} Event utils instance. - */ - self.clean = function(target) { - var i, children, unbind = self.unbind; - - // Don't bind to text nodes or comments - if (!target || target.nodeType === 3 || target.nodeType === 8) { - return self; - } - - // Unbind any element on the specificed target - if (target[expando]) { - unbind(target); - } - - // Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children - if (!target.getElementsByTagName) { - target = target.document; - } - - // Remove events from each child element - if (target && target.getElementsByTagName) { - unbind(target); - - children = target.getElementsByTagName('*'); - i = children.length; - while (i--) { - target = children[i]; - - if (target[expando]) { - unbind(target); - } - } - } - - return self; - }; - - /** - * Destroys the event object. Call this on IE to remove memory leaks. - */ - self.destroy = function() { - events = {}; - }; - - // Legacy function for canceling events - self.cancel = function(e) { - if (e) { - e.preventDefault(); - e.stopImmediatePropagation(); - } - - return false; - }; - } - - EventUtils.Event = new EventUtils(); - EventUtils.Event.bind(window, 'ready', function() {}); - - return EventUtils; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Range.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Range.js deleted file mode 100755 index d9aab1674f..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/Range.js +++ /dev/null @@ -1,777 +0,0 @@ -/** - * Range.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -define("tinymce/dom/Range", [ - "tinymce/util/Tools" -], function(Tools) { - // Range constructor - function Range(dom) { - var self = this, - doc = dom.doc, - EXTRACT = 0, - CLONE = 1, - DELETE = 2, - TRUE = true, - FALSE = false, - START_OFFSET = 'startOffset', - START_CONTAINER = 'startContainer', - END_CONTAINER = 'endContainer', - END_OFFSET = 'endOffset', - extend = Tools.extend, - nodeIndex = dom.nodeIndex; - - function createDocumentFragment() { - return doc.createDocumentFragment(); - } - - function setStart(n, o) { - _setEndPoint(TRUE, n, o); - } - - function setEnd(n, o) { - _setEndPoint(FALSE, n, o); - } - - function setStartBefore(n) { - setStart(n.parentNode, nodeIndex(n)); - } - - function setStartAfter(n) { - setStart(n.parentNode, nodeIndex(n) + 1); - } - - function setEndBefore(n) { - setEnd(n.parentNode, nodeIndex(n)); - } - - function setEndAfter(n) { - setEnd(n.parentNode, nodeIndex(n) + 1); - } - - function collapse(ts) { - if (ts) { - self[END_CONTAINER] = self[START_CONTAINER]; - self[END_OFFSET] = self[START_OFFSET]; - } else { - self[START_CONTAINER] = self[END_CONTAINER]; - self[START_OFFSET] = self[END_OFFSET]; - } - - self.collapsed = TRUE; - } - - function selectNode(n) { - setStartBefore(n); - setEndAfter(n); - } - - function selectNodeContents(n) { - setStart(n, 0); - setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length); - } - - function compareBoundaryPoints(h, r) { - var sc = self[START_CONTAINER], so = self[START_OFFSET], ec = self[END_CONTAINER], eo = self[END_OFFSET], - rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset; - - // Check START_TO_START - if (h === 0) { - return _compareBoundaryPoints(sc, so, rsc, rso); - } - - // Check START_TO_END - if (h === 1) { - return _compareBoundaryPoints(ec, eo, rsc, rso); - } - - // Check END_TO_END - if (h === 2) { - return _compareBoundaryPoints(ec, eo, rec, reo); - } - - // Check END_TO_START - if (h === 3) { - return _compareBoundaryPoints(sc, so, rec, reo); - } - } - - function deleteContents() { - _traverse(DELETE); - } - - function extractContents() { - return _traverse(EXTRACT); - } - - function cloneContents() { - return _traverse(CLONE); - } - - function insertNode(n) { - var startContainer = this[START_CONTAINER], - startOffset = this[START_OFFSET], nn, o; - - // Node is TEXT_NODE or CDATA - if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) { - if (!startOffset) { - // At the start of text - startContainer.parentNode.insertBefore(n, startContainer); - } else if (startOffset >= startContainer.nodeValue.length) { - // At the end of text - dom.insertAfter(n, startContainer); - } else { - // Middle, need to split - nn = startContainer.splitText(startOffset); - startContainer.parentNode.insertBefore(n, nn); - } - } else { - // Insert element node - if (startContainer.childNodes.length > 0) { - o = startContainer.childNodes[startOffset]; - } - - if (o) { - startContainer.insertBefore(n, o); - } else { - if (startContainer.nodeType == 3) { - dom.insertAfter(n, startContainer); - } else { - startContainer.appendChild(n); - } - } - } - } - - function surroundContents(n) { - var f = self.extractContents(); - - self.insertNode(n); - n.appendChild(f); - self.selectNode(n); - } - - function cloneRange() { - return extend(new Range(dom), { - startContainer: self[START_CONTAINER], - startOffset: self[START_OFFSET], - endContainer: self[END_CONTAINER], - endOffset: self[END_OFFSET], - collapsed: self.collapsed, - commonAncestorContainer: self.commonAncestorContainer - }); - } - - // Private methods - - function _getSelectedNode(container, offset) { - var child; - - if (container.nodeType == 3 /* TEXT_NODE */) { - return container; - } - - if (offset < 0) { - return container; - } - - child = container.firstChild; - while (child && offset > 0) { - --offset; - child = child.nextSibling; - } - - if (child) { - return child; - } - - return container; - } - - function _isCollapsed() { - return (self[START_CONTAINER] == self[END_CONTAINER] && self[START_OFFSET] == self[END_OFFSET]); - } - - function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) { - var c, offsetC, n, cmnRoot, childA, childB; - - // In the first case the boundary-points have the same container. A is before B - // if its offset is less than the offset of B, A is equal to B if its offset is - // equal to the offset of B, and A is after B if its offset is greater than the - // offset of B. - if (containerA == containerB) { - if (offsetA == offsetB) { - return 0; // equal - } - - if (offsetA < offsetB) { - return -1; // before - } - - return 1; // after - } - - // In the second case a child node C of the container of A is an ancestor - // container of B. In this case, A is before B if the offset of A is less than or - // equal to the index of the child node C and A is after B otherwise. - c = containerB; - while (c && c.parentNode != containerA) { - c = c.parentNode; - } - - if (c) { - offsetC = 0; - n = containerA.firstChild; - - while (n != c && offsetC < offsetA) { - offsetC++; - n = n.nextSibling; - } - - if (offsetA <= offsetC) { - return -1; // before - } - - return 1; // after - } - - // In the third case a child node C of the container of B is an ancestor container - // of A. In this case, A is before B if the index of the child node C is less than - // the offset of B and A is after B otherwise. - c = containerA; - while (c && c.parentNode != containerB) { - c = c.parentNode; - } - - if (c) { - offsetC = 0; - n = containerB.firstChild; - - while (n != c && offsetC < offsetB) { - offsetC++; - n = n.nextSibling; - } - - if (offsetC < offsetB) { - return -1; // before - } - - return 1; // after - } - - // In the fourth case, none of three other cases hold: the containers of A and B - // are siblings or descendants of sibling nodes. In this case, A is before B if - // the container of A is before the container of B in a pre-order traversal of the - // Ranges' context tree and A is after B otherwise. - cmnRoot = dom.findCommonAncestor(containerA, containerB); - childA = containerA; - - while (childA && childA.parentNode != cmnRoot) { - childA = childA.parentNode; - } - - if (!childA) { - childA = cmnRoot; - } - - childB = containerB; - while (childB && childB.parentNode != cmnRoot) { - childB = childB.parentNode; - } - - if (!childB) { - childB = cmnRoot; - } - - if (childA == childB) { - return 0; // equal - } - - n = cmnRoot.firstChild; - while (n) { - if (n == childA) { - return -1; // before - } - - if (n == childB) { - return 1; // after - } - - n = n.nextSibling; - } - } - - function _setEndPoint(st, n, o) { - var ec, sc; - - if (st) { - self[START_CONTAINER] = n; - self[START_OFFSET] = o; - } else { - self[END_CONTAINER] = n; - self[END_OFFSET] = o; - } - - // If one boundary-point of a Range is set to have a root container - // other than the current one for the Range, the Range is collapsed to - // the new position. This enforces the restriction that both boundary- - // points of a Range must have the same root container. - ec = self[END_CONTAINER]; - while (ec.parentNode) { - ec = ec.parentNode; - } - - sc = self[START_CONTAINER]; - while (sc.parentNode) { - sc = sc.parentNode; - } - - if (sc == ec) { - // The start position of a Range is guaranteed to never be after the - // end position. To enforce this restriction, if the start is set to - // be at a position after the end, the Range is collapsed to that - // position. - if (_compareBoundaryPoints(self[START_CONTAINER], self[START_OFFSET], self[END_CONTAINER], self[END_OFFSET]) > 0) { - self.collapse(st); - } - } else { - self.collapse(st); - } - - self.collapsed = _isCollapsed(); - self.commonAncestorContainer = dom.findCommonAncestor(self[START_CONTAINER], self[END_CONTAINER]); - } - - function _traverse(how) { - var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep; - - if (self[START_CONTAINER] == self[END_CONTAINER]) { - return _traverseSameContainer(how); - } - - for (c = self[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) { - if (p == self[START_CONTAINER]) { - return _traverseCommonStartContainer(c, how); - } - - ++endContainerDepth; - } - - for (c = self[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) { - if (p == self[END_CONTAINER]) { - return _traverseCommonEndContainer(c, how); - } - - ++startContainerDepth; - } - - depthDiff = startContainerDepth - endContainerDepth; - - startNode = self[START_CONTAINER]; - while (depthDiff > 0) { - startNode = startNode.parentNode; - depthDiff--; - } - - endNode = self[END_CONTAINER]; - while (depthDiff < 0) { - endNode = endNode.parentNode; - depthDiff++; - } - - // ascend the ancestor hierarchy until we have a common parent. - for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) { - startNode = sp; - endNode = ep; - } - - return _traverseCommonAncestors(startNode, endNode, how); - } - - function _traverseSameContainer(how) { - var frag, s, sub, n, cnt, sibling, xferNode, start, len; - - if (how != DELETE) { - frag = createDocumentFragment(); - } - - // If selection is empty, just return the fragment - if (self[START_OFFSET] == self[END_OFFSET]) { - return frag; - } - - // Text node needs special case handling - if (self[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) { - // get the substring - s = self[START_CONTAINER].nodeValue; - sub = s.substring(self[START_OFFSET], self[END_OFFSET]); - - // set the original text node to its new value - if (how != CLONE) { - n = self[START_CONTAINER]; - start = self[START_OFFSET]; - len = self[END_OFFSET] - self[START_OFFSET]; - - if (start === 0 && len >= n.nodeValue.length - 1) { - n.parentNode.removeChild(n); - } else { - n.deleteData(start, len); - } - - // Nothing is partially selected, so collapse to start point - self.collapse(TRUE); - } - - if (how == DELETE) { - return; - } - - if (sub.length > 0) { - frag.appendChild(doc.createTextNode(sub)); - } - - return frag; - } - - // Copy nodes between the start/end offsets. - n = _getSelectedNode(self[START_CONTAINER], self[START_OFFSET]); - cnt = self[END_OFFSET] - self[START_OFFSET]; - - while (n && cnt > 0) { - sibling = n.nextSibling; - xferNode = _traverseFullySelected(n, how); - - if (frag) { - frag.appendChild(xferNode); - } - - --cnt; - n = sibling; - } - - // Nothing is partially selected, so collapse to start point - if (how != CLONE) { - self.collapse(TRUE); - } - - return frag; - } - - function _traverseCommonStartContainer(endAncestor, how) { - var frag, n, endIdx, cnt, sibling, xferNode; - - if (how != DELETE) { - frag = createDocumentFragment(); - } - - n = _traverseRightBoundary(endAncestor, how); - - if (frag) { - frag.appendChild(n); - } - - endIdx = nodeIndex(endAncestor); - cnt = endIdx - self[START_OFFSET]; - - if (cnt <= 0) { - // Collapse to just before the endAncestor, which - // is partially selected. - if (how != CLONE) { - self.setEndBefore(endAncestor); - self.collapse(FALSE); - } - - return frag; - } - - n = endAncestor.previousSibling; - while (cnt > 0) { - sibling = n.previousSibling; - xferNode = _traverseFullySelected(n, how); - - if (frag) { - frag.insertBefore(xferNode, frag.firstChild); - } - - --cnt; - n = sibling; - } - - // Collapse to just before the endAncestor, which - // is partially selected. - if (how != CLONE) { - self.setEndBefore(endAncestor); - self.collapse(FALSE); - } - - return frag; - } - - function _traverseCommonEndContainer(startAncestor, how) { - var frag, startIdx, n, cnt, sibling, xferNode; - - if (how != DELETE) { - frag = createDocumentFragment(); - } - - n = _traverseLeftBoundary(startAncestor, how); - if (frag) { - frag.appendChild(n); - } - - startIdx = nodeIndex(startAncestor); - ++startIdx; // Because we already traversed it - - cnt = self[END_OFFSET] - startIdx; - n = startAncestor.nextSibling; - while (n && cnt > 0) { - sibling = n.nextSibling; - xferNode = _traverseFullySelected(n, how); - - if (frag) { - frag.appendChild(xferNode); - } - - --cnt; - n = sibling; - } - - if (how != CLONE) { - self.setStartAfter(startAncestor); - self.collapse(TRUE); - } - - return frag; - } - - function _traverseCommonAncestors(startAncestor, endAncestor, how) { - var n, frag, startOffset, endOffset, cnt, sibling, nextSibling; - - if (how != DELETE) { - frag = createDocumentFragment(); - } - - n = _traverseLeftBoundary(startAncestor, how); - if (frag) { - frag.appendChild(n); - } - - startOffset = nodeIndex(startAncestor); - endOffset = nodeIndex(endAncestor); - ++startOffset; - - cnt = endOffset - startOffset; - sibling = startAncestor.nextSibling; - - while (cnt > 0) { - nextSibling = sibling.nextSibling; - n = _traverseFullySelected(sibling, how); - - if (frag) { - frag.appendChild(n); - } - - sibling = nextSibling; - --cnt; - } - - n = _traverseRightBoundary(endAncestor, how); - - if (frag) { - frag.appendChild(n); - } - - if (how != CLONE) { - self.setStartAfter(startAncestor); - self.collapse(TRUE); - } - - return frag; - } - - function _traverseRightBoundary(root, how) { - var next = _getSelectedNode(self[END_CONTAINER], self[END_OFFSET] - 1), parent, clonedParent; - var prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != self[END_CONTAINER]; - - if (next == root) { - return _traverseNode(next, isFullySelected, FALSE, how); - } - - parent = next.parentNode; - clonedParent = _traverseNode(parent, FALSE, FALSE, how); - - while (parent) { - while (next) { - prevSibling = next.previousSibling; - clonedChild = _traverseNode(next, isFullySelected, FALSE, how); - - if (how != DELETE) { - clonedParent.insertBefore(clonedChild, clonedParent.firstChild); - } - - isFullySelected = TRUE; - next = prevSibling; - } - - if (parent == root) { - return clonedParent; - } - - next = parent.previousSibling; - parent = parent.parentNode; - - clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how); - - if (how != DELETE) { - clonedGrandParent.appendChild(clonedParent); - } - - clonedParent = clonedGrandParent; - } - } - - function _traverseLeftBoundary(root, how) { - var next = _getSelectedNode(self[START_CONTAINER], self[START_OFFSET]), isFullySelected = next != self[START_CONTAINER]; - var parent, clonedParent, nextSibling, clonedChild, clonedGrandParent; - - if (next == root) { - return _traverseNode(next, isFullySelected, TRUE, how); - } - - parent = next.parentNode; - clonedParent = _traverseNode(parent, FALSE, TRUE, how); - - while (parent) { - while (next) { - nextSibling = next.nextSibling; - clonedChild = _traverseNode(next, isFullySelected, TRUE, how); - - if (how != DELETE) { - clonedParent.appendChild(clonedChild); - } - - isFullySelected = TRUE; - next = nextSibling; - } - - if (parent == root) { - return clonedParent; - } - - next = parent.nextSibling; - parent = parent.parentNode; - - clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how); - - if (how != DELETE) { - clonedGrandParent.appendChild(clonedParent); - } - - clonedParent = clonedGrandParent; - } - } - - function _traverseNode(n, isFullySelected, isLeft, how) { - var txtValue, newNodeValue, oldNodeValue, offset, newNode; - - if (isFullySelected) { - return _traverseFullySelected(n, how); - } - - if (n.nodeType == 3 /* TEXT_NODE */) { - txtValue = n.nodeValue; - - if (isLeft) { - offset = self[START_OFFSET]; - newNodeValue = txtValue.substring(offset); - oldNodeValue = txtValue.substring(0, offset); - } else { - offset = self[END_OFFSET]; - newNodeValue = txtValue.substring(0, offset); - oldNodeValue = txtValue.substring(offset); - } - - if (how != CLONE) { - n.nodeValue = oldNodeValue; - } - - if (how == DELETE) { - return; - } - - newNode = dom.clone(n, FALSE); - newNode.nodeValue = newNodeValue; - - return newNode; - } - - if (how == DELETE) { - return; - } - - return dom.clone(n, FALSE); - } - - function _traverseFullySelected(n, how) { - if (how != DELETE) { - return how == CLONE ? dom.clone(n, TRUE) : n; - } - - n.parentNode.removeChild(n); - } - - function toStringIE() { - return dom.create('body', null, cloneContents()).outerText; - } - - extend(self, { - // Inital states - startContainer: doc, - startOffset: 0, - endContainer: doc, - endOffset: 0, - collapsed: TRUE, - commonAncestorContainer: doc, - - // Range constants - START_TO_START: 0, - START_TO_END: 1, - END_TO_END: 2, - END_TO_START: 3, - - // Public methods - setStart: setStart, - setEnd: setEnd, - setStartBefore: setStartBefore, - setStartAfter: setStartAfter, - setEndBefore: setEndBefore, - setEndAfter: setEndAfter, - collapse: collapse, - selectNode: selectNode, - selectNodeContents: selectNodeContents, - compareBoundaryPoints: compareBoundaryPoints, - deleteContents: deleteContents, - extractContents: extractContents, - cloneContents: cloneContents, - insertNode: insertNode, - surroundContents: surroundContents, - cloneRange: cloneRange, - toStringIE: toStringIE - }); - - return self; - } - - // Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype - Range.prototype.toString = function() { - return this.toStringIE(); - }; - - return Range; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/RangeUtils.js b/common/static/js/vendor/tinymce/js/tinymce/classes/dom/RangeUtils.js deleted file mode 100755 index 42d39f91f8..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/dom/RangeUtils.js +++ /dev/null @@ -1,476 +0,0 @@ -/** - * Range.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * RangeUtils - * - * @class tinymce.dom.RangeUtils - * @private - */ -define("tinymce/dom/RangeUtils", [ - "tinymce/util/Tools", - "tinymce/dom/TreeWalker" -], function(Tools, TreeWalker) { - var each = Tools.each; - - function RangeUtils(dom) { - /** - * Walks the specified range like object and executes the callback for each sibling collection it finds. - * - * @method walk - * @param {Object} rng Range like object. - * @param {function} callback Callback function to execute for each sibling collection. - */ - this.walk = function(rng, callback) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset, - ancestor, startPoint, - endPoint, node, parent, siblings, nodes; - - // Handle table cell selection the table plugin enables - // you to fake select table cells and perform formatting actions on them - nodes = dom.select('td.mce-item-selected,th.mce-item-selected'); - if (nodes.length > 0) { - each(nodes, function(node) { - callback([node]); - }); - - return; - } - - /** - * Excludes start/end text node if they are out side the range - * - * @private - * @param {Array} nodes Nodes to exclude items from. - * @return {Array} Array with nodes excluding the start/end container if needed. - */ - function exclude(nodes) { - var node; - - // First node is excluded - node = nodes[0]; - if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { - nodes.splice(0, 1); - } - - // Last node is excluded - node = nodes[nodes.length - 1]; - if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { - nodes.splice(nodes.length - 1, 1); - } - - return nodes; - } - - /** - * Collects siblings - * - * @private - * @param {Node} node Node to collect siblings from. - * @param {String} name Name of the sibling to check for. - * @return {Array} Array of collected siblings. - */ - function collectSiblings(node, name, end_node) { - var siblings = []; - - for (; node && node != end_node; node = node[name]) { - siblings.push(node); - } - - return siblings; - } - - /** - * Find an end point this is the node just before the common ancestor root. - * - * @private - * @param {Node} node Node to start at. - * @param {Node} root Root/ancestor element to stop just before. - * @return {Node} Node just before the root element. - */ - function findEndPoint(node, root) { - do { - if (node.parentNode == root) { - return node; - } - - node = node.parentNode; - } while(node); - } - - function walkBoundary(start_node, end_node, next) { - var siblingName = next ? 'nextSibling' : 'previousSibling'; - - for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { - parent = node.parentNode; - siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); - - if (siblings.length) { - if (!next) { - siblings.reverse(); - } - - callback(exclude(siblings)); - } - } - } - - // If index based start position then resolve it - if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { - startContainer = startContainer.childNodes[startOffset]; - } - - // If index based end position then resolve it - if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { - endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; - } - - // Same container - if (startContainer == endContainer) { - return callback(exclude([startContainer])); - } - - // Find common ancestor and end points - ancestor = dom.findCommonAncestor(startContainer, endContainer); - - // Process left side - for (node = startContainer; node; node = node.parentNode) { - if (node === endContainer) { - return walkBoundary(startContainer, ancestor, true); - } - - if (node === ancestor) { - break; - } - } - - // Process right side - for (node = endContainer; node; node = node.parentNode) { - if (node === startContainer) { - return walkBoundary(endContainer, ancestor); - } - - if (node === ancestor) { - break; - } - } - - // Find start/end point - startPoint = findEndPoint(startContainer, ancestor) || startContainer; - endPoint = findEndPoint(endContainer, ancestor) || endContainer; - - // Walk left leaf - walkBoundary(startContainer, startPoint, true); - - // Walk the middle from start to end point - siblings = collectSiblings( - startPoint == startContainer ? startPoint : startPoint.nextSibling, - 'nextSibling', - endPoint == endContainer ? endPoint.nextSibling : endPoint - ); - - if (siblings.length) { - callback(exclude(siblings)); - } - - // Walk right leaf - walkBoundary(endContainer, endPoint); - }; - - /** - * Splits the specified range at it's start/end points. - * - * @private - * @param {Range/RangeObject} rng Range to split. - * @return {Object} Range position object. - */ - this.split = function(rng) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset; - - function splitText(node, offset) { - return node.splitText(offset); - } - - // Handle single text node - if (startContainer == endContainer && startContainer.nodeType == 3) { - if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { - endContainer = splitText(startContainer, startOffset); - startContainer = endContainer.previousSibling; - - if (endOffset > startOffset) { - endOffset = endOffset - startOffset; - startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - startOffset = 0; - } else { - endOffset = 0; - } - } - } else { - // Split startContainer text node if needed - if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { - startContainer = splitText(startContainer, startOffset); - startOffset = 0; - } - - // Split endContainer text node if needed - if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { - endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - } - } - - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - }; - - /** - * Normalizes the specified range by finding the closest best suitable caret location. - * - * @private - * @param {Range} rng Range to normalize. - * @return {Boolean} True/false if the specified range was normalized or not. - */ - this.normalize = function(rng) { - var normalized, collapsed; - - function normalizeEndPoint(start) { - var container, offset, walker, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; - var directionLeft, isAfterNode; - - function hasBrBeforeAfter(node, left) { - var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); - - while ((node = walker[left ? 'prev' : 'next']())) { - if (node.nodeName === "BR") { - return true; - } - } - } - - function isPrevNode(node, name) { - return node.previousSibling && node.previousSibling.nodeName == name; - } - - // Walks the dom left/right to find a suitable text node to move the endpoint into - // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG - function findTextNodeRelative(left, startNode) { - var walker, lastInlineElement, parentBlockContainer; - - startNode = startNode || container; - parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body; - - // Lean left before the BR element if it's the only BR within a block element. Gecko bug: #6680 - // This:
|
|
x|
]
- rng.moveToElementText(rng2.parentElement()); - if (rng.compareEndPoints('StartToEnd', rng2) === 0) { - rng2.move('character', -1); - } - - rng2.pasteHTML('' + chr + ''); - } - } catch (ex) { - // IE might throw unspecified error so lets ignore it - return null; - } - } else { - // Control selection - element = rng.item(0); - name = element.nodeName; - - return {name: name, index: findIndex(name, element)}; - } - } else { - element = self.getNode(); - name = element.nodeName; - if (name == 'IMG') { - return {name: name, index: findIndex(name, element)}; - } - - // W3C method - rng2 = normalizeTableCellSelection(rng.cloneRange()); - - // Insert end marker - if (!collapsed) { - rng2.collapse(false); - rng2.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_end', style: styles}, chr)); - } - - rng = normalizeTableCellSelection(rng); - rng.collapse(true); - rng.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_start', style: styles}, chr)); - } - - self.moveToBookmark({id: id, keep: 1}); - - return {id: id}; - }, - - /** - * Restores the selection to the specified bookmark. - * - * @method moveToBookmark - * @param {Object} bookmark Bookmark to restore selection from. - * @return {Boolean} true/false if it was successful or not. - * @example - * // Stores a bookmark of the current selection - * var bm = tinymce.activeEditor.selection.getBookmark(); - * - * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); - * - * // Restore the selection bookmark - * tinymce.activeEditor.selection.moveToBookmark(bm); - */ - moveToBookmark: function(bookmark) { - var self = this, dom = self.dom, rng, root, startContainer, endContainer, startOffset, endOffset; - - function setEndPoint(start) { - var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; - - if (point) { - offset = point[0]; - - // Find container node - for (node = root, i = point.length - 1; i >= 1; i--) { - children = node.childNodes; - - if (point[i] > children.length - 1) { - return; - } - - node = children[point[i]]; - } - - // Move text offset to best suitable location - if (node.nodeType === 3) { - offset = Math.min(point[0], node.nodeValue.length); - } - - // Move element offset to best suitable location - if (node.nodeType === 1) { - offset = Math.min(point[0], node.childNodes.length); - } - - // Set offset within container node - if (start) { - rng.setStart(node, offset); - } else { - rng.setEnd(node, offset); - } - } - - return true; - } - - function restoreEndPoint(suffix) { - var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; - - if (marker) { - node = marker.parentNode; - - if (suffix == 'start') { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - startContainer = endContainer = node; - startOffset = endOffset = idx; - } else { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - endContainer = node; - endOffset = idx; - } - - if (!keep) { - prev = marker.previousSibling; - next = marker.nextSibling; - - // Remove all marker text nodes - each(grep(marker.childNodes), function(node) { - if (node.nodeType == 3) { - node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); - } - }); - - // Remove marker but keep children if for example contents where inserted into the marker - // Also remove duplicated instances of the marker for example by a - // split operation or by WebKit auto split on paste feature - while ((marker = dom.get(bookmark.id + '_' + suffix))) { - dom.remove(marker, 1); - } - - // If siblings are text nodes then merge them unless it's Opera since it some how removes the node - // and we are sniffing since adding a lot of detection code for a browser with 3% of the market - // isn't worth the effort. Sorry, Opera but it's just a fact - if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !isOpera) { - idx = prev.nodeValue.length; - prev.appendData(next.nodeValue); - dom.remove(next); - - if (suffix == 'start') { - startContainer = endContainer = prev; - startOffset = endOffset = idx; - } else { - endContainer = prev; - endOffset = idx; - } - } - } - } - } - - function addBogus(node) { - // Adds a bogus BR element for empty block elements - if (dom.isBlock(node) && !node.innerHTML && !isIE) { - node.innerHTML = '|
would become this:|
- sibling = startContainer.previousSibling; - if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { - sibling.innerHTML = ''; - } else { - sibling = null; - } - - startContainer.innerHTML = ''; - ieRng.moveToElementText(startContainer.lastChild); - ieRng.select(); - dom.doc.selection.clear(); - startContainer.innerHTML = ''; - - if (sibling) { - sibling.innerHTML = ''; - } - return; - } else { - startOffset = dom.nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - } - - if (startOffset == endOffset - 1) { - try { - ctrlElm = startContainer.childNodes[startOffset]; - ctrlRng = body.createControlRange(); - ctrlRng.addElement(ctrlElm); - ctrlRng.select(); - - // Check if the range produced is on the correct element and is a control range - // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 - nativeRng = selection.getRng(); - if (nativeRng.item && ctrlElm === nativeRng.item(0)) { - return; - } - } catch (ex) { - // Ignore - } - } - } - - // Set start/end point of selection - setEndPoint(true); - setEndPoint(); - - // Select the new range and scroll it into view - ieRng.select(); - }; - - // Expose range method - this.getRangeAt = getRange; - } - - return Selection; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/html/DomParser.js b/common/static/js/vendor/tinymce/js/tinymce/classes/html/DomParser.js deleted file mode 100755 index bc494adde3..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/html/DomParser.js +++ /dev/null @@ -1,756 +0,0 @@ -/** - * DomParser.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class parses HTML code into a DOM like structure of nodes it will remove redundant whitespace and make - * sure that the node tree is valid according to the specified schema. - * So for example:a
b
c will becomea
b
c
- * - * @example - * var parser = new tinymce.html.DomParser({validate: true}, schema); - * var rootNode = parser.parse('x
->x
- function trim(rootBlockNode) { - if (rootBlockNode) { - node = rootBlockNode.firstChild; - if (node && node.type == 3) { - node.value = node.value.replace(startWhiteSpaceRegExp, ''); - } - - node = rootBlockNode.lastChild; - if (node && node.type == 3) { - node.value = node.value.replace(endWhiteSpaceRegExp, ''); - } - } - } - - // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root - if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { - return; - } - - while (node) { - next = node.next; - - if (node.type == 3 || (node.type == 1 && node.name !== 'p' && - !blockElements[node.name] && !node.attr('data-mce-type'))) { - if (!rootBlockNode) { - // Create a new root block element - rootBlockNode = createNode(rootBlockName, 1); - rootBlockNode.attr(settings.forced_root_block_attrs); - rootNode.insert(rootBlockNode, node); - rootBlockNode.append(node); - } else { - rootBlockNode.append(node); - } - } else { - trim(rootBlockNode); - rootBlockNode = null; - } - - node = next; - } - - trim(rootBlockNode); - } - - function createNode(name, type) { - var node = new Node(name, type), list; - - if (name in nodeFilters) { - list = matchedNodes[name]; - - if (list) { - list.push(node); - } else { - matchedNodes[name] = [node]; - } - } - - return node; - } - - function removeWhitespaceBefore(node) { - var textNode, textVal, sibling; - - for (textNode = node.prev; textNode && textNode.type === 3; ) { - textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); - - if (textVal.length > 0) { - textNode.value = textVal; - textNode = textNode.prev; - } else { - sibling = textNode.prev; - textNode.remove(); - textNode = sibling; - } - } - } - - function cloneAndExcludeBlocks(input) { - var name, output = {}; - - for (name in input) { - if (name !== 'li' && name != 'p') { - output[name] = input[name]; - } - } - - return output; - } - - parser = new SaxParser({ - validate: validate, - allow_script_urls: settings.allow_script_urls, - allow_conditional_comments: settings.allow_conditional_comments, - - // Exclude P and LI from DOM parsing since it's treated better by the DOM parser - self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), - - cdata: function(text) { - node.append(createNode('#cdata', 4)).value = text; - }, - - text: function(text, raw) { - var textNode; - - // Trim all redundant whitespace on non white space elements - if (!isInWhiteSpacePreservedElement) { - text = text.replace(allWhiteSpaceRegExp, ' '); - - if (node.lastChild && blockElements[node.lastChild.name]) { - text = text.replace(startWhiteSpaceRegExp, ''); - } - } - - // Do we need to create the node - if (text.length !== 0) { - textNode = createNode('#text', 3); - textNode.raw = !!raw; - node.append(textNode).value = text; - } - }, - - comment: function(text) { - node.append(createNode('#comment', 8)).value = text; - }, - - pi: function(name, text) { - node.append(createNode(name, 7)).value = text; - removeWhitespaceBefore(node); - }, - - doctype: function(text) { - var newNode; - - newNode = node.append(createNode('#doctype', 10)); - newNode.value = text; - removeWhitespaceBefore(node); - }, - - start: function(name, attrs, empty) { - var newNode, attrFiltersLen, elementRule, attrName, parent; - - elementRule = validate ? schema.getElementRule(name) : {}; - if (elementRule) { - newNode = createNode(elementRule.outputName || name, 1); - newNode.attributes = attrs; - newNode.shortEnded = empty; - - node.append(newNode); - - // Check if node is valid child of the parent node is the child is - // unknown we don't collect it since it's probably a custom element - parent = children[node.name]; - if (parent && children[newNode.name] && !parent[newNode.name]) { - invalidChildren.push(newNode); - } - - attrFiltersLen = attributeFilters.length; - while (attrFiltersLen--) { - attrName = attributeFilters[attrFiltersLen].name; - - if (attrName in attrs.map) { - list = matchedAttributes[attrName]; - - if (list) { - list.push(newNode); - } else { - matchedAttributes[attrName] = [newNode]; - } - } - } - - // Trim whitespace before block - if (blockElements[name]) { - removeWhitespaceBefore(newNode); - } - - // Change current node if the element wasn't empty i.e nota
- lastParent = node; - while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) { - lastParent = parent; - - if (blockElements[parent.name]) { - break; - } - - parent = parent.parent; - } - - if (lastParent === parent) { - textNode = new Node('#text', 3); - textNode.value = '\u00a0'; - node.replace(textNode); - } - } - } - }); - } - - // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. - if (!settings.allow_html_in_named_anchor) { - self.addAttributeFilter('id,name', function(nodes) { - var i = nodes.length, sibling, prevSibling, parent, node; - - while (i--) { - node = nodes[i]; - if (node.name === 'a' && node.firstChild && !node.attr('href')) { - parent = node.parent; - - // Move children after current node - sibling = node.lastChild; - do { - prevSibling = sibling.prev; - parent.insert(sibling, node); - sibling = prevSibling; - } while (sibling); - } - } - }); - } - }; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/html/Entities.js b/common/static/js/vendor/tinymce/js/tinymce/classes/html/Entities.js deleted file mode 100755 index 71430a9dfc..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/html/Entities.js +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Entities.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*jshint bitwise:false */ -/*eslint no-bitwise:0 */ - -/** - * Entity encoder class. - * - * @class tinymce.html.Entities - * @static - * @version 3.4 - */ -define("tinymce/html/Entities", [ - "tinymce/util/Tools" -], function(Tools) { - var makeMap = Tools.makeMap; - - var namedEntities, baseEntities, reverseEntities, - attrsCharsRegExp = /[&<>\"\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, - textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, - rawCharsRegExp = /[<>&\"\']/g, - entityRegExp = /&(#x|#)?([\w]+);/g, - asciiMap = { - 128: "\u20AC", 130: "\u201A", 131: "\u0192", 132: "\u201E", 133: "\u2026", 134: "\u2020", - 135: "\u2021", 136: "\u02C6", 137: "\u2030", 138: "\u0160", 139: "\u2039", 140: "\u0152", - 142: "\u017D", 145: "\u2018", 146: "\u2019", 147: "\u201C", 148: "\u201D", 149: "\u2022", - 150: "\u2013", 151: "\u2014", 152: "\u02DC", 153: "\u2122", 154: "\u0161", 155: "\u203A", - 156: "\u0153", 158: "\u017E", 159: "\u0178" - }; - - // Raw entities - baseEntities = { - '\"': '"', // Needs to be escaped since the YUI compressor would otherwise break the code - "'": ''', - '<': '<', - '>': '>', - '&': '&' - }; - - // Reverse lookup table for raw entities - reverseEntities = { - '<': '<', - '>': '>', - '&': '&', - '"': '"', - ''': "'" - }; - - // Decodes text by using the browser - function nativeDecode(text) { - var elm; - - elm = document.createElement("div"); - elm.innerHTML = text; - - return elm.textContent || elm.innerText || text; - } - - // Build a two way lookup table for the entities - function buildEntitiesLookup(items, radix) { - var i, chr, entity, lookup = {}; - - if (items) { - items = items.split(','); - radix = radix || 10; - - // Build entities lookup table - for (i = 0; i < items.length; i += 2) { - chr = String.fromCharCode(parseInt(items[i], radix)); - - // Only add non base entities - if (!baseEntities[chr]) { - entity = '&' + items[i + 1] + ';'; - lookup[chr] = entity; - lookup[entity] = chr; - } - } - - return lookup; - } - } - - // Unpack entities lookup where the numbers are in radix 32 to reduce the size - namedEntities = buildEntitiesLookup( - '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' + - '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' + - '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' + - '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' + - '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' + - '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' + - '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' + - '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' + - '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' + - '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' + - 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' + - 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' + - 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' + - 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' + - 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' + - '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' + - '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' + - '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' + - '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' + - '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' + - 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' + - 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' + - 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' + - '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' + - '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32); - - var Entities = { - /** - * Encodes the specified string using raw entities. This means only the required XML base entities will be endoded. - * - * @method encodeRaw - * @param {String} text Text to encode. - * @param {Boolean} attr Optional flag to specify if the text is attribute contents. - * @return {String} Entity encoded text. - */ - encodeRaw: function(text, attr) { - return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { - return baseEntities[chr] || chr; - }); - }, - - /** - * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents - * since it doesn't know if the context is within a attribute or text node. This was added for compatibility - * and is exposed as the DOMUtils.encode function. - * - * @method encodeAllRaw - * @param {String} text Text to encode. - * @return {String} Entity encoded text. - */ - encodeAllRaw: function(text) { - return ('' + text).replace(rawCharsRegExp, function(chr) { - return baseEntities[chr] || chr; - }); - }, - - /** - * Encodes the specified string using numeric entities. The core entities will be - * encoded as named ones but all non lower ascii characters will be encoded into numeric entities. - * - * @method encodeNumeric - * @param {String} text Text to encode. - * @param {Boolean} attr Optional flag to specify if the text is attribute contents. - * @return {String} Entity encoded text. - */ - encodeNumeric: function(text, attr) { - return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { - // Multi byte sequence convert it to a single entity - if (chr.length > 1) { - return '' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';'; - } - - return baseEntities[chr] || '' + chr.charCodeAt(0) + ';'; - }); - }, - - /** - * Encodes the specified string using named entities. The core entities will be encoded - * as named ones but all non lower ascii characters will be encoded into named entities. - * - * @method encodeNamed - * @param {String} text Text to encode. - * @param {Boolean} attr Optional flag to specify if the text is attribute contents. - * @param {Object} entities Optional parameter with entities to use. - * @return {String} Entity encoded text. - */ - encodeNamed: function(text, attr, entities) { - entities = entities || namedEntities; - - return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { - return baseEntities[chr] || entities[chr] || chr; - }); - }, - - /** - * Returns an encode function based on the name(s) and it's optional entities. - * - * @method getEncodeFunc - * @param {String} name Comma separated list of encoders for example named,numeric. - * @param {String} entities Optional parameter with entities to use instead of the built in set. - * @return {function} Encode function to be used. - */ - getEncodeFunc: function(name, entities) { - entities = buildEntitiesLookup(entities) || namedEntities; - - function encodeNamedAndNumeric(text, attr) { - return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) { - return baseEntities[chr] || entities[chr] || '' + chr.charCodeAt(0) + ';' || chr; - }); - } - - function encodeCustomNamed(text, attr) { - return Entities.encodeNamed(text, attr, entities); - } - - // Replace + with , to be compatible with previous TinyMCE versions - name = makeMap(name.replace(/\+/g, ',')); - - // Named and numeric encoder - if (name.named && name.numeric) { - return encodeNamedAndNumeric; - } - - // Named encoder - if (name.named) { - // Custom names - if (entities) { - return encodeCustomNamed; - } - - return Entities.encodeNamed; - } - - // Numeric - if (name.numeric) { - return Entities.encodeNumeric; - } - - // Raw encoder - return Entities.encodeRaw; - }, - - /** - * Decodes the specified string, this will replace entities with raw UTF characters. - * - * @method decode - * @param {String} text Text to entity decode. - * @return {String} Entity decoded string. - */ - decode: function(text) { - return text.replace(entityRegExp, function(all, numeric, value) { - if (numeric) { - value = parseInt(value, numeric.length === 2 ? 16 : 10); - - // Support upper UTF - if (value > 0xFFFF) { - value -= 0x10000; - - return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF)); - } else { - return asciiMap[value] || String.fromCharCode(value); - } - } - - return reverseEntities[all] || namedEntities[all] || nativeDecode(all); - }); - } - }; - - return Entities; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/html/Node.js b/common/static/js/vendor/tinymce/js/tinymce/classes/html/Node.js deleted file mode 100755 index acfc57a9fb..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/html/Node.js +++ /dev/null @@ -1,496 +0,0 @@ -/** - * Node.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is a minimalistic implementation of a DOM like node used by the DomParser class. - * - * @example - * var node = new tinymce.html.Node('strong', 1); - * someRoot.append(node); - * - * @class tinymce.html.Node - * @version 3.4 - */ -define("tinymce/html/Node", [], function() { - var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { - '#text': 3, - '#comment': 8, - '#cdata': 4, - '#pi': 7, - '#doctype': 10, - '#document-fragment': 11 - }; - - // Walks the tree left/right - function walk(node, root_node, prev) { - var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; - - // Walk into nodes if it has a start - if (node[startName]) { - return node[startName]; - } - - // Return the sibling if it has one - if (node !== root_node) { - sibling = node[siblingName]; - - if (sibling) { - return sibling; - } - - // Walk up the parents to look for siblings - for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { - sibling = parent[siblingName]; - - if (sibling) { - return sibling; - } - } - } - } - - /** - * Constructs a new Node instance. - * - * @constructor - * @method Node - * @param {String} name Name of the node type. - * @param {Number} type Numeric type representing the node. - */ - function Node(name, type) { - this.name = name; - this.type = type; - - if (type === 1) { - this.attributes = []; - this.attributes.map = {}; - } - } - - Node.prototype = { - /** - * Replaces the current node with the specified one. - * - * @example - * someNode.replace(someNewNode); - * - * @method replace - * @param {tinymce.html.Node} node Node to replace the current node with. - * @return {tinymce.html.Node} The old node that got replaced. - */ - replace: function(node) { - var self = this; - - if (node.parent) { - node.remove(); - } - - self.insert(node, self); - self.remove(); - - return self; - }, - - /** - * Gets/sets or removes an attribute by name. - * - * @example - * someNode.attr("name", "value"); // Sets an attribute - * console.log(someNode.attr("name")); // Gets an attribute - * someNode.attr("name", null); // Removes an attribute - * - * @method attr - * @param {String} name Attribute name to set or get. - * @param {String} value Optional value to set. - * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. - */ - attr: function(name, value) { - var self = this, attrs, i, undef; - - if (typeof name !== "string") { - for (i in name) { - self.attr(i, name[i]); - } - - return self; - } - - if ((attrs = self.attributes)) { - if (value !== undef) { - // Remove attribute - if (value === null) { - if (name in attrs.map) { - delete attrs.map[name]; - - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs = attrs.splice(i, 1); - return self; - } - } - } - - return self; - } - - // Set attribute - if (name in attrs.map) { - // Set attribute - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs[i].value = value; - break; - } - } - } else { - attrs.push({name: name, value: value}); - } - - attrs.map[name] = value; - - return self; - } else { - return attrs.map[name]; - } - } - }, - - /** - * Does a shallow clones the node into a new node. It will also exclude id attributes since - * there should only be one id per document. - * - * @example - * var clonedNode = node.clone(); - * - * @method clone - * @return {tinymce.html.Node} New copy of the original node. - */ - clone: function() { - var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; - - // Clone element attributes - if ((selfAttrs = self.attributes)) { - cloneAttrs = []; - cloneAttrs.map = {}; - - for (i = 0, l = selfAttrs.length; i < l; i++) { - selfAttr = selfAttrs[i]; - - // Clone everything except id - if (selfAttr.name !== 'id') { - cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; - cloneAttrs.map[selfAttr.name] = selfAttr.value; - } - } - - clone.attributes = cloneAttrs; - } - - clone.value = self.value; - clone.shortEnded = self.shortEnded; - - return clone; - }, - - /** - * Wraps the node in in another node. - * - * @example - * node.wrap(wrapperNode); - * - * @method wrap - */ - wrap: function(wrapper) { - var self = this; - - self.parent.insert(wrapper, self); - wrapper.append(self); - - return self; - }, - - /** - * Unwraps the node in other words it removes the node but keeps the children. - * - * @example - * node.unwrap(); - * - * @method unwrap - */ - unwrap: function() { - var self = this, node, next; - - for (node = self.firstChild; node; ) { - next = node.next; - self.insert(node, self, true); - node = next; - } - - self.remove(); - }, - - /** - * Removes the node from it's parent. - * - * @example - * node.remove(); - * - * @method remove - * @return {tinymce.html.Node} Current node that got removed. - */ - remove: function() { - var self = this, parent = self.parent, next = self.next, prev = self.prev; - - if (parent) { - if (parent.firstChild === self) { - parent.firstChild = next; - - if (next) { - next.prev = null; - } - } else { - prev.next = next; - } - - if (parent.lastChild === self) { - parent.lastChild = prev; - - if (prev) { - prev.next = null; - } - } else { - next.prev = prev; - } - - self.parent = self.next = self.prev = null; - } - - return self; - }, - - /** - * Appends a new node as a child of the current node. - * - * @example - * node.append(someNode); - * - * @method append - * @param {tinymce.html.Node} node Node to append as a child of the current one. - * @return {tinymce.html.Node} The node that got appended. - */ - append: function(node) { - var self = this, last; - - if (node.parent) { - node.remove(); - } - - last = self.lastChild; - if (last) { - last.next = node; - node.prev = last; - self.lastChild = node; - } else { - self.lastChild = self.firstChild = node; - } - - node.parent = self; - - return node; - }, - - /** - * Inserts a node at a specific position as a child of the current node. - * - * @example - * parentNode.insert(newChildNode, oldChildNode); - * - * @method insert - * @param {tinymce.html.Node} node Node to insert as a child of the current node. - * @param {tinymce.html.Node} ref_node Reference node to set node before/after. - * @param {Boolean} before Optional state to insert the node before the reference node. - * @return {tinymce.html.Node} The node that got inserted. - */ - insert: function(node, ref_node, before) { - var parent; - - if (node.parent) { - node.remove(); - } - - parent = ref_node.parent || this; - - if (before) { - if (ref_node === parent.firstChild) { - parent.firstChild = node; - } else { - ref_node.prev.next = node; - } - - node.prev = ref_node.prev; - node.next = ref_node; - ref_node.prev = node; - } else { - if (ref_node === parent.lastChild) { - parent.lastChild = node; - } else { - ref_node.next.prev = node; - } - - node.next = ref_node.next; - node.prev = ref_node; - ref_node.next = node; - } - - node.parent = parent; - - return node; - }, - - /** - * Get all children by name. - * - * @method getAll - * @param {String} name Name of the child nodes to collect. - * @return {Array} Array with child nodes matchin the specified name. - */ - getAll: function(name) { - var self = this, node, collection = []; - - for (node = self.firstChild; node; node = walk(node, self)) { - if (node.name === name) { - collection.push(node); - } - } - - return collection; - }, - - /** - * Removes all children of the current node. - * - * @method empty - * @return {tinymce.html.Node} The current node that got cleared. - */ - empty: function() { - var self = this, nodes, i, node; - - // Remove all children - if (self.firstChild) { - nodes = []; - - // Collect the children - for (node = self.firstChild; node; node = walk(node, self)) { - nodes.push(node); - } - - // Remove the children - i = nodes.length; - while (i--) { - node = nodes[i]; - node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; - } - } - - self.firstChild = self.lastChild = null; - - return self; - }, - - /** - * Returns true/false if the node is to be considered empty or not. - * - * @example - * node.isEmpty({img: true}); - * @method isEmpty - * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. - * @return {Boolean} true/false if the node is empty or not. - */ - isEmpty: function(elements) { - var self = this, node = self.firstChild, i, name; - - if (node) { - do { - if (node.type === 1) { - // Ignore bogus elements - if (node.attributes.map['data-mce-bogus']) { - continue; - } - - // Keep empty elements like
text
')); - * @class tinymce.html.Serializer - * @version 3.4 - */ -define("tinymce/html/Serializer", [ - "tinymce/html/Writer", - "tinymce/html/Schema" -], function(Writer, Schema) { - /** - * Constructs a new Serializer instance. - * - * @constructor - * @method Serializer - * @param {Object} settings Name/value settings object. - * @param {tinymce.html.Schema} schema Schema instance to use. - */ - return function(settings, schema) { - var self = this, writer = new Writer(settings); - - settings = settings || {}; - settings.validate = "validate" in settings ? settings.validate : true; - - self.schema = schema = schema || new Schema(); - self.writer = writer; - - /** - * Serializes the specified node into a string. - * - * @example - * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('text
')); - * @method serialize - * @param {tinymce.html.Node} node Node instance to serialize. - * @return {String} String with HTML based on DOM tree. - */ - self.serialize = function(node) { - var handlers, validate; - - validate = settings.validate; - - handlers = { - // #text - 3: function(node) { - writer.text(node.value, node.raw); - }, - - // #comment - 8: function(node) { - writer.comment(node.value); - }, - - // Processing instruction - 7: function(node) { - writer.pi(node.name, node.value); - }, - - // Doctype - 10: function(node) { - writer.doctype(node.value); - }, - - // CDATA - 4: function(node) { - writer.cdata(node.value); - }, - - // Document fragment - 11: function(node) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - } - }; - - writer.reset(); - - function walk(node) { - var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; - - if (!handler) { - name = node.name; - isEmpty = node.shortEnded; - attrs = node.attributes; - - // Sort attributes - if (validate && attrs && attrs.length > 1) { - sortedAttrs = []; - sortedAttrs.map = {}; - - elementRule = schema.getElementRule(node.name); - for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { - attrName = elementRule.attributesOrder[i]; - - if (attrName in attrs.map) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - for (i = 0, l = attrs.length; i < l; i++) { - attrName = attrs[i].name; - - if (!(attrName in sortedAttrs.map)) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - attrs = sortedAttrs; - } - - writer.start(node.name, attrs, isEmpty); - - if (!isEmpty) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - - writer.end(name); - } - } else { - handler(node); - } - } - - // Serialize element and treat all non elements as fragments - if (node.type == 1 && !settings.inner) { - walk(node); - } else { - handlers[11](node); - } - - return writer.getContent(); - }; - }; -}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/html/Styles.js b/common/static/js/vendor/tinymce/js/tinymce/classes/html/Styles.js deleted file mode 100755 index 51b6f4621c..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/html/Styles.js +++ /dev/null @@ -1,324 +0,0 @@ -/** - * Styles.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to parse CSS styles it also compresses styles to reduce the output size. - * - * @example - * var Styles = new tinymce.html.Styles({ - * url_converter: function(url) { - * return url; - * } - * }); - * - * styles = Styles.parse('border: 1px solid red'); - * styles.color = 'red'; - * - * console.log(new tinymce.html.StyleSerializer().serialize(styles)); - * - * @class tinymce.html.Styles - * @version 3.4 - */ -define("tinymce/html/Styles", [], function() { - return function(settings, schema) { - /*jshint maxlen:255 */ - /*eslint max-len:0 */ - var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi, - urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi, - styleRegExp = /\s*([^:]+):\s*([^;]+);?/g, - trimRightRegExp = /\s+$/, - undef, i, encodingLookup = {}, encodingItems, invisibleChar = '\uFEFF'; - - settings = settings || {}; - - encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' '); - for (i = 0; i < encodingItems.length; i++) { - encodingLookup[encodingItems[i]] = invisibleChar + i; - encodingLookup[invisibleChar + i] = encodingItems[i]; - } - - function toHex(match, r, g, b) { - function hex(val) { - val = parseInt(val, 10).toString(16); - - return val.length > 1 ? val : '0' + val; // 0 -> 00 - } - - return '#' + hex(r) + hex(g) + hex(b); - } - - return { - /** - * Parses the specified RGB color value and returns a hex version of that color. - * - * @method toHex - * @param {String} color RGB string value like rgb(1,2,3) - * @return {String} Hex version of that RGB value like #FF00FF. - */ - toHex: function(color) { - return color.replace(rgbRegExp, toHex); - }, - - /** - * Parses the specified style value into an object collection. This parser will also - * merge and remove any redundant items that browsers might have added. It will also convert non hex - * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings. - * - * @method parse - * @param {String} css Style value to parse for example: border:1px solid red;. - * @return {Object} Object representation of that style like {border: '1px solid red'} - */ - parse: function(css) { - var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter; - var urlConverterScope = settings.url_converter_scope || this; - - function compress(prefix, suffix, noJoin) { - var top, right, bottom, left; - - top = styles[prefix + '-top' + suffix]; - if (!top) { - return; - } - - right = styles[prefix + '-right' + suffix]; - if (!right) { - return; - } - - bottom = styles[prefix + '-bottom' + suffix]; - if (!bottom) { - return; - } - - left = styles[prefix + '-left' + suffix]; - if (!left) { - return; - } - - var box = [top, right, bottom, left]; - i = box.length - 1; - while (i--) { - if (box[i] !== box[i + 1]) { - break; - } - } - - if (i > -1 && noJoin) { - return; - } - - styles[prefix + suffix] = i == -1 ? box[0] : box.join(' '); - delete styles[prefix + '-top' + suffix]; - delete styles[prefix + '-right' + suffix]; - delete styles[prefix + '-bottom' + suffix]; - delete styles[prefix + '-left' + suffix]; - } - - /** - * Checks if the specific style can be compressed in other words if all border-width are equal. - */ - function canCompress(key) { - var value = styles[key], i; - - if (!value) { - return; - } - - value = value.split(' '); - i = value.length; - while (i--) { - if (value[i] !== value[0]) { - return false; - } - } - - styles[key] = value[0]; - - return true; - } - - /** - * Compresses multiple styles into one style. - */ - function compress2(target, a, b, c) { - if (!canCompress(a)) { - return; - } - - if (!canCompress(b)) { - return; - } - - if (!canCompress(c)) { - return; - } - - // Compress - styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c]; - delete styles[a]; - delete styles[b]; - delete styles[c]; - } - - // Encodes the specified string by replacing all \" \' ; : with _.
- *
- * @method start
- * @param {String} name Name of the element.
- * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
- * @param {Boolean} empty Optional empty state if the tag should end like
.
- */
- start: function(name, attrs, empty) {
- var i, l, attr, value;
-
- if (indent && indentBefore[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
-
- html.push('<', name);
-
- if (attrs) {
- for (i = 0, l = attrs.length; i < l; i++) {
- attr = attrs[i];
- html.push(' ', attr.name, '="', encode(attr.value, true), '"');
- }
- }
-
- if (!empty || htmlOutput) {
- html[html.length] = '>';
- } else {
- html[html.length] = ' />';
- }
-
- if (empty && indent && indentAfter[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
- },
-
- /**
- * Writes the a end element such as
bug on IE 8 #6178 - DOMUtils.DOM.setHTML(elm, html); - } - }; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/DragHelper.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/DragHelper.js deleted file mode 100755 index c7c2850b26..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/DragHelper.js +++ /dev/null @@ -1,136 +0,0 @@ -/** - * DragHelper.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Drag/drop helper class. - * - * @example - * var dragHelper = new tinymce.ui.DragHelper('mydiv', { - * start: function(evt) { - * }, - * - * drag: function(evt) { - * }, - * - * end: function(evt) { - * } - * }); - * - * @class tinymce.ui.DragHelper - */ -define("tinymce/ui/DragHelper", [ - "tinymce/ui/DomUtils" -], function(DomUtils) { - "use strict"; - - function getDocumentSize() { - var doc = document, documentElement, body, scrollWidth, clientWidth; - var offsetWidth, scrollHeight, clientHeight, offsetHeight, max = Math.max; - - documentElement = doc.documentElement; - body = doc.body; - - scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); - clientWidth = max(documentElement.clientWidth, body.clientWidth); - offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); - - scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); - clientHeight = max(documentElement.clientHeight, body.clientHeight); - offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); - - return { - width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, - height: scrollHeight < offsetHeight ? clientHeight : scrollHeight - }; - } - - return function(id, settings) { - var eventOverlayElm, doc = document, downButton, start, stop, drag, startX, startY; - - settings = settings || {}; - - function getHandleElm() { - return doc.getElementById(settings.handle || id); - } - - start = function(e) { - var docSize = getDocumentSize(), handleElm, cursor; - - e.preventDefault(); - downButton = e.button; - handleElm = getHandleElm(); - startX = e.screenX; - startY = e.screenY; - - // Grab cursor from handle - if (window.getComputedStyle) { - cursor = window.getComputedStyle(handleElm, null).getPropertyValue("cursor"); - } else { - cursor = handleElm.runtimeStyle.cursor; - } - - // Create event overlay and add it to document - eventOverlayElm = doc.createElement('div'); - DomUtils.css(eventOverlayElm, { - position: "absolute", - top: 0, left: 0, - width: docSize.width, - height: docSize.height, - zIndex: 0x7FFFFFFF, - opacity: 0.0001, - background: 'red', - cursor: cursor - }); - - doc.body.appendChild(eventOverlayElm); - - // Bind mouse events - DomUtils.on(doc, 'mousemove', drag); - DomUtils.on(doc, 'mouseup', stop); - - // Begin drag - settings.start(e); - }; - - drag = function(e) { - if (e.button !== downButton) { - return stop(e); - } - - e.deltaX = e.screenX - startX; - e.deltaY = e.screenY - startY; - - e.preventDefault(); - settings.drag(e); - }; - - stop = function(e) { - DomUtils.off(doc, 'mousemove', drag); - DomUtils.off(doc, 'mouseup', stop); - - eventOverlayElm.parentNode.removeChild(eventOverlayElm); - - if (settings.stop) { - settings.stop(e); - } - }; - - /** - * Destroys the drag/drop helper instance. - * - * @method destroy - */ - this.destroy = function() { - DomUtils.off(getHandleElm()); - }; - - DomUtils.on(getHandleElm(), 'mousedown', start); - }; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/ElementPath.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/ElementPath.js deleted file mode 100755 index 5b9d7fbcec..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/ElementPath.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * ElementPath.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This control creates an path for the current selections parent elements in TinyMCE. - * - * @class tinymce.ui.ElementPath - * @extends tinymce.ui.Path - */ -define("tinymce/ui/ElementPath", [ - "tinymce/ui/Path", - "tinymce/EditorManager" -], function(Path, EditorManager) { - return Path.extend({ - /** - * Post render method. Called after the control has been rendered to the target. - * - * @method postRender - * @return {tinymce.ui.ElementPath} Current combobox instance. - */ - postRender: function() { - var self = this, editor = EditorManager.activeEditor; - - function isHidden(elm) { - if (elm.nodeType === 1) { - if (elm.nodeName == "BR" || !!elm.getAttribute('data-mce-bogus')) { - return true; - } - - if (elm.getAttribute('data-mce-type') === 'bookmark') { - return true; - } - } - - return false; - } - - self.on('select', function(e) { - var parents = [], node, body = editor.getBody(); - - editor.focus(); - - node = editor.selection.getStart(); - while (node && node != body) { - if (!isHidden(node)) { - parents.push(node); - } - - node = node.parentNode; - } - - editor.selection.select(parents[parents.length - 1 - e.index]); - editor.nodeChanged(); - }); - - editor.on('nodeChange', function(e) { - var parents = [], selectionParents = e.parents, i = selectionParents.length; - - while (i--) { - if (selectionParents[i].nodeType == 1 && !isHidden(selectionParents[i])) { - var args = editor.fire('ResolveName', { - name: selectionParents[i].nodeName.toLowerCase(), - target: selectionParents[i] - }); - - parents.push({name: args.name}); - } - } - - self.data(parents); - }); - - return self._super(); - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Factory.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Factory.js deleted file mode 100755 index 6e4fc1c513..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Factory.js +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Factory.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*global tinymce:true */ - -/** - * This class is a factory for control instances. This enables you - * to create instances of controls without having to require the UI controls directly. - * - * It also allow you to override or add new control types. - * - * @class tinymce.ui.Factory - */ -define("tinymce/ui/Factory", [], function() { - "use strict"; - - var types = {}, namespaceInit; - - return { - /** - * Adds a new control instance type to the factory. - * - * @method add - * @param {String} type Type name for example "button". - * @param {function} typeClass Class type function. - */ - add: function(type, typeClass) { - types[type.toLowerCase()] = typeClass; - }, - - /** - * Returns true/false if the specified type exists or not. - * - * @method has - * @param {String} type Type to look for. - * @return {Boolean} true/false if the control by name exists. - */ - has: function(type) { - return !!types[type.toLowerCase()]; - }, - - /** - * Creates a new control instance based on the settings provided. The instance created will be - * based on the specified type property it can also create whole structures of components out of - * the specified JSON object. - * - * @example - * tinymce.ui.Factory.create({ - * type: 'button', - * text: 'Hello world!' - * }); - * - * @method create - * @param {Object/String} settings Name/Value object with items used to create the type. - * @return {tinymce.ui.Control} Control instance based on the specified type. - */ - create: function(type, settings) { - var ControlType, name, namespace; - - // Build type lookup - if (!namespaceInit) { - namespace = tinymce.ui; - - for (name in namespace) { - types[name.toLowerCase()] = namespace[name]; - } - - namespaceInit = true; - } - - // If string is specified then use it as the type - if (typeof(type) == 'string') { - settings = settings || {}; - settings.type = type; - } else { - settings = type; - type = settings.type; - } - - // Find control type - type = type.toLowerCase(); - ControlType = types[type]; - - // #if debug - - if (!ControlType) { - throw new Error("Could not find control by type: " + type); - } - - // #endif - - ControlType = new ControlType(settings); - ControlType.type = type; // Set the type on the instance, this will be used by the Selector engine - - return ControlType; - } - }; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FieldSet.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FieldSet.js deleted file mode 100755 index 4142890cb0..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FieldSet.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * FieldSet.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class creates fieldset containers. - * - * @-x-less FieldSet.less - * @class tinymce.ui.FieldSet - * @extends tinymce.ui.Form - */ -define("tinymce/ui/FieldSet", [ - "tinymce/ui/Form" -], function(Form) { - "use strict"; - - return Form.extend({ - Defaults: { - containerCls: 'fieldset', - layout: 'flex', - direction: 'column', - align: 'stretch', - flex: 1, - padding: "25 15 5 15", - labelGap: 30, - spacing: 10, - border: 1 - }, - - /** - * Renders the control as a HTML string. - * - * @method renderHtml - * @return {String} HTML representing the control. - */ - renderHtml: function() { - var self = this, layout = self._layout, prefix = self.classPrefix; - - self.preRender(); - layout.preRender(self); - - return ( - '
' - ); - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FilePicker.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FilePicker.js deleted file mode 100755 index b95bf603de..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FilePicker.js +++ /dev/null @@ -1,53 +0,0 @@ -/** - * FilePicker.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*global tinymce:true */ - -/** - * This class creates a file picker control. - * - * @class tinymce.ui.FilePicker - * @extends tinymce.ui.ComboBox - */ -define("tinymce/ui/FilePicker", [ - "tinymce/ui/ComboBox" -], function(ComboBox) { - "use strict"; - - return ComboBox.extend({ - /** - * Constructs a new control instance with the specified settings. - * - * @constructor - * @param {Object} settings Name/value object with settings. - */ - init: function(settings) { - var self = this, editor = tinymce.activeEditor, fileBrowserCallback; - - settings.spellcheck = false; - - fileBrowserCallback = editor.settings.file_browser_callback; - if (fileBrowserCallback) { - settings.icon = 'browse'; - - settings.onaction = function() { - fileBrowserCallback( - self.getEl('inp').id, - self.getEl('inp').value, - settings.filetype, - window - ); - }; - } - - self._super(settings); - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FitLayout.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FitLayout.js deleted file mode 100755 index 6809204441..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FitLayout.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * FitLayout.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This layout manager will resize the control to be the size of it's parent container. - * In other words width: 100% and height: 100%. - * - * @-x-less FitLayout.less - * @class tinymce.ui.FitLayout - * @extends tinymce.ui.AbsoluteLayout - */ -define("tinymce/ui/FitLayout", [ - "tinymce/ui/AbsoluteLayout" -], function(AbsoluteLayout) { - "use strict"; - - return AbsoluteLayout.extend({ - /** - * Recalculates the positions of the controls in the specified container. - * - * @method recalc - * @param {tinymce.ui.Container} container Container instance to recalc. - */ - recalc: function(container) { - var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox(); - - container.items().filter(':visible').each(function(ctrl) { - ctrl.layoutRect({ - x: paddingBox.left, - y: paddingBox.top, - w: contLayoutRect.innerW - paddingBox.right - paddingBox.left, - h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom - }); - - if (ctrl.recalc) { - ctrl.recalc(); - } - }); - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FlexLayout.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FlexLayout.js deleted file mode 100755 index 99761c8068..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FlexLayout.js +++ /dev/null @@ -1,246 +0,0 @@ -/** - * FlexLayout.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This layout manager works similar to the CSS flex box. - * - * @setting {String} direction row|row-reverse|column|column-reverse - * @setting {Number} flex A positive-number to flex by. - * @setting {String} align start|end|center|stretch - * @setting {String} pack start|end|justify - * - * @class tinymce.ui.FlexLayout - * @extends tinymce.ui.AbsoluteLayout - */ -define("tinymce/ui/FlexLayout", [ - "tinymce/ui/AbsoluteLayout" -], function(AbsoluteLayout) { - "use strict"; - - return AbsoluteLayout.extend({ - /** - * Recalculates the positions of the controls in the specified container. - * - * @method recalc - * @param {tinymce.ui.Container} container Container instance to recalc. - */ - recalc: function(container) { - // A ton of variables, needs to be in the same scope for performance - var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction; - var ctrl, ctrlLayoutRect, ctrlSettings, flex, maxSizeItems = [], size, maxSize, ratio, rect, pos, maxAlignEndPos; - var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, deltaSizeName, contentSizeName; - var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignBeforeName, alignAfterName; - var alignDeltaSizeName, alignContentSizeName; - var max = Math.max, min = Math.min; - - // Get container items, properties and settings - items = container.items().filter(':visible'); - contLayoutRect = container.layoutRect(); - contPaddingBox = container._paddingBox; - contSettings = container.settings; - direction = container.isRtl() ? (contSettings.direction || 'row-reversed') : contSettings.direction; - align = contSettings.align; - pack = container.isRtl() ? (contSettings.pack || 'end') : contSettings.pack; - spacing = contSettings.spacing || 0; - - if (direction == "row-reversed" || direction == "column-reverse") { - items = items.set(items.toArray().reverse()); - direction = direction.split('-')[0]; - } - - // Setup axis variable name for row/column direction since the calculations is the same - if (direction == "column") { - posName = "y"; - sizeName = "h"; - minSizeName = "minH"; - maxSizeName = "maxH"; - innerSizeName = "innerH"; - beforeName = 'top'; - deltaSizeName = "deltaH"; - contentSizeName = "contentH"; - - alignBeforeName = "left"; - alignSizeName = "w"; - alignAxisName = "x"; - alignInnerSizeName = "innerW"; - alignMinSizeName = "minW"; - alignAfterName = "right"; - alignDeltaSizeName = "deltaW"; - alignContentSizeName = "contentW"; - } else { - posName = "x"; - sizeName = "w"; - minSizeName = "minW"; - maxSizeName = "maxW"; - innerSizeName = "innerW"; - beforeName = 'left'; - deltaSizeName = "deltaW"; - contentSizeName = "contentW"; - - alignBeforeName = "top"; - alignSizeName = "h"; - alignAxisName = "y"; - alignInnerSizeName = "innerH"; - alignMinSizeName = "minH"; - alignAfterName = "bottom"; - alignDeltaSizeName = "deltaH"; - alignContentSizeName = "contentH"; - } - - // Figure out total flex, availableSpace and collect any max size elements - availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName]; - maxAlignEndPos = totalFlex = 0; - for (i = 0, l = items.length; i < l; i++) { - ctrl = items[i]; - ctrlLayoutRect = ctrl.layoutRect(); - ctrlSettings = ctrl.settings; - flex = ctrlSettings.flex; - availableSpace -= (i < l - 1 ? spacing : 0); - - if (flex > 0) { - totalFlex += flex; - - // Flexed item has a max size then we need to check if we will hit that size - if (ctrlLayoutRect[maxSizeName]) { - maxSizeItems.push(ctrl); - } - - ctrlLayoutRect.flex = flex; - } - - availableSpace -= ctrlLayoutRect[minSizeName]; - - // Calculate the align end position to be used to check for overflow/underflow - size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName]; - if (size > maxAlignEndPos) { - maxAlignEndPos = size; - } - } - - // Calculate minW/minH - rect = {}; - if (availableSpace < 0) { - rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName]; - } else { - rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName]; - } - - rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName]; - - rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace; - rect[alignContentSizeName] = maxAlignEndPos; - rect.minW = min(rect.minW, contLayoutRect.maxW); - rect.minH = min(rect.minH, contLayoutRect.maxH); - rect.minW = max(rect.minW, contLayoutRect.startMinWidth); - rect.minH = max(rect.minH, contLayoutRect.startMinHeight); - - // Resize container container if minSize was changed - if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) { - rect.w = rect.minW; - rect.h = rect.minH; - - container.layoutRect(rect); - this.recalc(container); - - // Forced recalc for example if items are hidden/shown - if (container._lastRect === null) { - var parentCtrl = container.parent(); - if (parentCtrl) { - parentCtrl._lastRect = null; - parentCtrl.recalc(); - } - } - - return; - } - - // Handle max size elements, check if they will become to wide with current options - ratio = availableSpace / totalFlex; - for (i = 0, l = maxSizeItems.length; i < l; i++) { - ctrl = maxSizeItems[i]; - ctrlLayoutRect = ctrl.layoutRect(); - maxSize = ctrlLayoutRect[maxSizeName]; - size = ctrlLayoutRect[minSizeName] + ctrlLayoutRect.flex * ratio; - - if (size > maxSize) { - availableSpace -= (ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]); - totalFlex -= ctrlLayoutRect.flex; - ctrlLayoutRect.flex = 0; - ctrlLayoutRect.maxFlexSize = maxSize; - } else { - ctrlLayoutRect.maxFlexSize = 0; - } - } - - // Setup new ratio, target layout rect, start position - ratio = availableSpace / totalFlex; - pos = contPaddingBox[beforeName]; - rect = {}; - - // Handle pack setting moves the start position to end, center - if (totalFlex === 0) { - if (pack == "end") { - pos = availableSpace + contPaddingBox[beforeName]; - } else if (pack == "center") { - pos = Math.round( - (contLayoutRect[innerSizeName] / 2) - ((contLayoutRect[innerSizeName] - availableSpace) / 2) - ) + contPaddingBox[beforeName]; - - if (pos < 0) { - pos = contPaddingBox[beforeName]; - } - } else if (pack == "justify") { - pos = contPaddingBox[beforeName]; - spacing = Math.floor(availableSpace / (items.length - 1)); - } - } - - // Default aligning (start) the other ones needs to be calculated while doing the layout - rect[alignAxisName] = contPaddingBox[alignBeforeName]; - - // Start laying out controls - for (i = 0, l = items.length; i < l; i++) { - ctrl = items[i]; - ctrlLayoutRect = ctrl.layoutRect(); - size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName]; - - // Align the control on the other axis - if (align === "center") { - rect[alignAxisName] = Math.round((contLayoutRect[alignInnerSizeName] / 2) - (ctrlLayoutRect[alignSizeName] / 2)); - } else if (align === "stretch") { - rect[alignSizeName] = max( - ctrlLayoutRect[alignMinSizeName] || 0, - contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName] - ); - rect[alignAxisName] = contPaddingBox[alignBeforeName]; - } else if (align === "end") { - rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top; - } - - // Calculate new size based on flex - if (ctrlLayoutRect.flex > 0) { - size += ctrlLayoutRect.flex * ratio; - } - - rect[sizeName] = size; - rect[posName] = pos; - ctrl.layoutRect(rect); - - // Recalculate containers - if (ctrl.recalc) { - ctrl.recalc(); - } - - // Move x/y position - pos += size + spacing; - } - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FloatPanel.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FloatPanel.js deleted file mode 100755 index 27457eee0e..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FloatPanel.js +++ /dev/null @@ -1,366 +0,0 @@ -/** - * FloatPanel.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class creates a floating panel. - * - * @-x-less FloatPanel.less - * @class tinymce.ui.FloatPanel - * @extends tinymce.ui.Panel - * @mixes tinymce.ui.Movable - * @mixes tinymce.ui.Resizable - */ -define("tinymce/ui/FloatPanel", [ - "tinymce/ui/Panel", - "tinymce/ui/Movable", - "tinymce/ui/Resizable", - "tinymce/ui/DomUtils" -], function(Panel, Movable, Resizable, DomUtils) { - "use strict"; - - var documentClickHandler, documentScrollHandler, visiblePanels = []; - var zOrder = [], hasModal; - - var FloatPanel = Panel.extend({ - Mixins: [Movable, Resizable], - - /** - * Constructs a new control instance with the specified settings. - * - * @constructor - * @param {Object} settings Name/value object with settings. - * @setting {Boolean} autohide Automatically hide the panel. - */ - init: function(settings) { - var self = this; - - function reorder() { - var i, zIndex = FloatPanel.zIndex || 0xFFFF, topModal; - - if (zOrder.length) { - for (i = 0; i < zOrder.length; i++) { - if (zOrder[i].modal) { - zIndex++; - topModal = zOrder[i]; - } - - zOrder[i].getEl().style.zIndex = zIndex; - zOrder[i].zIndex = zIndex; - zIndex++; - } - } - - var modalBlockEl = document.getElementById(self.classPrefix + 'modal-block'); - - if (topModal) { - DomUtils.css(modalBlockEl, 'z-index', topModal.zIndex - 1); - } else if (modalBlockEl) { - modalBlockEl.parentNode.removeChild(modalBlockEl); - hasModal = false; - } - - FloatPanel.currentZIndex = zIndex; - } - - function isChildOf(ctrl, parent) { - while (ctrl) { - if (ctrl == parent) { - return true; - } - - ctrl = ctrl.parent(); - } - } - - /** - * Repositions the panel to the top of page if the panel is outside of the visual viewport. It will - * also reposition all child panels of the current panel. - */ - function repositionPanel(panel) { - var scrollY = DomUtils.getViewPort().y; - - function toggleFixedChildPanels(fixed, deltaY) { - var parent; - - for (var i = 0; i < visiblePanels.length; i++) { - if (visiblePanels[i] != panel) { - parent = visiblePanels[i].parent(); - - while (parent && (parent = parent.parent())) { - if (parent == panel) { - visiblePanels[i].fixed(fixed).moveBy(0, deltaY).repaint(); - } - } - } - } - } - - if (panel.settings.autofix) { - if (!panel._fixed) { - panel._autoFixY = panel.layoutRect().y; - - if (panel._autoFixY < scrollY) { - panel.fixed(true).layoutRect({y: 0}).repaint(); - toggleFixedChildPanels(true, scrollY - panel._autoFixY); - } - } else { - if (panel._autoFixY > scrollY) { - panel.fixed(false).layoutRect({y: panel._autoFixY}).repaint(); - toggleFixedChildPanels(false, panel._autoFixY - scrollY); - } - } - } - } - - self._super(settings); - self._eventsRoot = self; - - self.addClass('floatpanel'); - - // Hide floatpanes on click out side the root button - if (settings.autohide) { - if (!documentClickHandler) { - documentClickHandler = function(e) { - // Hide any float panel when a click is out side that float panel and the - // float panels direct parent for example a click on a menu button - var i = visiblePanels.length; - while (i--) { - var panel = visiblePanels[i], clickCtrl = panel.getParentCtrl(e.target); - - if (panel.settings.autohide) { - if (clickCtrl) { - if (isChildOf(clickCtrl, panel) || panel.parent() === clickCtrl) { - continue; - } - } - - e = panel.fire('autohide', {target: e.target}); - if (!e.isDefaultPrevented()) { - panel.hide(); - } - } - } - }; - - DomUtils.on(document, 'click', documentClickHandler); - } - - visiblePanels.push(self); - } - - if (settings.autofix) { - if (!documentScrollHandler) { - documentScrollHandler = function() { - var i; - - i = visiblePanels.length; - while (i--) { - repositionPanel(visiblePanels[i]); - } - }; - - DomUtils.on(window, 'scroll', documentScrollHandler); - } - - self.on('move', function() { - repositionPanel(this); - }); - } - - self.on('postrender show', function(e) { - if (e.control == self) { - var modalBlockEl, prefix = self.classPrefix; - - if (self.modal && !hasModal) { - modalBlockEl = DomUtils.createFragment(''); - modalBlockEl = modalBlockEl.firstChild; - - self.getContainerElm().appendChild(modalBlockEl); - - setTimeout(function() { - DomUtils.addClass(modalBlockEl, prefix + 'in'); - DomUtils.addClass(self.getEl(), prefix + 'in'); - }, 0); - - hasModal = true; - } - - zOrder.push(self); - reorder(); - } - }); - - self.on('close hide', function(e) { - if (e.control == self) { - var i = zOrder.length; - - while (i--) { - if (zOrder[i] === self) { - zOrder.splice(i, 1); - } - } - - reorder(); - } - }); - - self.on('show', function() { - self.parents().each(function(ctrl) { - if (ctrl._fixed) { - self.fixed(true); - return false; - } - }); - }); - - if (settings.popover) { - self._preBodyHtml = ''; - self.addClass('popover').addClass('bottom').addClass(self.isRtl() ? 'end' : 'start'); - } - }, - - fixed: function(state) { - var self = this; - - if (self._fixed != state) { - if (self._rendered) { - var viewport = DomUtils.getViewPort(); - - if (state) { - self.layoutRect().y -= viewport.y; - } else { - self.layoutRect().y += viewport.y; - } - } - - self.toggleClass('fixed', state); - self._fixed = state; - } - - return self; - }, - - /** - * Shows the current float panel. - * - * @method show - * @return {tinymce.ui.FloatPanel} Current floatpanel instance. - */ - show: function() { - var self = this, i, state = self._super(); - - i = visiblePanels.length; - while (i--) { - if (visiblePanels[i] === self) { - break; - } - } - - if (i === -1) { - visiblePanels.push(self); - } - - return state; - }, - - /** - * Hides the current float panel. - * - * @method hide - * @return {tinymce.ui.FloatPanel} Current floatpanel instance. - */ - hide: function() { - removeVisiblePanel(this); - return this._super(); - }, - - /** - * Hides all visible the float panels. - * - * @method hideAll - */ - hideAll: function() { - FloatPanel.hideAll(); - }, - - /** - * Closes the float panel. This will remove the float panel from page and fire the close event. - * - * @method close - */ - close: function() { - var self = this; - - self.fire('close'); - - return self.remove(); - }, - - /** - * Removes the float panel from page. - * - * @method remove - */ - remove: function() { - removeVisiblePanel(this); - this._super(); - }, - - postRender: function() { - var self = this; - - if (self.settings.bodyRole) { - this.getEl('body').setAttribute('role', self.settings.bodyRole); - } - - return self._super(); - } - }); - - /** - * Hides all visible the float panels. - * - * @static - * @method hideAll - */ - FloatPanel.hideAll = function() { - var i = visiblePanels.length; - - while (i--) { - var panel = visiblePanels[i]; - - if (panel && panel.settings.autohide) { - panel.hide(); - visiblePanels.splice(i, 1); - } - } - }; - - function removeVisiblePanel(panel) { - var i; - - i = visiblePanels.length; - while (i--) { - if (visiblePanels[i] === panel) { - visiblePanels.splice(i, 1); - } - } - - i = zOrder.length; - while (i--) { - if (zOrder[i] === panel) { - zOrder.splice(i, 1); - } - } - } - - return FloatPanel; -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FlowLayout.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FlowLayout.js deleted file mode 100755 index cc40c22b74..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FlowLayout.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * FlowLayout.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This layout manager will place the controls by using the browsers native layout. - * - * @-x-less FlowLayout.less - * @class tinymce.ui.FlowLayout - * @extends tinymce.ui.Layout - */ -define("tinymce/ui/FlowLayout", [ - "tinymce/ui/Layout" -], function(Layout) { - return Layout.extend({ - Defaults: { - containerClass: 'flow-layout', - controlClass: 'flow-layout-item', - endClass : 'break' - }, - - /** - * Recalculates the positions of the controls in the specified container. - * - * @method recalc - * @param {tinymce.ui.Container} container Container instance to recalc. - */ - recalc: function(container) { - container.items().filter(':visible').each(function(ctrl) { - if (ctrl.recalc) { - ctrl.recalc(); - } - }); - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Form.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Form.js deleted file mode 100755 index 074ebc2832..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/Form.js +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Form.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class creates a form container. A form container has the ability - * to automatically wrap items in tinymce.ui.FormItem instances. - * - * Each FormItem instance is a container for the label and the item. - * - * @example - * tinymce.ui.Factory.create({ - * type: 'form', - * items: [ - * {type: 'textbox', label: 'My text box'} - * ] - * }).renderTo(document.body); - * - * @class tinymce.ui.Form - * @extends tinymce.ui.Container - */ -define("tinymce/ui/Form", [ - "tinymce/ui/Container", - "tinymce/ui/FormItem" -], function(Container, FormItem) { - "use strict"; - - return Container.extend({ - Defaults: { - containerCls: 'form', - layout: 'flex', - direction: 'column', - align: 'stretch', - flex: 1, - padding: 20, - labelGap: 30, - spacing: 10, - callbacks: { - submit: function() { - this.submit(); - } - } - }, - - /** - * This method gets invoked before the control is rendered. - * - * @method preRender - */ - preRender: function() { - var self = this, items = self.items(); - - // Wrap any labeled items in FormItems - items.each(function(ctrl) { - var formItem, label = ctrl.settings.label; - - if (label) { - formItem = new FormItem({ - layout: 'flex', - autoResize: "overflow", - defaults: {flex: 1}, - items: [ - {type: 'label', id: ctrl._id + '-l', text: label, flex: 0, forId: ctrl._id, disabled: ctrl.disabled()} - ] - }); - - formItem.type = 'formitem'; - ctrl.aria('labelledby', ctrl._id + '-l'); - - if (typeof(ctrl.settings.flex) == "undefined") { - ctrl.settings.flex = 1; - } - - self.replace(ctrl, formItem); - formItem.add(ctrl); - } - }); - }, - - /** - * Recalcs label widths. - * - * @private - */ - recalcLabels: function() { - var self = this, maxLabelWidth = 0, labels = [], i, labelGap; - - if (self.settings.labelGapCalc === false) { - return; - } - - self.items().filter('formitem').each(function(item) { - var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth; - - maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth; - labels.push(labelCtrl); - }); - - labelGap = self.settings.labelGap || 0; - - i = labels.length; - while (i--) { - labels[i].settings.minWidth = maxLabelWidth + labelGap; - } - }, - - /** - * Getter/setter for the visibility state. - * - * @method visible - * @param {Boolean} [state] True/false state to show/hide. - * @return {tinymce.ui.Form|Boolean} True/false state or current control. - */ - visible: function(state) { - var val = this._super(state); - - if (state === true && this._rendered) { - this.recalcLabels(); - } - - return val; - }, - - /** - * Fires a submit event with the serialized form. - * - * @method submit - * @return {Object} Event arguments object. - */ - submit: function() { - return this.fire('submit', {data: this.toJSON()}); - }, - - /** - * Post render method. Called after the control has been rendered to the target. - * - * @method postRender - * @return {tinymce.ui.ComboBox} Current combobox instance. - */ - postRender: function() { - var self = this; - - self._super(); - self.recalcLabels(); - self.fromJSON(self.settings.data); - } - }); -}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FormItem.js b/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FormItem.js deleted file mode 100755 index 56408db8ac..0000000000 --- a/common/static/js/vendor/tinymce/js/tinymce/classes/ui/FormItem.js +++ /dev/null @@ -1,56 +0,0 @@ -/** - * FormItem.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is a container created by the form element with - * a label and control item. - * - * @class tinymce.ui.FormItem - * @extends tinymce.ui.Container - * @setting {String} label Label to display for the form item. - */ -define("tinymce/ui/FormItem", [ - "tinymce/ui/Container" -], function(Container) { - "use strict"; - - return Container.extend({ - Defaults: { - layout: 'flex', - align: 'center', - defaults: { - flex: 1 - } - }, - - /** - * Renders the control as a HTML string. - * - * @method renderHtml - * @return {String} HTML representing the control. - */ - renderHtml: function() { - var self = this, layout = self._layout, prefix = self.classPrefix; - - self.addClass('formitem'); - layout.preRender(self); - - return ( - '|b
- * - * Will produce this on backspace: - *|
- * - * Or: - *|
- if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { - isCollapsed = editor.selection.isCollapsed(); - body = editor.getBody(); - - // Selection is collapsed but the editor isn't empty - if (isCollapsed && !dom.isEmpty(body)) { - return; - } - - // Selection isn't collapsed but not all the contents is selected - if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { - return; - } - - // Manually empty the editor - e.preventDefault(); - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - - editor.nodeChanged(); - } - }); - } - - /** - * WebKit doesn't select all the nodes in the body when you press Ctrl+A. - * IE selects more than the contents [a
] instead of[a]
see bug #6438 - * This selects the whole body so that backspace/delete logic will delete everything - */ - function selectAll() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { - e.preventDefault(); - editor.execCommand('SelectAll'); - } - }); - } - - /** - * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. - * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. - * - * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until - * you enter a character into the editor. - * - * It also happens when the first focus in made to the body. - * - * See: https://bugs.webkit.org/show_bug.cgi?id=83566 - */ - function inputMethodFocus() { - if (!editor.settings.content_editable) { - // Case 1 IME doesn't initialize if you focus the document - dom.bind(editor.getDoc(), 'focusin', function() { - selection.setRng(selection.getRng()); - }); - - // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event - dom.bind(editor.getDoc(), 'mousedown', function(e) { - if (e.target == editor.getDoc().documentElement) { - editor.getBody().focus(); - selection.setRng(selection.getRng()); - } - }); - } - } - - /** - * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the - * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is - * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js - * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other - * browsers. - * - * It also fixes a bug on Firefox where it's impossible to delete HR elements. - */ - function removeHrOnBackspace() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var node = selection.getNode(); - var previousSibling = node.previousSibling; - - if (node.nodeName == 'HR') { - dom.remove(node); - e.preventDefault(); - return; - } - - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { - dom.remove(previousSibling); - e.preventDefault(); - } - } - } - }); - } - - /** - * Firefox 3.x has an issue where the body element won't get proper focus if you click out - * side it's rectangle. - */ - function focusBody() { - // Fix for a focus bug in FF 3.x where the body element - // wouldn't get proper focus if the user clicked on the HTML element - if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 - editor.on('mousedown', function(e) { - if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") { - var body = editor.getBody(); - - // Blur the body it's focused but not correctly focused - body.blur(); - - // Refocus the body after a little while - setTimeout(function() { - body.focus(); - }, 0); - } - }); - } - } - - /** - * WebKit has a bug where it isn't possible to select image, hr or anchor elements - * by clicking on them so we need to fake that. - */ - function selectControlElements() { - editor.on('click', function(e) { - e = e.target; - - // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 - // WebKit can't even do simple things like selecting an image - // Needs tobe the setBaseAndExtend or it will fail to select floated images - if (/^(IMG|HR)$/.test(e.nodeName)) { - selection.getSel().setBaseAndExtent(e, 0, e, 1); - } - - if (e.nodeName == 'A' && dom.hasClass(e, 'mce-item-anchor')) { - selection.select(e); - } - - editor.nodeChanged(); - }); - } - - /** - * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. - * - * Fixes do backspace/delete on this: - *bla[ck
r]ed
- * - * Would become: - *bla|ed
- * - * Instead of: - *bla|ed
- */ - function removeStylesWhenDeletingAcrossBlockElements() { - function getAttributeApplyFunction() { - var template = dom.getAttribs(selection.getStart().cloneNode(false)); - - return function() { - var target = selection.getStart(); - - if (target !== editor.getBody()) { - dom.setAttrib(target, "style", null); - - each(template, function(attr) { - target.setAttributeNode(attr.cloneNode(true)); - }); - } - }; - } - - function isSelectionAcrossElements() { - return !selection.isCollapsed() && - dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); - } - - editor.on('keypress', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - editor.getDoc().execCommand('delete', false, null); - applyAttributes(); - e.preventDefault(); - return false; - } - }); - - dom.bind(editor.getDoc(), 'cut', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - - setTimeout(function() { - applyAttributes(); - }, 0); - } - }); - } - - /** - * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange - * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. - */ - function selectionChangeNodeChanged() { - var lastRng, selectionTimer; - - editor.on('selectionchange', function() { - if (selectionTimer) { - clearTimeout(selectionTimer); - selectionTimer = 0; - } - - selectionTimer = window.setTimeout(function() { - if (editor.removed) { - return; - } - - var rng = selection.getRng(); - - // Compare the ranges to see if it was a real change or not - if (!lastRng || !RangeUtils.compareRanges(rng, lastRng)) { - editor.nodeChanged(); - lastRng = rng; - } - }, 50); - }); - } - - /** - * Screen readers on IE needs to have the role application set on the body. - */ - function ensureBodyHasRoleApplication() { - document.body.setAttribute("role", "application"); - } - - /** - * Backspacing into a table behaves differently depending upon browser type. - * Therefore, disable Backspace when cursor immediately follows a table. - */ - function disableBackspaceIntoATable() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var previousSibling = selection.getNode().previousSibling; - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { - e.preventDefault(); - return false; - } - } - } - }); - } - - /** - * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this - * logic adds a \n before the BR so that it will get rendered. - */ - function addNewLinesBeforeBrInPre() { - // IE8+ rendering mode does the right thing with BR in PRE - if (getDocumentMode() > 7) { - return; - } - - // Enable display: none in area and add a specific class that hides all BR elements in PRE to - // avoid the caret from getting stuck at the BR elements while pressing the right arrow key - setEditorCommandState('RespectVisibilityInDesign', true); - editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); - dom.addClass(editor.getBody(), 'mceHideBrInPre'); - - // Adds a \n before all BR elements in PRE to get them visual - parser.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - - // Add \n before BR in PRE elements on older IE:s so the new lines get rendered - sibling = brElm.prev; - if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { - sibling.value += '\n'; - } else { - brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n'; - } - } - } - }); - - // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible - serializer.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - sibling = brElm.prev; - if (sibling && sibling.type == 3) { - sibling.value = sibling.value.replace(/\r?\n$/, ''); - } - } - } - }); - } - - /** - * Moves style width/height to attribute width/height when the user resizes an image on IE. - */ - function removePreSerializedStylesWhenSelectingControls() { - dom.bind(editor.getBody(), 'mouseup', function() { - var value, node = selection.getNode(); - - // Moved styles to attributes on IMG eements - if (node.nodeName == 'IMG') { - // Convert style width to width attribute - if ((value = dom.getStyle(node, 'width'))) { - dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'width', ''); - } - - // Convert style height to height attribute - if ((value = dom.getStyle(node, 'height'))) { - dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'height', ''); - } - } - }); - } - - /** - * Removes a blockquote when backspace is pressed at the beginning of it. - * - * For example: - *- * - * Becomes: - *|x
|x
- */ - function removeBlockQuoteOnBackSpace() { - // Add block quote deletion handler - editor.on('keydown', function(e) { - var rng, container, offset, root, parent; - - if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) { - return; - } - - rng = selection.getRng(); - container = rng.startContainer; - offset = rng.startOffset; - root = dom.getRoot(); - parent = container; - - if (!rng.collapsed || offset !== 0) { - return; - } - - while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) { - parent = parent.parentNode; - } - - // Is the cursor at the beginning of a blockquote? - if (parent.tagName === 'BLOCKQUOTE') { - // Remove the blockquote - editor.formatter.toggle('blockquote', null, parent); - - // Move the caret to the beginning of container - rng = dom.createRng(); - rng.setStart(container, 0); - rng.setEnd(container, 0); - selection.setRng(rng); - } - }); - } - - /** - * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. - */ - function setGeckoEditingOptions() { - function setOpts() { - editor._refreshContentEditable(); - - setEditorCommandState("StyleWithCSS", false); - setEditorCommandState("enableInlineTableEditing", false); - - if (!settings.object_resizing) { - setEditorCommandState("enableObjectResizing", false); - } - } - - if (!settings.readonly) { - editor.on('BeforeExecCommand MouseDown', setOpts); - } - } - - /** - * Fixes a gecko link bug, when a link is placed at the end of block elements there is - * no way to move the caret behind the link. This fix adds a bogus br element after the link. - * - * For example this: - * - * - * Becomes this: - * - */ - function addBrAfterLastLinks() { - function fixLinks() { - each(dom.select('a'), function(node) { - var parentNode = node.parentNode, root = dom.getRoot(); - - if (parentNode.lastChild === node) { - while (parentNode && !dom.isBlock(parentNode)) { - if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { - return; - } - - parentNode = parentNode.parentNode; - } - - dom.add(parentNode, 'br', {'data-mce-bogus': 1}); - } - }); - } - - editor.on('SetContent ExecCommand', function(e) { - if (e.type == "setcontent" || e.command === 'mceInsertLink') { - fixLinks(); - } - }); - } - - /** - * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by - * default we want to change that behavior. - */ - function setDefaultBlockType() { - if (settings.forced_root_block) { - editor.on('init', function() { - setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); - }); - } - } - - /** - * Removes ghost selections from images/tables on Gecko. - */ - function removeGhostSelection() { - editor.on('Undo Redo SetContent', function(e) { - if (!e.initial) { - editor.execCommand('mceRepaint'); - } - }); - } - - /** - * Deletes the selected image on IE instead of navigating to previous page. - */ - function deleteControlItemOnBackSpace() { - editor.on('keydown', function(e) { - var rng; - - if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { - rng = editor.getDoc().selection.createRange(); - if (rng && rng.item) { - e.preventDefault(); - editor.undoManager.beforeChange(); - dom.remove(rng.item(0)); - editor.undoManager.add(); - } - } - }); - } - - /** - * IE10 doesn't properly render block elements with the right height until you add contents to them. - * This fixes that by adding a padding-right to all empty text block elements. - * See: https://connect.microsoft.com/IE/feedback/details/743881 - */ - function renderEmptyBlocksFix() { - var emptyBlocksCSS; - - // IE10+ - if (getDocumentMode() >= 10) { - emptyBlocksCSS = ''; - each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { - emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; - }); - - editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); - } - } - - /** - * Old IE versions can't retain contents within noscript elements so this logic will store the contents - * as a attribute and the insert that value as it's raw text when the DOM is serialized. - */ - function keepNoScriptContents() { - if (getDocumentMode() < 9) { - parser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode; - - while (i--) { - node = nodes[i]; - textNode = node.firstChild; - - if (textNode) { - node.attr('data-mce-innertext', textNode.value); - } - } - }); - - serializer.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode, value; - - while (i--) { - node = nodes[i]; - textNode = nodes[i].firstChild; - - if (textNode) { - textNode.value = Entities.decode(textNode.value); - } else { - // Old IE can't retain noscript value so an attribute is used to store it - value = node.attributes.map['data-mce-innertext']; - if (value) { - node.attr('data-mce-innertext', null); - textNode = new Node('#text', 3); - textNode.value = value; - textNode.raw = true; - node.append(textNode); - } - } - } - }); - } - } - - /** - * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. - */ - function fixCaretSelectionOfDocumentElementOnIe() { - var doc = dom.doc, body = doc.body, started, startRng, htmlElm; - - // Return range from point or null if it failed - function rngFromPoint(x, y) { - var rng = body.createTextRange(); - - try { - rng.moveToPoint(x, y); - } catch (ex) { - // IE sometimes throws and exception, so lets just ignore it - rng = null; - } - - return rng; - } - - // Fires while the selection is changing - function selectionChange(e) { - var pointRng; - - // Check if the button is down or not - if (e.button) { - // Create range from mouse position - pointRng = rngFromPoint(e.x, e.y); - - if (pointRng) { - // Check if pointRange is before/after selection then change the endPoint - if (pointRng.compareEndPoints('StartToStart', startRng) > 0) { - pointRng.setEndPoint('StartToStart', startRng); - } else { - pointRng.setEndPoint('EndToEnd', startRng); - } - - pointRng.select(); - } - } else { - endSelection(); - } - } - - // Removes listeners - function endSelection() { - var rng = doc.selection.createRange(); - - // If the range is collapsed then use the last start range - if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) { - startRng.select(); - } - - dom.unbind(doc, 'mouseup', endSelection); - dom.unbind(doc, 'mousemove', selectionChange); - startRng = started = 0; - } - - // Make HTML element unselectable since we are going to handle selection by hand - doc.documentElement.unselectable = true; - - // Detect when user selects outside BODY - dom.bind(doc, 'mousedown contextmenu', function(e) { - if (e.target.nodeName === 'HTML') { - if (started) { - endSelection(); - } - - // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML - htmlElm = doc.documentElement; - if (htmlElm.scrollHeight > htmlElm.clientHeight) { - return; - } - - started = 1; - // Setup start position - startRng = rngFromPoint(e.x, e.y); - if (startRng) { - // Listen for selection change events - dom.bind(doc, 'mouseup', endSelection); - dom.bind(doc, 'mousemove', selectionChange); - - dom.getRoot().focus(); - startRng.select(); - } - } - }); - } - - /** - * Fixes selection issues where the caret can be placed between two inline elements like a|b - * this fix will lean the caret right into the closest inline element. - */ - function normalizeSelection() { - // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything - editor.on('keyup focusin mouseup', function(e) { - if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { - selection.normalize(); - } - }, true); - } - - /** - * Forces Gecko to render a broken image icon if it fails to load an image. - */ - function showBrokenImageIcon() { - editor.contentStyles.push( - 'img:-moz-broken {' + - '-moz-force-broken-image-icon:1;' + - 'min-width:24px;' + - 'min-height:24px' + - '}' - ); - } - - /** - * iOS has a bug where it's impossible to type if the document has a touchstart event - * bound and the user touches the document while having the on screen keyboard visible. - * - * The touch event moves the focus to the parent document while having the caret inside the iframe - * this fix moves the focus back into the iframe document. - */ - function restoreFocusOnKeyDown() { - if (!editor.inline) { - editor.on('keydown', function() { - if (document.activeElement == document.body) { - editor.getWin().focus(); - } - }); - } - } - - /** - * IE 11 has an annoying issue where you can't move focus into the editor - * by clicking on the white area HTML element. We used to be able to to fix this with - * the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection - * object it's not possible anymore. So we need to hack in a ungly CSS to force the - * body to be at least 150px. If the user clicks the HTML element out side this 150px region - * we simply move the focus into the first paragraph. Not ideal since you loose the - * positioning of the caret but goot enough for most cases. - */ - function bodyHeight() { - if (!editor.inline) { - editor.contentStyles.push('body {min-height: 150px}'); - editor.on('click', function(e) { - if (e.target.nodeName == 'HTML') { - editor.getBody().focus(); - editor.selection.normalize(); - editor.nodeChanged(); - } - }); - } - } - - /** - * Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow. - * You might then loose all your work so we need to block that behavior and replace it with our own. - */ - function blockCmdArrowNavigation() { - if (Env.mac) { - editor.on('keydown', function(e) { - if (VK.metaKeyPressed(e) && (e.keyCode == 37 || e.keyCode == 39)) { - e.preventDefault(); - editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'word'); - } - }); - } - } - - /** - * Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin. - */ - function disableAutoUrlDetect() { - setEditorCommandState("AutoUrlDetect", false); - } - - /** - * IE 11 has a fantastic bug where it will produce two trailing BR elements to iframe bodies when - * the iframe is hidden by display: none on a parent container. The DOM is actually out of sync - * with innerHTML in this case. It's like IE adds shadow DOM BR elements that appears on innerHTML - * but not as the lastChild of the body. However is we add a BR element to the body then remove it - * it doesn't seem to add these BR elements makes sence right?! - * - * Example of what happens: text becomes text]*>/gi, '[quote]'); + rep(/<\/blockquote>/gi, '[/quote]'); + rep(/- * - * @param {DOMRange} rng DOM Range to get bookmark on. - * @return {Object} Bookmark object. - */ - function createBookmark(rng) { - var bookmark = {}; - - function setupEndPoint(start) { - var offsetNode, container, offset; - - container = rng[start ? 'startContainer' : 'endContainer']; - offset = rng[start ? 'startOffset' : 'endOffset']; - - if (container.nodeType == 1) { - offsetNode = dom.create('span', {'data-mce-type': 'bookmark'}); - - if (container.hasChildNodes()) { - offset = Math.min(offset, container.childNodes.length - 1); - - if (start) { - container.insertBefore(offsetNode, container.childNodes[offset]); - } else { - dom.insertAfter(offsetNode, container.childNodes[offset]); - } - } else { - container.appendChild(offsetNode); - } - - container = offsetNode; - offset = 0; - } - - bookmark[start ? 'startContainer' : 'endContainer'] = container; - bookmark[start ? 'startOffset' : 'endOffset'] = offset; - } - - setupEndPoint(true); - - if (!rng.collapsed) { - setupEndPoint(); - } - - return bookmark; - } - - /** - * Moves the selection to the current bookmark and removes any selection container wrappers. - * - * @param {Object} bookmark Bookmark object to move selection to. - */ - function moveToBookmark(bookmark) { - function restoreEndPoint(start) { - var container, offset, node; - - function nodeIndex(container) { - var node = container.parentNode.firstChild, idx = 0; - - while (node) { - if (node == container) { - return idx; - } - - // Skip data-mce-type=bookmark nodes - if (node.nodeType != 1 || node.getAttribute('data-mce-type') != 'bookmark') { - idx++; - } - - node = node.nextSibling; - } - - return -1; - } - - container = node = bookmark[start ? 'startContainer' : 'endContainer']; - offset = bookmark[start ? 'startOffset' : 'endOffset']; - - if (!container) { - return; - } - - if (container.nodeType == 1) { - offset = nodeIndex(container); - container = container.parentNode; - dom.remove(node); - } - - bookmark[start ? 'startContainer' : 'endContainer'] = container; - bookmark[start ? 'startOffset' : 'endOffset'] = offset; - } - - restoreEndPoint(true); - restoreEndPoint(); - - var rng = dom.createRng(); - - rng.setStart(bookmark.startContainer, bookmark.startOffset); - - if (bookmark.endContainer) { - rng.setEnd(bookmark.endContainer, bookmark.endOffset); - } - - selection.setRng(rng); - } - - function createNewTextBlock(contentNode, blockName) { - var node, textBlock, fragment = dom.createFragment(), hasContentNode; - var blockElements = editor.schema.getBlockElements(); - - if (editor.settings.forced_root_block) { - blockName = blockName || editor.settings.forced_root_block; - } - - if (blockName) { - textBlock = dom.create(blockName); - - if (textBlock.tagName === editor.settings.forced_root_block) { - dom.setAttribs(textBlock, editor.settings.forced_root_block_attrs); - } - - fragment.appendChild(textBlock); - } - - if (contentNode) { - while ((node = contentNode.firstChild)) { - var nodeName = node.nodeName; - - if (!hasContentNode && (nodeName != 'SPAN' || node.getAttribute('data-mce-type') != 'bookmark')) { - hasContentNode = true; - } - - if (blockElements[nodeName]) { - fragment.appendChild(node); - textBlock = null; - } else { - if (blockName) { - if (!textBlock) { - textBlock = dom.create(blockName); - fragment.appendChild(textBlock); - } - - textBlock.appendChild(node); - } else { - fragment.appendChild(node); - } - } - } - } - - if (!editor.settings.forced_root_block) { - fragment.appendChild(dom.create('br')); - } else { - // BR is needed in empty blocks on non IE browsers - if (!hasContentNode && (!tinymce.Env.ie || tinymce.Env.ie > 10)) { - textBlock.appendChild(dom.create('br', {'data-mce-bogus': '1'})); - } - } - - return fragment; - } - - function getSelectedListItems() { - return tinymce.grep(selection.getSelectedBlocks(), function(block) { - return block.nodeName == 'LI'; - }); - } - - function splitList(ul, li, newBlock) { - var tmpRng, fragment; - - var bookmarks = dom.select('span[data-mce-type="bookmark"]', ul); - - newBlock = newBlock || createNewTextBlock(li); - tmpRng = dom.createRng(); - tmpRng.setStartAfter(li); - tmpRng.setEndAfter(ul); - fragment = tmpRng.extractContents(); - - if (!dom.isEmpty(fragment)) { - dom.insertAfter(fragment, ul); - } - - dom.insertAfter(newBlock, ul); - - if (dom.isEmpty(li.parentNode)) { - tinymce.each(bookmarks, function(node) { - li.parentNode.parentNode.insertBefore(node, li.parentNode); - }); - - dom.remove(li.parentNode); - } - - dom.remove(li); - } - - function mergeWithAdjacentLists(listBlock) { - var sibling, node; - - sibling = listBlock.nextSibling; - if (sibling && isListNode(sibling) && sibling.nodeName == listBlock.nodeName) { - while ((node = sibling.firstChild)) { - listBlock.appendChild(node); - } - - dom.remove(sibling); - } - - sibling = listBlock.previousSibling; - if (sibling && isListNode(sibling) && sibling.nodeName == listBlock.nodeName) { - while ((node = sibling.firstChild)) { - listBlock.insertBefore(node, listBlock.firstChild); - } - - dom.remove(sibling); - } - } - - /** - * Normalizes the all lists in the specified element. - */ - function normalizeList(element) { - tinymce.each(tinymce.grep(dom.select('ol,ul', element)), function(ul) { - var sibling, parentNode = ul.parentNode; - - // Move UL/OL to previous LI if it's the only child of a LI - if (parentNode.nodeName == 'LI' && parentNode.firstChild == ul) { - sibling = parentNode.previousSibling; - if (sibling && sibling.nodeName == 'LI') { - sibling.appendChild(ul); - - if (dom.isEmpty(parentNode)) { - dom.remove(parentNode); - } - } - } - - // Append OL/UL to previous LI if it's in a parent OL/UL i.e. old HTML4 - if (isListNode(parentNode)) { - sibling = parentNode.previousSibling; - if (sibling && sibling.nodeName == 'LI') { - sibling.appendChild(ul); - } - } - }); - } - - function outdent(li) { - var ul = li.parentNode, ulParent = ul.parentNode, newBlock; - - function removeEmptyLi(li) { - if (dom.isEmpty(li)) { - dom.remove(li); - } - } - - if (isFirstChild(li) && isLastChild(li)) { - if (ulParent.nodeName == "LI") { - dom.insertAfter(li, ulParent); - removeEmptyLi(ulParent); - dom.remove(ul); - } else if (isListNode(ulParent)) { - dom.remove(ul, true); - } else { - ulParent.insertBefore(createNewTextBlock(li), ul); - dom.remove(ul); - } - - return true; - } else if (isFirstChild(li)) { - if (ulParent.nodeName == "LI") { - dom.insertAfter(li, ulParent); - li.appendChild(ul); - removeEmptyLi(ulParent); - } else if (isListNode(ulParent)) { - ulParent.insertBefore(li, ul); - } else { - ulParent.insertBefore(createNewTextBlock(li), ul); - dom.remove(li); - } - - return true; - } else if (isLastChild(li)) { - if (ulParent.nodeName == "LI") { - dom.insertAfter(li, ulParent); - } else if (isListNode(ulParent)) { - dom.insertAfter(li, ul); - } else { - dom.insertAfter(createNewTextBlock(li), ul); - dom.remove(li); - } - - return true; - } else { - if (ulParent.nodeName == 'LI') { - ul = ulParent; - newBlock = createNewTextBlock(li, 'LI'); - } else if (isListNode(ulParent)) { - newBlock = createNewTextBlock(li, 'LI'); - } else { - newBlock = createNewTextBlock(li); - } - - splitList(ul, li, newBlock); - normalizeList(ul.parentNode); - - return true; - } - - return false; - } - - function indent(li) { - var sibling, newList; - - function mergeLists(from, to) { - var node; - - if (isListNode(from)) { - while ((node = li.lastChild.firstChild)) { - to.appendChild(node); - } - - dom.remove(from); - } - } - - sibling = li.previousSibling; - - if (sibling && isListNode(sibling)) { - sibling.appendChild(li); - return true; - } - - if (sibling && sibling.nodeName == 'LI' && isListNode(sibling.lastChild)) { - sibling.lastChild.appendChild(li); - mergeLists(li.lastChild, sibling.lastChild); - return true; - } - - sibling = li.nextSibling; - - if (sibling && isListNode(sibling)) { - sibling.insertBefore(li, sibling.firstChild); - return true; - } - - if (sibling && sibling.nodeName == 'LI' && isListNode(li.lastChild)) { - return false; - } - - sibling = li.previousSibling; - if (sibling && sibling.nodeName == 'LI') { - newList = dom.create(li.parentNode.nodeName); - sibling.appendChild(newList); - newList.appendChild(li); - mergeLists(li.lastChild, newList); - return true; - } - - return false; - } - - function indentSelection() { - var listElements = getSelectedListItems(); - - if (listElements.length) { - var bookmark = createBookmark(selection.getRng(true)); - - for (var i = 0; i < listElements.length; i++) { - if (!indent(listElements[i]) && i === 0) { - break; - } - } - - moveToBookmark(bookmark); - editor.nodeChanged(); - - return true; - } - } - - function outdentSelection() { - var listElements = getSelectedListItems(); - - if (listElements.length) { - var bookmark = createBookmark(selection.getRng(true)); - var i, y, root = editor.getBody(); - - i = listElements.length; - while (i--) { - var node = listElements[i].parentNode; - - while (node && node != root) { - y = listElements.length; - while (y--) { - if (listElements[y] === node) { - listElements.splice(i, 1); - break; - } - } - - node = node.parentNode; - } - } - - for (i = 0; i < listElements.length; i++) { - if (!outdent(listElements[i]) && i === 0) { - break; - } - } - - moveToBookmark(bookmark); - editor.nodeChanged(); - - return true; - } - } - - function applyList(listName) { - var rng = selection.getRng(true), bookmark = createBookmark(rng); - - function getSelectedTextBlocks() { - var textBlocks = [], root = editor.getBody(); - - function getEndPointNode(start) { - var container, offset; - - container = rng[start ? 'startContainer' : 'endContainer']; - offset = rng[start ? 'startOffset' : 'endOffset']; - - // Resolve node index - if (container.nodeType == 1) { - container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; - } - - while (container.parentNode != root) { - if (isTextBlock(container)) { - return container; - } - - if (/^(TD|TH)$/.test(container.parentNode.nodeName)) { - return container; - } - - container = container.parentNode; - } - - return container; - } - - var startNode = getEndPointNode(true); - var endNode = getEndPointNode(); - var block, siblings = []; - - for (var node = startNode; node; node = node.nextSibling) { - siblings.push(node); - - if (node == endNode) { - break; - } - } - - tinymce.each(siblings, function(node) { - if (isTextBlock(node)) { - textBlocks.push(node); - block = null; - return; - } - - if (dom.isBlock(node) || node.nodeName == 'BR') { - if (node.nodeName == 'BR') { - dom.remove(node); - } - - block = null; - return; - } - - var nextSibling = node.nextSibling; - if (isBookmarkNode(node)) { - if (isTextBlock(nextSibling) || (!nextSibling && node.parentNode == root)) { - block = null; - return; - } - } - - if (!block) { - block = dom.create('p'); - node.parentNode.insertBefore(block, node); - textBlocks.push(block); - } - - block.appendChild(node); - }); - - return textBlocks; - } - - var textBlocks = getSelectedTextBlocks(); - - tinymce.each(textBlocks, function(block) { - var listBlock, sibling; - - sibling = block.previousSibling; - if (sibling && isListNode(sibling) && sibling.nodeName == listName) { - listBlock = sibling; - block = dom.rename(block, 'LI'); - sibling.appendChild(block); - } else { - listBlock = dom.create(listName); - block.parentNode.insertBefore(listBlock, block); - listBlock.appendChild(block); - block = dom.rename(block, 'LI'); - } - - mergeWithAdjacentLists(listBlock); - }); - - moveToBookmark(bookmark); - } - - function removeList() { - var bookmark = createBookmark(selection.getRng(true)), root = editor.getBody(); - - tinymce.each(getSelectedListItems(), function(li) { - var node, rootList; - - if (dom.isEmpty(li)) { - outdent(li); - return; - } - - for (node = li; node && node != root; node = node.parentNode) { - if (isListNode(node)) { - rootList = node; - } - } - - splitList(rootList, li); - }); - - moveToBookmark(bookmark); - } - - function toggleList(listName) { - var parentList = dom.getParent(selection.getStart(), 'OL,UL'); - - if (parentList) { - if (parentList.nodeName == listName) { - removeList(listName); - } else { - var bookmark = createBookmark(selection.getRng(true)); - mergeWithAdjacentLists(dom.rename(parentList, listName)); - moveToBookmark(bookmark); - } - } else { - applyList(listName); - } - } - - self.backspaceDelete = function(isForward) { - function findNextCaretContainer(rng, isForward) { - var node = rng.startContainer, offset = rng.startOffset; - - if (node.nodeType == 3 && (isForward ? offset < node.data.length : offset > 0)) { - return node; - } - - var walker = new tinymce.dom.TreeWalker(rng.startContainer); - while ((node = walker[isForward ? 'next' : 'prev']())) { - if (node.nodeType == 3 && node.data.length > 0) { - return node; - } - } - } - - function mergeLiElements(fromElm, toElm) { - var node, listNode, ul = fromElm.parentNode; - - if (isListNode(toElm.lastChild)) { - listNode = toElm.lastChild; - } - - node = toElm.lastChild; - if (node && node.nodeName == 'BR' && fromElm.hasChildNodes()) { - dom.remove(node); - } - - while ((node = fromElm.firstChild)) { - toElm.appendChild(node); - } - - if (listNode) { - toElm.appendChild(listNode); - } - - dom.remove(fromElm); - - if (dom.isEmpty(ul)) { - dom.remove(ul); - } - } - - if (selection.isCollapsed()) { - var li = dom.getParent(selection.getStart(), 'LI'); - - if (li) { - var rng = selection.getRng(true); - var otherLi = dom.getParent(findNextCaretContainer(rng, isForward), 'LI'); - - if (otherLi && otherLi != li) { - var bookmark = createBookmark(rng); - - if (isForward) { - mergeLiElements(otherLi, li); - } else { - mergeLiElements(li, otherLi); - } - - moveToBookmark(bookmark); - - return true; - } else if (!otherLi) { - if (!isForward && removeList(li.parentNode.nodeName)) { - return true; - } - } - } - } - }; - - editor.addCommand('Indent', function() { - if (!indentSelection()) { - return true; - } - }); - - editor.addCommand('Outdent', function() { - if (!outdentSelection()) { - return true; - } - }); - - editor.addCommand('InsertUnorderedList', function() { - toggleList('UL'); - }); - - editor.addCommand('InsertOrderedList', function() { - toggleList('OL'); - }); - - editor.on('keydown', function(e) { - if (e.keyCode == 9 && editor.dom.getParent(editor.selection.getStart(), 'LI')) { - e.preventDefault(); - - if (e.shiftKey) { - outdentSelection(); - } else { - indentSelection(); - } - } - }); - }); - - editor.addButton('indent', { - icon: 'indent', - title: 'Increase indent', - cmd: 'Indent', - onPostRender: function() { - var ctrl = this; - - editor.on('nodechange', function() { - var li = editor.dom.getParent(editor.selection.getNode(), 'LI,UL,OL'); - ctrl.disabled(li && (li.nodeName != 'LI' || isFirstChild(li))); - }); - } - }); - - editor.on('keydown', function(e) { - if (e.keyCode == tinymce.util.VK.BACKSPACE) { - if (self.backspaceDelete()) { - e.preventDefault(); - } - } else if (e.keyCode == tinymce.util.VK.DELETE) { - if (self.backspaceDelete(true)) { - e.preventDefault(); - } - } - }); -}); +(function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var noop = function () { + }; + var constant = function (value) { + return function () { + return value; + }; + }; + var not = function (f) { + return function (t) { + return !f(t); + }; + }; + var never = constant(false); + var always = constant(true); + + var none = function () { + return NONE; + }; + var NONE = function () { + var eq = function (o) { + return o.isNone(); + }; + var call = function (thunk) { + return thunk(); + }; + var id = function (n) { + return n; + }; + var me = { + fold: function (n, _s) { + return n(); + }, + is: never, + isSome: never, + isNone: always, + getOr: id, + getOrThunk: call, + getOrDie: function (msg) { + throw new Error(msg || 'error: getOrDie called on none.'); + }, + getOrNull: constant(null), + getOrUndefined: constant(undefined), + or: id, + orThunk: call, + map: none, + each: noop, + bind: none, + exists: never, + forall: always, + filter: none, + equals: eq, + equals_: eq, + toArray: function () { + return []; + }, + toString: constant('none()') + }; + return me; + }(); + var some = function (a) { + var constant_a = constant(a); + var self = function () { + return me; + }; + var bind = function (f) { + return f(a); + }; + var me = { + fold: function (n, s) { + return s(a); + }, + is: function (v) { + return a === v; + }, + isSome: always, + isNone: never, + getOr: constant_a, + getOrThunk: constant_a, + getOrDie: constant_a, + getOrNull: constant_a, + getOrUndefined: constant_a, + or: self, + orThunk: self, + map: function (f) { + return some(f(a)); + }, + each: function (f) { + f(a); + }, + bind: bind, + exists: bind, + forall: bind, + filter: function (f) { + return f(a) ? me : NONE; + }, + toArray: function () { + return [a]; + }, + toString: function () { + return 'some(' + a + ')'; + }, + equals: function (o) { + return o.is(a); + }, + equals_: function (o, elementEq) { + return o.fold(never, function (b) { + return elementEq(a, b); + }); + } + }; + return me; + }; + var from = function (value) { + return value === null || value === undefined ? NONE : some(value); + }; + var Optional = { + some: some, + none: none, + from: from + }; + + var typeOf = function (x) { + var t = typeof x; + if (x === null) { + return 'null'; + } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { + return 'array'; + } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { + return 'string'; + } else { + return t; + } + }; + var isType = function (type) { + return function (value) { + return typeOf(value) === type; + }; + }; + var isSimpleType = function (type) { + return function (value) { + return typeof value === type; + }; + }; + var isString = isType('string'); + var isArray = isType('array'); + var isBoolean = isSimpleType('boolean'); + var isFunction = isSimpleType('function'); + var isNumber = isSimpleType('number'); + + var nativeSlice = Array.prototype.slice; + var nativePush = Array.prototype.push; + var map = function (xs, f) { + var len = xs.length; + var r = new Array(len); + for (var i = 0; i < len; i++) { + var x = xs[i]; + r[i] = f(x, i); + } + return r; + }; + var each = function (xs, f) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + f(x, i); + } + }; + var filter = function (xs, pred) { + var r = []; + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + if (pred(x, i)) { + r.push(x); + } + } + return r; + }; + var groupBy = function (xs, f) { + if (xs.length === 0) { + return []; + } else { + var wasType = f(xs[0]); + var r = []; + var group = []; + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + var type = f(x); + if (type !== wasType) { + r.push(group); + group = []; + } + wasType = type; + group.push(x); + } + if (group.length !== 0) { + r.push(group); + } + return r; + } + }; + var foldl = function (xs, f, acc) { + each(xs, function (x) { + acc = f(acc, x); + }); + return acc; + }; + var findUntil = function (xs, pred, until) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + if (pred(x, i)) { + return Optional.some(x); + } else if (until(x, i)) { + break; + } + } + return Optional.none(); + }; + var find = function (xs, pred) { + return findUntil(xs, pred, never); + }; + var flatten = function (xs) { + var r = []; + for (var i = 0, len = xs.length; i < len; ++i) { + if (!isArray(xs[i])) { + throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); + } + nativePush.apply(r, xs[i]); + } + return r; + }; + var bind = function (xs, f) { + return flatten(map(xs, f)); + }; + var reverse = function (xs) { + var r = nativeSlice.call(xs, 0); + r.reverse(); + return r; + }; + var head = function (xs) { + return xs.length === 0 ? Optional.none() : Optional.some(xs[0]); + }; + var last = function (xs) { + return xs.length === 0 ? Optional.none() : Optional.some(xs[xs.length - 1]); + }; + + var __assign = function () { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + var cached = function (f) { + var called = false; + var r; + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!called) { + called = true; + r = f.apply(null, args); + } + return r; + }; + }; + + var DeviceType = function (os, browser, userAgent, mediaMatch) { + var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; + var isiPhone = os.isiOS() && !isiPad; + var isMobile = os.isiOS() || os.isAndroid(); + var isTouch = isMobile || mediaMatch('(pointer:coarse)'); + var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)'); + var isPhone = isiPhone || isMobile && !isTablet; + var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; + var isDesktop = !isPhone && !isTablet && !iOSwebview; + return { + isiPad: constant(isiPad), + isiPhone: constant(isiPhone), + isTablet: constant(isTablet), + isPhone: constant(isPhone), + isTouch: constant(isTouch), + isAndroid: os.isAndroid, + isiOS: os.isiOS, + isWebView: constant(iOSwebview), + isDesktop: constant(isDesktop) + }; + }; + + var firstMatch = function (regexes, s) { + for (var i = 0; i < regexes.length; i++) { + var x = regexes[i]; + if (x.test(s)) { + return x; + } + } + return undefined; + }; + var find$1 = function (regexes, agent) { + var r = firstMatch(regexes, agent); + if (!r) { + return { + major: 0, + minor: 0 + }; + } + var group = function (i) { + return Number(agent.replace(r, '$' + i)); + }; + return nu(group(1), group(2)); + }; + var detect = function (versionRegexes, agent) { + var cleanedAgent = String(agent).toLowerCase(); + if (versionRegexes.length === 0) { + return unknown(); + } + return find$1(versionRegexes, cleanedAgent); + }; + var unknown = function () { + return nu(0, 0); + }; + var nu = function (major, minor) { + return { + major: major, + minor: minor + }; + }; + var Version = { + nu: nu, + detect: detect, + unknown: unknown + }; + + var detect$1 = function (candidates, userAgent) { + var agent = String(userAgent).toLowerCase(); + return find(candidates, function (candidate) { + return candidate.search(agent); + }); + }; + var detectBrowser = function (browsers, userAgent) { + return detect$1(browsers, userAgent).map(function (browser) { + var version = Version.detect(browser.versionRegexes, userAgent); + return { + current: browser.name, + version: version + }; + }); + }; + var detectOs = function (oses, userAgent) { + return detect$1(oses, userAgent).map(function (os) { + var version = Version.detect(os.versionRegexes, userAgent); + return { + current: os.name, + version: version + }; + }); + }; + var UaString = { + detectBrowser: detectBrowser, + detectOs: detectOs + }; + + var contains = function (str, substr) { + return str.indexOf(substr) !== -1; + }; + + var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; + var checkContains = function (target) { + return function (uastring) { + return contains(uastring, target); + }; + }; + var browsers = [ + { + name: 'Edge', + versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], + search: function (uastring) { + return contains(uastring, 'edge/') && contains(uastring, 'chrome') && contains(uastring, 'safari') && contains(uastring, 'applewebkit'); + } + }, + { + name: 'Chrome', + versionRegexes: [ + /.*?chrome\/([0-9]+)\.([0-9]+).*/, + normalVersionRegex + ], + search: function (uastring) { + return contains(uastring, 'chrome') && !contains(uastring, 'chromeframe'); + } + }, + { + name: 'IE', + versionRegexes: [ + /.*?msie\ ?([0-9]+)\.([0-9]+).*/, + /.*?rv:([0-9]+)\.([0-9]+).*/ + ], + search: function (uastring) { + return contains(uastring, 'msie') || contains(uastring, 'trident'); + } + }, + { + name: 'Opera', + versionRegexes: [ + normalVersionRegex, + /.*?opera\/([0-9]+)\.([0-9]+).*/ + ], + search: checkContains('opera') + }, + { + name: 'Firefox', + versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/], + search: checkContains('firefox') + }, + { + name: 'Safari', + versionRegexes: [ + normalVersionRegex, + /.*?cpu os ([0-9]+)_([0-9]+).*/ + ], + search: function (uastring) { + return (contains(uastring, 'safari') || contains(uastring, 'mobile/')) && contains(uastring, 'applewebkit'); + } + } + ]; + var oses = [ + { + name: 'Windows', + search: checkContains('win'), + versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/] + }, + { + name: 'iOS', + search: function (uastring) { + return contains(uastring, 'iphone') || contains(uastring, 'ipad'); + }, + versionRegexes: [ + /.*?version\/\ ?([0-9]+)\.([0-9]+).*/, + /.*cpu os ([0-9]+)_([0-9]+).*/, + /.*cpu iphone os ([0-9]+)_([0-9]+).*/ + ] + }, + { + name: 'Android', + search: checkContains('android'), + versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/] + }, + { + name: 'OSX', + search: checkContains('mac os x'), + versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/] + }, + { + name: 'Linux', + search: checkContains('linux'), + versionRegexes: [] + }, + { + name: 'Solaris', + search: checkContains('sunos'), + versionRegexes: [] + }, + { + name: 'FreeBSD', + search: checkContains('freebsd'), + versionRegexes: [] + }, + { + name: 'ChromeOS', + search: checkContains('cros'), + versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/] + } + ]; + var PlatformInfo = { + browsers: constant(browsers), + oses: constant(oses) + }; + + var edge = 'Edge'; + var chrome = 'Chrome'; + var ie = 'IE'; + var opera = 'Opera'; + var firefox = 'Firefox'; + var safari = 'Safari'; + var unknown$1 = function () { + return nu$1({ + current: undefined, + version: Version.unknown() + }); + }; + var nu$1 = function (info) { + var current = info.current; + var version = info.version; + var isBrowser = function (name) { + return function () { + return current === name; + }; + }; + return { + current: current, + version: version, + isEdge: isBrowser(edge), + isChrome: isBrowser(chrome), + isIE: isBrowser(ie), + isOpera: isBrowser(opera), + isFirefox: isBrowser(firefox), + isSafari: isBrowser(safari) + }; + }; + var Browser = { + unknown: unknown$1, + nu: nu$1, + edge: constant(edge), + chrome: constant(chrome), + ie: constant(ie), + opera: constant(opera), + firefox: constant(firefox), + safari: constant(safari) + }; + + var windows = 'Windows'; + var ios = 'iOS'; + var android = 'Android'; + var linux = 'Linux'; + var osx = 'OSX'; + var solaris = 'Solaris'; + var freebsd = 'FreeBSD'; + var chromeos = 'ChromeOS'; + var unknown$2 = function () { + return nu$2({ + current: undefined, + version: Version.unknown() + }); + }; + var nu$2 = function (info) { + var current = info.current; + var version = info.version; + var isOS = function (name) { + return function () { + return current === name; + }; + }; + return { + current: current, + version: version, + isWindows: isOS(windows), + isiOS: isOS(ios), + isAndroid: isOS(android), + isOSX: isOS(osx), + isLinux: isOS(linux), + isSolaris: isOS(solaris), + isFreeBSD: isOS(freebsd), + isChromeOS: isOS(chromeos) + }; + }; + var OperatingSystem = { + unknown: unknown$2, + nu: nu$2, + windows: constant(windows), + ios: constant(ios), + android: constant(android), + linux: constant(linux), + osx: constant(osx), + solaris: constant(solaris), + freebsd: constant(freebsd), + chromeos: constant(chromeos) + }; + + var detect$2 = function (userAgent, mediaMatch) { + var browsers = PlatformInfo.browsers(); + var oses = PlatformInfo.oses(); + var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu); + var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu); + var deviceType = DeviceType(os, browser, userAgent, mediaMatch); + return { + browser: browser, + os: os, + deviceType: deviceType + }; + }; + var PlatformDetection = { detect: detect$2 }; + + var mediaMatch = function (query) { + return window.matchMedia(query).matches; + }; + var platform = cached(function () { + return PlatformDetection.detect(navigator.userAgent, mediaMatch); + }); + var detect$3 = function () { + return platform(); + }; + + var compareDocumentPosition = function (a, b, match) { + return (a.compareDocumentPosition(b) & match) !== 0; + }; + var documentPositionContainedBy = function (a, b) { + return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY); + }; + + var ELEMENT = 1; + + var fromHtml = function (html, scope) { + var doc = scope || document; + var div = doc.createElement('div'); + div.innerHTML = html; + if (!div.hasChildNodes() || div.childNodes.length > 1) { + console.error('HTML does not have a single root node', html); + throw new Error('HTML must have a single root node'); + } + return fromDom(div.childNodes[0]); + }; + var fromTag = function (tag, scope) { + var doc = scope || document; + var node = doc.createElement(tag); + return fromDom(node); + }; + var fromText = function (text, scope) { + var doc = scope || document; + var node = doc.createTextNode(text); + return fromDom(node); + }; + var fromDom = function (node) { + if (node === null || node === undefined) { + throw new Error('Node cannot be null or undefined'); + } + return { dom: node }; + }; + var fromPoint = function (docElm, x, y) { + return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); + }; + var SugarElement = { + fromHtml: fromHtml, + fromTag: fromTag, + fromText: fromText, + fromDom: fromDom, + fromPoint: fromPoint + }; + + var is = function (element, selector) { + var dom = element.dom; + if (dom.nodeType !== ELEMENT) { + return false; + } else { + var elem = dom; + if (elem.matches !== undefined) { + return elem.matches(selector); + } else if (elem.msMatchesSelector !== undefined) { + return elem.msMatchesSelector(selector); + } else if (elem.webkitMatchesSelector !== undefined) { + return elem.webkitMatchesSelector(selector); + } else if (elem.mozMatchesSelector !== undefined) { + return elem.mozMatchesSelector(selector); + } else { + throw new Error('Browser lacks native selectors'); + } + } + }; + + var eq = function (e1, e2) { + return e1.dom === e2.dom; + }; + var regularContains = function (e1, e2) { + var d1 = e1.dom; + var d2 = e2.dom; + return d1 === d2 ? false : d1.contains(d2); + }; + var ieContains = function (e1, e2) { + return documentPositionContainedBy(e1.dom, e2.dom); + }; + var contains$1 = function (e1, e2) { + return detect$3().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2); + }; + var is$1 = is; + + var global$1 = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils'); + + var global$2 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker'); + + var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK'); + + var keys = Object.keys; + var each$1 = function (obj, f) { + var props = keys(obj); + for (var k = 0, len = props.length; k < len; k++) { + var i = props[k]; + var x = obj[i]; + f(x, i); + } + }; + var objAcc = function (r) { + return function (x, i) { + r[i] = x; + }; + }; + var internalFilter = function (obj, pred, onTrue, onFalse) { + var r = {}; + each$1(obj, function (x, i) { + (pred(x, i) ? onTrue : onFalse)(x, i); + }); + return r; + }; + var filter$1 = function (obj, pred) { + var t = {}; + internalFilter(obj, pred, objAcc(t), noop); + return t; + }; + + var Global = typeof window !== 'undefined' ? window : Function('return this;')(); + + var name = function (element) { + var r = element.dom.nodeName; + return r.toLowerCase(); + }; + var type = function (element) { + return element.dom.nodeType; + }; + var isType$1 = function (t) { + return function (element) { + return type(element) === t; + }; + }; + var isElement = isType$1(ELEMENT); + + var rawSet = function (dom, key, value) { + if (isString(value) || isBoolean(value) || isNumber(value)) { + dom.setAttribute(key, value + ''); + } else { + console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom); + throw new Error('Attribute value was not simple'); + } + }; + var setAll = function (element, attrs) { + var dom = element.dom; + each$1(attrs, function (v, k) { + rawSet(dom, k, v); + }); + }; + var clone = function (element) { + return foldl(element.dom.attributes, function (acc, attr) { + acc[attr.name] = attr.value; + return acc; + }, {}); + }; + + var parent = function (element) { + return Optional.from(element.dom.parentNode).map(SugarElement.fromDom); + }; + var children = function (element) { + return map(element.dom.childNodes, SugarElement.fromDom); + }; + var child = function (element, index) { + var cs = element.dom.childNodes; + return Optional.from(cs[index]).map(SugarElement.fromDom); + }; + var firstChild = function (element) { + return child(element, 0); + }; + var lastChild = function (element) { + return child(element, element.dom.childNodes.length - 1); + }; + + var before = function (marker, element) { + var parent$1 = parent(marker); + parent$1.each(function (v) { + v.dom.insertBefore(element.dom, marker.dom); + }); + }; + var append = function (parent, element) { + parent.dom.appendChild(element.dom); + }; + + var before$1 = function (marker, elements) { + each(elements, function (x) { + before(marker, x); + }); + }; + var append$1 = function (parent, elements) { + each(elements, function (x) { + append(parent, x); + }); + }; + + var remove = function (element) { + var dom = element.dom; + if (dom.parentNode !== null) { + dom.parentNode.removeChild(dom); + } + }; + + var clone$1 = function (original, isDeep) { + return SugarElement.fromDom(original.dom.cloneNode(isDeep)); + }; + var deep = function (original) { + return clone$1(original, true); + }; + var shallowAs = function (original, tag) { + var nu = SugarElement.fromTag(tag); + var attributes = clone(original); + setAll(nu, attributes); + return nu; + }; + var mutate = function (original, tag) { + var nu = shallowAs(original, tag); + before(original, nu); + var children$1 = children(original); + append$1(nu, children$1); + remove(original); + return nu; + }; + + var global$4 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); + + var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools'); + + var matchNodeName = function (name) { + return function (node) { + return node && node.nodeName.toLowerCase() === name; + }; + }; + var matchNodeNames = function (regex) { + return function (node) { + return node && regex.test(node.nodeName); + }; + }; + var isTextNode = function (node) { + return node && node.nodeType === 3; + }; + var isListNode = matchNodeNames(/^(OL|UL|DL)$/); + var isOlUlNode = matchNodeNames(/^(OL|UL)$/); + var isOlNode = matchNodeName('ol'); + var isListItemNode = matchNodeNames(/^(LI|DT|DD)$/); + var isDlItemNode = matchNodeNames(/^(DT|DD)$/); + var isTableCellNode = matchNodeNames(/^(TH|TD)$/); + var isBr = matchNodeName('br'); + var isFirstChild = function (node) { + return node.parentNode.firstChild === node; + }; + var isTextBlock = function (editor, node) { + return node && !!editor.schema.getTextBlockElements()[node.nodeName]; + }; + var isBlock = function (node, blockElements) { + return node && node.nodeName in blockElements; + }; + var isBogusBr = function (dom, node) { + if (!isBr(node)) { + return false; + } + return dom.isBlock(node.nextSibling) && !isBr(node.previousSibling); + }; + var isEmpty = function (dom, elm, keepBookmarks) { + var empty = dom.isEmpty(elm); + if (keepBookmarks && dom.select('span[data-mce-type=bookmark]', elm).length > 0) { + return false; + } + return empty; + }; + var isChildOfBody = function (dom, elm) { + return dom.isChildOf(elm, dom.getRoot()); + }; + + var shouldIndentOnTab = function (editor) { + return editor.getParam('lists_indent_on_tab', true); + }; + var getForcedRootBlock = function (editor) { + var block = editor.getParam('forced_root_block', 'p'); + if (block === false) { + return ''; + } else if (block === true) { + return 'p'; + } else { + return block; + } + }; + var getForcedRootBlockAttrs = function (editor) { + return editor.getParam('forced_root_block_attrs', {}); + }; + + var createTextBlock = function (editor, contentNode) { + var dom = editor.dom; + var blockElements = editor.schema.getBlockElements(); + var fragment = dom.createFragment(); + var blockName = getForcedRootBlock(editor); + var node, textBlock, hasContentNode; + if (blockName) { + textBlock = dom.create(blockName); + if (textBlock.tagName === blockName.toUpperCase()) { + dom.setAttribs(textBlock, getForcedRootBlockAttrs(editor)); + } + if (!isBlock(contentNode.firstChild, blockElements)) { + fragment.appendChild(textBlock); + } + } + if (contentNode) { + while (node = contentNode.firstChild) { + var nodeName = node.nodeName; + if (!hasContentNode && (nodeName !== 'SPAN' || node.getAttribute('data-mce-type') !== 'bookmark')) { + hasContentNode = true; + } + if (isBlock(node, blockElements)) { + fragment.appendChild(node); + textBlock = null; + } else { + if (blockName) { + if (!textBlock) { + textBlock = dom.create(blockName); + fragment.appendChild(textBlock); + } + textBlock.appendChild(node); + } else { + fragment.appendChild(node); + } + } + } + } + if (!blockName) { + fragment.appendChild(dom.create('br')); + } else { + if (!hasContentNode) { + textBlock.appendChild(dom.create('br', { 'data-mce-bogus': '1' })); + } + } + return fragment; + }; + + var DOM = global$4.DOM; + var splitList = function (editor, ul, li) { + var removeAndKeepBookmarks = function (targetNode) { + global$5.each(bookmarks, function (node) { + targetNode.parentNode.insertBefore(node, li.parentNode); + }); + DOM.remove(targetNode); + }; + var bookmarks = DOM.select('span[data-mce-type="bookmark"]', ul); + var newBlock = createTextBlock(editor, li); + var tmpRng = DOM.createRng(); + tmpRng.setStartAfter(li); + tmpRng.setEndAfter(ul); + var fragment = tmpRng.extractContents(); + for (var node = fragment.firstChild; node; node = node.firstChild) { + if (node.nodeName === 'LI' && editor.dom.isEmpty(node)) { + DOM.remove(node); + break; + } + } + if (!editor.dom.isEmpty(fragment)) { + DOM.insertAfter(fragment, ul); + } + DOM.insertAfter(newBlock, ul); + if (isEmpty(editor.dom, li.parentNode)) { + removeAndKeepBookmarks(li.parentNode); + } + DOM.remove(li); + if (isEmpty(editor.dom, ul)) { + DOM.remove(ul); + } + }; + + var outdentDlItem = function (editor, item) { + if (is$1(item, 'dd')) { + mutate(item, 'dt'); + } else if (is$1(item, 'dt')) { + parent(item).each(function (dl) { + return splitList(editor, dl.dom, item.dom); + }); + } + }; + var indentDlItem = function (item) { + if (is$1(item, 'dt')) { + mutate(item, 'dd'); + } + }; + var dlIndentation = function (editor, indentation, dlItems) { + if (indentation === 'Indent') { + each(dlItems, indentDlItem); + } else { + each(dlItems, function (item) { + return outdentDlItem(editor, item); + }); + } + }; + + var getNormalizedPoint = function (container, offset) { + if (isTextNode(container)) { + return { + container: container, + offset: offset + }; + } + var node = global$1.getNode(container, offset); + if (isTextNode(node)) { + return { + container: node, + offset: offset >= container.childNodes.length ? node.data.length : 0 + }; + } else if (node.previousSibling && isTextNode(node.previousSibling)) { + return { + container: node.previousSibling, + offset: node.previousSibling.data.length + }; + } else if (node.nextSibling && isTextNode(node.nextSibling)) { + return { + container: node.nextSibling, + offset: 0 + }; + } + return { + container: container, + offset: offset + }; + }; + var normalizeRange = function (rng) { + var outRng = rng.cloneRange(); + var rangeStart = getNormalizedPoint(rng.startContainer, rng.startOffset); + outRng.setStart(rangeStart.container, rangeStart.offset); + var rangeEnd = getNormalizedPoint(rng.endContainer, rng.endOffset); + outRng.setEnd(rangeEnd.container, rangeEnd.offset); + return outRng; + }; + + var global$6 = tinymce.util.Tools.resolve('tinymce.dom.DomQuery'); + + var getParentList = function (editor, node) { + var selectionStart = node || editor.selection.getStart(true); + return editor.dom.getParent(selectionStart, 'OL,UL,DL', getClosestListRootElm(editor, selectionStart)); + }; + var isParentListSelected = function (parentList, selectedBlocks) { + return parentList && selectedBlocks.length === 1 && selectedBlocks[0] === parentList; + }; + var findSubLists = function (parentList) { + return global$5.grep(parentList.querySelectorAll('ol,ul,dl'), function (elm) { + return isListNode(elm); + }); + }; + var getSelectedSubLists = function (editor) { + var parentList = getParentList(editor); + var selectedBlocks = editor.selection.getSelectedBlocks(); + if (isParentListSelected(parentList, selectedBlocks)) { + return findSubLists(parentList); + } else { + return global$5.grep(selectedBlocks, function (elm) { + return isListNode(elm) && parentList !== elm; + }); + } + }; + var findParentListItemsNodes = function (editor, elms) { + var listItemsElms = global$5.map(elms, function (elm) { + var parentLi = editor.dom.getParent(elm, 'li,dd,dt', getClosestListRootElm(editor, elm)); + return parentLi ? parentLi : elm; + }); + return global$6.unique(listItemsElms); + }; + var getSelectedListItems = function (editor) { + var selectedBlocks = editor.selection.getSelectedBlocks(); + return global$5.grep(findParentListItemsNodes(editor, selectedBlocks), function (block) { + return isListItemNode(block); + }); + }; + var getSelectedDlItems = function (editor) { + return filter(getSelectedListItems(editor), isDlItemNode); + }; + var getClosestListRootElm = function (editor, elm) { + var parentTableCell = editor.dom.getParents(elm, 'TD,TH'); + var root = parentTableCell.length > 0 ? parentTableCell[0] : editor.getBody(); + return root; + }; + var findLastParentListNode = function (editor, elm) { + var parentLists = editor.dom.getParents(elm, 'ol,ul', getClosestListRootElm(editor, elm)); + return last(parentLists); + }; + var getSelectedLists = function (editor) { + var firstList = findLastParentListNode(editor, editor.selection.getStart()); + var subsequentLists = filter(editor.selection.getSelectedBlocks(), isOlUlNode); + return firstList.toArray().concat(subsequentLists); + }; + var getSelectedListRoots = function (editor) { + var selectedLists = getSelectedLists(editor); + return getUniqueListRoots(editor, selectedLists); + }; + var getUniqueListRoots = function (editor, lists) { + var listRoots = map(lists, function (list) { + return findLastParentListNode(editor, list).getOr(list); + }); + return global$6.unique(listRoots); + }; + + var lift2 = function (oa, ob, f) { + return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none(); + }; + + var fromElements = function (elements, scope) { + var doc = scope || document; + var fragment = doc.createDocumentFragment(); + each(elements, function (element) { + fragment.appendChild(element.dom); + }); + return SugarElement.fromDom(fragment); + }; + + var fireListEvent = function (editor, action, element) { + return editor.fire('ListMutation', { + action: action, + element: element + }); + }; + + var isSupported = function (dom) { + return dom.style !== undefined && isFunction(dom.style.getPropertyValue); + }; + + var internalSet = function (dom, property, value) { + if (!isString(value)) { + console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom); + throw new Error('CSS value must be a string: ' + value); + } + if (isSupported(dom)) { + dom.style.setProperty(property, value); + } + }; + var set = function (element, property, value) { + var dom = element.dom; + internalSet(dom, property, value); + }; + + var joinSegment = function (parent, child) { + append(parent.item, child.list); + }; + var joinSegments = function (segments) { + for (var i = 1; i < segments.length; i++) { + joinSegment(segments[i - 1], segments[i]); + } + }; + var appendSegments = function (head$1, tail) { + lift2(last(head$1), head(tail), joinSegment); + }; + var createSegment = function (scope, listType) { + var segment = { + list: SugarElement.fromTag(listType, scope), + item: SugarElement.fromTag('li', scope) + }; + append(segment.list, segment.item); + return segment; + }; + var createSegments = function (scope, entry, size) { + var segments = []; + for (var i = 0; i < size; i++) { + segments.push(createSegment(scope, entry.listType)); + } + return segments; + }; + var populateSegments = function (segments, entry) { + for (var i = 0; i < segments.length - 1; i++) { + set(segments[i].item, 'list-style-type', 'none'); + } + last(segments).each(function (segment) { + setAll(segment.list, entry.listAttributes); + setAll(segment.item, entry.itemAttributes); + append$1(segment.item, entry.content); + }); + }; + var normalizeSegment = function (segment, entry) { + if (name(segment.list) !== entry.listType) { + segment.list = mutate(segment.list, entry.listType); + } + setAll(segment.list, entry.listAttributes); + }; + var createItem = function (scope, attr, content) { + var item = SugarElement.fromTag('li', scope); + setAll(item, attr); + append$1(item, content); + return item; + }; + var appendItem = function (segment, item) { + append(segment.list, item); + segment.item = item; + }; + var writeShallow = function (scope, cast, entry) { + var newCast = cast.slice(0, entry.depth); + last(newCast).each(function (segment) { + var item = createItem(scope, entry.itemAttributes, entry.content); + appendItem(segment, item); + normalizeSegment(segment, entry); + }); + return newCast; + }; + var writeDeep = function (scope, cast, entry) { + var segments = createSegments(scope, entry, entry.depth - cast.length); + joinSegments(segments); + populateSegments(segments, entry); + appendSegments(cast, segments); + return cast.concat(segments); + }; + var composeList = function (scope, entries) { + var cast = foldl(entries, function (cast, entry) { + return entry.depth > cast.length ? writeDeep(scope, cast, entry) : writeShallow(scope, cast, entry); + }, []); + return head(cast).map(function (segment) { + return segment.list; + }); + }; + + var isList = function (el) { + return is$1(el, 'OL,UL'); + }; + var hasFirstChildList = function (el) { + return firstChild(el).map(isList).getOr(false); + }; + var hasLastChildList = function (el) { + return lastChild(el).map(isList).getOr(false); + }; + + var isIndented = function (entry) { + return entry.depth > 0; + }; + var isSelected = function (entry) { + return entry.isSelected; + }; + var cloneItemContent = function (li) { + var children$1 = children(li); + var content = hasLastChildList(li) ? children$1.slice(0, -1) : children$1; + return map(content, deep); + }; + var createEntry = function (li, depth, isSelected) { + return parent(li).filter(isElement).map(function (list) { + return { + depth: depth, + dirty: false, + isSelected: isSelected, + content: cloneItemContent(li), + itemAttributes: clone(li), + listAttributes: clone(list), + listType: name(list) + }; + }); + }; + + var indentEntry = function (indentation, entry) { + switch (indentation) { + case 'Indent': + entry.depth++; + break; + case 'Outdent': + entry.depth--; + break; + case 'Flatten': + entry.depth = 0; + } + entry.dirty = true; + }; + + var cloneListProperties = function (target, source) { + target.listType = source.listType; + target.listAttributes = __assign({}, source.listAttributes); + }; + var cleanListProperties = function (entry) { + entry.listAttributes = filter$1(entry.listAttributes, function (_value, key) { + return key !== 'start'; + }); + }; + var closestSiblingEntry = function (entries, start) { + var depth = entries[start].depth; + var matches = function (entry) { + return entry.depth === depth && !entry.dirty; + }; + var until = function (entry) { + return entry.depth < depth; + }; + return findUntil(reverse(entries.slice(0, start)), matches, until).orThunk(function () { + return findUntil(entries.slice(start + 1), matches, until); + }); + }; + var normalizeEntries = function (entries) { + each(entries, function (entry, i) { + closestSiblingEntry(entries, i).fold(function () { + if (entry.dirty) { + cleanListProperties(entry); + } + }, function (matchingEntry) { + return cloneListProperties(entry, matchingEntry); + }); + }); + return entries; + }; + + var Cell = function (initial) { + var value = initial; + var get = function () { + return value; + }; + var set = function (v) { + value = v; + }; + return { + get: get, + set: set + }; + }; + + var parseItem = function (depth, itemSelection, selectionState, item) { + return firstChild(item).filter(isList).fold(function () { + itemSelection.each(function (selection) { + if (eq(selection.start, item)) { + selectionState.set(true); + } + }); + var currentItemEntry = createEntry(item, depth, selectionState.get()); + itemSelection.each(function (selection) { + if (eq(selection.end, item)) { + selectionState.set(false); + } + }); + var childListEntries = lastChild(item).filter(isList).map(function (list) { + return parseList(depth, itemSelection, selectionState, list); + }).getOr([]); + return currentItemEntry.toArray().concat(childListEntries); + }, function (list) { + return parseList(depth, itemSelection, selectionState, list); + }); + }; + var parseList = function (depth, itemSelection, selectionState, list) { + return bind(children(list), function (element) { + var parser = isList(element) ? parseList : parseItem; + var newDepth = depth + 1; + return parser(newDepth, itemSelection, selectionState, element); + }); + }; + var parseLists = function (lists, itemSelection) { + var selectionState = Cell(false); + var initialDepth = 0; + return map(lists, function (list) { + return { + sourceList: list, + entries: parseList(initialDepth, itemSelection, selectionState, list) + }; + }); + }; + + var outdentedComposer = function (editor, entries) { + var normalizedEntries = normalizeEntries(entries); + return map(normalizedEntries, function (entry) { + var content = fromElements(entry.content); + return SugarElement.fromDom(createTextBlock(editor, content.dom)); + }); + }; + var indentedComposer = function (editor, entries) { + var normalizedEntries = normalizeEntries(entries); + return composeList(editor.contentDocument, normalizedEntries).toArray(); + }; + var composeEntries = function (editor, entries) { + return bind(groupBy(entries, isIndented), function (entries) { + var groupIsIndented = head(entries).map(isIndented).getOr(false); + return groupIsIndented ? indentedComposer(editor, entries) : outdentedComposer(editor, entries); + }); + }; + var indentSelectedEntries = function (entries, indentation) { + each(filter(entries, isSelected), function (entry) { + return indentEntry(indentation, entry); + }); + }; + var getItemSelection = function (editor) { + var selectedListItems = map(getSelectedListItems(editor), SugarElement.fromDom); + return lift2(find(selectedListItems, not(hasFirstChildList)), find(reverse(selectedListItems), not(hasFirstChildList)), function (start, end) { + return { + start: start, + end: end + }; + }); + }; + var listIndentation = function (editor, lists, indentation) { + var entrySets = parseLists(lists, getItemSelection(editor)); + each(entrySets, function (entrySet) { + indentSelectedEntries(entrySet.entries, indentation); + var composedLists = composeEntries(editor, entrySet.entries); + each(composedLists, function (composedList) { + fireListEvent(editor, indentation === 'Indent' ? 'IndentList' : 'OutdentList', composedList.dom); + }); + before$1(entrySet.sourceList, composedLists); + remove(entrySet.sourceList); + }); + }; + + var selectionIndentation = function (editor, indentation) { + var lists = map(getSelectedListRoots(editor), SugarElement.fromDom); + var dlItems = map(getSelectedDlItems(editor), SugarElement.fromDom); + var isHandled = false; + if (lists.length || dlItems.length) { + var bookmark = editor.selection.getBookmark(); + listIndentation(editor, lists, indentation); + dlIndentation(editor, indentation, dlItems); + editor.selection.moveToBookmark(bookmark); + editor.selection.setRng(normalizeRange(editor.selection.getRng())); + editor.nodeChanged(); + isHandled = true; + } + return isHandled; + }; + var indentListSelection = function (editor) { + return selectionIndentation(editor, 'Indent'); + }; + var outdentListSelection = function (editor) { + return selectionIndentation(editor, 'Outdent'); + }; + var flattenListSelection = function (editor) { + return selectionIndentation(editor, 'Flatten'); + }; + + var global$7 = tinymce.util.Tools.resolve('tinymce.dom.BookmarkManager'); + + var DOM$1 = global$4.DOM; + var createBookmark = function (rng) { + var bookmark = {}; + var setupEndPoint = function (start) { + var offsetNode, container, offset; + container = rng[start ? 'startContainer' : 'endContainer']; + offset = rng[start ? 'startOffset' : 'endOffset']; + if (container.nodeType === 1) { + offsetNode = DOM$1.create('span', { 'data-mce-type': 'bookmark' }); + if (container.hasChildNodes()) { + offset = Math.min(offset, container.childNodes.length - 1); + if (start) { + container.insertBefore(offsetNode, container.childNodes[offset]); + } else { + DOM$1.insertAfter(offsetNode, container.childNodes[offset]); + } + } else { + container.appendChild(offsetNode); + } + container = offsetNode; + offset = 0; + } + bookmark[start ? 'startContainer' : 'endContainer'] = container; + bookmark[start ? 'startOffset' : 'endOffset'] = offset; + }; + setupEndPoint(true); + if (!rng.collapsed) { + setupEndPoint(); + } + return bookmark; + }; + var resolveBookmark = function (bookmark) { + function restoreEndPoint(start) { + var container, offset, node; + var nodeIndex = function (container) { + var node = container.parentNode.firstChild, idx = 0; + while (node) { + if (node === container) { + return idx; + } + if (node.nodeType !== 1 || node.getAttribute('data-mce-type') !== 'bookmark') { + idx++; + } + node = node.nextSibling; + } + return -1; + }; + container = node = bookmark[start ? 'startContainer' : 'endContainer']; + offset = bookmark[start ? 'startOffset' : 'endOffset']; + if (!container) { + return; + } + if (container.nodeType === 1) { + offset = nodeIndex(container); + container = container.parentNode; + DOM$1.remove(node); + if (!container.hasChildNodes() && DOM$1.isBlock(container)) { + container.appendChild(DOM$1.create('br')); + } + } + bookmark[start ? 'startContainer' : 'endContainer'] = container; + bookmark[start ? 'startOffset' : 'endOffset'] = offset; + } + restoreEndPoint(true); + restoreEndPoint(); + var rng = DOM$1.createRng(); + rng.setStart(bookmark.startContainer, bookmark.startOffset); + if (bookmark.endContainer) { + rng.setEnd(bookmark.endContainer, bookmark.endOffset); + } + return normalizeRange(rng); + }; + + var listToggleActionFromListName = function (listName) { + switch (listName) { + case 'UL': + return 'ToggleUlList'; + case 'OL': + return 'ToggleOlList'; + case 'DL': + return 'ToggleDLList'; + } + }; + + var isCustomList = function (list) { + return /\btox\-/.test(list.className); + }; + var listState = function (editor, listName, activate) { + var nodeChangeHandler = function (e) { + var inList = findUntil(e.parents, isListNode, isTableCellNode).filter(function (list) { + return list.nodeName === listName && !isCustomList(list); + }).isSome(); + activate(inList); + }; + var parents = editor.dom.getParents(editor.selection.getNode()); + nodeChangeHandler({ parents: parents }); + editor.on('NodeChange', nodeChangeHandler); + return function () { + return editor.off('NodeChange', nodeChangeHandler); + }; + }; + + var updateListStyle = function (dom, el, detail) { + var type = detail['list-style-type'] ? detail['list-style-type'] : null; + dom.setStyle(el, 'list-style-type', type); + }; + var setAttribs = function (elm, attrs) { + global$5.each(attrs, function (value, key) { + elm.setAttribute(key, value); + }); + }; + var updateListAttrs = function (dom, el, detail) { + setAttribs(el, detail['list-attributes']); + global$5.each(dom.select('li', el), function (li) { + setAttribs(li, detail['list-item-attributes']); + }); + }; + var updateListWithDetails = function (dom, el, detail) { + updateListStyle(dom, el, detail); + updateListAttrs(dom, el, detail); + }; + var removeStyles = function (dom, element, styles) { + global$5.each(styles, function (style) { + var _a; + return dom.setStyle(element, (_a = {}, _a[style] = '', _a)); + }); + }; + var getEndPointNode = function (editor, rng, start, root) { + var container = rng[start ? 'startContainer' : 'endContainer']; + var offset = rng[start ? 'startOffset' : 'endOffset']; + if (container.nodeType === 1) { + container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; + } + if (!start && isBr(container.nextSibling)) { + container = container.nextSibling; + } + while (container.parentNode !== root) { + if (isTextBlock(editor, container)) { + return container; + } + if (/^(TD|TH)$/.test(container.parentNode.nodeName)) { + return container; + } + container = container.parentNode; + } + return container; + }; + var getSelectedTextBlocks = function (editor, rng, root) { + var textBlocks = [], dom = editor.dom; + var startNode = getEndPointNode(editor, rng, true, root); + var endNode = getEndPointNode(editor, rng, false, root); + var block; + var siblings = []; + for (var node = startNode; node; node = node.nextSibling) { + siblings.push(node); + if (node === endNode) { + break; + } + } + global$5.each(siblings, function (node) { + if (isTextBlock(editor, node)) { + textBlocks.push(node); + block = null; + return; + } + if (dom.isBlock(node) || isBr(node)) { + if (isBr(node)) { + dom.remove(node); + } + block = null; + return; + } + var nextSibling = node.nextSibling; + if (global$7.isBookmarkNode(node)) { + if (isTextBlock(editor, nextSibling) || !nextSibling && node.parentNode === root) { + block = null; + return; + } + } + if (!block) { + block = dom.create('p'); + node.parentNode.insertBefore(block, node); + textBlocks.push(block); + } + block.appendChild(node); + }); + return textBlocks; + }; + var hasCompatibleStyle = function (dom, sib, detail) { + var sibStyle = dom.getStyle(sib, 'list-style-type'); + var detailStyle = detail ? detail['list-style-type'] : ''; + detailStyle = detailStyle === null ? '' : detailStyle; + return sibStyle === detailStyle; + }; + var applyList = function (editor, listName, detail) { + if (detail === void 0) { + detail = {}; + } + var rng = editor.selection.getRng(); + var listItemName = 'LI'; + var root = getClosestListRootElm(editor, editor.selection.getStart(true)); + var dom = editor.dom; + if (dom.getContentEditable(editor.selection.getNode()) === 'false') { + return; + } + listName = listName.toUpperCase(); + if (listName === 'DL') { + listItemName = 'DT'; + } + var bookmark = createBookmark(rng); + global$5.each(getSelectedTextBlocks(editor, rng, root), function (block) { + var listBlock; + var sibling = block.previousSibling; + if (sibling && isListNode(sibling) && sibling.nodeName === listName && hasCompatibleStyle(dom, sibling, detail)) { + listBlock = sibling; + block = dom.rename(block, listItemName); + sibling.appendChild(block); + } else { + listBlock = dom.create(listName); + block.parentNode.insertBefore(listBlock, block); + listBlock.appendChild(block); + block = dom.rename(block, listItemName); + } + removeStyles(dom, block, [ + 'margin', + 'margin-right', + 'margin-bottom', + 'margin-left', + 'margin-top', + 'padding', + 'padding-right', + 'padding-bottom', + 'padding-left', + 'padding-top' + ]); + updateListWithDetails(dom, listBlock, detail); + mergeWithAdjacentLists(editor.dom, listBlock); + }); + editor.selection.setRng(resolveBookmark(bookmark)); + }; + var isValidLists = function (list1, list2) { + return list1 && list2 && isListNode(list1) && list1.nodeName === list2.nodeName; + }; + var hasSameListStyle = function (dom, list1, list2) { + var targetStyle = dom.getStyle(list1, 'list-style-type', true); + var style = dom.getStyle(list2, 'list-style-type', true); + return targetStyle === style; + }; + var hasSameClasses = function (elm1, elm2) { + return elm1.className === elm2.className; + }; + var shouldMerge = function (dom, list1, list2) { + return isValidLists(list1, list2) && hasSameListStyle(dom, list1, list2) && hasSameClasses(list1, list2); + }; + var mergeWithAdjacentLists = function (dom, listBlock) { + var sibling, node; + sibling = listBlock.nextSibling; + if (shouldMerge(dom, listBlock, sibling)) { + while (node = sibling.firstChild) { + listBlock.appendChild(node); + } + dom.remove(sibling); + } + sibling = listBlock.previousSibling; + if (shouldMerge(dom, listBlock, sibling)) { + while (node = sibling.lastChild) { + listBlock.insertBefore(node, listBlock.firstChild); + } + dom.remove(sibling); + } + }; + var updateList = function (editor, list, listName, detail) { + if (list.nodeName !== listName) { + var newList = editor.dom.rename(list, listName); + updateListWithDetails(editor.dom, newList, detail); + fireListEvent(editor, listToggleActionFromListName(listName), newList); + } else { + updateListWithDetails(editor.dom, list, detail); + fireListEvent(editor, listToggleActionFromListName(listName), list); + } + }; + var toggleMultipleLists = function (editor, parentList, lists, listName, detail) { + if (parentList.nodeName === listName && !hasListStyleDetail(detail)) { + flattenListSelection(editor); + } else { + var bookmark = createBookmark(editor.selection.getRng(true)); + global$5.each([parentList].concat(lists), function (elm) { + updateList(editor, elm, listName, detail); + }); + editor.selection.setRng(resolveBookmark(bookmark)); + } + }; + var hasListStyleDetail = function (detail) { + return 'list-style-type' in detail; + }; + var toggleSingleList = function (editor, parentList, listName, detail) { + if (parentList === editor.getBody()) { + return; + } + if (parentList) { + if (parentList.nodeName === listName && !hasListStyleDetail(detail) && !isCustomList(parentList)) { + flattenListSelection(editor); + } else { + var bookmark = createBookmark(editor.selection.getRng(true)); + updateListWithDetails(editor.dom, parentList, detail); + var newList = editor.dom.rename(parentList, listName); + mergeWithAdjacentLists(editor.dom, newList); + editor.selection.setRng(resolveBookmark(bookmark)); + fireListEvent(editor, listToggleActionFromListName(listName), newList); + } + } else { + applyList(editor, listName, detail); + fireListEvent(editor, listToggleActionFromListName(listName), parentList); + } + }; + var toggleList = function (editor, listName, detail) { + var parentList = getParentList(editor); + var selectedSubLists = getSelectedSubLists(editor); + detail = detail ? detail : {}; + if (parentList && selectedSubLists.length > 0) { + toggleMultipleLists(editor, parentList, selectedSubLists, listName, detail); + } else { + toggleSingleList(editor, parentList, listName, detail); + } + }; + + var DOM$2 = global$4.DOM; + var normalizeList = function (dom, ul) { + var sibling; + var parentNode = ul.parentNode; + if (parentNode.nodeName === 'LI' && parentNode.firstChild === ul) { + sibling = parentNode.previousSibling; + if (sibling && sibling.nodeName === 'LI') { + sibling.appendChild(ul); + if (isEmpty(dom, parentNode)) { + DOM$2.remove(parentNode); + } + } else { + DOM$2.setStyle(parentNode, 'listStyleType', 'none'); + } + } + if (isListNode(parentNode)) { + sibling = parentNode.previousSibling; + if (sibling && sibling.nodeName === 'LI') { + sibling.appendChild(ul); + } + } + }; + var normalizeLists = function (dom, element) { + global$5.each(global$5.grep(dom.select('ol,ul', element)), function (ul) { + normalizeList(dom, ul); + }); + }; + + var findNextCaretContainer = function (editor, rng, isForward, root) { + var node = rng.startContainer; + var offset = rng.startOffset; + if (isTextNode(node) && (isForward ? offset < node.data.length : offset > 0)) { + return node; + } + var nonEmptyBlocks = editor.schema.getNonEmptyElements(); + if (node.nodeType === 1) { + node = global$1.getNode(node, offset); + } + var walker = new global$2(node, root); + if (isForward) { + if (isBogusBr(editor.dom, node)) { + walker.next(); + } + } + while (node = walker[isForward ? 'next' : 'prev2']()) { + if (node.nodeName === 'LI' && !node.hasChildNodes()) { + return node; + } + if (nonEmptyBlocks[node.nodeName]) { + return node; + } + if (isTextNode(node) && node.data.length > 0) { + return node; + } + } + }; + var hasOnlyOneBlockChild = function (dom, elm) { + var childNodes = elm.childNodes; + return childNodes.length === 1 && !isListNode(childNodes[0]) && dom.isBlock(childNodes[0]); + }; + var unwrapSingleBlockChild = function (dom, elm) { + if (hasOnlyOneBlockChild(dom, elm)) { + dom.remove(elm.firstChild, true); + } + }; + var moveChildren = function (dom, fromElm, toElm) { + var node; + var targetElm = hasOnlyOneBlockChild(dom, toElm) ? toElm.firstChild : toElm; + unwrapSingleBlockChild(dom, fromElm); + if (!isEmpty(dom, fromElm, true)) { + while (node = fromElm.firstChild) { + targetElm.appendChild(node); + } + } + }; + var mergeLiElements = function (dom, fromElm, toElm) { + var listNode; + var ul = fromElm.parentNode; + if (!isChildOfBody(dom, fromElm) || !isChildOfBody(dom, toElm)) { + return; + } + if (isListNode(toElm.lastChild)) { + listNode = toElm.lastChild; + } + if (ul === toElm.lastChild) { + if (isBr(ul.previousSibling)) { + dom.remove(ul.previousSibling); + } + } + var node = toElm.lastChild; + if (node && isBr(node) && fromElm.hasChildNodes()) { + dom.remove(node); + } + if (isEmpty(dom, toElm, true)) { + dom.$(toElm).empty(); + } + moveChildren(dom, fromElm, toElm); + if (listNode) { + toElm.appendChild(listNode); + } + var contains = contains$1(SugarElement.fromDom(toElm), SugarElement.fromDom(fromElm)); + var nestedLists = contains ? dom.getParents(fromElm, isListNode, toElm) : []; + dom.remove(fromElm); + each(nestedLists, function (list) { + if (isEmpty(dom, list) && list !== dom.getRoot()) { + dom.remove(list); + } + }); + }; + var mergeIntoEmptyLi = function (editor, fromLi, toLi) { + editor.dom.$(toLi).empty(); + mergeLiElements(editor.dom, fromLi, toLi); + editor.selection.setCursorLocation(toLi); + }; + var mergeForward = function (editor, rng, fromLi, toLi) { + var dom = editor.dom; + if (dom.isEmpty(toLi)) { + mergeIntoEmptyLi(editor, fromLi, toLi); + } else { + var bookmark = createBookmark(rng); + mergeLiElements(dom, fromLi, toLi); + editor.selection.setRng(resolveBookmark(bookmark)); + } + }; + var mergeBackward = function (editor, rng, fromLi, toLi) { + var bookmark = createBookmark(rng); + mergeLiElements(editor.dom, fromLi, toLi); + var resolvedBookmark = resolveBookmark(bookmark); + editor.selection.setRng(resolvedBookmark); + }; + var backspaceDeleteFromListToListCaret = function (editor, isForward) { + var dom = editor.dom, selection = editor.selection; + var selectionStartElm = selection.getStart(); + var root = getClosestListRootElm(editor, selectionStartElm); + var li = dom.getParent(selection.getStart(), 'LI', root); + if (li) { + var ul = li.parentNode; + if (ul === editor.getBody() && isEmpty(dom, ul)) { + return true; + } + var rng_1 = normalizeRange(selection.getRng()); + var otherLi_1 = dom.getParent(findNextCaretContainer(editor, rng_1, isForward, root), 'LI', root); + if (otherLi_1 && otherLi_1 !== li) { + editor.undoManager.transact(function () { + if (isForward) { + mergeForward(editor, rng_1, otherLi_1, li); + } else { + if (isFirstChild(li)) { + outdentListSelection(editor); + } else { + mergeBackward(editor, rng_1, li, otherLi_1); + } + } + }); + return true; + } else if (!otherLi_1) { + if (!isForward && rng_1.startOffset === 0 && rng_1.endOffset === 0) { + editor.undoManager.transact(function () { + flattenListSelection(editor); + }); + return true; + } + } + } + return false; + }; + var removeBlock = function (dom, block, root) { + var parentBlock = dom.getParent(block.parentNode, dom.isBlock, root); + dom.remove(block); + if (parentBlock && dom.isEmpty(parentBlock)) { + dom.remove(parentBlock); + } + }; + var backspaceDeleteIntoListCaret = function (editor, isForward) { + var dom = editor.dom; + var selectionStartElm = editor.selection.getStart(); + var root = getClosestListRootElm(editor, selectionStartElm); + var block = dom.getParent(selectionStartElm, dom.isBlock, root); + if (block && dom.isEmpty(block)) { + var rng = normalizeRange(editor.selection.getRng()); + var otherLi_2 = dom.getParent(findNextCaretContainer(editor, rng, isForward, root), 'LI', root); + if (otherLi_2) { + editor.undoManager.transact(function () { + removeBlock(dom, block, root); + mergeWithAdjacentLists(dom, otherLi_2.parentNode); + editor.selection.select(otherLi_2, true); + editor.selection.collapse(isForward); + }); + return true; + } + } + return false; + }; + var backspaceDeleteCaret = function (editor, isForward) { + return backspaceDeleteFromListToListCaret(editor, isForward) || backspaceDeleteIntoListCaret(editor, isForward); + }; + var backspaceDeleteRange = function (editor) { + var selectionStartElm = editor.selection.getStart(); + var root = getClosestListRootElm(editor, selectionStartElm); + var startListParent = editor.dom.getParent(selectionStartElm, 'LI,DT,DD', root); + if (startListParent || getSelectedListItems(editor).length > 0) { + editor.undoManager.transact(function () { + editor.execCommand('Delete'); + normalizeLists(editor.dom, editor.getBody()); + }); + return true; + } + return false; + }; + var backspaceDelete = function (editor, isForward) { + return editor.selection.isCollapsed() ? backspaceDeleteCaret(editor, isForward) : backspaceDeleteRange(editor); + }; + var setup = function (editor) { + editor.on('keydown', function (e) { + if (e.keyCode === global$3.BACKSPACE) { + if (backspaceDelete(editor, false)) { + e.preventDefault(); + } + } else if (e.keyCode === global$3.DELETE) { + if (backspaceDelete(editor, true)) { + e.preventDefault(); + } + } + }); + }; + + var get = function (editor) { + return { + backspaceDelete: function (isForward) { + backspaceDelete(editor, isForward); + } + }; + }; + + var open = function (editor) { + var dom = editor.dom; + var currentList = getParentList(editor); + if (!isOlNode(currentList)) { + return; + } + editor.windowManager.open({ + title: 'List Properties', + body: { + type: 'panel', + items: [{ + type: 'input', + name: 'start', + label: 'Start list at number', + inputMode: 'numeric' + }] + }, + initialData: { start: dom.getAttrib(currentList, 'start') || '1' }, + buttons: [ + { + type: 'cancel', + name: 'cancel', + text: 'Cancel' + }, + { + type: 'submit', + name: 'save', + text: 'Save', + primary: true + } + ], + onSubmit: function (api) { + var data = api.getData(); + editor.undoManager.transact(function () { + dom.setAttrib(getParentList(editor), 'start', data.start === '1' ? '' : data.start); + }); + api.close(); + } + }); + }; + + var queryListCommandState = function (editor, listName) { + return function () { + var parentList = editor.dom.getParent(editor.selection.getStart(), 'UL,OL,DL'); + return parentList && parentList.nodeName === listName; + }; + }; + var register = function (editor) { + editor.on('BeforeExecCommand', function (e) { + var cmd = e.command.toLowerCase(); + if (cmd === 'indent') { + indentListSelection(editor); + } else if (cmd === 'outdent') { + outdentListSelection(editor); + } + }); + editor.addCommand('InsertUnorderedList', function (ui, detail) { + toggleList(editor, 'UL', detail); + }); + editor.addCommand('InsertOrderedList', function (ui, detail) { + toggleList(editor, 'OL', detail); + }); + editor.addCommand('InsertDefinitionList', function (ui, detail) { + toggleList(editor, 'DL', detail); + }); + editor.addCommand('RemoveList', function () { + flattenListSelection(editor); + }); + editor.addCommand('mceListProps', function () { + open(editor); + }); + editor.addQueryStateHandler('InsertUnorderedList', queryListCommandState(editor, 'UL')); + editor.addQueryStateHandler('InsertOrderedList', queryListCommandState(editor, 'OL')); + editor.addQueryStateHandler('InsertDefinitionList', queryListCommandState(editor, 'DL')); + }; + + var setupTabKey = function (editor) { + editor.on('keydown', function (e) { + if (e.keyCode !== global$3.TAB || global$3.metaKeyPressed(e)) { + return; + } + editor.undoManager.transact(function () { + if (e.shiftKey ? outdentListSelection(editor) : indentListSelection(editor)) { + e.preventDefault(); + } + }); + }); + }; + var setup$1 = function (editor) { + if (shouldIndentOnTab(editor)) { + setupTabKey(editor); + } + setup(editor); + }; + + var register$1 = function (editor) { + var exec = function (command) { + return function () { + return editor.execCommand(command); + }; + }; + if (!editor.hasPlugin('advlist')) { + editor.ui.registry.addToggleButton('numlist', { + icon: 'ordered-list', + active: false, + tooltip: 'Numbered list', + onAction: exec('InsertOrderedList'), + onSetup: function (api) { + return listState(editor, 'OL', api.setActive); + } + }); + editor.ui.registry.addToggleButton('bullist', { + icon: 'unordered-list', + active: false, + tooltip: 'Bullet list', + onAction: exec('InsertUnorderedList'), + onSetup: function (api) { + return listState(editor, 'UL', api.setActive); + } + }); + } + }; + + var register$2 = function (editor) { + var listProperties = { + text: 'List properties...', + icon: 'ordered-list', + onAction: function () { + return open(editor); + }, + onSetup: function (api) { + return listState(editor, 'OL', function (active) { + return api.setDisabled(!active); + }); + } + }; + editor.ui.registry.addMenuItem('listprops', listProperties); + editor.ui.registry.addContextMenu('lists', { + update: function (node) { + var parentList = getParentList(editor, node); + return isOlNode(parentList) ? ['listprops'] : []; + } + }); + }; + + function Plugin () { + global.add('lists', function (editor) { + if (editor.hasPlugin('rtc', true) === false) { + setup$1(editor); + register(editor); + } + register$1(editor); + register$2(editor); + return get(editor); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js index 4391553061..01a36ea7ea 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/lists/plugin.min.js @@ -1 +1,9 @@ -tinymce.PluginManager.add("lists",function(e){function t(e){return e&&/^(OL|UL)$/.test(e.nodeName)}function n(e){return e.parentNode.firstChild==e}function r(e){return e.parentNode.lastChild==e}function o(t){return t&&!!e.schema.getTextBlockElements()[t.nodeName]}function i(e){return e&&"SPAN"===e.nodeName&&"bookmark"===e.getAttribute("data-mce-type")}var a=this;e.on("init",function(){function d(e){function t(t){var r,o,i;o=e[t?"startContainer":"endContainer"],i=e[t?"startOffset":"endOffset"],1==o.nodeType&&(r=b.create("span",{"data-mce-type":"bookmark"}),o.hasChildNodes()?(i=Math.min(i,o.childNodes.length-1),t?o.insertBefore(r,o.childNodes[i]):b.insertAfter(r,o.childNodes[i])):o.appendChild(r),o=r,i=0),n[t?"startContainer":"endContainer"]=o,n[t?"startOffset":"endOffset"]=i}var n={};return t(!0),e.collapsed||t(),n}function s(e){function t(t){function n(e){for(var t=e.parentNode.firstChild,n=0;t;){if(t==e)return n;(1!=t.nodeType||"bookmark"!=t.getAttribute("data-mce-type"))&&n++,t=t.nextSibling}return-1}var r,o,i;r=i=e[t?"startContainer":"endContainer"],o=e[t?"startOffset":"endOffset"],r&&(1==r.nodeType&&(o=n(r),r=r.parentNode,b.remove(i)),e[t?"startContainer":"endContainer"]=r,e[t?"startOffset":"endOffset"]=o)}t(!0),t();var n=b.createRng();n.setStart(e.startContainer,e.startOffset),e.endContainer&&n.setEnd(e.endContainer,e.endOffset),L.setRng(n)}function f(t,n){var r,o,i,a=b.createFragment(),d=e.schema.getBlockElements();if(e.settings.forced_root_block&&(n=n||e.settings.forced_root_block),n&&(o=b.create(n),o.tagName===e.settings.forced_root_block&&b.setAttribs(o,e.settings.forced_root_block_attrs),a.appendChild(o)),t)for(;r=t.firstChild;){var s=r.nodeName;i||"SPAN"==s&&"bookmark"==r.getAttribute("data-mce-type")||(i=!0),d[s]?(a.appendChild(r),o=null):n?(o||(o=b.create(n),a.appendChild(o)),o.appendChild(r)):a.appendChild(r)}return e.settings.forced_root_block?i||tinymce.Env.ie&&!(tinymce.Env.ie>10)||o.appendChild(b.create("br",{"data-mce-bogus":"1"})):a.appendChild(b.create("br")),a}function l(){return tinymce.grep(L.getSelectedBlocks(),function(e){return"LI"==e.nodeName})}function c(e,t,n){var r,o,i=b.select('span[data-mce-type="bookmark"]',e);n=n||f(t),r=b.createRng(),r.setStartAfter(t),r.setEndAfter(e),o=r.extractContents(),b.isEmpty(o)||b.insertAfter(o,e),b.insertAfter(n,e),b.isEmpty(t.parentNode)&&(tinymce.each(i,function(e){t.parentNode.parentNode.insertBefore(e,t.parentNode)}),b.remove(t.parentNode)),b.remove(t)}function p(e){var n,r;if(n=e.nextSibling,n&&t(n)&&n.nodeName==e.nodeName){for(;r=n.firstChild;)e.appendChild(r);b.remove(n)}if(n=e.previousSibling,n&&t(n)&&n.nodeName==e.nodeName){for(;r=n.firstChild;)e.insertBefore(r,e.firstChild);b.remove(n)}}function u(e){tinymce.each(tinymce.grep(b.select("ol,ul",e)),function(e){var n,r=e.parentNode;"LI"==r.nodeName&&r.firstChild==e&&(n=r.previousSibling,n&&"LI"==n.nodeName&&(n.appendChild(e),b.isEmpty(r)&&b.remove(r))),t(r)&&(n=r.previousSibling,n&&"LI"==n.nodeName&&n.appendChild(e))})}function m(e){function o(e){b.isEmpty(e)&&b.remove(e)}var i,a=e.parentNode,d=a.parentNode;return n(e)&&r(e)?("LI"==d.nodeName?(b.insertAfter(e,d),o(d),b.remove(a)):t(d)?b.remove(a,!0):(d.insertBefore(f(e),a),b.remove(a)),!0):n(e)?("LI"==d.nodeName?(b.insertAfter(e,d),e.appendChild(a),o(d)):t(d)?d.insertBefore(e,a):(d.insertBefore(f(e),a),b.remove(e)),!0):r(e)?("LI"==d.nodeName?b.insertAfter(e,d):t(d)?b.insertAfter(e,a):(b.insertAfter(f(e),a),b.remove(e)),!0):("LI"==d.nodeName?(a=d,i=f(e,"LI")):i=t(d)?f(e,"LI"):f(e),c(a,e,i),u(a.parentNode),!0)}function h(e){function n(n,r){var o;if(t(n)){for(;o=e.lastChild.firstChild;)r.appendChild(o);b.remove(n)}}var r,o;return r=e.previousSibling,r&&t(r)?(r.appendChild(e),!0):r&&"LI"==r.nodeName&&t(r.lastChild)?(r.lastChild.appendChild(e),n(e.lastChild,r.lastChild),!0):(r=e.nextSibling,r&&t(r)?(r.insertBefore(e,r.firstChild),!0):r&&"LI"==r.nodeName&&t(e.lastChild)?!1:(r=e.previousSibling,r&&"LI"==r.nodeName?(o=b.create(e.parentNode.nodeName),r.appendChild(o),o.appendChild(e),n(e.lastChild,o),!0):!1))}function v(){var t=l();if(t.length){for(var n=d(L.getRng(!0)),r=0;r
/gi, '\n'); + rep(/
/gi, '\n'); + rep(/
/gi, '\n'); + rep(//gi, ''); + rep(/<\/p>/gi, '\n'); + rep(/ |\u00a0/gi, ' '); + rep(/"/gi, '"'); + rep(/</gi, '<'); + rep(/>/gi, '>'); + rep(/&/gi, '&'); + return s; + }; + var bbcode2html = function (s) { + s = global$1.trim(s); + var rep = function (re, str) { + s = s.replace(re, str); + }; + rep(/\n/gi, '
"}]},buttons:[{type:"cancel",text:"Close",primary:!0}],initialData:{pattern:"",results:[]}}),f.focus(x),f.unblock()}))};o.add("emoticons",function(n,t){var e,o,r,i,u,a,c,l=(o=t,(e=n).getParam("emoticons_database_url",o+"/js/emojis"+e.suffix+".js")),s=n.getParam("emoticons_database_id","tinymce.plugins.emoticons","string"),f=_(n,l,s);i=f,u=function(){return L(r,i)},(r=n).ui.registry.addButton("emoticons",{tooltip:"Emoticons",icon:"emoji",onAction:u}),r.ui.registry.addMenuItem("emoticons",{text:"Emoticons...",icon:"emoji",onAction:u}),c=f,(a=n).ui.registry.addAutocompleter("emoticons",{ch:":",columns:"auto",minChars:2,fetch:function(t,e){return c.waitForLoad().then(function(){var n=c.listAll();return P(n,t,y.some(e))})},onAction:function(n,t,e){a.selection.setRng(t),a.insertContent(e),n.hide()}})})}(); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/fullpage/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullpage/plugin.js new file mode 100644 index 0000000000..a38816220b --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullpage/plugin.js @@ -0,0 +1,544 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +(function () { + 'use strict'; + + var Cell = function (initial) { + var value = initial; + var get = function () { + return value; + }; + var set = function (v) { + value = v; + }; + return { + get: get, + set: set + }; + }; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var __assign = function () { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools'); + + var global$2 = tinymce.util.Tools.resolve('tinymce.html.DomParser'); + + var global$3 = tinymce.util.Tools.resolve('tinymce.html.Node'); + + var global$4 = tinymce.util.Tools.resolve('tinymce.html.Serializer'); + + var shouldHideInSourceView = function (editor) { + return editor.getParam('fullpage_hide_in_source_view'); + }; + var getDefaultXmlPi = function (editor) { + return editor.getParam('fullpage_default_xml_pi'); + }; + var getDefaultEncoding = function (editor) { + return editor.getParam('fullpage_default_encoding'); + }; + var getDefaultFontFamily = function (editor) { + return editor.getParam('fullpage_default_font_family'); + }; + var getDefaultFontSize = function (editor) { + return editor.getParam('fullpage_default_font_size'); + }; + var getDefaultTextColor = function (editor) { + return editor.getParam('fullpage_default_text_color'); + }; + var getDefaultTitle = function (editor) { + return editor.getParam('fullpage_default_title'); + }; + var getDefaultDocType = function (editor) { + return editor.getParam('fullpage_default_doctype', ''); + }; + var getProtect = function (editor) { + return editor.getParam('protect'); + }; + + var parseHeader = function (head) { + return global$2({ + validate: false, + root_name: '#document' + }).parse(head, { format: 'xhtml' }); + }; + var htmlToData = function (editor, head) { + var headerFragment = parseHeader(head); + var data = {}; + var elm, matches; + function getAttr(elm, name) { + var value = elm.attr(name); + return value || ''; + } + data.fontface = getDefaultFontFamily(editor); + data.fontsize = getDefaultFontSize(editor); + elm = headerFragment.firstChild; + if (elm.type === 7) { + data.xml_pi = true; + matches = /encoding="([^"]+)"/.exec(elm.value); + if (matches) { + data.docencoding = matches[1]; + } + } + elm = headerFragment.getAll('#doctype')[0]; + if (elm) { + data.doctype = ''; + } + elm = headerFragment.getAll('title')[0]; + if (elm && elm.firstChild) { + data.title = elm.firstChild.value; + } + global$1.each(headerFragment.getAll('meta'), function (meta) { + var name = meta.attr('name'); + var httpEquiv = meta.attr('http-equiv'); + var matches; + if (name) { + data[name.toLowerCase()] = meta.attr('content'); + } else if (httpEquiv === 'Content-Type') { + matches = /charset\s*=\s*(.*)\s*/gi.exec(meta.attr('content')); + if (matches) { + data.docencoding = matches[1]; + } + } + }); + elm = headerFragment.getAll('html')[0]; + if (elm) { + data.langcode = getAttr(elm, 'lang') || getAttr(elm, 'xml:lang'); + } + data.stylesheets = []; + global$1.each(headerFragment.getAll('link'), function (link) { + if (link.attr('rel') === 'stylesheet') { + data.stylesheets.push(link.attr('href')); + } + }); + elm = headerFragment.getAll('body')[0]; + if (elm) { + data.langdir = getAttr(elm, 'dir'); + data.style = getAttr(elm, 'style'); + data.visited_color = getAttr(elm, 'vlink'); + data.link_color = getAttr(elm, 'link'); + data.active_color = getAttr(elm, 'alink'); + } + return data; + }; + var dataToHtml = function (editor, data, head) { + var headElement, elm, value; + var dom = editor.dom; + function setAttr(elm, name, value) { + elm.attr(name, value ? value : undefined); + } + function addHeadNode(node) { + if (headElement.firstChild) { + headElement.insert(node, headElement.firstChild); + } else { + headElement.append(node); + } + } + var headerFragment = parseHeader(head); + headElement = headerFragment.getAll('head')[0]; + if (!headElement) { + elm = headerFragment.getAll('html')[0]; + headElement = new global$3('head', 1); + if (elm.firstChild) { + elm.insert(headElement, elm.firstChild, true); + } else { + elm.append(headElement); + } + } + elm = headerFragment.firstChild; + if (data.xml_pi) { + value = 'version="1.0"'; + if (data.docencoding) { + value += ' encoding="' + data.docencoding + '"'; + } + if (elm.type !== 7) { + elm = new global$3('xml', 7); + headerFragment.insert(elm, headerFragment.firstChild, true); + } + elm.value = value; + } else if (elm && elm.type === 7) { + elm.remove(); + } + elm = headerFragment.getAll('#doctype')[0]; + if (data.doctype) { + if (!elm) { + elm = new global$3('#doctype', 10); + if (data.xml_pi) { + headerFragment.insert(elm, headerFragment.firstChild); + } else { + addHeadNode(elm); + } + } + elm.value = data.doctype.substring(9, data.doctype.length - 1); + } else if (elm) { + elm.remove(); + } + elm = null; + global$1.each(headerFragment.getAll('meta'), function (meta) { + if (meta.attr('http-equiv') === 'Content-Type') { + elm = meta; + } + }); + if (data.docencoding) { + if (!elm) { + elm = new global$3('meta', 1); + elm.attr('http-equiv', 'Content-Type'); + elm.shortEnded = true; + addHeadNode(elm); + } + elm.attr('content', 'text/html; charset=' + data.docencoding); + } else if (elm) { + elm.remove(); + } + elm = headerFragment.getAll('title')[0]; + if (data.title) { + if (!elm) { + elm = new global$3('title', 1); + addHeadNode(elm); + } else { + elm.empty(); + } + elm.append(new global$3('#text', 3)).value = data.title; + } else if (elm) { + elm.remove(); + } + global$1.each('keywords,description,author,copyright,robots'.split(','), function (name) { + var nodes = headerFragment.getAll('meta'); + var i, meta; + var value = data[name]; + for (i = 0; i < nodes.length; i++) { + meta = nodes[i]; + if (meta.attr('name') === name) { + if (value) { + meta.attr('content', value); + } else { + meta.remove(); + } + return; + } + } + if (value) { + elm = new global$3('meta', 1); + elm.attr('name', name); + elm.attr('content', value); + elm.shortEnded = true; + addHeadNode(elm); + } + }); + var currentStyleSheetsMap = {}; + global$1.each(headerFragment.getAll('link'), function (stylesheet) { + if (stylesheet.attr('rel') === 'stylesheet') { + currentStyleSheetsMap[stylesheet.attr('href')] = stylesheet; + } + }); + global$1.each(data.stylesheets, function (stylesheet) { + if (!currentStyleSheetsMap[stylesheet]) { + elm = new global$3('link', 1); + elm.attr({ + rel: 'stylesheet', + text: 'text/css', + href: stylesheet + }); + elm.shortEnded = true; + addHeadNode(elm); + } + delete currentStyleSheetsMap[stylesheet]; + }); + global$1.each(currentStyleSheetsMap, function (stylesheet) { + stylesheet.remove(); + }); + elm = headerFragment.getAll('body')[0]; + if (elm) { + setAttr(elm, 'dir', data.langdir); + setAttr(elm, 'style', data.style); + setAttr(elm, 'vlink', data.visited_color); + setAttr(elm, 'link', data.link_color); + setAttr(elm, 'alink', data.active_color); + dom.setAttribs(editor.getBody(), { + style: data.style, + dir: data.dir, + vLink: data.visited_color, + link: data.link_color, + aLink: data.active_color + }); + } + elm = headerFragment.getAll('html')[0]; + if (elm) { + setAttr(elm, 'lang', data.langcode); + setAttr(elm, 'xml:lang', data.langcode); + } + if (!headElement.firstChild) { + headElement.remove(); + } + var html = global$4({ + validate: false, + indent: true, + indent_before: 'head,html,body,meta,title,script,link,style', + indent_after: 'head,html,body,meta,title,script,link,style' + }).serialize(headerFragment); + return html.substring(0, html.indexOf('')); + }; + + var open = function (editor, headState) { + var data = htmlToData(editor, headState.get()); + var defaultData = { + title: '', + keywords: '', + description: '', + robots: '', + author: '', + docencoding: '' + }; + var initialData = __assign(__assign({}, defaultData), data); + editor.windowManager.open({ + title: 'Metadata and Document Properties', + size: 'normal', + body: { + type: 'panel', + items: [ + { + name: 'title', + type: 'input', + label: 'Title' + }, + { + name: 'keywords', + type: 'input', + label: 'Keywords' + }, + { + name: 'description', + type: 'input', + label: 'Description' + }, + { + name: 'robots', + type: 'input', + label: 'Robots' + }, + { + name: 'author', + type: 'input', + label: 'Author' + }, + { + name: 'docencoding', + type: 'input', + label: 'Encoding' + } + ] + }, + buttons: [ + { + type: 'cancel', + name: 'cancel', + text: 'Cancel' + }, + { + type: 'submit', + name: 'save', + text: 'Save', + primary: true + } + ], + initialData: initialData, + onSubmit: function (api) { + var nuData = api.getData(); + var headHtml = dataToHtml(editor, global$1.extend(data, nuData), headState.get()); + headState.set(headHtml); + api.close(); + } + }); + }; + + var register = function (editor, headState) { + editor.addCommand('mceFullPageProperties', function () { + open(editor, headState); + }); + }; + + var protectHtml = function (protect, html) { + global$1.each(protect, function (pattern) { + html = html.replace(pattern, function (str) { + return ''; + }); + }); + return html; + }; + var unprotectHtml = function (html) { + return html.replace(//g, function (a, m) { + return unescape(m); + }); + }; + + var each = global$1.each; + var low = function (s) { + return s.replace(/<\/?[A-Z]+/g, function (a) { + return a.toLowerCase(); + }); + }; + var handleSetContent = function (editor, headState, footState, evt) { + var startPos, endPos, content, styles = ''; + var dom = editor.dom; + if (evt.selection) { + return; + } + content = protectHtml(getProtect(editor), evt.content); + if (evt.format === 'raw' && headState.get()) { + return; + } + if (evt.source_view && shouldHideInSourceView(editor)) { + return; + } + if (content.length === 0 && !evt.source_view) { + content = global$1.trim(headState.get()) + '\n' + global$1.trim(content) + '\n' + global$1.trim(footState.get()); + } + content = content.replace(/<(\/?)BODY/gi, '<$1body'); + startPos = content.indexOf('', startPos); + headState.set(low(content.substring(0, startPos + 1))); + endPos = content.indexOf('\n'); + } + var headerFragment = parseHeader(headState.get()); + each(headerFragment.getAll('style'), function (node) { + if (node.firstChild) { + styles += node.firstChild.value; + } + }); + var bodyElm = headerFragment.getAll('body')[0]; + if (bodyElm) { + dom.setAttribs(editor.getBody(), { + style: bodyElm.attr('style') || '', + dir: bodyElm.attr('dir') || '', + vLink: bodyElm.attr('vlink') || '', + link: bodyElm.attr('link') || '', + aLink: bodyElm.attr('alink') || '' + }); + } + dom.remove('fullpage_styles'); + var headElm = editor.getDoc().getElementsByTagName('head')[0]; + if (styles) { + var styleElm = dom.add(headElm, 'style', { id: 'fullpage_styles' }); + styleElm.appendChild(document.createTextNode(styles)); + } + var currentStyleSheetsMap = {}; + global$1.each(headElm.getElementsByTagName('link'), function (stylesheet) { + if (stylesheet.rel === 'stylesheet' && stylesheet.getAttribute('data-mce-fullpage')) { + currentStyleSheetsMap[stylesheet.href] = stylesheet; + } + }); + global$1.each(headerFragment.getAll('link'), function (stylesheet) { + var href = stylesheet.attr('href'); + if (!href) { + return true; + } + if (!currentStyleSheetsMap[href] && stylesheet.attr('rel') === 'stylesheet') { + dom.add(headElm, 'link', { + 'rel': 'stylesheet', + 'text': 'text/css', + href: href, + 'data-mce-fullpage': '1' + }); + } + delete currentStyleSheetsMap[href]; + }); + global$1.each(currentStyleSheetsMap, function (stylesheet) { + stylesheet.parentNode.removeChild(stylesheet); + }); + }; + var getDefaultHeader = function (editor) { + var header = '', value, styles = ''; + if (getDefaultXmlPi(editor)) { + var piEncoding = getDefaultEncoding(editor); + header += '\n'; + } + header += getDefaultDocType(editor); + header += '\n\n\n'; + if (value = getDefaultTitle(editor)) { + header += '
'); + rep(/\[b\]/gi, ''); + rep(/\[\/b\]/gi, ''); + rep(/\[i\]/gi, ''); + rep(/\[\/i\]/gi, ''); + rep(/\[u\]/gi, ''); + rep(/\[\/u\]/gi, ''); + rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, '$2'); + rep(/\[url\](.*?)\[\/url\]/gi, '$1'); + rep(/\[img\](.*?)\[\/img\]/gi, ''); + rep(/\[color=(.*?)\](.*?)\[\/color\]/gi, '$2'); + rep(/\[code\](.*?)\[\/code\]/gi, '$1 '); + rep(/\[quote.*?\](.*?)\[\/quote\]/gi, '$1 '); + return s; + }; + + function Plugin () { + global.add('bbcode', function (editor) { + editor.on('BeforeSetContent', function (e) { + e.content = bbcode2html(e.content); + }); + editor.on('PostProcess', function (e) { + if (e.set) { + e.content = bbcode2html(e.content); + } + if (e.get) { + e.content = html2bbcode(e.content); + } + }); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/bbcode/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/bbcode/plugin.min.js new file mode 100644 index 0000000000..4c26eab1f8 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/bbcode/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var o=tinymce.util.Tools.resolve("tinymce.PluginManager"),e=tinymce.util.Tools.resolve("tinymce.util.Tools"),t=function(t){t=e.trim(t);var o=function(o,e){t=t.replace(o,e)};return o(/\n/gi,"
"),o(/\[b\]/gi,""),o(/\[\/b\]/gi,""),o(/\[i\]/gi,""),o(/\[\/i\]/gi,""),o(/\[u\]/gi,""),o(/\[\/u\]/gi,""),o(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,'$2'),o(/\[url\](.*?)\[\/url\]/gi,'$1'),o(/\[img\](.*?)\[\/img\]/gi,''),o(/\[color=(.*?)\](.*?)\[\/color\]/gi,'$2'),o(/\[code\](.*?)\[\/code\]/gi,'$1 '),o(/\[quote.*?\](.*?)\[\/quote\]/gi,'$1 '),t};o.add("bbcode",function(o){o.on("BeforeSetContent",function(o){o.content=t(o.content)}),o.on("PostProcess",function(o){o.set&&(o.content=t(o.content)),o.get&&(o.content=function(t){t=e.trim(t);var o=function(o,e){t=t.replace(o,e)};return o(/
(.*?)<\/a>/gi,"[url=$1]$2[/url]"),o(/ (.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"),o(/ (.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"),o(/ (.*?)<\/font>/gi,"[code][color=$1]$2[/color][/code]"),o(/ (.*?)<\/font>/gi,"[quote][color=$1]$2[/color][/quote]"),o(/(.*?)<\/span>/gi,"[color=$1]$2[/color]"),o(/ (.*?)<\/font>/gi,"[color=$1]$2[/color]"),o(/(.*?)<\/span>/gi,"[size=$1]$2[/size]"),o(/(.*?)<\/font>/gi,"$1"),o(/ /gi,"[img]$1[/img]"),o(/(.*?)<\/span>/gi,"[code]$1[/code]"),o(/(.*?)<\/span>/gi,"[quote]$1[/quote]"),o(/(.*?)<\/strong>/gi,"[code][b]$1[/b][/code]"),o(/(.*?)<\/strong>/gi,"[quote][b]$1[/b][/quote]"),o(/(.*?)<\/em>/gi,"[code][i]$1[/i][/code]"),o(/(.*?)<\/em>/gi,"[quote][i]$1[/i][/quote]"),o(/(.*?)<\/u>/gi,"[code][u]$1[/u][/code]"),o(/(.*?)<\/u>/gi,"[quote][u]$1[/u][/quote]"),o(/<\/(strong|b)>/gi,"[/b]"),o(/<(strong|b)>/gi,"[b]"),o(/<\/(em|i)>/gi,"[/i]"),o(/<(em|i)>/gi,"[i]"),o(/<\/u>/gi,"[/u]"),o(/(.*?)<\/span>/gi,"[u]$1[/u]"),o(//gi,"[u]"),o(/ ]*>/gi,"[quote]"),o(/<\/blockquote>/gi,"[/quote]"),o(/
/gi,"\n"),o(/
/gi,"\n"),o(/
/gi,"\n"),o(//gi,""),o(/<\/p>/gi,"\n"),o(/ |\u00a0/gi," "),o(/"/gi,'"'),o(/</gi,"<"),o(/>/gi,">"),o(/&/gi,"&"),t}(o.content))})})}(); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js index 203a38067a..9d4d8f06b1 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.js @@ -1,365 +1,1706 @@ /** - * plugin.js + * 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/ * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing + * Version: 5.5.1 (2020-10-01) */ +(function () { + 'use strict'; -/*global tinymce:true */ + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); -tinymce.PluginManager.add('charmap', function(editor) { - var charmap = [ - ['160', 'no-break space'], - ['38', 'ampersand'], - ['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'], - ['198', 'ligature AE'], - ['199', 'C - cedilla'], - ['200', 'E - grave'], - ['201', 'E - acute'], - ['202', 'E - circumflex'], - ['203', 'E - diaeresis'], - ['204', 'I - grave'], - ['205', 'I - acute'], - ['206', 'I - circumflex'], - ['207', 'I - diaeresis'], - ['208', 'ETH'], - ['209', 'N - tilde'], - ['210', 'O - grave'], - ['211', 'O - acute'], - ['212', 'O - circumflex'], - ['213', 'O - tilde'], - ['214', 'O - diaeresis'], - ['216', 'O - slash'], - ['338', 'ligature OE'], - ['352', 'S - caron'], - ['217', 'U - grave'], - ['218', 'U - acute'], - ['219', 'U - circumflex'], - ['220', 'U - diaeresis'], - ['221', 'Y - acute'], - ['376', 'Y - diaeresis'], - ['222', 'THORN'], - ['224', 'a - grave'], - ['225', 'a - acute'], - ['226', 'a - circumflex'], - ['227', 'a - tilde'], - ['228', 'a - diaeresis'], - ['229', 'a - ring above'], - ['230', 'ligature ae'], - ['231', 'c - cedilla'], - ['232', 'e - grave'], - ['233', 'e - acute'], - ['234', 'e - circumflex'], - ['235', 'e - diaeresis'], - ['236', 'i - grave'], - ['237', 'i - acute'], - ['238', 'i - circumflex'], - ['239', 'i - diaeresis'], - ['240', 'eth'], - ['241', 'n - tilde'], - ['242', 'o - grave'], - ['243', 'o - acute'], - ['244', 'o - circumflex'], - ['245', 'o - tilde'], - ['246', 'o - diaeresis'], - ['248', 'o slash'], - ['339', 'ligature oe'], - ['353', 's - caron'], - ['249', 'u - grave'], - ['250', 'u - acute'], - ['251', 'u - circumflex'], - ['252', 'u - diaeresis'], - ['253', 'y - acute'], - ['254', 'thorn'], - ['255', 'y - diaeresis'], - ['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'], - ['173', 'soft hyphen'] - ]; + var fireInsertCustomChar = function (editor, chr) { + return editor.fire('insertCustomChar', { chr: chr }); + }; - function showDialog() { - var gridHtml, x, y, win; + var insertChar = function (editor, chr) { + var evtChr = fireInsertCustomChar(editor, chr).chr; + editor.execCommand('mceInsertContent', false, evtChr); + }; - function getParentTd(elm) { - while (elm) { - if (elm.nodeName == 'TD') { - return elm; - } + var noop = function () { + }; + var constant = function (value) { + return function () { + return value; + }; + }; + var never = constant(false); + var always = constant(true); - elm = elm.parentNode; - } - } + var none = function () { + return NONE; + }; + var NONE = function () { + var eq = function (o) { + return o.isNone(); + }; + var call = function (thunk) { + return thunk(); + }; + var id = function (n) { + return n; + }; + var me = { + fold: function (n, _s) { + return n(); + }, + is: never, + isSome: never, + isNone: always, + getOr: id, + getOrThunk: call, + getOrDie: function (msg) { + throw new Error(msg || 'error: getOrDie called on none.'); + }, + getOrNull: constant(null), + getOrUndefined: constant(undefined), + or: id, + orThunk: call, + map: none, + each: noop, + bind: none, + exists: never, + forall: always, + filter: none, + equals: eq, + equals_: eq, + toArray: function () { + return []; + }, + toString: constant('none()') + }; + return me; + }(); + var some = function (a) { + var constant_a = constant(a); + var self = function () { + return me; + }; + var bind = function (f) { + return f(a); + }; + var me = { + fold: function (n, s) { + return s(a); + }, + is: function (v) { + return a === v; + }, + isSome: always, + isNone: never, + getOr: constant_a, + getOrThunk: constant_a, + getOrDie: constant_a, + getOrNull: constant_a, + getOrUndefined: constant_a, + or: self, + orThunk: self, + map: function (f) { + return some(f(a)); + }, + each: function (f) { + f(a); + }, + bind: bind, + exists: bind, + forall: bind, + filter: function (f) { + return f(a) ? me : NONE; + }, + toArray: function () { + return [a]; + }, + toString: function () { + return 'some(' + a + ')'; + }, + equals: function (o) { + return o.is(a); + }, + equals_: function (o, elementEq) { + return o.fold(never, function (b) { + return elementEq(a, b); + }); + } + }; + return me; + }; + var from = function (value) { + return value === null || value === undefined ? NONE : some(value); + }; + var Optional = { + some: some, + none: none, + from: from + }; - gridHtml = '
'; + var typeOf = function (x) { + var t = typeof x; + if (x === null) { + return 'null'; + } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { + return 'array'; + } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { + return 'string'; + } else { + return t; + } + }; + var isType = function (type) { + return function (value) { + return typeOf(value) === type; + }; + }; + var isArray = isType('array'); - var width = 25; - for (y = 0; y < 10; y++) { - gridHtml += '
'; + var get = function (editor) { + var getCharMap = function () { + return getCharMap$1(editor); + }; + var insertChar$1 = function (chr) { + insertChar(editor, chr); + }; + return { + getCharMap: getCharMap, + insertChar: insertChar$1 + }; + }; - var charMapPanel = { - type: 'container', - html: gridHtml, - onclick: function(e) { - var target = e.target; - if (/^(TD|DIV)$/.test(target.nodeName)) { - editor.execCommand('mceInsertContent', false, tinymce.trim(target.innerText || target.textContent)); + var Cell = function (initial) { + var value = initial; + var get = function () { + return value; + }; + var set = function (v) { + value = v; + }; + return { + get: get, + set: set + }; + }; - if (!e.ctrlKey) { - win.close(); - } - } - }, - onmouseover: function(e) { - var td = getParentTd(e.target); + var last = function (fn, rate) { + var timer = null; + var cancel = function () { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + }; + var throttle = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (timer !== null) { + clearTimeout(timer); + } + timer = setTimeout(function () { + fn.apply(null, args); + timer = null; + }, rate); + }; + return { + cancel: cancel, + throttle: throttle + }; + }; - if (td) { - win.find('#preview').text(td.firstChild.firstChild.data); - } - } - }; + var nativeFromCodePoint = String.fromCodePoint; + var contains = function (str, substr) { + return str.indexOf(substr) !== -1; + }; + var fromCodePoint = function () { + var codePoints = []; + for (var _i = 0; _i < arguments.length; _i++) { + codePoints[_i] = arguments[_i]; + } + if (nativeFromCodePoint) { + return nativeFromCodePoint.apply(void 0, codePoints); + } else { + var codeUnits = []; + var codeLen = 0; + var result = ''; + for (var index = 0, len = codePoints.length; index !== len; ++index) { + var codePoint = +codePoints[index]; + if (!(codePoint < 1114111 && codePoint >>> 0 === codePoint)) { + throw RangeError('Invalid code point: ' + codePoint); + } + if (codePoint <= 65535) { + codeLen = codeUnits.push(codePoint); + } else { + codePoint -= 65536; + codeLen = codeUnits.push((codePoint >> 10) + 55296, codePoint % 1024 + 56320); + } + if (codeLen >= 16383) { + result += String.fromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result + String.fromCharCode.apply(null, codeUnits); + } + }; - win = editor.windowManager.open({ - title: "Special character", - spacing: 10, - padding: 10, - items: [ - charMapPanel, - { - type: 'label', - name: 'preview', - text: ' ', - style: 'font-size: 40px; text-align: center', - border: 1, - minWidth: 100, - minHeight: 80 - } - ], - buttons: [ - {text: "Close", onclick: function() { - win.close(); - }} - ] - }); - } + var charMatches = function (charCode, name, lowerCasePattern) { + if (contains(fromCodePoint(charCode).toLowerCase(), lowerCasePattern)) { + return true; + } else { + return contains(name.toLowerCase(), lowerCasePattern) || contains(name.toLowerCase().replace(/\s+/g, ''), lowerCasePattern); + } + }; + var scan = function (group, pattern) { + var matches = []; + var lowerCasePattern = pattern.toLowerCase(); + each(group.characters, function (g) { + if (charMatches(g[0], g[1], lowerCasePattern)) { + matches.push(g); + } + }); + return map(matches, function (m) { + return { + text: m[1], + value: fromCodePoint(m[0]), + icon: fromCodePoint(m[0]) + }; + }); + }; - editor.addButton('charmap', { - icon: 'charmap', - tooltip: 'Special character', - onclick: showDialog - }); + var patternName = 'pattern'; + var open = function (editor, charMap) { + var makeGroupItems = function () { + return [ + { + label: 'Search', + type: 'input', + name: patternName + }, + { + type: 'collection', + name: 'results' + } + ]; + }; + var makeTabs = function () { + return map(charMap, function (charGroup) { + return { + title: charGroup.name, + name: charGroup.name, + items: makeGroupItems() + }; + }); + }; + var makePanel = function () { + return { + type: 'panel', + items: makeGroupItems() + }; + }; + var makeTabPanel = function () { + return { + type: 'tabpanel', + tabs: makeTabs() + }; + }; + var currentTab = charMap.length === 1 ? Cell(UserDefined) : Cell('All'); + var scanAndSet = function (dialogApi, pattern) { + find(charMap, function (group) { + return group.name === currentTab.get(); + }).each(function (f) { + var items = scan(f, pattern); + dialogApi.setData({ results: items }); + }); + }; + var SEARCH_DELAY = 40; + var updateFilter = last(function (dialogApi) { + var pattern = dialogApi.getData().pattern; + scanAndSet(dialogApi, pattern); + }, SEARCH_DELAY); + var body = charMap.length === 1 ? makePanel() : makeTabPanel(); + var initialData = { + pattern: '', + results: scan(charMap[0], '') + }; + var bridgeSpec = { + title: 'Special Character', + size: 'normal', + body: body, + buttons: [{ + type: 'cancel', + name: 'close', + text: 'Close', + primary: true + }], + initialData: initialData, + onAction: function (api, details) { + if (details.name === 'results') { + insertChar(editor, details.value); + api.close(); + } + }, + onTabChange: function (dialogApi, details) { + currentTab.set(details.newTabName); + updateFilter.throttle(dialogApi); + }, + onChange: function (dialogApi, changeData) { + if (changeData.name === patternName) { + updateFilter.throttle(dialogApi); + } + } + }; + var dialogApi = editor.windowManager.open(bridgeSpec); + dialogApi.focus(patternName); + }; - editor.addMenuItem('charmap', { - icon: 'charmap', - text: 'Special character', - onclick: showDialog, - context: 'insert' - }); -}); \ No newline at end of file + var register = function (editor, charMap) { + editor.addCommand('mceShowCharmap', function () { + open(editor, charMap); + }); + }; + + var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise'); + + var init = function (editor, all) { + editor.ui.registry.addAutocompleter('charmap', { + ch: ':', + columns: 'auto', + minChars: 2, + fetch: function (pattern, _maxResults) { + return new global$2(function (resolve, _reject) { + resolve(scan(all, pattern)); + }); + }, + onAction: function (autocompleteApi, rng, value) { + editor.selection.setRng(rng); + editor.insertContent(value); + autocompleteApi.hide(); + } + }); + }; + + var register$1 = function (editor) { + editor.ui.registry.addButton('charmap', { + icon: 'insert-character', + tooltip: 'Special character', + onAction: function () { + return editor.execCommand('mceShowCharmap'); + } + }); + editor.ui.registry.addMenuItem('charmap', { + icon: 'insert-character', + text: 'Special character...', + onAction: function () { + return editor.execCommand('mceShowCharmap'); + } + }); + }; + + function Plugin () { + global.add('charmap', function (editor) { + var charMap = getCharMap$1(editor); + register(editor, charMap); + register$1(editor); + init(editor, charMap[0]); + return get(editor); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js index 69d189143a..05c0f3d79f 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/charmap/plugin.min.js @@ -1 +1,9 @@ -tinymce.PluginManager.add("charmap",function(e){function a(){function a(e){for(;e;){if("TD"==e.nodeName)return e;e=e.parentNode}}var i,r,o,n;i=''; + var nativePush = Array.prototype.push; + var map = function (xs, f) { + var len = xs.length; + var r = new Array(len); + for (var i = 0; i < len; i++) { + var x = xs[i]; + r[i] = f(x, i); + } + return r; + }; + var each = function (xs, f) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + f(x, i); + } + }; + var findUntil = function (xs, pred, until) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + if (pred(x, i)) { + return Optional.some(x); + } else if (until(x, i)) { + break; + } + } + return Optional.none(); + }; + var find = function (xs, pred) { + return findUntil(xs, pred, never); + }; + var flatten = function (xs) { + var r = []; + for (var i = 0, len = xs.length; i < len; ++i) { + if (!isArray(xs[i])) { + throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); + } + nativePush.apply(r, xs[i]); + } + return r; + }; + var bind = function (xs, f) { + return flatten(map(xs, f)); + }; - for (x = 0; x < width; x++) { - var chr = charmap[y * width + x]; + var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools'); - gridHtml += ' '; - } + var isArray$1 = global$1.isArray; + var UserDefined = 'User Defined'; + var getDefaultCharMap = function () { + return [ + { + name: 'Currency', + characters: [ + [ + 36, + 'dollar sign' + ], + [ + 162, + 'cent sign' + ], + [ + 8364, + 'euro sign' + ], + [ + 163, + 'pound sign' + ], + [ + 165, + 'yen sign' + ], + [ + 164, + 'currency sign' + ], + [ + 8352, + 'euro-currency sign' + ], + [ + 8353, + 'colon sign' + ], + [ + 8354, + 'cruzeiro sign' + ], + [ + 8355, + 'french franc sign' + ], + [ + 8356, + 'lira sign' + ], + [ + 8357, + 'mill sign' + ], + [ + 8358, + 'naira sign' + ], + [ + 8359, + 'peseta sign' + ], + [ + 8360, + 'rupee sign' + ], + [ + 8361, + 'won sign' + ], + [ + 8362, + 'new sheqel sign' + ], + [ + 8363, + 'dong sign' + ], + [ + 8365, + 'kip sign' + ], + [ + 8366, + 'tugrik sign' + ], + [ + 8367, + 'drachma sign' + ], + [ + 8368, + 'german penny symbol' + ], + [ + 8369, + 'peso sign' + ], + [ + 8370, + 'guarani sign' + ], + [ + 8371, + 'austral sign' + ], + [ + 8372, + 'hryvnia sign' + ], + [ + 8373, + 'cedi sign' + ], + [ + 8374, + 'livre tournois sign' + ], + [ + 8375, + 'spesmilo sign' + ], + [ + 8376, + 'tenge sign' + ], + [ + 8377, + 'indian rupee sign' + ], + [ + 8378, + 'turkish lira sign' + ], + [ + 8379, + 'nordic mark sign' + ], + [ + 8380, + 'manat sign' + ], + [ + 8381, + 'ruble sign' + ], + [ + 20870, + 'yen character' + ], + [ + 20803, + 'yuan character' + ], + [ + 22291, + 'yuan character, in hong kong and taiwan' + ], + [ + 22278, + 'yen/yuan character variant one' + ] + ] + }, + { + name: 'Text', + characters: [ + [ + 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' + ] + ] + }, + { + name: 'Quotations', + characters: [ + [ + 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' + ] + ] + }, + { + name: 'Mathematical', + characters: [ + [ + 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' + ] + ] + }, + { + name: 'Extended Latin', + characters: [ + [ + 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' + ] + ] + }, + { + name: 'Symbols', + characters: [ + [ + 8501, + 'alef symbol' + ], + [ + 982, + 'pi symbol' + ], + [ + 8476, + 'real part symbol' + ], + [ + 978, + 'upsilon - hook symbol' + ], + [ + 8472, + 'Weierstrass p' + ], + [ + 8465, + 'imaginary part' + ] + ] + }, + { + name: 'Arrows', + characters: [ + [ + 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' + ] + ] + } + ]; + }; + var charmapFilter = function (charmap) { + return global$1.grep(charmap, function (item) { + return isArray$1(item) && item.length === 2; + }); + }; + var getCharsFromSetting = function (settingValue) { + if (isArray$1(settingValue)) { + return [].concat(charmapFilter(settingValue)); + } + if (typeof settingValue === 'function') { + return settingValue(); + } + return []; + }; + var extendCharMap = function (editor, charmap) { + var userCharMap = getCharMap(editor); + if (userCharMap) { + charmap = [{ + name: UserDefined, + characters: getCharsFromSetting(userCharMap) + }]; + } + var userCharMapAppend = getCharMapAppend(editor); + if (userCharMapAppend) { + var userDefinedGroup = global$1.grep(charmap, function (cg) { + return cg.name === UserDefined; + }); + if (userDefinedGroup.length) { + userDefinedGroup[0].characters = [].concat(userDefinedGroup[0].characters).concat(getCharsFromSetting(userCharMapAppend)); + return charmap; + } + return [].concat(charmap).concat({ + name: UserDefined, + characters: getCharsFromSetting(userCharMapAppend) + }); + } + return charmap; + }; + var getCharMap$1 = function (editor) { + var groups = extendCharMap(editor, getDefaultCharMap()); + return groups.length > 1 ? [{ + name: 'All', + characters: bind(groups, function (g) { + return g.characters; + }) + }].concat(groups) : groups; + }; - gridHtml += ''; - } + var getCharMap = function (editor) { + return editor.getParam('charmap'); + }; + var getCharMapAppend = function (editor) { + return editor.getParam('charmap_append'); + }; - gridHtml += ' ' + - (chr ? String.fromCharCode(parseInt(chr[0], 10)) : ' ') + '';var l=25;for(o=0;o<10;o++){for(i+="
";var c={type:"container",html:i,onclick:function(a){var t=a.target;/^(TD|DIV)$/.test(t.nodeName)&&(e.execCommand("mceInsertContent",!1,tinymce.trim(t.innerText||t.textContent)),a.ctrlKey||n.close())},onmouseover:function(e){var t=a(e.target);t&&n.find("#preview").text(t.firstChild.firstChild.data)}};n=e.windowManager.open({title:"Special character",spacing:10,padding:10,items:[c,{type:"label",name:"preview",text:" ",style:"font-size: 40px; text-align: center",border:1,minWidth:100,minHeight:80}],buttons:[{text:"Close",onclick:function(){n.close()}}]})}var t=[["160","no-break space"],["38","ampersand"],["34","quotation mark"],["162","cent sign"],["8364","euro sign"],["163","pound sign"],["165","yen sign"],["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"],["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"],["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"],["180","acute accent"],["184","cedilla"],["170","feminine ordinal indicator"],["186","masculine ordinal indicator"],["8224","dagger"],["8225","double dagger"],["192","A - grave"],["193","A - acute"],["194","A - circumflex"],["195","A - tilde"],["196","A - diaeresis"],["197","A - ring above"],["198","ligature AE"],["199","C - cedilla"],["200","E - grave"],["201","E - acute"],["202","E - circumflex"],["203","E - diaeresis"],["204","I - grave"],["205","I - acute"],["206","I - circumflex"],["207","I - diaeresis"],["208","ETH"],["209","N - tilde"],["210","O - grave"],["211","O - acute"],["212","O - circumflex"],["213","O - tilde"],["214","O - diaeresis"],["216","O - slash"],["338","ligature OE"],["352","S - caron"],["217","U - grave"],["218","U - acute"],["219","U - circumflex"],["220","U - diaeresis"],["221","Y - acute"],["376","Y - diaeresis"],["222","THORN"],["224","a - grave"],["225","a - acute"],["226","a - circumflex"],["227","a - tilde"],["228","a - diaeresis"],["229","a - ring above"],["230","ligature ae"],["231","c - cedilla"],["232","e - grave"],["233","e - acute"],["234","e - circumflex"],["235","e - diaeresis"],["236","i - grave"],["237","i - acute"],["238","i - circumflex"],["239","i - diaeresis"],["240","eth"],["241","n - tilde"],["242","o - grave"],["243","o - acute"],["244","o - circumflex"],["245","o - tilde"],["246","o - diaeresis"],["248","o slash"],["339","ligature oe"],["353","s - caron"],["249","u - grave"],["250","u - acute"],["251","u - circumflex"],["252","u - diaeresis"],["253","y - acute"],["254","thorn"],["255","y - diaeresis"],["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"],["8501","alef symbol"],["982","pi symbol"],["8476","real part symbol"],["978","upsilon - hook symbol"],["8472","Weierstrass p"],["8465","imaginary part"],["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"],["173","soft hyphen"]];e.addButton("charmap",{icon:"charmap",tooltip:"Special character",onclick:a}),e.addMenuItem("charmap",{icon:"charmap",text:"Special character",onclick:a,context:"insert"})}); \ No newline at end of file +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var e,n,r,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),s=function(e,n){var r,t=(r=n,e.fire("insertCustomChar",{chr:r}).chr);e.execCommand("mceInsertContent",!1,t)},i=function(e){return function(){return e}},o=i(!1),c=i(!0),u=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:o,isSome:o,isNone:c,getOr:r=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:r,orThunk:n,map:u,each:function(){},bind:u,exists:o,forall:c,filter:u,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),g=function(r){var e=i(r),n=function(){return a},t=function(e){return e(r)},a={fold:function(e,n){return n(r)},is:function(e){return r===e},isSome:c,isNone:o,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return g(e(r))},each:function(e){e(r)},bind:t,exists:t,forall:t,filter:function(e){return e(r)?a:l},toArray:function(){return[r]},toString:function(){return"some("+r+")"},equals:function(e){return e.is(r)},equals_:function(e,n){return e.fold(o,function(e){return n(r,e)})}};return a},m={some:g,none:u,from:function(e){return null===e||e===undefined?l:g(e)}},f=(t="array",function(e){return r=typeof(n=e),(null===n?"null":"object"==r&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==r&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":r)===t;var n,r}),h=Array.prototype.push,p=function(e,n){for(var r=e.length,t=new Array(r),a=0;a",r=0;r "}i+=" '+(s?String.fromCharCode(parseInt(s[0],10)):" ")+""}i+=">>0===o))throw RangeError("Invalid code point: "+o);16383<=(o<=65535?r.push(o):(o-=65536,r.push(55296+(o>>10),o%1024+56320)))&&(t+=String.fromCharCode.apply(null,r),r.length=0)}return t+String.fromCharCode.apply(null,r)},S=function(e,n){var a=[],i=n.toLowerCase();return function(e,n){for(var r=0,t=e.length;r . - -Version 1.1 - 2013-07-19 -- New options jsFiles and cssFiles. - -Version 1.0 - 2013-06-29 -- Initial release. diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/cs_CZ.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/cs_CZ.js new file mode 100644 index 0000000000..0b7c42576e --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/cs_CZ.js @@ -0,0 +1,8 @@ +tinymce.addI18n('cs_CZ',{ + 'HTML source code': 'Zdrojový HTML kód', + 'Start search': 'Hledat', + 'Find next': 'Najít další', + 'Find previous': 'Najít předchozí', + 'Replace': 'Nahradit', + 'Replace all': 'Nahradit vše' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/de.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/de.js new file mode 100644 index 0000000000..4763bbcbb5 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/de.js @@ -0,0 +1,8 @@ +tinymce.addI18n('de',{ + 'HTML source code': 'HTML-Quellcode', + 'Start search': 'Suchen', + 'Find next': 'Suche nächstes', + 'Find previous': 'Suche vorheriges', + 'Replace': 'Ersetzen', + 'Replace all': 'Alles ersetzen' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/es_ES.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/es_ES.js new file mode 100644 index 0000000000..1b2740dca9 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/es_ES.js @@ -0,0 +1,8 @@ +tinymce.addI18n('es_ES',{ + 'HTML source code': 'Código fuente HTML', + 'Start search': 'Buscar', + 'Find next': 'Siguiente', + 'Find previous': 'Anterior', + 'Replace': 'Reemplazar', + 'Replace all': 'Reemplazar todo' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/fr_FR.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/fr_FR.js new file mode 100644 index 0000000000..f2e464428c --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/fr_FR.js @@ -0,0 +1,8 @@ +tinymce.addI18n('fr_FR',{ + 'HTML source code': 'Code source HTML', + 'Start search': 'Rechercher', + 'Find next': 'Chercher suiv.', + 'Find previous': 'Chercher préc.', + 'Replace': 'Replace', + 'Replace all': 'Replace all' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/pt_BR.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/pt_BR.js new file mode 100644 index 0000000000..613b21ea11 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/pt_BR.js @@ -0,0 +1,8 @@ +tinymce.addI18n('pt_BR',{ + 'HTML source code': 'Código Fonte HTML', + 'Start search': 'Iniciar Pesquisa', + 'Find next': 'Encontrar Próximo', + 'Find previous': 'Encontrar Anterior', + 'Replace': 'Substituir', + 'Replace all': 'Substituir all' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/pt_PT.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/pt_PT.js new file mode 100644 index 0000000000..6e4b54be08 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/pt_PT.js @@ -0,0 +1,8 @@ +tinymce.addI18n('pt_PT',{ + 'HTML source code': 'Código Fonte HTML', + 'Start search': 'Iniciar Pesquisa', + 'Find next': 'Encontrar Próximo', + 'Find previous': 'Encontrar Anterior', + 'Replace': 'Substituir', + 'Replace all': 'Substituir all' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/ru.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/ru.js new file mode 100644 index 0000000000..01ee0c4f58 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/ru.js @@ -0,0 +1,8 @@ +tinymce.addI18n('ru',{ + 'HTML source code': '\u0418\u0441\u0445\u043e\u0434\u043d\u044b\u0439 HTML \u043a\u043e\u0434', + 'Start search': '\u041d\u0430\u0447\u0430\u0442\u044c \u043f\u043e\u0438\u0441\u043a', + 'Find next': '\u041d\u0430\u0439\u0442\u0438 \u0441\u043b\u0435\u0434\u0443\u044e\u0449\u0438\u0439', + 'Find previous': '\u041d\u0430\u0439\u0442\u0438 \u043f\u0440\u0435\u0434\u044b\u0434\u0443\u0449\u0438\u0439', + 'Replace': '\u0417\u0430\u043c\u0435\u043d\u0438\u0442\u044c', + 'Replace all': '\u0417\u0430\u043c\u0435\u043d\u0438\u0442\u044c \u0432\u0441\u0435' +}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/uk.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/uk.js new file mode 100755 index 0000000000..59918fe448 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/uk.js @@ -0,0 +1,8 @@ +tinymce.addI18n('uk',{ + 'HTML source code': 'Вихідний код HTML', + 'Start search': 'Пошук', + 'Find next': 'Знайти наступне', + 'Find previous': 'Знайти попереднє', + 'Replace': 'Замінити', + 'Replace all': 'Замінити все' +}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/zh_TW.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/zh_TW.js new file mode 100644 index 0000000000..8647164c3e --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/langs/zh_TW.js @@ -0,0 +1,8 @@ +tinymce.addI18n('zh_TW',{ + 'HTML source code': 'HTML原始碼', + 'Start search': '開始搜尋', + 'Find next': '搜尋下一個.', + 'Find previous': '搜尋上一個.', + 'Replace': '取代', + 'Replace all': '全部取代' +}); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.js index c6d8fc7ad4..82922554fc 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.js @@ -5,19 +5,22 @@ * @author Arjan Haverkamp */ -/*jshint unused:false */ -/*global tinymce:true */ +/* jshint unused:false */ +/* global tinymce:true */ -tinymce.PluginManager.requireLangPack('codemirror'); +tinymce.PluginManager.requireLangPack('codemirror') -tinymce.PluginManager.add('codemirror', function(editor, url) { +tinymce.PluginManager.add('codemirror', function (editor, url) { + function showSourceEditor() { + editor.focus() + editor.selection.collapse(true) - function showSourceEditor() { - // Insert caret marker - editor.focus(); - editor.selection.collapse(true); - editor.selection.setContent(''); + // Insert caret marker + if (editor.settings.codemirror.saveCursorPosition) { + editor.selection.setContent('') + } + // EDX: Use Iframe based URLs // Determine the origin of the window that will host the code editor. // If tinyMCE's baseURL is relative, then static files are hosted in the // same origin as the containing page. If it is not relative, then we know that @@ -35,33 +38,90 @@ tinymce.PluginManager.add('codemirror', function(editor, url) { // Send the path location for CodeMirror and the parent origin to use in postMessage. var sourceHtmlParams = "?CodeMirrorPath=" + editor.settings.codemirror.path + "&ParentOrigin=" + window.location.origin; + var codemirrorWidth = 800 + if (editor.settings.codemirror.width) { + codemirrorWidth = editor.settings.codemirror.width + } - // Open editor window - var win = editor.windowManager.open({ - title: 'HTML source code', - url: url + '/source.html' + sourceHtmlParams, - width: 800, - height: 550, - resizable: true, - maximizable: true, - buttons: [ - { text: 'OK', subtype: 'primary', onclick: function () { - postToCodeEditor({type: "save"}); - }}, - { text: 'Cancel', onclick: function () { - postToCodeEditor({type: "cancel"}); - }} + var codemirrorHeight = 550 + if (editor.settings.codemirror.height) { + codemirrorHeight = editor.settings.codemirror.height + } + + var buttonsConfig = (tinymce.majorVersion < 5) + ? [ + { + text: 'Ok', + subtype: 'primary', + onclick: function() { + var doc = document.querySelectorAll('.mce-container-body>iframe')[0] + doc.contentWindow.submit() + win.close() + } + }, + { + text: 'Cancel', + onclick: 'close' + } + ] + : [ + { + type: 'custom', + text: 'Ok', + name: 'codemirrorOk', + primary: true + }, + { + type: 'cancel', + text: 'Cancel', + name: 'codemirrorCancel' + } ] - }); + var config = { + title: 'HTML source code', + url: url + '/source.html' + sourceHtmlParams, + width: codemirrorWidth, + height: codemirrorHeight, + resizable: true, + maximizable: true, + fullScreen: editor.settings.codemirror.fullscreen, + saveCursorPosition: false, + buttons: buttonsConfig, + // EDX: Use the onClose callback to remove the message listener. + onClose: function () { + window.removeEventListener("message", messageListener); + } + } - // The master version of TinyMCE has a win.getContentWindow() method. This is its implementation. - var codeWindow = win.getEl().getElementsByTagName('iframe')[0].contentWindow; + if (tinymce.majorVersion >= 5) { + config.onAction = function (dialogApi, actionData) { + // EDX: Change the onAction to use messages instead of window object references + if (actionData.name === 'codemirrorOk') { + postToCodeEditor({type: "save"}); + } else if (actionData.name === 'codemirrorCancel') { + postToCodeEditor({type: "cancel"}); + win.close(); + } + } + } - var postToCodeEditor = function (data) { - codeWindow.postMessage(data, codeEditorOrigin); + var win = (tinymce.majorVersion < 5) + ? editor.windowManager.open(config) + : editor.windowManager.openUrl(config) + + // EDX: The if block is commented because, + // In TinyMCE windowManager.openUrl returns a dialog instance API object + // and not a window object. So fullscreen cannot be called directly on `win`. + // if (editor.settings.codemirror.fullscreen) { + // win.fullscreen(true) + // } + + // EDX: Functions to send message to the CodeMirror Iframe and listen to + // messages posted by the iframe + var postToCodeEditor = function (message) { + win.sendMessage(message); }; - var messageListener = function (event) { // Check that the message came from the code editor. if (codeEditorOrigin !== event.origin) { @@ -70,7 +130,7 @@ tinymce.PluginManager.add('codemirror', function(editor, url) { var source; if (event.data.type === "init") { - source = {content: editor.getContent({source_view: true})}; + source = { content: editor.getContent({ source_view: true }) }; // Post an event to allow rewriting of static links on the content. editor.fire("ShowCodeEditor", source); @@ -83,7 +143,7 @@ tinymce.PluginManager.add('codemirror', function(editor, url) { editor.dom.remove(editor.dom.select('.CmCaReT')); } else if (event.data.type === "setText") { - source = {content: event.data.text}; + source = { content: event.data.text }; var isDirty = event.data.isDirty; // Post an event to allow rewriting of static links on the content. @@ -95,7 +155,7 @@ tinymce.PluginManager.add('codemirror', function(editor, url) { var el = editor.dom.select('span#CmCaReT')[0]; if (el) { editor.selection.scrollIntoView(el); - editor.selection.setCursorLocation(el,0); + editor.selection.setCursorLocation(el, 0); editor.dom.remove(el); } // EDX: added because CmCaReT span was getting left in when caret was within a style tag. @@ -117,30 +177,39 @@ tinymce.PluginManager.add('codemirror', function(editor, url) { else if (event.data.type === "closeWindow") { win.close(); } - }; - - win.on("close", function() { - window.removeEventListener("message", messageListener); - }); + } window.addEventListener("message", messageListener, false); + } - } + if (tinymce.majorVersion < 5) { + // Add a button to the button bar + editor.addButton('code', { + title: 'Source code', + icon: 'code', + onclick: showSourceEditor + }) - // Add a button to the button bar - // EDX changed to show "HTML" on toolbar button - editor.addButton('code', { - title: 'Edit HTML', - text: 'HTML', - icon: false, - onclick: showSourceEditor - }); + // Add a menu item to the tools menu + editor.addMenuItem('code', { + icon: 'code', + text: 'Source code', + context: 'tools', + onclick: showSourceEditor + }) + } else { + // EDX changed to show "HTML" on toolbar button + editor.ui.registry.addButton('code', { + text: 'HTML', + tooltip: 'Edit HTML', + onAction: showSourceEditor + }) - // Add a menu item to the tools menu - editor.addMenuItem('code', { - icon: 'code', - text: 'Edit HTML', - context: 'tools', - onclick: showSourceEditor - }); -}); + editor.ui.registry.addMenuItem('code', { + icon: 'sourcecode', + text: 'Edit HTML', + onAction: showSourceEditor, + context: 'tools' + }) + } +}) diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.min.js index 05db12ebdc..eb162e9e65 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/plugin.min.js @@ -1 +1 @@ -tinymce.PluginManager.requireLangPack("codemirror"),tinymce.PluginManager.add("codemirror",function(e,t){function n(){e.focus(),e.selection.collapse(!0),e.selection.setContent('');var n,o=tinyMCE.baseURL.indexOf("/static/");n=o>0?tinyMCE.baseURL.substring(0,o):window.location.origin;var i="?CodeMirrorPath="+e.settings.codemirror.path+"&ParentOrigin="+window.location.origin,a=e.windowManager.open({title:"HTML source code",url:t+"/source.html"+i,width:800,height:550,resizable:!0,maximizable:!0,buttons:[{text:"OK",subtype:"primary",onclick:function(){s({type:"save"})}},{text:"Cancel",onclick:function(){s({type:"cancel"})}}]}),c=a.getEl().getElementsByTagName("iframe")[0].contentWindow,s=function(e){c.postMessage(e,n)},r=function(t){if(n===t.origin){var o;if("init"===t.data.type)o={content:e.getContent({source_view:!0})},e.fire("ShowCodeEditor",o),s({type:"init",content:o.content}),e.dom.remove(e.dom.select(".CmCaReT"));else if("setText"===t.data.type){o={content:t.data.text};var i=t.data.isDirty;e.fire("SaveCodeEditor",o),e.setContent(o.content);var c=e.dom.select("span#CmCaReT")[0];if(c)e.selection.scrollIntoView(c),e.selection.setCursorLocation(c,0),e.dom.remove(c);else{var r=e.getContent(),d=r.replace('',"");r!==d&&e.setContent(d)}e.isNotDirty=!i,i&&e.nodeChanged()}else"closeWindow"===t.data.type&&a.close()}};a.on("close",function(){window.removeEventListener("message",r)}),window.addEventListener("message",r,!1)}e.addButton("code",{title:"Edit HTML",text:"HTML",icon:!1,onclick:n}),e.addMenuItem("code",{icon:"code",text:"Edit HTML",context:"tools",onclick:n})}); \ No newline at end of file +tinymce.PluginManager.requireLangPack("codemirror");tinymce.PluginManager.add("codemirror",function(l,m){function e(){l.focus();l.selection.collapse(true);if(l.settings.codemirror.saveCursorPosition){l.selection.setContent('')}var c;var e=tinyMCE.baseURL.indexOf("/static/");if(e>0){c=tinyMCE.baseURL.substring(0,e)}else{c=window.location.origin}var t="?CodeMirrorPath="+l.settings.codemirror.path+"&ParentOrigin="+window.location.origin;var o=800;if(l.settings.codemirror.width){o=l.settings.codemirror.width}var n=550;if(l.settings.codemirror.height){n=l.settings.codemirror.height}var i=tinymce.majorVersion<5?[{text:"Ok",subtype:"primary",onclick:function(){var e=document.querySelectorAll(".mce-container-body>iframe")[0];e.contentWindow.submit();a.close()}},{text:"Cancel",onclick:"close"}]:[{type:"custom",text:"Ok",name:"codemirrorOk",primary:true},{type:"cancel",text:"Cancel",name:"codemirrorCancel"}];var r={title:"HTML source code",url:m+"/source.html"+t,width:o,height:n,resizable:true,maximizable:true,fullScreen:l.settings.codemirror.fullscreen,saveCursorPosition:false,buttons:i,onClose:function(){window.removeEventListener("message",d)}};if(tinymce.majorVersion>=5){r.onAction=function(e,t){if(t.name==="codemirrorOk"){s({type:"save"})}else if(t.name==="codemirrorCancel"){s({type:"cancel"});a.close()}}}var a=tinymce.majorVersion<5?l.windowManager.open(r):l.windowManager.openUrl(r);var s=function(e){a.sendMessage(e)};var d=function(e){if(c!==e.origin){return}var t;if(e.data.type==="init"){t={content:l.getContent({source_view:true})};l.fire("ShowCodeEditor",t);s({type:"init",content:t.content});l.dom.remove(l.dom.select(".CmCaReT"))}else if(e.data.type==="setText"){t={content:e.data.text};var o=e.data.isDirty;l.fire("SaveCodeEditor",t);l.setContent(t.content);var n=l.dom.select("span#CmCaReT")[0];if(n){l.selection.scrollIntoView(n);l.selection.setCursorLocation(n,0);l.dom.remove(n)}else{var i=l.getContent();var r=i.replace('',"");if(i!==r){l.setContent(r)}}l.isNotDirty=!o;if(o){l.nodeChanged()}}else if(e.data.type==="closeWindow"){a.close()}};window.addEventListener("message",d,false)}if(tinymce.majorVersion<5){l.addButton("code",{title:"Source code",icon:"code",onclick:e});l.addMenuItem("code",{icon:"code",text:"Source code",context:"tools",onclick:e})}else{l.ui.registry.addButton("code",{text:"HTML",tooltip:"Edit HTML",onAction:e});l.ui.registry.addMenuItem("code",{icon:"sourcecode",text:"Edit HTML",onAction:e,context:"tools"})}}); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/source.html b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/source.html index 11e11be5e0..1252f3b237 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/source.html +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codemirror/source.html @@ -1,9 +1,8 @@ - - - - - - - + + + diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.js new file mode 100644 index 0000000000..ab50889a0c --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.js @@ -0,0 +1,1717 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +(function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var noop = function () { + }; + var constant = function (value) { + return function () { + return value; + }; + }; + var never = constant(false); + var always = constant(true); + + var none = function () { + return NONE; + }; + var NONE = function () { + var eq = function (o) { + return o.isNone(); + }; + var call = function (thunk) { + return thunk(); + }; + var id = function (n) { + return n; + }; + var me = { + fold: function (n, _s) { + return n(); + }, + is: never, + isSome: never, + isNone: always, + getOr: id, + getOrThunk: call, + getOrDie: function (msg) { + throw new Error(msg || 'error: getOrDie called on none.'); + }, + getOrNull: constant(null), + getOrUndefined: constant(undefined), + or: id, + orThunk: call, + map: none, + each: noop, + bind: none, + exists: never, + forall: always, + filter: none, + equals: eq, + equals_: eq, + toArray: function () { + return []; + }, + toString: constant('none()') + }; + return me; + }(); + var some = function (a) { + var constant_a = constant(a); + var self = function () { + return me; + }; + var bind = function (f) { + return f(a); + }; + var me = { + fold: function (n, s) { + return s(a); + }, + is: function (v) { + return a === v; + }, + isSome: always, + isNone: never, + getOr: constant_a, + getOrThunk: constant_a, + getOrDie: constant_a, + getOrNull: constant_a, + getOrUndefined: constant_a, + or: self, + orThunk: self, + map: function (f) { + return some(f(a)); + }, + each: function (f) { + f(a); + }, + bind: bind, + exists: bind, + forall: bind, + filter: function (f) { + return f(a) ? me : NONE; + }, + toArray: function () { + return [a]; + }, + toString: function () { + return 'some(' + a + ')'; + }, + equals: function (o) { + return o.is(a); + }, + equals_: function (o, elementEq) { + return o.fold(never, function (b) { + return elementEq(a, b); + }); + } + }; + return me; + }; + var from = function (value) { + return value === null || value === undefined ? NONE : some(value); + }; + var Optional = { + some: some, + none: none, + from: from + }; + + var head = function (xs) { + return xs.length === 0 ? Optional.none() : Optional.some(xs[0]); + }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); + + function isCodeSample(elm) { + return elm && elm.nodeName === 'PRE' && elm.className.indexOf('language-') !== -1; + } + function trimArg(predicateFn) { + return function (arg1, arg2) { + return predicateFn(arg2); + }; + } + + var Global = typeof window !== 'undefined' ? window : Function('return this;')(); + + var exports$1 = {}, module = { exports: exports$1 }, global$2 = {}; + (function (define, exports, module, require) { + var oldprism = window.Prism; + window.Prism = { manual: true }; + (function (f) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + module.exports = f(); + } else if (typeof define === 'function' && define.amd) { + define([], f); + } else { + var g; + if (typeof window !== 'undefined') { + g = window; + } else if (typeof global$2 !== 'undefined') { + g = global$2; + } else if (typeof self !== 'undefined') { + g = self; + } else { + g = this; + } + g.EphoxContactWrapper = f(); + } + }(function () { + return function () { + function r(e, n, t) { + function o(i, f) { + if (!n[i]) { + if (!e[i]) { + var c = 'function' == typeof require && require; + if (!f && c) + return c(i, !0); + if (u) + return u(i, !0); + var a = new Error('Cannot find module \'' + i + '\''); + throw a.code = 'MODULE_NOT_FOUND', a; + } + var p = n[i] = { exports: {} }; + e[i][0].call(p.exports, function (r) { + var n = e[i][1][r]; + return o(n || r); + }, p, p.exports, r, e, n, t); + } + return n[i].exports; + } + for (var u = 'function' == typeof require && require, i = 0; i < t.length; i++) + o(t[i]); + return o; + } + return r; + }()({ + 1: [ + function (require, module, exports) { + Prism.languages.c = Prism.languages.extend('clike', { + 'class-name': { + pattern: /(\b(?:enum|struct)\s+)\w+/, + lookbehind: true + }, + 'keyword': /\b(?:_Alignas|_Alignof|_Atomic|_Bool|_Complex|_Generic|_Imaginary|_Noreturn|_Static_assert|_Thread_local|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': />>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/, + 'number': /(?:\b0x(?:[\da-f]+\.?[\da-f]*|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?)[ful]*/i + }); + Prism.languages.insertBefore('c', 'string', { + 'macro': { + pattern: /(^\s*)#\s*[a-z]+(?:[^\r\n\\]|\\(?:\r\n|[\s\S]))*/im, + lookbehind: true, + alias: 'property', + inside: { + 'string': { + pattern: /(#\s*include\s*)(?:<.+?>|("|')(?:\\?.)+?\2)/, + lookbehind: true + }, + 'directive': { + pattern: /(#\s*)\b(?:define|defined|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/, + lookbehind: true, + alias: 'keyword' + } + } + }, + 'constant': /\b(?:__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|stdin|stdout|stderr)\b/ + }); + delete Prism.languages.c['boolean']; + }, + {} + ], + 2: [ + function (require, module, exports) { + Prism.languages.clike = { + 'comment': [ + { + pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, + lookbehind: true + }, + { + pattern: /(^|[^\\:])\/\/.*/, + lookbehind: true, + greedy: true + } + ], + 'string': { + pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, + greedy: true + }, + 'class-name': { + pattern: /(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/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': /\w+(?=\()/, + 'number': /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i, + 'operator': /[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/, + 'punctuation': /[{}[\];(),.:]/ + }; + }, + {} + ], + 3: [ + function (require, module, exports) { + (function (global) { + var _self = typeof window !== 'undefined' ? window : typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope ? self : {}; + var Prism = function (_self) { + var lang = /\blang(?:uage)?-([\w-]+)\b/i; + var uniqueId = 0; + var _ = { + manual: _self.Prism && _self.Prism.manual, + disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler, + util: { + encode: function (tokens) { + if (tokens instanceof Token) { + return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); + } else if (Array.isArray(tokens)) { + return tokens.map(_.util.encode); + } else { + return tokens.replace(/&/g, '&').replace(/ text.length) { + return; + } + if (str instanceof Token) { + continue; + } + if (greedy && i != strarr.length - 1) { + pattern.lastIndex = pos; + var match = pattern.exec(text); + if (!match) { + break; + } + var from = match.index + (lookbehind && match[1] ? match[1].length : 0), to = match.index + match[0].length, k = i, p = pos; + for (var len = strarr.length; k < len && (p < to || !strarr[k].type && !strarr[k - 1].greedy); ++k) { + p += strarr[k].length; + if (from >= p) { + ++i; + pos = p; + } + } + if (strarr[i] instanceof Token) { + continue; + } + delNum = k - i; + str = text.slice(pos, p); + match.index -= pos; + } else { + pattern.lastIndex = 0; + var match = pattern.exec(str), delNum = 1; + } + if (!match) { + if (oneshot) { + break; + } + continue; + } + if (lookbehind) { + lookbehindLength = match[1] ? match[1].length : 0; + } + var from = match.index + lookbehindLength, match = match[0].slice(lookbehindLength), to = from + match.length, before = str.slice(0, from), after = str.slice(to); + var args = [ + i, + delNum + ]; + if (before) { + ++i; + pos += before.length; + args.push(before); + } + var wrapped = new Token(token, inside ? _.tokenize(match, inside) : match, alias, match, greedy); + args.push(wrapped); + if (after) { + args.push(after); + } + Array.prototype.splice.apply(strarr, args); + if (delNum != 1) + _.matchGrammar(text, strarr, grammar, i, pos, true, token + ',' + j); + if (oneshot) + break; + } + } + } + }, + tokenize: function (text, grammar) { + var strarr = [text]; + var rest = grammar.rest; + if (rest) { + for (var token in rest) { + grammar[token] = rest[token]; + } + delete grammar.rest; + } + _.matchGrammar(text, strarr, grammar, 0, 0, false); + return strarr; + }, + hooks: { + all: {}, + add: function (name, callback) { + var hooks = _.hooks.all; + hooks[name] = hooks[name] || []; + hooks[name].push(callback); + }, + run: function (name, env) { + var callbacks = _.hooks.all[name]; + if (!callbacks || !callbacks.length) { + return; + } + for (var i = 0, callback; callback = callbacks[i++];) { + callback(env); + } + } + }, + Token: Token + }; + _self.Prism = _; + function Token(type, content, alias, matchedStr, greedy) { + this.type = type; + this.content = content; + this.alias = alias; + this.length = (matchedStr || '').length | 0; + this.greedy = !!greedy; + } + Token.stringify = function (o, language) { + if (typeof o == 'string') { + return o; + } + if (Array.isArray(o)) { + return o.map(function (element) { + return Token.stringify(element, language); + }).join(''); + } + var env = { + type: o.type, + content: Token.stringify(o.content, language), + tag: 'span', + classes: [ + 'token', + o.type + ], + attributes: {}, + language: language + }; + if (o.alias) { + var aliases = Array.isArray(o.alias) ? o.alias : [o.alias]; + Array.prototype.push.apply(env.classes, aliases); + } + _.hooks.run('wrap', env); + var attributes = Object.keys(env.attributes).map(function (name) { + return name + '="' + (env.attributes[name] || '').replace(/"/g, '"') + '"'; + }).join(' '); + return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '' + env.tag + '>'; + }; + if (!_self.document) { + if (!_self.addEventListener) { + return _; + } + if (!_.disableWorkerMessageHandler) { + _self.addEventListener('message', function (evt) { + var 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 _; + } + var script = _.util.currentScript(); + if (script) { + _.filename = script.src; + if (script.hasAttribute('data-manual')) { + _.manual = true; + } + } + if (!_.manual) { + var highlightAutomaticallyCallback = function () { + if (!_.manual) { + _.highlightAll(); + } + }; + var readyState = document.readyState; + if (readyState === 'loading' || readyState === 'interactive' && script && script.defer) { + document.addEventListener('DOMContentLoaded', highlightAutomaticallyCallback); + } else { + if (window.requestAnimationFrame) { + window.requestAnimationFrame(highlightAutomaticallyCallback); + } else { + window.setTimeout(highlightAutomaticallyCallback, 16); + } + } + } + return _; + }(_self); + if (typeof module !== 'undefined' && module.exports) { + module.exports = Prism; + } + if (typeof global !== 'undefined') { + global.Prism = Prism; + } + }.call(this, typeof global$2 !== 'undefined' ? global$2 : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {})); + }, + {} + ], + 4: [ + function (require, module, exports) { + Prism.languages.cpp = Prism.languages.extend('c', { + 'class-name': { + pattern: /(\b(?:class|enum|struct)\s+)\w+/, + lookbehind: true + }, + '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|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|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/, + 'number': { + pattern: /(?:\b0b[01']+|\b0x(?:[\da-f']+\.?[\da-f']*|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+\.?[\d']*|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]*/i, + greedy: true + }, + 'operator': />>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/, + 'boolean': /\b(?:true|false)\b/ + }); + Prism.languages.insertBefore('cpp', 'string', { + 'raw-string': { + pattern: /R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/, + alias: 'string', + greedy: true + } + }); + }, + {} + ], + 5: [ + function (require, module, exports) { + Prism.languages.csharp = Prism.languages.extend('clike', { + 'keyword': /\b(?:abstract|add|alias|as|ascending|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|descending|do|double|dynamic|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|from|get|global|goto|group|if|implicit|in|int|interface|internal|into|is|join|let|lock|long|namespace|new|null|object|operator|orderby|out|override|params|partial|private|protected|public|readonly|ref|remove|return|sbyte|sealed|select|set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|value|var|virtual|void|volatile|where|while|yield)\b/, + 'string': [ + { + pattern: /@("|')(?:\1\1|\\[\s\S]|(?!\1)[^\\])*\1/, + greedy: true + }, + { + pattern: /("|')(?:\\.|(?!\1)[^\\\r\n])*?\1/, + greedy: true + } + ], + 'class-name': [ + { + pattern: /\b[A-Z]\w*(?:\.\w+)*\b(?=\s+\w+)/, + inside: { punctuation: /\./ } + }, + { + pattern: /(\[)[A-Z]\w*(?:\.\w+)*\b/, + lookbehind: true, + inside: { punctuation: /\./ } + }, + { + pattern: /(\b(?:class|interface)\s+[A-Z]\w*(?:\.\w+)*\s*:\s*)[A-Z]\w*(?:\.\w+)*\b/, + lookbehind: true, + inside: { punctuation: /\./ } + }, + { + pattern: /((?:\b(?:class|interface|new)\s+)|(?:catch\s+\())[A-Z]\w*(?:\.\w+)*\b/, + lookbehind: true, + inside: { punctuation: /\./ } + } + ], + 'number': /\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)f?/i, + 'operator': />>=?|<<=?|[-=]>|([-+&|?])\1|~|[-+*/%&|^!=<>]=?/, + 'punctuation': /\?\.?|::|[{}[\];(),.:]/ + }); + Prism.languages.insertBefore('csharp', 'class-name', { + 'generic-method': { + pattern: /\w+\s*<[^>\r\n]+?>\s*(?=\()/, + inside: { + function: /^\w+/, + 'class-name': { + pattern: /\b[A-Z]\w*(?:\.\w+)*\b/, + inside: { punctuation: /\./ } + }, + keyword: Prism.languages.csharp.keyword, + punctuation: /[<>(),.:]/ + } + }, + 'preprocessor': { + pattern: /(^\s*)#.*/m, + lookbehind: true, + alias: 'property', + inside: { + 'directive': { + pattern: /(\s*#)\b(?:define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/, + lookbehind: true, + alias: 'keyword' + } + } + } + }); + Prism.languages.dotnet = Prism.languages.cs = Prism.languages.csharp; + }, + {} + ], + 6: [ + function (require, module, exports) { + (function (Prism) { + var string = /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/; + Prism.languages.css = { + 'comment': /\/\*[\s\S]*?\*\//, + 'atrule': { + pattern: /@[\w-]+[\s\S]*?(?:;|(?=\s*\{))/, + inside: { 'rule': /@[\w-]+/ } + }, + 'url': { + pattern: RegExp('url\\((?:' + string.source + '|[^\n\r()]*)\\)', 'i'), + inside: { + 'function': /^url/i, + 'punctuation': /^\(|\)$/ + } + }, + 'selector': RegExp('[^{}\\s](?:[^{};"\']|' + string.source + ')*?(?=\\s*\\{)'), + 'string': { + pattern: string, + greedy: true + }, + 'property': /[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i, + 'important': /!important\b/i, + 'function': /[-a-z0-9]+(?=\()/i, + 'punctuation': /[(){};:,]/ + }; + Prism.languages.css['atrule'].inside.rest = Prism.languages.css; + var markup = Prism.languages.markup; + if (markup) { + markup.tag.addInlined('style', 'css'); + Prism.languages.insertBefore('inside', 'attr-value', { + 'style-attr': { + pattern: /\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i, + inside: { + 'attr-name': { + pattern: /^\s*style/i, + inside: markup.tag.inside + }, + 'punctuation': /^\s*=\s*['"]|['"]\s*$/, + 'attr-value': { + pattern: /.+/i, + inside: Prism.languages.css + } + }, + alias: 'language-css' + } + }, markup.tag); + } + }(Prism)); + }, + {} + ], + 7: [ + function (require, module, exports) { + (function (Prism) { + var keywords = /\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|null|open|opens|package|private|protected|provides|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/; + var className = /\b[A-Z](?:\w*[a-z]\w*)?\b/; + Prism.languages.java = Prism.languages.extend('clike', { + 'class-name': [ + className, + /\b[A-Z]\w*(?=\s+\w+\s*[;,=())])/ + ], + 'keyword': keywords, + 'function': [ + Prism.languages.clike.function, + { + pattern: /(\:\:)[a-z_]\w*/, + lookbehind: true + } + ], + 'number': /\b0b[01][01_]*L?\b|\b0x[\da-f_]*\.?[\da-f_p+-]+\b|(?:\b\d[\d_]*\.?[\d_]*|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i, + 'operator': { + pattern: /(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m, + lookbehind: true + } + }); + Prism.languages.insertBefore('java', 'string', { + 'triple-quoted-string': { + pattern: /"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/, + greedy: true, + alias: 'string' + } + }); + Prism.languages.insertBefore('java', 'class-name', { + 'annotation': { + alias: 'punctuation', + pattern: /(^|[^.])@\w+/, + lookbehind: true + }, + 'namespace': { + pattern: /(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)[a-z]\w*(?:\.[a-z]\w*)+/, + lookbehind: true, + inside: { 'punctuation': /\./ } + }, + 'generics': { + pattern: /<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/, + inside: { + 'class-name': className, + 'keyword': keywords, + 'punctuation': /[<>(),.:]/, + 'operator': /[?&|]/ + } + } + }); + }(Prism)); + }, + {} + ], + 8: [ + function (require, module, exports) { + Prism.languages.javascript = Prism.languages.extend('clike', { + 'class-name': [ + Prism.languages.clike['class-name'], + { + pattern: /(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/, + lookbehind: true + } + ], + 'keyword': [ + { + pattern: /((?:^|})\s*)(?:catch|finally)\b/, + lookbehind: true + }, + { + pattern: /(^|[^.]|\.\.\.\s*)\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|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|try|typeof|undefined|var|void|while|with|yield)\b/, + lookbehind: true + } + ], + 'number': /\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/, + 'function': /#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/, + 'operator': /--|\+\+|\*\*=?|=>|&&|\|\||[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?[.?]?|[~:]/ + }); + Prism.languages.javascript['class-name'][0].pattern = /(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/; + Prism.languages.insertBefore('javascript', 'keyword', { + 'regex': { + pattern: /((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=(?:\s|\/\*[\s\S]*?\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/, + lookbehind: true, + greedy: true + }, + 'function-variable': { + pattern: /#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/, + alias: 'function' + }, + 'parameter': [ + { + pattern: /(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/, + lookbehind: true, + inside: Prism.languages.javascript + }, + { + pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i, + inside: Prism.languages.javascript + }, + { + pattern: /(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/, + lookbehind: true, + inside: Prism.languages.javascript + }, + { + pattern: /((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|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|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/, + lookbehind: true, + inside: Prism.languages.javascript + } + ], + 'constant': /\b[A-Z](?:[A-Z_]|\dx?)*\b/ + }); + Prism.languages.insertBefore('javascript', 'string', { + 'template-string': { + pattern: /`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}|(?!\${)[^\\`])*`/, + greedy: true, + inside: { + 'template-punctuation': { + pattern: /^`|`$/, + alias: 'string' + }, + 'interpolation': { + pattern: /((?:^|[^\\])(?:\\{2})*)\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}/, + lookbehind: true, + inside: { + 'interpolation-punctuation': { + pattern: /^\${|}$/, + alias: 'punctuation' + }, + rest: Prism.languages.javascript + } + }, + 'string': /[\s\S]+/ + } + } + }); + if (Prism.languages.markup) { + Prism.languages.markup.tag.addInlined('script', 'javascript'); + } + Prism.languages.js = Prism.languages.javascript; + }, + {} + ], + 9: [ + function (require, module, exports) { + (function (Prism) { + function getPlaceholder(language, index) { + return '___' + language.toUpperCase() + index + '___'; + } + Object.defineProperties(Prism.languages['markup-templating'] = {}, { + buildPlaceholders: { + value: function (env, language, placeholderPattern, replaceFilter) { + if (env.language !== language) { + return; + } + var tokenStack = env.tokenStack = []; + env.code = env.code.replace(placeholderPattern, function (match) { + if (typeof replaceFilter === 'function' && !replaceFilter(match)) { + return match; + } + var i = tokenStack.length; + var placeholder; + while (env.code.indexOf(placeholder = getPlaceholder(language, i)) !== -1) + ++i; + tokenStack[i] = match; + return placeholder; + }); + env.grammar = Prism.languages.markup; + } + }, + tokenizePlaceholders: { + value: function (env, language) { + if (env.language !== language || !env.tokenStack) { + return; + } + env.grammar = Prism.languages[language]; + var j = 0; + var keys = Object.keys(env.tokenStack); + function walkTokens(tokens) { + for (var i = 0; i < tokens.length; i++) { + if (j >= keys.length) { + break; + } + var token = tokens[i]; + if (typeof token === 'string' || token.content && typeof token.content === 'string') { + var k = keys[j]; + var t = env.tokenStack[k]; + var s = typeof token === 'string' ? token : token.content; + var placeholder = getPlaceholder(language, k); + var index = s.indexOf(placeholder); + if (index > -1) { + ++j; + var before = s.substring(0, index); + var middle = new Prism.Token(language, Prism.tokenize(t, env.grammar), 'language-' + language, t); + var after = s.substring(index + placeholder.length); + var replacement = []; + if (before) { + replacement.push.apply(replacement, walkTokens([before])); + } + replacement.push(middle); + if (after) { + replacement.push.apply(replacement, walkTokens([after])); + } + if (typeof token === 'string') { + tokens.splice.apply(tokens, [ + i, + 1 + ].concat(replacement)); + } else { + token.content = replacement; + } + } + } else if (token.content) { + walkTokens(token.content); + } + } + return tokens; + } + walkTokens(env.tokens); + } + } + }); + }(Prism)); + }, + {} + ], + 10: [ + function (require, module, exports) { + Prism.languages.markup = { + 'comment': //, + 'prolog': /<\?[\s\S]+?\?>/, + 'doctype': { + pattern: /"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:(?!)*\]\s*)?>/i, + greedy: true + }, + 'cdata': //i, + 'tag': { + pattern: /<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/i, + greedy: true, + inside: { + 'tag': { + pattern: /^<\/?[^\s>\/]+/i, + inside: { + 'punctuation': /^<\/?/, + 'namespace': /^[^\s>\/:]+:/ + } + }, + 'attr-value': { + pattern: /=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/i, + inside: { + 'punctuation': [ + /^=/, + { + pattern: /^(\s*)["']|["']$/, + lookbehind: true + } + ] + } + }, + 'punctuation': /\/?>/, + 'attr-name': { + pattern: /[^\s>\/]+/, + inside: { 'namespace': /^[^\s>\/:]+:/ } + } + } + }, + 'entity': /?[\da-z]{1,8};/i + }; + Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] = Prism.languages.markup['entity']; + Prism.hooks.add('wrap', function (env) { + if (env.type === 'entity') { + env.attributes['title'] = env.content.replace(/&/, '&'); + } + }); + Object.defineProperty(Prism.languages.markup.tag, 'addInlined', { + value: function addInlined(tagName, lang) { + var includedCdataInside = {}; + includedCdataInside['language-' + lang] = { + pattern: /(^$)/i, + lookbehind: true, + inside: Prism.languages[lang] + }; + includedCdataInside['cdata'] = /^$/i; + var inside = { + 'included-cdata': { + pattern: //i, + inside: includedCdataInside + } + }; + inside['language-' + lang] = { + pattern: /[\s\S]+/, + inside: Prism.languages[lang] + }; + var def = {}; + def[tagName] = { + pattern: RegExp(/(<__[\s\S]*?>)(?:\s*|[\s\S])*?(?=<\/__>)/.source.replace(/__/g, tagName), 'i'), + lookbehind: true, + greedy: true, + inside: inside + }; + Prism.languages.insertBefore('markup', 'cdata', def); + } + }); + Prism.languages.xml = Prism.languages.extend('markup', {}); + Prism.languages.html = Prism.languages.markup; + Prism.languages.mathml = Prism.languages.markup; + Prism.languages.svg = Prism.languages.markup; + }, + {} + ], + 11: [ + function (require, module, exports) { + (function (Prism) { + Prism.languages.php = Prism.languages.extend('clike', { + 'keyword': /\b(?:__halt_compiler|abstract|and|array|as|break|callable|case|catch|class|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|eval|exit|extends|final|finally|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|namespace|new|or|parent|print|private|protected|public|require|require_once|return|static|switch|throw|trait|try|unset|use|var|while|xor|yield)\b/i, + 'boolean': { + pattern: /\b(?:false|true)\b/i, + alias: 'constant' + }, + 'constant': [ + /\b[A-Z_][A-Z0-9_]*\b/, + /\b(?:null)\b/i + ], + 'comment': { + pattern: /(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/, + lookbehind: true + } + }); + Prism.languages.insertBefore('php', 'string', { + 'shell-comment': { + pattern: /(^|[^\\])#.*/, + lookbehind: true, + alias: 'comment' + } + }); + Prism.languages.insertBefore('php', 'comment', { + 'delimiter': { + pattern: /\?>$|^<\?(?:php(?=\s)|=)?/i, + alias: 'important' + } + }); + Prism.languages.insertBefore('php', 'keyword', { + 'variable': /\$+(?:\w+\b|(?={))/i, + 'package': { + pattern: /(\\|namespace\s+|use\s+)[\w\\]+/, + lookbehind: true, + inside: { punctuation: /\\/ } + } + }); + Prism.languages.insertBefore('php', 'operator', { + 'property': { + pattern: /(->)[\w]+/, + lookbehind: true + } + }); + var string_interpolation = { + pattern: /{\$(?:{(?:{[^{}]+}|[^{}]+)}|[^{}])+}|(^|[^\\{])\$+(?:\w+(?:\[.+?]|->\w+)*)/, + lookbehind: true, + inside: Prism.languages.php + }; + Prism.languages.insertBefore('php', 'string', { + 'nowdoc-string': { + pattern: /<<<'([^']+)'(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\1;/, + greedy: true, + alias: 'string', + inside: { + 'delimiter': { + pattern: /^<<<'[^']+'|[a-z_]\w*;$/i, + alias: 'symbol', + inside: { 'punctuation': /^<<<'?|[';]$/ } + } + } + }, + 'heredoc-string': { + pattern: /<<<(?:"([^"]+)"(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\1;|([a-z_]\w*)(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\2;)/i, + greedy: true, + alias: 'string', + inside: { + 'delimiter': { + pattern: /^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i, + alias: 'symbol', + inside: { 'punctuation': /^<<<"?|[";]$/ } + }, + 'interpolation': string_interpolation + } + }, + 'single-quoted-string': { + pattern: /'(?:\\[\s\S]|[^\\'])*'/, + greedy: true, + alias: 'string' + }, + 'double-quoted-string': { + pattern: /"(?:\\[\s\S]|[^\\"])*"/, + greedy: true, + alias: 'string', + inside: { 'interpolation': string_interpolation } + } + }); + delete Prism.languages.php['string']; + Prism.hooks.add('before-tokenize', function (env) { + if (!/<\?/.test(env.code)) { + return; + } + var phpPattern = /<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#)(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|\/\*[\s\S]*?(?:\*\/|$))*?(?:\?>|$)/ig; + Prism.languages['markup-templating'].buildPlaceholders(env, 'php', phpPattern); + }); + Prism.hooks.add('after-tokenize', function (env) { + Prism.languages['markup-templating'].tokenizePlaceholders(env, 'php'); + }); + }(Prism)); + }, + {} + ], + 12: [ + function (require, module, exports) { + Prism.languages.python = { + 'comment': { + pattern: /(^|[^\\])#.*/, + lookbehind: true + }, + 'string-interpolation': { + pattern: /(?:f|rf|fr)(?:("""|''')[\s\S]+?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i, + greedy: true, + inside: { + 'interpolation': { + pattern: /((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/, + lookbehind: true, + inside: { + 'format-spec': { + pattern: /(:)[^:(){}]+(?=}$)/, + lookbehind: true + }, + 'conversion-option': { + pattern: //, + alias: 'punctuation' + }, + rest: null + } + }, + 'string': /[\s\S]+/ + } + }, + 'triple-quoted-string': { + pattern: /(?:[rub]|rb|br)?("""|''')[\s\S]+?\1/i, + greedy: true, + alias: 'string' + }, + 'string': { + pattern: /(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i, + greedy: true + }, + 'function': { + pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g, + lookbehind: true + }, + 'class-name': { + pattern: /(\bclass\s+)\w+/i, + lookbehind: true + }, + 'decorator': { + pattern: /(^\s*)@\w+(?:\.\w+)*/im, + lookbehind: true, + alias: [ + 'annotation', + 'punctuation' + ], + inside: { 'punctuation': /\./ } + }, + 'keyword': /\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/, + 'builtin': /\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/, + 'boolean': /\b(?:True|False|None)\b/, + 'number': /(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i, + 'operator': /[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/, + 'punctuation': /[{}[\];(),.:]/ + }; + Prism.languages.python['string-interpolation'].inside['interpolation'].inside.rest = Prism.languages.python; + Prism.languages.py = Prism.languages.python; + }, + {} + ], + 13: [ + function (require, module, exports) { + (function (Prism) { + Prism.languages.ruby = Prism.languages.extend('clike', { + 'comment': [ + /#.*/, + { + pattern: /^=begin\s[\s\S]*?^=end/m, + greedy: true + } + ], + 'class-name': { + pattern: /(\b(?:class)\s+|\bcatch\s+\()[\w.\\]+/i, + lookbehind: true, + inside: { 'punctuation': /[.\\]/ } + }, + 'keyword': /\b(?:alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|protected|private|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/ + }); + var interpolation = { + pattern: /#\{[^}]+\}/, + inside: { + 'delimiter': { + pattern: /^#\{|\}$/, + alias: 'tag' + }, + rest: Prism.languages.ruby + } + }; + delete Prism.languages.ruby.function; + Prism.languages.insertBefore('ruby', 'keyword', { + 'regex': [ + { + pattern: /%r([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1[gim]{0,3}/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /(^|[^/])\/(?!\/)(?:\[.+?]|\\.|[^/\\\r\n])+\/[gim]{0,3}(?=\s*(?:$|[\r\n,.;})]))/, + lookbehind: true, + greedy: true + } + ], + 'variable': /[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/, + 'symbol': { + pattern: /(^|[^:]):[a-zA-Z_]\w*(?:[?!]|\b)/, + lookbehind: true + }, + 'method-definition': { + pattern: /(\bdef\s+)[\w.]+/, + lookbehind: true, + inside: { + 'function': /\w+$/, + rest: Prism.languages.ruby + } + } + }); + Prism.languages.insertBefore('ruby', 'number', { + 'builtin': /\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|Fixnum|Float|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]\w*(?:[?!]|\b)/ + }); + Prism.languages.ruby.string = [ + { + pattern: /%[qQiIwWxs]?([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/, + greedy: true, + inside: { 'interpolation': interpolation } + }, + { + pattern: /("|')(?:#\{[^}]+\}|\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, + greedy: true, + inside: { 'interpolation': interpolation } + } + ]; + Prism.languages.rb = Prism.languages.ruby; + }(Prism)); + }, + {} + ], + 14: [ + function (require, module, exports) { + var Prism = require('prismjs/components/prism-core'); + require('prismjs/components/prism-clike'); + require('prismjs/components/prism-markup-templating'); + require('prismjs/components/prism-c'); + require('prismjs/components/prism-cpp'); + require('prismjs/components/prism-csharp'); + require('prismjs/components/prism-css'); + require('prismjs/components/prism-java'); + require('prismjs/components/prism-javascript'); + require('prismjs/components/prism-markup'); + require('prismjs/components/prism-php'); + require('prismjs/components/prism-python'); + require('prismjs/components/prism-ruby'); + module.exports = { boltExport: Prism }; + }, + { + 'prismjs/components/prism-c': 1, + 'prismjs/components/prism-clike': 2, + 'prismjs/components/prism-core': 3, + 'prismjs/components/prism-cpp': 4, + 'prismjs/components/prism-csharp': 5, + 'prismjs/components/prism-css': 6, + 'prismjs/components/prism-java': 7, + 'prismjs/components/prism-javascript': 8, + 'prismjs/components/prism-markup': 10, + 'prismjs/components/prism-markup-templating': 9, + 'prismjs/components/prism-php': 11, + 'prismjs/components/prism-python': 12, + 'prismjs/components/prism-ruby': 13 + } + ] + }, {}, [14])(14); + })); + var prism = window.Prism; + window.Prism = oldprism; + return prism; + }(undefined, exports$1, module, undefined)); + var Prism$1 = module.exports.boltExport; + + var getLanguages = function (editor) { + return editor.getParam('codesample_languages'); + }; + var useGlobalPrismJS = function (editor) { + return editor.getParam('codesample_global_prismjs', false, 'boolean'); + }; + + var get = function (editor) { + return Global.Prism && useGlobalPrismJS(editor) ? Global.Prism : Prism$1; + }; + + var getSelectedCodeSample = function (editor) { + var node = editor.selection ? editor.selection.getNode() : null; + if (isCodeSample(node)) { + return Optional.some(node); + } + return Optional.none(); + }; + var insertCodeSample = function (editor, language, code) { + editor.undoManager.transact(function () { + var node = getSelectedCodeSample(editor); + code = global$1.DOM.encode(code); + return node.fold(function () { + editor.insertContent(' ' + code + ''); + editor.selection.select(editor.$('#__new').removeAttr('id')[0]); + }, function (n) { + editor.dom.setAttrib(n, 'class', 'language-' + language); + n.innerHTML = code; + get(editor).highlightElement(n); + editor.selection.select(n); + }); + }); + }; + var getCurrentCode = function (editor) { + var node = getSelectedCodeSample(editor); + return node.fold(function () { + return ''; + }, function (n) { + return n.textContent; + }); + }; + + var getLanguages$1 = function (editor) { + var 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' + } + ]; + var customLanguages = getLanguages(editor); + return customLanguages ? customLanguages : defaultLanguages; + }; + var getCurrentLanguage = function (editor, fallback) { + var node = getSelectedCodeSample(editor); + return node.fold(function () { + return fallback; + }, function (n) { + var matches = n.className.match(/language-(\w+)/); + return matches ? matches[1] : fallback; + }); + }; + + var open = function (editor) { + var languages = getLanguages$1(editor); + var defaultLanguage = head(languages).fold(function () { + return ''; + }, function (l) { + return l.value; + }); + var currentLanguage = getCurrentLanguage(editor, defaultLanguage); + var currentCode = getCurrentCode(editor); + editor.windowManager.open({ + title: 'Insert/Edit Code Sample', + size: 'large', + body: { + type: 'panel', + items: [ + { + type: 'selectbox', + name: 'language', + label: 'Language', + items: languages + }, + { + type: 'textarea', + name: 'code', + label: 'Code view' + } + ] + }, + buttons: [ + { + type: 'cancel', + name: 'cancel', + text: 'Cancel' + }, + { + type: 'submit', + name: 'save', + text: 'Save', + primary: true + } + ], + initialData: { + language: currentLanguage, + code: currentCode + }, + onSubmit: function (api) { + var data = api.getData(); + insertCodeSample(editor, data.language, data.code); + api.close(); + } + }); + }; + + var register = function (editor) { + editor.addCommand('codesample', function () { + var node = editor.selection.getNode(); + if (editor.selection.isCollapsed() || isCodeSample(node)) { + open(editor); + } else { + editor.formatter.toggle('code'); + } + }); + }; + + var setup = function (editor) { + var $ = editor.$; + editor.on('PreProcess', function (e) { + $('pre[contenteditable=false]', e.node).filter(trimArg(isCodeSample)).each(function (idx, elm) { + var $elm = $(elm), code = elm.textContent; + $elm.attr('class', $.trim($elm.attr('class'))); + $elm.removeAttr('contentEditable'); + $elm.empty().append($('').each(function () { + this.textContent = code; + })); + }); + }); + editor.on('SetContent', function () { + var unprocessedCodeSamples = $('pre').filter(trimArg(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); + get(editor).highlightElement(elm); + elm.className = $.trim(elm.className); + }); + }); + } + }); + }; + + var isCodeSampleSelection = function (editor) { + var node = editor.selection.getStart(); + return editor.dom.is(node, 'pre[class*="language-"]'); + }; + var register$1 = function (editor) { + editor.ui.registry.addToggleButton('codesample', { + icon: 'code-sample', + tooltip: 'Insert/edit code sample', + onAction: function () { + return open(editor); + }, + onSetup: function (api) { + var nodeChangeHandler = function () { + api.setActive(isCodeSampleSelection(editor)); + }; + editor.on('NodeChange', nodeChangeHandler); + return function () { + return editor.off('NodeChange', nodeChangeHandler); + }; + } + }); + editor.ui.registry.addMenuItem('codesample', { + text: 'Code sample...', + icon: 'code-sample', + onAction: function () { + return open(editor); + } + }); + }; + + function Plugin () { + global.add('codesample', function (editor) { + setup(editor); + register$1(editor); + register(editor); + editor.on('dblclick', function (ev) { + if (isCodeSample(ev.target)) { + open(editor); + } + }); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.min.js new file mode 100644 index 0000000000..e094d08e6b --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/codesample/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var e,n,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),i=function(e){return function(){return e}},s=i(!1),o=i(!0),r=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:s,isSome:s,isNone:o,getOr:t=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:t,orThunk:n,map:r,each:function(){},bind:r,exists:s,forall:o,filter:r,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),u=function(t){var e=i(t),n=function(){return r},a=function(e){return e(t)},r={fold:function(e,n){return n(t)},is:function(e){return t===e},isSome:o,isNone:s,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return u(e(t))},each:function(e){e(t)},bind:a,exists:a,forall:a,filter:function(e){return e(t)?r:l},toArray:function(){return[t]},toString:function(){return"some("+t+")"},equals:function(e){return e.is(t)},equals_:function(e,n){return e.fold(s,function(e){return n(t,e)})}};return r},c={some:u,none:r,from:function(e){return null===e||e===undefined?l:u(e)}},d=tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");function p(e){return e&&"PRE"===e.nodeName&&-1!==e.className.indexOf("language-")}function g(t){return function(e,n){return t(n)}}var m="undefined"!=typeof window?window:Function("return this;")(),f={},h={exports:f},b={};!function(n,t,a,d){var e=window.Prism;window.Prism={manual:!0},function(e){"object"==typeof t&&void 0!==a?a.exports=e():"function"==typeof n&&n.amd?n([],e):("undefined"!=typeof window?window:void 0!==b?b:"undefined"!=typeof self?self:this).EphoxContactWrapper=e()}(function(){return function c(i,s,o){function l(n,e){if(!s[n]){if(!i[n]){var t="function"==typeof d&&d;if(!e&&t)return t(n,!0);if(u)return u(n,!0);var a=new Error("Cannot find module '"+n+"'");throw a.code="MODULE_NOT_FOUND",a}var r=s[n]={exports:{}};i[n][0].call(r.exports,function(e){return l(i[n][1][e]||e)},r,r.exports,c,i,s,o)}return s[n].exports}for(var u="function"==typeof d&&d,e=0;e>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?/,number:/(?:\b0x(?:[\da-f]+\.?[\da-f]*|\.[\da-f]+)(?:p[+-]?\d+)?|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?)[ful]*/i}),Prism.languages.insertBefore("c","string",{macro:{pattern:/(^\s*)#\s*[a-z]+(?:[^\r\n\\]|\\(?:\r\n|[\s\S]))*/im,lookbehind:!0,alias:"property",inside:{string:{pattern:/(#\s*include\s*)(?:<.+?>|("|')(?:\\?.)+?\2)/,lookbehind:!0},directive:{pattern:/(#\s*)\b(?:define|defined|elif|else|endif|error|ifdef|ifndef|if|import|include|line|pragma|undef|using)\b/,lookbehind:!0,alias:"keyword"}}},constant:/\b(?:__FILE__|__LINE__|__DATE__|__TIME__|__TIMESTAMP__|__func__|EOF|NULL|SEEK_CUR|SEEK_END|SEEK_SET|stdin|stdout|stderr)\b/}),delete Prism.languages.c["boolean"]},{}],2:[function(e,n,t){Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,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":/\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/}},{}],3:[function(e,t,n){(function(e){var n=function(u){var c=/\blang(?:uage)?-([\w-]+)\b/i,n=0,C={manual:u.Prism&&u.Prism.manual,disableWorkerMessageHandler:u.Prism&&u.Prism.disableWorkerMessageHandler,util:{encode:function(e){return e instanceof O?new O(e.type,C.util.encode(e.content),e.alias):Array.isArray(e)?e.map(C.util.encode):e.replace(/&/g,"&").replace(/e.length)return;if(!(w instanceof O)){if(m&&b!=n.length-1){if(d.lastIndex=y,!(P=d.exec(e)))break;for(var v=P.index+(g&&P[1]?P[1].length:0),k=P.index+P[0].length,x=b,_=y,F=n.length;x "+a.content+""+a.tag+">"},!u.document)return u.addEventListener&&(C.disableWorkerMessageHandler||u.addEventListener("message",function(e){var n=JSON.parse(e.data),t=n.language,a=n.code,r=n.immediateClose;u.postMessage(C.highlight(a,C.languages[t],t)),r&&u.close()},!1)),C;var e,t,a=C.util.currentScript();return a&&(C.filename=a.src,a.hasAttribute("data-manual")&&(C.manual=!0)),C.manual||(e=function(){C.manual||C.highlightAll()},"loading"===(t=document.readyState)||"interactive"===t&&a&&a.defer?document.addEventListener("DOMContentLoaded",e):window.requestAnimationFrame?window.requestAnimationFrame(e):window.setTimeout(e,16)),C}("undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{});void 0!==t&&t.exports&&(t.exports=n),void 0!==e&&(e.Prism=n)}).call(this,void 0!==b?b:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],4:[function(e,n,t){Prism.languages.cpp=Prism.languages.extend("c",{"class-name":{pattern:/(\b(?:class|enum|struct)\s+)\w+/,lookbehind:!0},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|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t|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/,number:{pattern:/(?:\b0b[01']+|\b0x(?:[\da-f']+\.?[\da-f']*|\.[\da-f']+)(?:p[+-]?[\d']+)?|(?:\b[\d']+\.?[\d']*|\B\.[\d']+)(?:e[+-]?[\d']+)?)[ful]*/i,greedy:!0},operator:/>>=?|<<=?|->|([-+&|:])\1|[?:~]|[-+*/%&|^!=<>]=?|\b(?:and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/,"boolean":/\b(?:true|false)\b/}),Prism.languages.insertBefore("cpp","string",{"raw-string":{pattern:/R"([^()\\ ]{0,16})\([\s\S]*?\)\1"/,alias:"string",greedy:!0}})},{}],5:[function(e,n,t){Prism.languages.csharp=Prism.languages.extend("clike",{keyword:/\b(?:abstract|add|alias|as|ascending|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|descending|do|double|dynamic|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|from|get|global|goto|group|if|implicit|in|int|interface|internal|into|is|join|let|lock|long|namespace|new|null|object|operator|orderby|out|override|params|partial|private|protected|public|readonly|ref|remove|return|sbyte|sealed|select|set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|value|var|virtual|void|volatile|where|while|yield)\b/,string:[{pattern:/@("|')(?:\1\1|\\[\s\S]|(?!\1)[^\\])*\1/,greedy:!0},{pattern:/("|')(?:\\.|(?!\1)[^\\\r\n])*?\1/,greedy:!0}],"class-name":[{pattern:/\b[A-Z]\w*(?:\.\w+)*\b(?=\s+\w+)/,inside:{punctuation:/\./}},{pattern:/(\[)[A-Z]\w*(?:\.\w+)*\b/,lookbehind:!0,inside:{punctuation:/\./}},{pattern:/(\b(?:class|interface)\s+[A-Z]\w*(?:\.\w+)*\s*:\s*)[A-Z]\w*(?:\.\w+)*\b/,lookbehind:!0,inside:{punctuation:/\./}},{pattern:/((?:\b(?:class|interface|new)\s+)|(?:catch\s+\())[A-Z]\w*(?:\.\w+)*\b/,lookbehind:!0,inside:{punctuation:/\./}}],number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)f?/i,operator:/>>=?|<<=?|[-=]>|([-+&|?])\1|~|[-+*/%&|^!=<>]=?/,punctuation:/\?\.?|::|[{}[\];(),.:]/}),Prism.languages.insertBefore("csharp","class-name",{"generic-method":{pattern:/\w+\s*<[^>\r\n]+?>\s*(?=\()/,inside:{"function":/^\w+/,"class-name":{pattern:/\b[A-Z]\w*(?:\.\w+)*\b/,inside:{punctuation:/\./}},keyword:Prism.languages.csharp.keyword,punctuation:/[<>(),.:]/}},preprocessor:{pattern:/(^\s*)#.*/m,lookbehind:!0,alias:"property",inside:{directive:{pattern:/(\s*#)\b(?:define|elif|else|endif|endregion|error|if|line|pragma|region|undef|warning)\b/,lookbehind:!0,alias:"keyword"}}}}),Prism.languages.dotnet=Prism.languages.cs=Prism.languages.csharp},{}],6:[function(e,n,t){!function(e){var n=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/;e.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-]+[\s\S]*?(?:;|(?=\s*\{))/,inside:{rule:/@[\w-]+/}},url:{pattern:RegExp("url\\((?:"+n.source+"|[^\n\r()]*)\\)","i"),inside:{"function":/^url/i,punctuation:/^\(|\)$/}},selector:RegExp("[^{}\\s](?:[^{};\"']|"+n.source+")*?(?=\\s*\\{)"),string:{pattern:n,greedy:!0},property:/[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,important:/!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:,]/},e.languages.css.atrule.inside.rest=e.languages.css;var t=e.languages.markup;t&&(t.tag.addInlined("style","css"),e.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:t.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:e.languages.css}},alias:"language-css"}},t.tag))}(Prism)},{}],7:[function(e,n,t){var a,r,i;a=Prism,r=/\b(?:abstract|assert|boolean|break|byte|case|catch|char|class|const|continue|default|do|double|else|enum|exports|extends|final|finally|float|for|goto|if|implements|import|instanceof|int|interface|long|module|native|new|null|open|opens|package|private|protected|provides|public|requires|return|short|static|strictfp|super|switch|synchronized|this|throw|throws|to|transient|transitive|try|uses|var|void|volatile|while|with|yield)\b/,i=/\b[A-Z](?:\w*[a-z]\w*)?\b/,a.languages.java=a.languages.extend("clike",{"class-name":[i,/\b[A-Z]\w*(?=\s+\w+\s*[;,=())])/],keyword:r,"function":[a.languages.clike["function"],{pattern:/(\:\:)[a-z_]\w*/,lookbehind:!0}],number:/\b0b[01][01_]*L?\b|\b0x[\da-f_]*\.?[\da-f_p+-]+\b|(?:\b\d[\d_]*\.?[\d_]*|\B\.\d[\d_]*)(?:e[+-]?\d[\d_]*)?[dfl]?/i,operator:{pattern:/(^|[^.])(?:<<=?|>>>?=?|->|--|\+\+|&&|\|\||::|[?:~]|[-+*/%&|^!=<>]=?)/m,lookbehind:!0}}),a.languages.insertBefore("java","string",{"triple-quoted-string":{pattern:/"""[ \t]*[\r\n](?:(?:"|"")?(?:\\.|[^"\\]))*"""/,greedy:!0,alias:"string"}}),a.languages.insertBefore("java","class-name",{annotation:{alias:"punctuation",pattern:/(^|[^.])@\w+/,lookbehind:!0},namespace:{pattern:/(\b(?:exports|import(?:\s+static)?|module|open|opens|package|provides|requires|to|transitive|uses|with)\s+)[a-z]\w*(?:\.[a-z]\w*)+/,lookbehind:!0,inside:{punctuation:/\./}},generics:{pattern:/<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<(?:[\w\s,.&?]|<[\w\s,.&?]*>)*>)*>)*>/,inside:{"class-name":i,keyword:r,punctuation:/[<>(),.:]/,operator:/[?&|]/}}})},{}],8:[function(e,n,t){Prism.languages.javascript=Prism.languages.extend("clike",{"class-name":[Prism.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/,lookbehind:!0}],keyword:[{pattern:/((?:^|})\s*)(?:catch|finally)\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|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|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],number:/\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,"function":/#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,operator:/--|\+\+|\*\*=?|=>|&&|\|\||[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?[.?]?|[~:]/}),Prism.languages.javascript["class-name"][0].pattern=/(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/,Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=(?:\s|\/\*[\s\S]*?\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,lookbehind:!0,greedy:!0},"function-variable":{pattern:/#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i,inside:Prism.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/,lookbehind:!0,inside:Prism.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|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|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/,lookbehind:!0,inside:Prism.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),Prism.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}|(?!\${)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\${|}$/,alias:"punctuation"},rest:Prism.languages.javascript}},string:/[\s\S]+/}}}),Prism.languages.markup&&Prism.languages.markup.tag.addInlined("script","javascript"),Prism.languages.js=Prism.languages.javascript},{}],9:[function(e,n,t){function b(e,n){return"___"+e.toUpperCase()+n+"___"}var y;y=Prism,Object.defineProperties(y.languages["markup-templating"]={},{buildPlaceholders:{value:function(a,r,e,i){var s;a.language===r&&(s=a.tokenStack=[],a.code=a.code.replace(e,function(e){if("function"==typeof i&&!i(e))return e;for(var n,t=s.length;-1!==a.code.indexOf(n=b(r,t));)++t;return s[t]=e,n}),a.grammar=y.languages.markup)}},tokenizePlaceholders:{value:function(p,g){var m,f;p.language===g&&p.tokenStack&&(p.grammar=y.languages[g],m=0,f=Object.keys(p.tokenStack),function h(e){for(var n=0;n =f.length);n++){var t,a,r,i,s,o,l,u,c,d=e[n];"string"==typeof d||d.content&&"string"==typeof d.content?(t=f[m],a=p.tokenStack[t],r="string"==typeof d?d:d.content,i=b(g,t),-1<(s=r.indexOf(i))&&(++m,o=r.substring(0,s),l=new y.Token(g,y.tokenize(a,p.grammar),"language-"+g,a),u=r.substring(s+i.length),c=[],o&&c.push.apply(c,h([o])),c.push(l),u&&c.push.apply(c,h([u])),"string"==typeof d?e.splice.apply(e,[n,1].concat(c)):d.content=c)):d.content&&h(d.content)}return e}(p.tokens))}}})},{}],10:[function(e,n,t){Prism.languages.markup={comment://,prolog:/<\?[\s\S]+?\?>/,doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:(?!)*\]\s*)?>/i,greedy:!0},cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/i,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/i,inside:{punctuation:[/^=/,{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/?[\da-z]{1,8};/i},Prism.languages.markup.tag.inside["attr-value"].inside.entity=Prism.languages.markup.entity,Prism.hooks.add("wrap",function(e){"entity"===e.type&&(e.attributes.title=e.content.replace(/&/,"&"))}),Object.defineProperty(Prism.languages.markup.tag,"addInlined",{value:function(e,n){var t={};t["language-"+n]={pattern:/(^$)/i,lookbehind:!0,inside:Prism.languages[n]},t.cdata=/^$/i;var a={"included-cdata":{pattern://i,inside:t}};a["language-"+n]={pattern:/[\s\S]+/,inside:Prism.languages[n]};var r={};r[e]={pattern:RegExp(/(<__[\s\S]*?>)(?:\s*|[\s\S])*?(?=<\/__>)/.source.replace(/__/g,e),"i"),lookbehind:!0,greedy:!0,inside:a},Prism.languages.insertBefore("markup","cdata",r)}}),Prism.languages.xml=Prism.languages.extend("markup",{}),Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup},{}],11:[function(e,n,t){!function(n){n.languages.php=n.languages.extend("clike",{keyword:/\b(?:__halt_compiler|abstract|and|array|as|break|callable|case|catch|class|clone|const|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|eval|exit|extends|final|finally|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|namespace|new|or|parent|print|private|protected|public|require|require_once|return|static|switch|throw|trait|try|unset|use|var|while|xor|yield)\b/i,"boolean":{pattern:/\b(?:false|true)\b/i,alias:"constant"},constant:[/\b[A-Z_][A-Z0-9_]*\b/,/\b(?:null)\b/i],comment:{pattern:/(^|[^\\])(?:\/\*[\s\S]*?\*\/|\/\/.*)/,lookbehind:!0}}),n.languages.insertBefore("php","string",{"shell-comment":{pattern:/(^|[^\\])#.*/,lookbehind:!0,alias:"comment"}}),n.languages.insertBefore("php","comment",{delimiter:{pattern:/\?>$|^<\?(?:php(?=\s)|=)?/i,alias:"important"}}),n.languages.insertBefore("php","keyword",{variable:/\$+(?:\w+\b|(?={))/i,"package":{pattern:/(\\|namespace\s+|use\s+)[\w\\]+/,lookbehind:!0,inside:{punctuation:/\\/}}}),n.languages.insertBefore("php","operator",{property:{pattern:/(->)[\w]+/,lookbehind:!0}});var e={pattern:/{\$(?:{(?:{[^{}]+}|[^{}]+)}|[^{}])+}|(^|[^\\{])\$+(?:\w+(?:\[.+?]|->\w+)*)/,lookbehind:!0,inside:n.languages.php};n.languages.insertBefore("php","string",{"nowdoc-string":{pattern:/<<<'([^']+)'(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\1;/,greedy:!0,alias:"string",inside:{delimiter:{pattern:/^<<<'[^']+'|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<'?|[';]$/}}}},"heredoc-string":{pattern:/<<<(?:"([^"]+)"(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\1;|([a-z_]\w*)(?:\r\n?|\n)(?:.*(?:\r\n?|\n))*?\2;)/i,greedy:!0,alias:"string",inside:{delimiter:{pattern:/^<<<(?:"[^"]+"|[a-z_]\w*)|[a-z_]\w*;$/i,alias:"symbol",inside:{punctuation:/^<<<"?|[";]$/}},interpolation:e}},"single-quoted-string":{pattern:/'(?:\\[\s\S]|[^\\'])*'/,greedy:!0,alias:"string"},"double-quoted-string":{pattern:/"(?:\\[\s\S]|[^\\"])*"/,greedy:!0,alias:"string",inside:{interpolation:e}}}),delete n.languages.php.string,n.hooks.add("before-tokenize",function(e){/<\?/.test(e.code)&&n.languages["markup-templating"].buildPlaceholders(e,"php",/<\?(?:[^"'/#]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|(?:\/\/|#)(?:[^?\n\r]|\?(?!>))*(?=$|\?>|[\r\n])|\/\*[\s\S]*?(?:\*\/|$))*?(?:\?>|$)/gi)}),n.hooks.add("after-tokenize",function(e){n.languages["markup-templating"].tokenizePlaceholders(e,"php")})}(Prism)},{}],12:[function(e,n,t){Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"string-interpolation":{pattern:/(?:f|rf|fr)(?:("""|''')[\s\S]+?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=}$)/,lookbehind:!0},"conversion-option":{pattern://,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|rb|br)?("""|''')[\s\S]+?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},"function":{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/im,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,"boolean":/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python},{}],13:[function(e,n,t){!function(e){e.languages.ruby=e.languages.extend("clike",{comment:[/#.*/,{pattern:/^=begin\s[\s\S]*?^=end/m,greedy:!0}],"class-name":{pattern:/(\b(?:class)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|extend|for|if|in|include|module|new|next|nil|not|or|prepend|protected|private|public|raise|redo|require|rescue|retry|return|self|super|then|throw|undef|unless|until|when|while|yield)\b/});var n={pattern:/#\{[^}]+\}/,inside:{delimiter:{pattern:/^#\{|\}$/,alias:"tag"},rest:e.languages.ruby}};delete e.languages.ruby["function"],e.languages.insertBefore("ruby","keyword",{regex:[{pattern:/%r([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/,greedy:!0,inside:{interpolation:n}},{pattern:/(^|[^/])\/(?!\/)(?:\[.+?]|\\.|[^/\\\r\n])+\/[gim]{0,3}(?=\s*(?:$|[\r\n,.;})]))/,lookbehind:!0,greedy:!0}],variable:/[@$]+[a-zA-Z_]\w*(?:[?!]|\b)/,symbol:{pattern:/(^|[^:]):[a-zA-Z_]\w*(?:[?!]|\b)/,lookbehind:!0},"method-definition":{pattern:/(\bdef\s+)[\w.]+/,lookbehind:!0,inside:{"function":/\w+$/,rest:e.languages.ruby}}}),e.languages.insertBefore("ruby","number",{builtin:/\b(?:Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|Fixnum|Float|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]\w*(?:[?!]|\b)/}),e.languages.ruby.string=[{pattern:/%[qQiIwWxs]?([^a-zA-Z0-9\s{(\[<])(?:(?!\1)[^\\]|\\[\s\S])*\1/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/,greedy:!0,inside:{interpolation:n}},{pattern:/%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/,greedy:!0,inside:{interpolation:n}},{pattern:/("|')(?:#\{[^}]+\}|\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0,inside:{interpolation:n}}],e.languages.rb=e.languages.ruby}(Prism)},{}],14:[function(e,n,t){var a=e("prismjs/components/prism-core");e("prismjs/components/prism-clike"),e("prismjs/components/prism-markup-templating"),e("prismjs/components/prism-c"),e("prismjs/components/prism-cpp"),e("prismjs/components/prism-csharp"),e("prismjs/components/prism-css"),e("prismjs/components/prism-java"),e("prismjs/components/prism-javascript"),e("prismjs/components/prism-markup"),e("prismjs/components/prism-php"),e("prismjs/components/prism-python"),e("prismjs/components/prism-ruby"),n.exports={boltExport:a}},{"prismjs/components/prism-c":1,"prismjs/components/prism-clike":2,"prismjs/components/prism-core":3,"prismjs/components/prism-cpp":4,"prismjs/components/prism-csharp":5,"prismjs/components/prism-css":6,"prismjs/components/prism-java":7,"prismjs/components/prism-javascript":8,"prismjs/components/prism-markup":10,"prismjs/components/prism-markup-templating":9,"prismjs/components/prism-php":11,"prismjs/components/prism-python":12,"prismjs/components/prism-ruby":13}]},{},[14])(14)});var r=window.Prism;window.Prism=e}(undefined,f,h,undefined);var y=h.exports.boltExport,w=function(e){return m.Prism&&e.getParam("codesample_global_prismjs",!1,"boolean")?m.Prism:y},v=function(e){var n=e.selection?e.selection.getNode():null;return p(n)?c.some(n):c.none()},k=function(i){var e,t,n=i.getParam("codesample_languages")||[{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"}],a=(0===(e=n).length?c.none():c.some(e[0])).fold(function(){return""},function(e){return e.value}),r=(t=a,v(i).fold(function(){return t},function(e){var n=e.className.match(/language-(\w+)/);return n?n[1]:t})),s=v(i).fold(function(){return""},function(e){return e.textContent});i.windowManager.open({title:"Insert/Edit Code Sample",size:"large",body:{type:"panel",items:[{type:"selectbox",name:"language",label:"Language",items:n},{type:"textarea",name:"code",label:"Code view"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:{language:r,code:s},onSubmit:function(e){var n,t,a,r=e.getData();n=i,t=r.language,a=r.code,n.undoManager.transact(function(){var e=v(n);return a=d.DOM.encode(a),e.fold(function(){n.insertContent(' '+a+""),n.selection.select(n.$("#__new").removeAttr("id")[0])},function(e){n.dom.setAttrib(e,"class","language-"+t),e.innerHTML=a,w(n).highlightElement(e),n.selection.select(e)})}),e.close()}})},x=function(a){a.ui.registry.addToggleButton("codesample",{icon:"code-sample",tooltip:"Insert/edit code sample",onAction:function(){return k(a)},onSetup:function(t){var e=function(){var e,n;t.setActive((n=(e=a).selection.getStart(),e.dom.is(n,'pre[class*="language-"]')))};return a.on("NodeChange",e),function(){return a.off("NodeChange",e)}}}),a.ui.registry.addMenuItem("codesample",{text:"Code sample...",icon:"code-sample",onAction:function(){return k(a)}})};a.add("codesample",function(n){var t,r,a;r=(t=n).$,t.on("PreProcess",function(e){r("pre[contenteditable=false]",e.node).filter(g(p)).each(function(e,n){var t=r(n),a=n.textContent;t.attr("class",r.trim(t.attr("class"))),t.removeAttr("contentEditable"),t.empty().append(r("").each(function(){this.textContent=a}))})}),t.on("SetContent",function(){var e=r("pre").filter(g(p)).filter(function(e,n){return"false"!==n.contentEditable});e.length&&t.undoManager.transact(function(){e.each(function(e,n){r(n).find("br").each(function(e,n){n.parentNode.replaceChild(t.getDoc().createTextNode("\n"),n)}),n.contentEditable="false",n.innerHTML=t.dom.encode(n.textContent),w(t).highlightElement(n),n.className=r.trim(n.className)})})}),x(n),(a=n).addCommand("codesample",function(){var e=a.selection.getNode();a.selection.isCollapsed()||p(e)?k(a):a.formatter.toggle("code")}),n.on("dblclick",function(e){p(e.target)&&k(n)})})}(); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.js new file mode 100644 index 0000000000..2d0623aacb --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.js @@ -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/ + * + * Version: 5.5.1 (2020-10-01) + */ +(function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + function Plugin () { + global.add('colorpicker', function () { + console.warn('Color picker plugin is now built in to the core editor, please remove it from your editor configuration'); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.min.js new file mode 100644 index 0000000000..ccdf6629cb --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/colorpicker/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";tinymce.util.Tools.resolve("tinymce.PluginManager").add("colorpicker",function(){console.warn("Color picker plugin is now built in to the core editor, please remove it from your editor configuration")})}(); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js index ada25f77b7..0a7ef19bce 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.js @@ -1,77 +1,22 @@ /** - * plugin.js + * 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/ * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing + * Version: 5.5.1 (2020-10-01) */ +(function () { + 'use strict'; -/*global tinymce:true */ + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); -tinymce.PluginManager.add('contextmenu', function(editor) { - var menu, contextmenuNeverUseNative = editor.settings.contextmenu_never_use_native; + function Plugin () { + global.add('contextmenu', function () { + console.warn('Context menu plugin is now built in to the core editor, please remove it from your editor configuration'); + }); + } - editor.on('contextmenu', function(e) { - var contextmenu; + Plugin(); - // Block TinyMCE menu on ctrlKey - if (e.ctrlKey && !contextmenuNeverUseNative) { - return; - } - - e.preventDefault(); - - contextmenu = editor.settings.contextmenu || 'link image inserttable | cell row column deletetable'; - - // Render menu - if (!menu) { - var items = []; - - tinymce.each(contextmenu.split(/[ ,]/), function(name) { - var item = editor.menuItems[name]; - - if (name == '|') { - item = {text: name}; - } - - if (item) { - item.shortcut = ''; // Hide shortcuts - items.push(item); - } - }); - - for (var i = 0; i < items.length; i++) { - if (items[i].text == '|') { - if (i === 0 || i == items.length - 1) { - items.splice(i, 1); - } - } - } - - menu = new tinymce.ui.Menu({ - items: items, - context: 'contextmenu' - }).addClass('contextmenu').renderTo(); - - editor.on('remove', function() { - menu.remove(); - menu = null; - }); - } else { - menu.show(); - } - - // Position menu - var pos = {x: e.pageX, y: e.pageY}; - - if (!editor.inline) { - pos = tinymce.DOM.getPos(editor.getContentAreaContainer()); - pos.x += e.clientX; - pos.y += e.clientY; - } - - menu.moveTo(pos.x, pos.y); - }); -}); \ No newline at end of file +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js index 06f0d4bd5d..9ecd56617a 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/contextmenu/plugin.min.js @@ -1 +1,9 @@ -tinymce.PluginManager.add("contextmenu",function(e){var n,t=e.settings.contextmenu_never_use_native;e.on("contextmenu",function(i){var o;if(!i.ctrlKey||t){if(i.preventDefault(),o=e.settings.contextmenu||"link image inserttable | cell row column deletetable",n)n.show();else{var c=[];tinymce.each(o.split(/[ ,]/),function(n){var t=e.menuItems[n];"|"==n&&(t={text:n}),t&&(t.shortcut="",c.push(t))});for(var a=0;a1) { + console.error('HTML does not have a single root node', html); + throw new Error('HTML must have a single root node'); + } + return fromDom(div.childNodes[0]); + }; + var fromTag = function (tag, scope) { + var doc = scope || document; + var node = doc.createElement(tag); + return fromDom(node); + }; + var fromText = function (text, scope) { + var doc = scope || document; + var node = doc.createTextNode(text); + return fromDom(node); + }; + var fromDom = function (node) { + if (node === null || node === undefined) { + throw new Error('Node cannot be null or undefined'); + } + return { dom: node }; + }; + var fromPoint = function (docElm, x, y) { + return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); + }; + var SugarElement = { + fromHtml: fromHtml, + fromTag: fromTag, + fromText: fromText, + fromDom: fromDom, + fromPoint: fromPoint + }; + + var Global = typeof window !== 'undefined' ? window : Function('return this;')(); + + var DOCUMENT = 9; + var DOCUMENT_FRAGMENT = 11; + var TEXT = 3; + + var type = function (element) { + return element.dom.nodeType; + }; + var isType = function (t) { + return function (element) { + return type(element) === t; + }; + }; + var isText = isType(TEXT); + var isDocument = isType(DOCUMENT); + var isDocumentFragment = isType(DOCUMENT_FRAGMENT); + + var owner = function (element) { + return SugarElement.fromDom(element.dom.ownerDocument); + }; + var documentOrOwner = function (dos) { + return isDocument(dos) ? dos : owner(dos); + }; + + var isShadowRoot = function (dos) { + return isDocumentFragment(dos); + }; + var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode); + var getRootNode = supported ? function (e) { + return SugarElement.fromDom(e.dom.getRootNode()); + } : documentOrOwner; + var getShadowRoot = function (e) { + var r = getRootNode(e); + return isShadowRoot(r) ? Optional.some(r) : Optional.none(); + }; + var getShadowHost = function (e) { + return SugarElement.fromDom(e.dom.host); + }; + + var inBody = function (element) { + var dom = isText(element) ? element.dom.parentNode : element.dom; + if (dom === undefined || dom === null || dom.ownerDocument === null) { + return false; + } + var doc = dom.ownerDocument; + return getShadowRoot(SugarElement.fromDom(dom)).fold(function () { + return doc.body.contains(dom); + }, compose1(inBody, getShadowHost)); + }; + + var get = function (element, property) { + var dom = element.dom; + var styles = window.getComputedStyle(dom); + var r = styles.getPropertyValue(property); + return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r; + }; + var getUnsafeProperty = function (dom, property) { + return isSupported(dom) ? dom.style.getPropertyValue(property) : ''; + }; + + var getDirection = function (element) { + return get(element, 'direction') === 'rtl' ? 'rtl' : 'ltr'; + }; + + var getNodeChangeHandler = function (editor, dir) { + return function (api) { + var nodeChangeHandler = function (e) { + var element = SugarElement.fromDom(e.element); + api.setActive(getDirection(element) === dir); + }; + editor.on('NodeChange', nodeChangeHandler); + return function () { + return editor.off('NodeChange', nodeChangeHandler); + }; + }; + }; + var register$1 = function (editor) { + editor.ui.registry.addToggleButton('ltr', { + tooltip: 'Left to right', + icon: 'ltr', + onAction: function () { + return editor.execCommand('mceDirectionLTR'); + }, + onSetup: getNodeChangeHandler(editor, 'ltr') + }); + editor.ui.registry.addToggleButton('rtl', { + tooltip: 'Right to left', + icon: 'rtl', + onAction: function () { + return editor.execCommand('mceDirectionRTL'); + }, + onSetup: getNodeChangeHandler(editor, 'rtl') + }); + }; + + function Plugin () { + global.add('directionality', function (editor) { + register(editor); + register$1(editor); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/directionality/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/directionality/plugin.min.js new file mode 100644 index 0000000000..e556a29755 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/directionality/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var n,t,e,o,r=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=tinymce.util.Tools.resolve("tinymce.util.Tools"),i=function(n,t){var e,o=n.dom,r=n.selection.getSelectedBlocks();r.length&&(e=o.getAttrib(r[0],"dir"),u.each(r,function(n){o.getParent(n.parentNode,'*[dir="'+t+'"]',o.getRoot())||o.setAttrib(n,"dir",e!==t?t:null)}),n.nodeChanged())},c=function(n){return function(){return n}},f=c(!1),d=c(!0),l=function(){return m},m=(n=function(n){return n.isNone()},{fold:function(n,t){return n()},is:f,isSome:f,isNone:d,getOr:e=function(n){return n},getOrThunk:t=function(n){return n()},getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:c(null),getOrUndefined:c(undefined),or:e,orThunk:t,map:l,each:function(){},bind:l,exists:f,forall:d,filter:l,equals:n,equals_:n,toArray:function(){return[]},toString:c("none()")}),a=function(e){var n=c(e),t=function(){return r},o=function(n){return n(e)},r={fold:function(n,t){return t(e)},is:function(n){return e===n},isSome:d,isNone:f,getOr:n,getOrThunk:n,getOrDie:n,getOrNull:n,getOrUndefined:n,or:t,orThunk:t,map:function(n){return a(n(e))},each:function(n){n(e)},bind:o,exists:o,forall:o,filter:function(n){return n(e)?r:m},toArray:function(){return[e]},toString:function(){return"some("+e+")"},equals:function(n){return n.is(e)},equals_:function(n,t){return n.fold(f,function(n){return t(e,n)})}};return r},s={some:a,none:l,from:function(n){return null===n||n===undefined?m:a(n)}},g=(o="function",function(n){return typeof n===o}),h=function(n){if(null===n||n===undefined)throw new Error("Node cannot be null or undefined");return{dom:n}},y={fromHtml:function(n,t){var e=(t||document).createElement("div");if(e.innerHTML=n,!e.hasChildNodes()||1 = max; + }; + }); + for (var i = 0; i < list.length; i++) { + if (pattern.length === 0 || emojiMatches(list[i], lowerCasePattern)) { + matches.push({ + value: list[i].char, + text: list[i].title, + icon: list[i].char + }); + if (reachedLimit(matches.length)) { + break; + } + } + } + return matches; + }; + + var init = function (editor, database) { + editor.ui.registry.addAutocompleter('emoticons', { + ch: ':', + columns: 'auto', + minChars: 2, + fetch: function (pattern, maxResults) { + return database.waitForLoad().then(function () { + var candidates = database.listAll(); + return emojisFrom(candidates, pattern, Optional.some(maxResults)); + }); + }, + onAction: function (autocompleteApi, rng, value) { + editor.selection.setRng(rng); + editor.insertContent(value); + autocompleteApi.hide(); + } + }); + }; + + var last = function (fn, rate) { + var timer = null; + var cancel = function () { + if (timer !== null) { + clearTimeout(timer); + timer = null; + } + }; + var throttle = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (timer !== null) { + clearTimeout(timer); + } + timer = setTimeout(function () { + fn.apply(null, args); + timer = null; + }, rate); + }; + return { + cancel: cancel, + throttle: throttle + }; + }; + + var insertEmoticon = function (editor, ch) { + editor.insertContent(ch); + }; + + var patternName = 'pattern'; + var open = function (editor, database) { + var initialState = { + pattern: '', + results: emojisFrom(database.listAll(), '', Optional.some(300)) + }; + var currentTab = Cell(ALL_CATEGORY); + var scan = function (dialogApi) { + var dialogData = dialogApi.getData(); + var category = currentTab.get(); + var candidates = database.listCategory(category); + var results = emojisFrom(candidates, dialogData[patternName], category === ALL_CATEGORY ? Optional.some(300) : Optional.none()); + dialogApi.setData({ results: results }); + }; + var updateFilter = last(function (dialogApi) { + scan(dialogApi); + }, 200); + var searchField = { + label: 'Search', + type: 'input', + name: patternName + }; + var resultsField = { + type: 'collection', + name: 'results' + }; + var getInitialState = function () { + var body = { + type: 'tabpanel', + tabs: map$1(database.listCategories(), function (cat) { + return { + title: cat, + name: cat, + items: [ + searchField, + resultsField + ] + }; + }) + }; + return { + title: 'Emoticons', + size: 'normal', + body: body, + initialData: initialState, + onTabChange: function (dialogApi, details) { + currentTab.set(details.newTabName); + updateFilter.throttle(dialogApi); + }, + onChange: updateFilter.throttle, + onAction: function (dialogApi, actionData) { + if (actionData.name === 'results') { + insertEmoticon(editor, actionData.value); + dialogApi.close(); + } + }, + buttons: [{ + type: 'cancel', + text: 'Close', + primary: true + }] + }; + }; + var dialogApi = editor.windowManager.open(getInitialState()); + dialogApi.focus(patternName); + if (!database.hasLoaded()) { + dialogApi.block('Loading emoticons...'); + database.waitForLoad().then(function () { + dialogApi.redial(getInitialState()); + updateFilter.throttle(dialogApi); + dialogApi.focus(patternName); + dialogApi.unblock(); + }).catch(function (_err) { + dialogApi.redial({ + title: 'Emoticons', + body: { + type: 'panel', + items: [{ + type: 'alertbanner', + level: 'error', + icon: 'warning', + text: ' Could not load emoticons
' + }] + }, + buttons: [{ + type: 'cancel', + text: 'Close', + primary: true + }], + initialData: { + pattern: '', + results: [] + } + }); + dialogApi.focus(patternName); + dialogApi.unblock(); + }); + } + }; + + var register = function (editor, database) { + var onAction = function () { + return open(editor, database); + }; + editor.ui.registry.addButton('emoticons', { + tooltip: 'Emoticons', + icon: 'emoji', + onAction: onAction + }); + editor.ui.registry.addMenuItem('emoticons', { + text: 'Emoticons...', + icon: 'emoji', + onAction: onAction + }); + }; + + function Plugin () { + global.add('emoticons', function (editor, pluginUrl) { + var databaseUrl = getEmoticonDatabaseUrl(editor, pluginUrl); + var databaseId = getEmoticonDatabaseId(editor); + var database = initDatabase(editor, databaseUrl, databaseId); + register(editor, database); + init(editor, database); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/emoticons/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/emoticons/plugin.min.js new file mode 100644 index 0000000000..a44a370f6b --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/emoticons/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var u,n,t,e,o=tinymce.util.Tools.resolve("tinymce.PluginManager"),r=function(){return(r=Object.assign||function(n){for(var t,e=1,o=arguments.length;eCould not load emoticons ' + value + ' \n'; + } + if (value = getDefaultEncoding(editor)) { + header += '\n'; + } + if (value = getDefaultFontFamily(editor)) { + styles += 'font-family: ' + value + ';'; + } + if (value = getDefaultFontSize(editor)) { + styles += 'font-size: ' + value + ';'; + } + if (value = getDefaultTextColor(editor)) { + styles += 'color: ' + value + ';'; + } + header += '\n\n'; + return header; + }; + var handleGetContent = function (editor, head, foot, evt) { + if (!evt.selection && (!evt.source_view || !shouldHideInSourceView(editor))) { + evt.content = unprotectHtml(global$1.trim(head) + '\n' + global$1.trim(evt.content) + '\n' + global$1.trim(foot)); + } + }; + var setup = function (editor, headState, footState) { + editor.on('BeforeSetContent', function (evt) { + handleSetContent(editor, headState, footState, evt); + }); + editor.on('GetContent', function (evt) { + handleGetContent(editor, headState.get(), footState.get(), evt); + }); + }; + + var register$1 = function (editor) { + editor.ui.registry.addButton('fullpage', { + tooltip: 'Metadata and document properties', + icon: 'document-properties', + onAction: function () { + editor.execCommand('mceFullPageProperties'); + } + }); + editor.ui.registry.addMenuItem('fullpage', { + text: 'Metadata and document properties', + icon: 'document-properties', + onAction: function () { + editor.execCommand('mceFullPageProperties'); + } + }); + }; + + function Plugin () { + global.add('fullpage', function (editor) { + var headState = Cell(''), footState = Cell(''); + register(editor, headState); + register$1(editor); + setup(editor, headState, footState); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/fullpage/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullpage/plugin.min.js new file mode 100644 index 0000000000..ee30e994b2 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullpage/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var s=function(e){var t=e;return{get:function(){return t},set:function(e){t=e}}},e=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=function(){return(u=Object.assign||function(e){for(var t,n=1,l=arguments.length;n"),(n=r.getAll("title")[0])&&n.firstChild&&(a.title=n.firstChild.value),p.each(r.getAll("meta"),function(e){var t,n=e.attr("name"),l=e.attr("http-equiv");n?a[n.toLowerCase()]=e.attr("content"):"Content-Type"===l&&(t=/charset\s*=\s*(.*)\s*/gi.exec(e.attr("content")))&&(a.docencoding=t[1])}),(n=r.getAll("html")[0])&&(a.langcode=s(n,"lang")||s(n,"xml:lang")),a.stylesheets=[],p.each(r.getAll("link"),function(e){"stylesheet"===e.attr("rel")&&a.stylesheets.push(e.attr("href"))}),(n=r.getAll("body")[0])&&(a.langdir=s(n,"dir"),a.style=s(n,"style"),a.visited_color=s(n,"vlink"),a.link_color=s(n,"link"),a.active_color=s(n,"alink")),a);function s(e,t){return e.attr(t)||""}var d=u(u({},{title:"",keywords:"",description:"",robots:"",author:"",docencoding:""}),c);l.windowManager.open({title:"Metadata and Document Properties",size:"normal",body:{type:"panel",items:[{name:"title",type:"input",label:"Title"},{name:"keywords",type:"input",label:"Keywords"},{name:"description",type:"input",label:"Description"},{name:"robots",type:"input",label:"Robots"},{name:"author",type:"input",label:"Author"},{name:"docencoding",type:"input",label:"Encoding"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:d,onSubmit:function(e){var t=e.getData(),n=function(e,o,t){var r,n,l=e.dom;function i(e,t,n){e.attr(t,n||undefined)}function a(e){c.firstChild?c.insert(e,c.firstChild):c.append(e)}var c,s=v(t);(c=s.getAll("head")[0])||(r=s.getAll("html")[0],c=new m("head",1),r.firstChild?r.insert(c,r.firstChild,!0):r.append(c)),r=s.firstChild,o.xml_pi?(n='version="1.0"',o.docencoding&&(n+=' encoding="'+o.docencoding+'"'),7!==r.type&&(r=new m("xml",7),s.insert(r,s.firstChild,!0)),r.value=n):r&&7===r.type&&r.remove(),r=s.getAll("#doctype")[0],o.doctype?(r||(r=new m("#doctype",10),o.xml_pi?s.insert(r,s.firstChild):a(r)),r.value=o.doctype.substring(9,o.doctype.length-1)):r&&r.remove(),r=null,p.each(s.getAll("meta"),function(e){"Content-Type"===e.attr("http-equiv")&&(r=e)}),o.docencoding?(r||((r=new m("meta",1)).attr("http-equiv","Content-Type"),r.shortEnded=!0,a(r)),r.attr("content","text/html; charset="+o.docencoding)):r&&r.remove(),r=s.getAll("title")[0],o.title?(r?r.empty():a(r=new m("title",1)),r.append(new m("#text",3)).value=o.title):r&&r.remove(),p.each("keywords,description,author,copyright,robots".split(","),function(e){for(var t,n=s.getAll("meta"),l=o[e],i=0;i "))}(l,p.extend(c,t),i.get());i.set(n),e.close()}})},_=p.each,b=function(e){return e.replace(/<\/?[A-Z]+/g,function(e){return e.toLowerCase()})},x=function(e,t,n,l){var i,o,r,a,c,s,d,u,m,f="",g=e.dom;l.selection||(a=e.getParam("protect"),c=l.content,p.each(a,function(e){c=c.replace(e,function(e){return"\x3c!--mce:protected "+escape(e)+"--\x3e"})}),r=c,"raw"===l.format&&t.get()||l.source_view&&y(e)||(0!==r.length||l.source_view||(r=p.trim(t.get())+"\n"+p.trim(r)+"\n"+p.trim(n.get())),-1!==(i=(r=r.replace(/<(\/?)BODY/gi,"<$1body")).indexOf("",i),t.set(b(r.substring(0,i+1))),-1===(o=r.indexOf("\n")),s=v(t.get()),_(s.getAll("style"),function(e){e.firstChild&&(f+=e.firstChild.value)}),(d=s.getAll("body")[0])&&g.setAttribs(e.getBody(),{style:d.attr("style")||"",dir:d.attr("dir")||"",vLink:d.attr("vlink")||"",link:d.attr("link")||"",aLink:d.attr("alink")||""}),g.remove("fullpage_styles"),u=e.getDoc().getElementsByTagName("head")[0],f&&g.add(u,"style",{id:"fullpage_styles"}).appendChild(document.createTextNode(f)),m={},p.each(u.getElementsByTagName("link"),function(e){"stylesheet"===e.rel&&e.getAttribute("data-mce-fullpage")&&(m[e.href]=e)}),p.each(s.getAll("link"),function(e){var t=e.attr("href");if(!t)return!0;m[t]||"stylesheet"!==e.attr("rel")||g.add(u,"link",{rel:"stylesheet",text:"text/css",href:t,"data-mce-fullpage":"1"}),delete m[t]}),p.each(m,function(e){e.parentNode.removeChild(e)})))},k=function(e){var t,n="",l="";return e.getParam("fullpage_default_xml_pi")&&(n+='\n'),n+=e.getParam("fullpage_default_doctype",""),n+="\n\n\n",(t=e.getParam("fullpage_default_title"))&&(n+=" "+t+" \n"),(t=i(e))&&(n+='\n'),(t=g(e))&&(l+="font-family: "+t+";"),(t=h(e))&&(l+="font-size: "+t+";"),(t=e.getParam("fullpage_default_text_color"))&&(l+="color: "+t+";"),n+="\n\n"},C=function(e,t,n,l){l.selection||l.source_view&&y(e)||(l.content=(p.trim(t)+"\n"+p.trim(l.content)+"\n"+p.trim(n)).replace(//g,function(e,t){return unescape(t)}))};e.add("fullpage",function(e){var t,n,l,i,o,r,a=s(""),c=s("");n=a,(t=e).addCommand("mceFullPageProperties",function(){d(t,n)}),(l=e).ui.registry.addButton("fullpage",{tooltip:"Metadata and document properties",icon:"document-properties",onAction:function(){l.execCommand("mceFullPageProperties")}}),l.ui.registry.addMenuItem("fullpage",{text:"Metadata and document properties",icon:"document-properties",onAction:function(){l.execCommand("mceFullPageProperties")}}),o=a,r=c,(i=e).on("BeforeSetContent",function(e){x(i,o,r,e)}),i.on("GetContent",function(e){C(i,o.get(),r.get(),e)})})}(); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/fullscreen/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullscreen/plugin.js new file mode 100644 index 0000000000..270aa7a30b --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullscreen/plugin.js @@ -0,0 +1,969 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +(function () { + 'use strict'; + + var Cell = function (initial) { + var value = initial; + var get = function () { + return value; + }; + var set = function (v) { + value = v; + }; + return { + get: get, + set: set + }; + }; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var get = function (fullscreenState) { + return { + isFullscreen: function () { + return fullscreenState.get() !== null; + } + }; + }; + + var noop = function () { + }; + var compose = function (fa, fb) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return fa(fb.apply(null, args)); + }; + }; + var compose1 = function (fbc, fab) { + return function (a) { + return fbc(fab(a)); + }; + }; + var constant = function (value) { + return function () { + return value; + }; + }; + function curry(fn) { + var initialArgs = []; + for (var _i = 1; _i < arguments.length; _i++) { + initialArgs[_i - 1] = arguments[_i]; + } + return function () { + var restArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + restArgs[_i] = arguments[_i]; + } + var all = initialArgs.concat(restArgs); + return fn.apply(null, all); + }; + } + var never = constant(false); + var always = constant(true); + + var none = function () { + return NONE; + }; + var NONE = function () { + var eq = function (o) { + return o.isNone(); + }; + var call = function (thunk) { + return thunk(); + }; + var id = function (n) { + return n; + }; + var me = { + fold: function (n, _s) { + return n(); + }, + is: never, + isSome: never, + isNone: always, + getOr: id, + getOrThunk: call, + getOrDie: function (msg) { + throw new Error(msg || 'error: getOrDie called on none.'); + }, + getOrNull: constant(null), + getOrUndefined: constant(undefined), + or: id, + orThunk: call, + map: none, + each: noop, + bind: none, + exists: never, + forall: always, + filter: none, + equals: eq, + equals_: eq, + toArray: function () { + return []; + }, + toString: constant('none()') + }; + return me; + }(); + var some = function (a) { + var constant_a = constant(a); + var self = function () { + return me; + }; + var bind = function (f) { + return f(a); + }; + var me = { + fold: function (n, s) { + return s(a); + }, + is: function (v) { + return a === v; + }, + isSome: always, + isNone: never, + getOr: constant_a, + getOrThunk: constant_a, + getOrDie: constant_a, + getOrNull: constant_a, + getOrUndefined: constant_a, + or: self, + orThunk: self, + map: function (f) { + return some(f(a)); + }, + each: function (f) { + f(a); + }, + bind: bind, + exists: bind, + forall: bind, + filter: function (f) { + return f(a) ? me : NONE; + }, + toArray: function () { + return [a]; + }, + toString: function () { + return 'some(' + a + ')'; + }, + equals: function (o) { + return o.is(a); + }, + equals_: function (o, elementEq) { + return o.fold(never, function (b) { + return elementEq(a, b); + }); + } + }; + return me; + }; + var from = function (value) { + return value === null || value === undefined ? NONE : some(value); + }; + var Optional = { + some: some, + none: none, + from: from + }; + + var revocable = function (doRevoke) { + var subject = Cell(Optional.none()); + var revoke = function () { + return subject.get().each(doRevoke); + }; + var clear = function () { + revoke(); + subject.set(Optional.none()); + }; + var isSet = function () { + return subject.get().isSome(); + }; + var set = function (s) { + revoke(); + subject.set(Optional.some(s)); + }; + return { + clear: clear, + isSet: isSet, + set: set + }; + }; + var unbindable = function () { + return revocable(function (s) { + return s.unbind(); + }); + }; + var value = function () { + var subject = Cell(Optional.none()); + var clear = function () { + return subject.set(Optional.none()); + }; + var set = function (s) { + return subject.set(Optional.some(s)); + }; + var isSet = function () { + return subject.get().isSome(); + }; + var on = function (f) { + return subject.get().each(f); + }; + return { + clear: clear, + set: set, + isSet: isSet, + on: on + }; + }; + + var typeOf = function (x) { + var t = typeof x; + if (x === null) { + return 'null'; + } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { + return 'array'; + } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { + return 'string'; + } else { + return t; + } + }; + var isType = function (type) { + return function (value) { + return typeOf(value) === type; + }; + }; + var isSimpleType = function (type) { + return function (value) { + return typeof value === type; + }; + }; + var isString = isType('string'); + var isArray = isType('array'); + var isBoolean = isSimpleType('boolean'); + var isNullable = function (a) { + return a === null || a === undefined; + }; + var isNonNullable = function (a) { + return !isNullable(a); + }; + var isFunction = isSimpleType('function'); + var isNumber = isSimpleType('number'); + + var nativePush = Array.prototype.push; + var map = function (xs, f) { + var len = xs.length; + var r = new Array(len); + for (var i = 0; i < len; i++) { + var x = xs[i]; + r[i] = f(x, i); + } + return r; + }; + var each = function (xs, f) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + f(x, i); + } + }; + var filter = function (xs, pred) { + var r = []; + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + if (pred(x, i)) { + r.push(x); + } + } + return r; + }; + var flatten = function (xs) { + var r = []; + for (var i = 0, len = xs.length; i < len; ++i) { + if (!isArray(xs[i])) { + throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); + } + nativePush.apply(r, xs[i]); + } + return r; + }; + var bind = function (xs, f) { + return flatten(map(xs, f)); + }; + var head = function (xs) { + return xs.length === 0 ? Optional.none() : Optional.some(xs[0]); + }; + + var keys = Object.keys; + var each$1 = function (obj, f) { + var props = keys(obj); + for (var k = 0, len = props.length; k < len; k++) { + var i = props[k]; + var x = obj[i]; + f(x, i); + } + }; + + var isSupported = function (dom) { + return dom.style !== undefined && isFunction(dom.style.getPropertyValue); + }; + + var fromHtml = function (html, scope) { + var doc = scope || document; + var div = doc.createElement('div'); + div.innerHTML = html; + if (!div.hasChildNodes() || div.childNodes.length > 1) { + console.error('HTML does not have a single root node', html); + throw new Error('HTML must have a single root node'); + } + return fromDom(div.childNodes[0]); + }; + var fromTag = function (tag, scope) { + var doc = scope || document; + var node = doc.createElement(tag); + return fromDom(node); + }; + var fromText = function (text, scope) { + var doc = scope || document; + var node = doc.createTextNode(text); + return fromDom(node); + }; + var fromDom = function (node) { + if (node === null || node === undefined) { + throw new Error('Node cannot be null or undefined'); + } + return { dom: node }; + }; + var fromPoint = function (docElm, x, y) { + return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); + }; + var SugarElement = { + fromHtml: fromHtml, + fromTag: fromTag, + fromText: fromText, + fromDom: fromDom, + fromPoint: fromPoint + }; + + var Global = typeof window !== 'undefined' ? window : Function('return this;')(); + + var DOCUMENT = 9; + var DOCUMENT_FRAGMENT = 11; + var ELEMENT = 1; + var TEXT = 3; + + var type = function (element) { + return element.dom.nodeType; + }; + var isType$1 = function (t) { + return function (element) { + return type(element) === t; + }; + }; + var isElement = isType$1(ELEMENT); + var isText = isType$1(TEXT); + var isDocument = isType$1(DOCUMENT); + var isDocumentFragment = isType$1(DOCUMENT_FRAGMENT); + + var is = function (element, selector) { + var dom = element.dom; + if (dom.nodeType !== ELEMENT) { + return false; + } else { + var elem = dom; + if (elem.matches !== undefined) { + return elem.matches(selector); + } else if (elem.msMatchesSelector !== undefined) { + return elem.msMatchesSelector(selector); + } else if (elem.webkitMatchesSelector !== undefined) { + return elem.webkitMatchesSelector(selector); + } else if (elem.mozMatchesSelector !== undefined) { + return elem.mozMatchesSelector(selector); + } else { + throw new Error('Browser lacks native selectors'); + } + } + }; + var bypassSelector = function (dom) { + return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0; + }; + var all = function (selector, scope) { + var base = scope === undefined ? document : scope.dom; + return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom); + }; + + var eq = function (e1, e2) { + return e1.dom === e2.dom; + }; + + var owner = function (element) { + return SugarElement.fromDom(element.dom.ownerDocument); + }; + var documentOrOwner = function (dos) { + return isDocument(dos) ? dos : owner(dos); + }; + var parent = function (element) { + return Optional.from(element.dom.parentNode).map(SugarElement.fromDom); + }; + var parents = function (element, isRoot) { + var stop = isFunction(isRoot) ? isRoot : never; + var dom = element.dom; + var ret = []; + while (dom.parentNode !== null && dom.parentNode !== undefined) { + var rawParent = dom.parentNode; + var p = SugarElement.fromDom(rawParent); + ret.push(p); + if (stop(p) === true) { + break; + } else { + dom = rawParent; + } + } + return ret; + }; + var siblings = function (element) { + var filterSelf = function (elements) { + return filter(elements, function (x) { + return !eq(element, x); + }); + }; + return parent(element).map(children).map(filterSelf).getOr([]); + }; + var children = function (element) { + return map(element.dom.childNodes, SugarElement.fromDom); + }; + + var isShadowRoot = function (dos) { + return isDocumentFragment(dos); + }; + var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode); + var isSupported$1 = constant(supported); + var getRootNode = supported ? function (e) { + return SugarElement.fromDom(e.dom.getRootNode()); + } : documentOrOwner; + var getShadowRoot = function (e) { + var r = getRootNode(e); + return isShadowRoot(r) ? Optional.some(r) : Optional.none(); + }; + var getShadowHost = function (e) { + return SugarElement.fromDom(e.dom.host); + }; + var getOriginalEventTarget = function (event) { + if (isSupported$1() && isNonNullable(event.target)) { + var el = SugarElement.fromDom(event.target); + if (isElement(el) && isOpenShadowHost(el)) { + if (event.composed && event.composedPath) { + var composedPath = event.composedPath(); + if (composedPath) { + return head(composedPath); + } + } + } + } + return Optional.from(event.target); + }; + var isOpenShadowHost = function (element) { + return isNonNullable(element.dom.shadowRoot); + }; + + var inBody = function (element) { + var dom = isText(element) ? element.dom.parentNode : element.dom; + if (dom === undefined || dom === null || dom.ownerDocument === null) { + return false; + } + var doc = dom.ownerDocument; + return getShadowRoot(SugarElement.fromDom(dom)).fold(function () { + return doc.body.contains(dom); + }, compose1(inBody, getShadowHost)); + }; + var getBody = function (doc) { + var b = doc.dom.body; + if (b === null || b === undefined) { + throw new Error('Body is not available yet'); + } + return SugarElement.fromDom(b); + }; + + var rawSet = function (dom, key, value) { + if (isString(value) || isBoolean(value) || isNumber(value)) { + dom.setAttribute(key, value + ''); + } else { + console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom); + throw new Error('Attribute value was not simple'); + } + }; + var set = function (element, key, value) { + rawSet(element.dom, key, value); + }; + var get$1 = function (element, key) { + var v = element.dom.getAttribute(key); + return v === null ? undefined : v; + }; + var remove = function (element, key) { + element.dom.removeAttribute(key); + }; + + var internalSet = function (dom, property, value) { + if (!isString(value)) { + console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom); + throw new Error('CSS value must be a string: ' + value); + } + if (isSupported(dom)) { + dom.style.setProperty(property, value); + } + }; + var setAll = function (element, css) { + var dom = element.dom; + each$1(css, function (v, k) { + internalSet(dom, k, v); + }); + }; + var get$2 = function (element, property) { + var dom = element.dom; + var styles = window.getComputedStyle(dom); + var r = styles.getPropertyValue(property); + return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r; + }; + var getUnsafeProperty = function (dom, property) { + return isSupported(dom) ? dom.style.getPropertyValue(property) : ''; + }; + + var mkEvent = function (target, x, y, stop, prevent, kill, raw) { + return { + target: target, + x: x, + y: y, + stop: stop, + prevent: prevent, + kill: kill, + raw: raw + }; + }; + var fromRawEvent = function (rawEvent) { + var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target)); + var stop = function () { + return rawEvent.stopPropagation(); + }; + var prevent = function () { + return rawEvent.preventDefault(); + }; + var kill = compose(prevent, stop); + return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent); + }; + var handle = function (filter, handler) { + return function (rawEvent) { + if (filter(rawEvent)) { + handler(fromRawEvent(rawEvent)); + } + }; + }; + var binder = function (element, event, filter, handler, useCapture) { + var wrapped = handle(filter, handler); + element.dom.addEventListener(event, wrapped, useCapture); + return { unbind: curry(unbind, element, event, wrapped, useCapture) }; + }; + var bind$1 = function (element, event, filter, handler) { + return binder(element, event, filter, handler, false); + }; + var unbind = function (element, event, handler, useCapture) { + element.dom.removeEventListener(event, handler, useCapture); + }; + + var filter$1 = always; + var bind$2 = function (element, event, handler) { + return bind$1(element, event, filter$1, handler); + }; + + var r = function (left, top) { + var translate = function (x, y) { + return r(left + x, top + y); + }; + return { + left: left, + top: top, + translate: translate + }; + }; + var SugarPosition = r; + + var get$3 = function (_DOC) { + var doc = _DOC !== undefined ? _DOC.dom : document; + var x = doc.body.scrollLeft || doc.documentElement.scrollLeft; + var y = doc.body.scrollTop || doc.documentElement.scrollTop; + return SugarPosition(x, y); + }; + + var get$4 = function (_win) { + var win = _win === undefined ? window : _win; + return Optional.from(win['visualViewport']); + }; + var bounds = function (x, y, width, height) { + return { + x: x, + y: y, + width: width, + height: height, + right: x + width, + bottom: y + height + }; + }; + var getBounds = function (_win) { + var win = _win === undefined ? window : _win; + var doc = win.document; + var scroll = get$3(SugarElement.fromDom(doc)); + return get$4(win).fold(function () { + var html = win.document.documentElement; + var width = html.clientWidth; + var height = html.clientHeight; + return bounds(scroll.left, scroll.top, width, height); + }, function (visualViewport) { + return bounds(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height); + }); + }; + var bind$3 = function (name, callback, _win) { + return get$4(_win).map(function (visualViewport) { + var handler = function (e) { + return callback(fromRawEvent(e)); + }; + visualViewport.addEventListener(name, handler); + return { + unbind: function () { + return visualViewport.removeEventListener(name, handler); + } + }; + }).getOrThunk(function () { + return { unbind: noop }; + }); + }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); + + var global$2 = tinymce.util.Tools.resolve('tinymce.Env'); + + var global$3 = tinymce.util.Tools.resolve('tinymce.util.Delay'); + + var fireFullscreenStateChanged = function (editor, state) { + editor.fire('FullscreenStateChanged', { state: state }); + }; + + var getFullscreenNative = function (editor) { + return editor.getParam('fullscreen_native', false, 'boolean'); + }; + + var getFullscreenRoot = function (editor) { + var elem = SugarElement.fromDom(editor.getElement()); + return getShadowRoot(elem).map(getShadowHost).getOrThunk(function () { + return getBody(owner(elem)); + }); + }; + var getFullscreenElement = function (root) { + if (root.fullscreenElement !== undefined) { + return root.fullscreenElement; + } else if (root.msFullscreenElement !== undefined) { + return root.msFullscreenElement; + } else if (root.webkitFullscreenElement !== undefined) { + return root.webkitFullscreenElement; + } else { + return null; + } + }; + var getFullscreenchangeEventName = function () { + if (document.fullscreenElement !== undefined) { + return 'fullscreenchange'; + } else if (document.msFullscreenElement !== undefined) { + return 'MSFullscreenChange'; + } else if (document.webkitFullscreenElement !== undefined) { + return 'webkitfullscreenchange'; + } else { + return 'fullscreenchange'; + } + }; + var requestFullscreen = function (sugarElem) { + var elem = sugarElem.dom; + if (elem.requestFullscreen) { + elem.requestFullscreen(); + } else if (elem.msRequestFullscreen) { + elem.msRequestFullscreen(); + } else if (elem.webkitRequestFullScreen) { + elem.webkitRequestFullScreen(); + } + }; + var exitFullscreen = function (sugarDoc) { + var doc = sugarDoc.dom; + if (doc.exitFullscreen) { + doc.exitFullscreen(); + } else if (doc.msExitFullscreen) { + doc.msExitFullscreen(); + } else if (doc.webkitCancelFullScreen) { + doc.webkitCancelFullScreen(); + } + }; + var isFullscreenElement = function (elem) { + return elem.dom === getFullscreenElement(owner(elem).dom); + }; + + var ancestors = function (scope, predicate, isRoot) { + return filter(parents(scope, isRoot), predicate); + }; + var siblings$1 = function (scope, predicate) { + return filter(siblings(scope), predicate); + }; + + var all$1 = function (selector) { + return all(selector); + }; + var ancestors$1 = function (scope, selector, isRoot) { + return ancestors(scope, function (e) { + return is(e, selector); + }, isRoot); + }; + var siblings$2 = function (scope, selector) { + return siblings$1(scope, function (e) { + return is(e, selector); + }); + }; + + var attr = 'data-ephox-mobile-fullscreen-style'; + var siblingStyles = 'display:none!important;'; + var ancestorPosition = 'position:absolute!important;'; + var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;'; + var bgFallback = 'background-color:rgb(255,255,255)!important;'; + var isAndroid = global$2.os.isAndroid(); + var matchColor = function (editorBody) { + var color = get$2(editorBody, 'background-color'); + return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback; + }; + var clobberStyles = function (dom, container, editorBody) { + var gatherSiblings = function (element) { + return siblings$2(element, '*:not(.tox-silver-sink)'); + }; + var clobber = function (clobberStyle) { + return function (element) { + var styles = get$1(element, 'style'); + var backup = styles === undefined ? 'no-styles' : styles.trim(); + if (backup === clobberStyle) { + return; + } else { + set(element, attr, backup); + setAll(element, dom.parseStyle(clobberStyle)); + } + }; + }; + var ancestors = ancestors$1(container, '*'); + var siblings = bind(ancestors, gatherSiblings); + var bgColor = matchColor(editorBody); + each(siblings, clobber(siblingStyles)); + each(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor)); + var containerStyles = isAndroid === true ? '' : ancestorPosition; + clobber(containerStyles + ancestorStyles + bgColor)(container); + }; + var restoreStyles = function (dom) { + var clobberedEls = all$1('[' + attr + ']'); + each(clobberedEls, function (element) { + var restore = get$1(element, attr); + if (restore !== 'no-styles') { + setAll(element, dom.parseStyle(restore)); + } else { + remove(element, 'style'); + } + remove(element, attr); + }); + }; + + var DOM = global$1.DOM; + var getScrollPos = function () { + var vp = getBounds(window); + return { + x: vp.x, + y: vp.y + }; + }; + var setScrollPos = function (pos) { + window.scrollTo(pos.x, pos.y); + }; + var viewportUpdate = get$4().fold(function () { + return { + bind: noop, + unbind: noop + }; + }, function (visualViewport) { + var editorContainer = value(); + var resizeBinder = unbindable(); + var scrollBinder = unbindable(); + var refreshScroll = function () { + document.body.scrollTop = 0; + document.documentElement.scrollTop = 0; + }; + var refreshVisualViewport = function () { + window.requestAnimationFrame(function () { + editorContainer.on(function (container) { + return setAll(container, { + top: visualViewport.offsetTop + 'px', + left: visualViewport.offsetLeft + 'px', + height: visualViewport.height + 'px', + width: visualViewport.width + 'px' + }); + }); + }); + }; + var update = global$3.throttle(function () { + refreshScroll(); + refreshVisualViewport(); + }, 50); + var bind = function (element) { + editorContainer.set(element); + update(); + resizeBinder.set(bind$3('resize', update)); + scrollBinder.set(bind$3('scroll', update)); + }; + var unbind = function () { + editorContainer.on(function () { + resizeBinder.clear(); + scrollBinder.clear(); + }); + editorContainer.clear(); + }; + return { + bind: bind, + unbind: unbind + }; + }); + var toggleFullscreen = function (editor, fullscreenState) { + var body = document.body; + var documentElement = document.documentElement; + var editorContainer = editor.getContainer(); + var editorContainerS = SugarElement.fromDom(editorContainer); + var fullscreenRoot = getFullscreenRoot(editor); + var fullscreenInfo = fullscreenState.get(); + var editorBody = SugarElement.fromDom(editor.getBody()); + var isTouch = global$2.deviceType.isTouch(); + var editorContainerStyle = editorContainer.style; + var iframe = editor.iframeElement; + var iframeStyle = iframe.style; + var cleanup = function () { + if (isTouch) { + restoreStyles(editor.dom); + } + DOM.removeClass(body, 'tox-fullscreen'); + DOM.removeClass(documentElement, 'tox-fullscreen'); + DOM.removeClass(editorContainer, 'tox-fullscreen'); + viewportUpdate.unbind(); + Optional.from(fullscreenState.get()).each(function (info) { + return info.fullscreenChangeHandler.unbind(); + }); + }; + if (!fullscreenInfo) { + var fullscreenChangeHandler = bind$2(owner(fullscreenRoot), getFullscreenchangeEventName(), function (_evt) { + if (getFullscreenNative(editor)) { + if (!isFullscreenElement(fullscreenRoot) && fullscreenState.get() !== null) { + toggleFullscreen(editor, fullscreenState); + } + } + }); + var newFullScreenInfo = { + scrollPos: getScrollPos(), + containerWidth: editorContainerStyle.width, + containerHeight: editorContainerStyle.height, + containerTop: editorContainerStyle.top, + containerLeft: editorContainerStyle.left, + iframeWidth: iframeStyle.width, + iframeHeight: iframeStyle.height, + fullscreenChangeHandler: fullscreenChangeHandler + }; + if (isTouch) { + clobberStyles(editor.dom, editorContainerS, editorBody); + } + iframeStyle.width = iframeStyle.height = '100%'; + editorContainerStyle.width = editorContainerStyle.height = ''; + DOM.addClass(body, 'tox-fullscreen'); + DOM.addClass(documentElement, 'tox-fullscreen'); + DOM.addClass(editorContainer, 'tox-fullscreen'); + viewportUpdate.bind(editorContainerS); + editor.on('remove', cleanup); + fullscreenState.set(newFullScreenInfo); + if (getFullscreenNative(editor)) { + requestFullscreen(fullscreenRoot); + } + fireFullscreenStateChanged(editor, true); + } else { + fullscreenInfo.fullscreenChangeHandler.unbind(); + if (getFullscreenNative(editor) && isFullscreenElement(fullscreenRoot)) { + exitFullscreen(owner(fullscreenRoot)); + } + iframeStyle.width = fullscreenInfo.iframeWidth; + iframeStyle.height = fullscreenInfo.iframeHeight; + editorContainerStyle.width = fullscreenInfo.containerWidth; + editorContainerStyle.height = fullscreenInfo.containerHeight; + editorContainerStyle.top = fullscreenInfo.containerTop; + editorContainerStyle.left = fullscreenInfo.containerLeft; + setScrollPos(fullscreenInfo.scrollPos); + fullscreenState.set(null); + fireFullscreenStateChanged(editor, false); + cleanup(); + editor.off('remove', cleanup); + } + }; + + var register = function (editor, fullscreenState) { + editor.addCommand('mceFullScreen', function () { + toggleFullscreen(editor, fullscreenState); + }); + }; + + var makeSetupHandler = function (editor, fullscreenState) { + return function (api) { + api.setActive(fullscreenState.get() !== null); + var editorEventCallback = function (e) { + return api.setActive(e.state); + }; + editor.on('FullscreenStateChanged', editorEventCallback); + return function () { + return editor.off('FullscreenStateChanged', editorEventCallback); + }; + }; + }; + var register$1 = function (editor, fullscreenState) { + editor.ui.registry.addToggleMenuItem('fullscreen', { + text: 'Fullscreen', + icon: 'fullscreen', + shortcut: 'Meta+Shift+F', + onAction: function () { + return editor.execCommand('mceFullScreen'); + }, + onSetup: makeSetupHandler(editor, fullscreenState) + }); + editor.ui.registry.addToggleButton('fullscreen', { + tooltip: 'Fullscreen', + icon: 'fullscreen', + onAction: function () { + return editor.execCommand('mceFullScreen'); + }, + onSetup: makeSetupHandler(editor, fullscreenState) + }); + }; + + function Plugin () { + global.add('fullscreen', function (editor) { + var fullscreenState = Cell(null); + if (editor.inline) { + return get(fullscreenState); + } + register(editor, fullscreenState); + register$1(editor, fullscreenState); + editor.addShortcut('Meta+Shift+F', '', 'mceFullScreen'); + return get(fullscreenState); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/fullscreen/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullscreen/plugin.min.js new file mode 100644 index 0000000000..81fe157ef9 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/fullscreen/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var l=function(n){var e=n;return{get:function(){return e},set:function(n){e=n}}},n=tinymce.util.Tools.resolve("tinymce.PluginManager"),i=function(n){return{isFullscreen:function(){return null!==n.get()}}},e=function(){},u=function(n){return function(){return n}};var t,r,o,c=u(!1),f=u(!0),a=function(){return d},d=(t=function(n){return n.isNone()},{fold:function(n,e){return n()},is:c,isSome:c,isNone:f,getOr:o=function(n){return n},getOrThunk:r=function(n){return n()},getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:u(null),getOrUndefined:u(undefined),or:o,orThunk:r,map:a,each:e,bind:a,exists:c,forall:f,filter:a,equals:t,equals_:t,toArray:function(){return[]},toString:u("none()")}),s=function(t){var n=u(t),e=function(){return o},r=function(n){return n(t)},o={fold:function(n,e){return e(t)},is:function(n){return t===n},isSome:f,isNone:c,getOr:n,getOrThunk:n,getOrDie:n,getOrNull:n,getOrUndefined:n,or:e,orThunk:e,map:function(n){return s(n(t))},each:function(n){n(t)},bind:r,exists:r,forall:r,filter:function(n){return n(t)?o:d},toArray:function(){return[t]},toString:function(){return"some("+t+")"},equals:function(n){return n.is(t)},equals_:function(n,e){return n.fold(c,function(n){return e(t,n)})}};return o},b={some:s,none:a,from:function(n){return null===n||n===undefined?d:s(n)}},m=function(){return n=function(n){return n.unbind()},e=l(b.none()),t=function(){return e.get().each(n)},{clear:function(){t(),e.set(b.none())},isSet:function(){return e.get().isSome()},set:function(n){t(),e.set(b.some(n))}};var n,e,t},h=function(r){return function(n){return t=typeof(e=n),(null===e?"null":"object"==t&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==t&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":t)===r;var e,t}},g=function(e){return function(n){return typeof n===e}},p=h("string"),v=h("array"),y=g("boolean"),w=function(n){return!(null===(e=n)||e===undefined);var e},S=g("function"),E=g("number"),F=Array.prototype.push,T=function(n,e){for(var t=n.length,r=new Array(t),o=0;o-1; + }; + var map = function (xs, f) { + var len = xs.length; + var r = new Array(len); + for (var i = 0; i < len; i++) { + var x = xs[i]; + r[i] = f(x, i); + } + return r; + }; + var filter = function (xs, pred) { + var r = []; + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + if (pred(x, i)) { + r.push(x); + } + } + return r; + }; + var findUntil = function (xs, pred, until) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + if (pred(x, i)) { + return Optional.some(x); + } else if (until(x, i)) { + break; + } + } + return Optional.none(); + }; + var find = function (xs, pred) { + return findUntil(xs, pred, never); + }; + + var keys = Object.keys; + var hasOwnProperty = Object.hasOwnProperty; + var get$1 = function (obj, key) { + return has(obj, key) ? Optional.from(obj[key]) : Optional.none(); + }; + var has = function (obj, key) { + return hasOwnProperty.call(obj, key); + }; + + var cat = function (arr) { + var r = []; + var push = function (x) { + r.push(x); + }; + for (var i = 0; i < arr.length; i++) { + arr[i].each(push); + } + return r; + }; + + var getHelpTabs = function (editor) { + return Optional.from(editor.getParam('help_tabs')); + }; + var getForcedPlugins = function (editor) { + return editor.getParam('forced_plugins'); + }; + + var description = ' Editor UI keyboard navigation
\n\nActivating keyboard navigation
\n\nThe sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation:
\n\n
\n\n- Focus the menubar: Alt + F9 (Windows) or ⌥F9 (MacOS)
\n- Focus the toolbar: Alt + F10 (Windows) or ⌥F10 (MacOS)
\n- Focus the footer: Alt + F11 (Windows) or ⌥F11 (MacOS)
\nFocusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline.
\n\nMoving between UI sections
\n\nWhen keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are:
\n\n
\n\n- the menubar
\n- each group of the toolbar
\n- the sidebar
\n- the element path in the footer
\n- the wordcount toggle button in the footer
\n- the branding link in the footer
\nPressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last.
\n\nMoving within UI sections
\n\nKeyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes:
\n\n
\n\n- moving between menus in the menubar
\n- moving between buttons in a toolbar group
\n- moving between items in the element path
\nIn all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group.
\n\nExecuting buttons
\n\nTo execute a button, navigate the selection to the desired button and hit space or enter.
\n\nOpening, navigating and closing menus
\n\nWhen focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys.
\n\nTo close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus.
\n\nContext toolbars and menus
\n\nTo focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS).
\n\nContext toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation.
\n\nDialog navigation
\n\nThere are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs.
\n\nWhen a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards.
\n\nWhen a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons.
'; + var tab = function () { + var body = { + type: 'htmlpanel', + presets: 'document', + html: description + }; + return { + name: 'keyboardnav', + title: 'Keyboard Navigation', + items: [body] + }; + }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.Env'); + + var convertText = function (source) { + var mac = { + alt: '⌥', + ctrl: '⌃', + shift: '⇧', + meta: '⌘', + access: '⌃⌥' + }; + var other = { + meta: 'Ctrl ', + access: 'Shift + Alt ' + }; + var replace = global$1.mac ? mac : other; + var shortcut = source.split('+'); + var updated = map(shortcut, function (segment) { + var search = segment.toLowerCase().trim(); + return has(replace, search) ? replace[search] : segment; + }); + return global$1.mac ? updated.join('').replace(/\s/, '') : updated.join('+'); + }; + + var shortcuts = [ + { + shortcuts: ['Meta + B'], + action: 'Bold' + }, + { + shortcuts: ['Meta + I'], + action: 'Italic' + }, + { + shortcuts: ['Meta + U'], + action: 'Underline' + }, + { + shortcuts: ['Meta + A'], + action: 'Select all' + }, + { + shortcuts: [ + 'Meta + Y', + 'Meta + Shift + Z' + ], + action: 'Redo' + }, + { + shortcuts: ['Meta + Z'], + action: 'Undo' + }, + { + shortcuts: ['Access + 1'], + action: 'Heading 1' + }, + { + shortcuts: ['Access + 2'], + action: 'Heading 2' + }, + { + shortcuts: ['Access + 3'], + action: 'Heading 3' + }, + { + shortcuts: ['Access + 4'], + action: 'Heading 4' + }, + { + shortcuts: ['Access + 5'], + action: 'Heading 5' + }, + { + shortcuts: ['Access + 6'], + action: 'Heading 6' + }, + { + shortcuts: ['Access + 7'], + action: 'Paragraph' + }, + { + shortcuts: ['Access + 8'], + action: 'Div' + }, + { + shortcuts: ['Access + 9'], + action: 'Address' + }, + { + shortcuts: ['Alt + 0'], + action: 'Open help dialog' + }, + { + shortcuts: ['Alt + F9'], + action: 'Focus to menubar' + }, + { + shortcuts: ['Alt + F10'], + action: 'Focus to toolbar' + }, + { + shortcuts: ['Alt + F11'], + action: 'Focus to element path' + }, + { + shortcuts: ['Ctrl + F9'], + action: 'Focus to contextual toolbar' + }, + { + shortcuts: ['Shift + Enter'], + action: 'Open popup menu for split buttons' + }, + { + shortcuts: ['Meta + K'], + action: 'Insert link (if link plugin activated)' + }, + { + shortcuts: ['Meta + S'], + action: 'Save (if save plugin activated)' + }, + { + shortcuts: ['Meta + F'], + action: 'Find (if searchreplace plugin activated)' + }, + { + shortcuts: ['Meta + Shift + F'], + action: 'Switch to or from fullscreen mode' + } + ]; + + var tab$1 = function () { + var shortcutList = map(shortcuts, function (shortcut) { + var shortcutText = map(shortcut.shortcuts, convertText).join(' or '); + return [ + shortcut.action, + shortcutText + ]; + }); + var tablePanel = { + type: 'table', + header: [ + 'Action', + 'Shortcut' + ], + cells: shortcutList + }; + return { + name: 'shortcuts', + title: 'Handy Shortcuts', + items: [tablePanel] + }; + }; + + var global$2 = tinymce.util.Tools.resolve('tinymce.util.I18n'); + + var urls = [ + { + key: 'advlist', + name: 'Advanced List' + }, + { + key: 'anchor', + name: 'Anchor' + }, + { + key: 'autolink', + name: 'Autolink' + }, + { + key: 'autoresize', + name: 'Autoresize' + }, + { + key: 'autosave', + name: 'Autosave' + }, + { + key: 'bbcode', + name: 'BBCode' + }, + { + key: 'charmap', + name: 'Character Map' + }, + { + key: 'code', + name: 'Code' + }, + { + key: 'codesample', + name: 'Code Sample' + }, + { + key: 'colorpicker', + name: 'Color Picker' + }, + { + key: 'directionality', + name: 'Directionality' + }, + { + key: 'emoticons', + name: 'Emoticons' + }, + { + key: 'fullpage', + name: 'Full Page' + }, + { + key: 'fullscreen', + name: 'Full Screen' + }, + { + key: 'help', + name: 'Help' + }, + { + key: 'hr', + name: 'Horizontal Rule' + }, + { + key: 'image', + name: 'Image' + }, + { + key: 'imagetools', + name: 'Image Tools' + }, + { + key: 'importcss', + name: 'Import CSS' + }, + { + key: 'insertdatetime', + name: 'Insert Date/Time' + }, + { + key: 'legacyoutput', + name: 'Legacy Output' + }, + { + key: 'link', + name: 'Link' + }, + { + key: 'lists', + name: 'Lists' + }, + { + key: 'media', + name: 'Media' + }, + { + key: 'nonbreaking', + name: 'Nonbreaking' + }, + { + key: 'noneditable', + name: 'Noneditable' + }, + { + key: 'pagebreak', + name: 'Page Break' + }, + { + key: 'paste', + name: 'Paste' + }, + { + key: 'preview', + name: 'Preview' + }, + { + key: 'print', + name: 'Print' + }, + { + key: 'save', + name: 'Save' + }, + { + key: 'searchreplace', + name: 'Search and Replace' + }, + { + key: 'spellchecker', + name: 'Spell Checker' + }, + { + key: 'tabfocus', + name: 'Tab Focus' + }, + { + key: 'table', + name: 'Table' + }, + { + key: 'template', + name: 'Template' + }, + { + key: 'textcolor', + name: 'Text Color' + }, + { + key: 'textpattern', + name: 'Text Pattern' + }, + { + key: 'toc', + name: 'Table of Contents' + }, + { + key: 'visualblocks', + name: 'Visual Blocks' + }, + { + key: 'visualchars', + name: 'Visual Characters' + }, + { + key: 'wordcount', + name: 'Word Count' + }, + { + key: 'advcode', + name: 'Advanced Code Editor*' + }, + { + key: 'formatpainter', + name: 'Format Painter*' + }, + { + key: 'powerpaste', + name: 'PowerPaste*' + }, + { + key: 'tinydrive', + name: 'Tiny Drive*', + slug: 'drive' + }, + { + key: 'tinymcespellchecker', + name: 'Spell Checker Pro*' + }, + { + key: 'a11ychecker', + name: 'Accessibility Checker*' + }, + { + key: 'linkchecker', + name: 'Link Checker*' + }, + { + key: 'mentions', + name: 'Mentions*' + }, + { + key: 'mediaembed', + name: 'Enhanced Media Embed*' + }, + { + key: 'checklist', + name: 'Checklist*' + }, + { + key: 'casechange', + name: 'Case Change*' + }, + { + key: 'permanentpen', + name: 'Permanent Pen*' + }, + { + key: 'pageembed', + name: 'Page Embed*' + }, + { + key: 'tinycomments', + name: 'Tiny Comments*', + slug: 'comments' + }, + { + key: 'advtable', + name: 'Advanced Tables*' + }, + { + key: 'autocorrect', + name: 'Autocorrect*' + } + ]; + + var tab$2 = function (editor) { + var availablePlugins = function () { + var premiumPlugins = [ + 'Accessibility Checker', + 'Advanced Code Editor', + 'Advanced Tables', + 'Case Change', + 'Checklist', + 'Tiny Comments', + 'Tiny Drive', + 'Enhanced Media Embed', + 'Format Painter', + 'Link Checker', + 'Mentions', + 'MoxieManager', + 'Page Embed', + 'Permanent Pen', + 'PowerPaste', + 'Spell Checker Pro' + ]; + var premiumPluginList = map(premiumPlugins, function (plugin) { + return '' + global$2.translate(plugin) + ' '; + }).join(''); + return '' + ''; + }; + var makeLink = function (p) { + return '' + p.name + ''; + }; + var maybeUrlize = function (editor, key) { + return find(urls, function (x) { + return x.key === key; + }).fold(function () { + var getMetadata = editor.plugins[key].getMetadata; + return typeof getMetadata === 'function' ? makeLink(getMetadata()) : key; + }, function (x) { + var urlSlug = x.slug || x.key; + return makeLink({ + name: x.name, + url: 'https://www.tiny.cloud/docs/plugins/' + urlSlug + }); + }); + }; + var getPluginKeys = function (editor) { + var keys$1 = keys(editor.plugins); + var forced_plugins = getForcedPlugins(editor); + return forced_plugins === undefined ? keys$1 : filter(keys$1, function (k) { + return !contains(forced_plugins, k); + }); + }; + var pluginLister = function (editor) { + var pluginKeys = getPluginKeys(editor); + var pluginLis = map(pluginKeys, function (key) { + return '' + global$2.translate('Premium plugins:') + '
' + '' + premiumPluginList + '
' + '- ' + global$2.translate('Learn more...') + '
' + '' + maybeUrlize(editor, key) + ' '; + }); + var count = pluginLis.length; + var pluginsString = pluginLis.join(''); + var html = '' + global$2.translate([ + 'Plugins installed ({0}):', + count + ]) + '
' + '' + pluginsString + '
'; + return html; + }; + var installedPlugins = function (editor) { + if (editor == null) { + return ''; + } + return '' + pluginLister(editor) + ''; + }; + var htmlPanel = { + type: 'htmlpanel', + presets: 'document', + html: [ + installedPlugins(editor), + availablePlugins() + ].join('') + }; + return { + name: 'plugins', + title: 'Plugins', + items: [htmlPanel] + }; + }; + + var global$3 = tinymce.util.Tools.resolve('tinymce.EditorManager'); + + var tab$3 = function () { + var getVersion = function (major, minor) { + return major.indexOf('@') === 0 ? 'X.X.X' : major + '.' + minor; + }; + var version = getVersion(global$3.majorVersion, global$3.minorVersion); + var changeLogLink = 'TinyMCE ' + version + ''; + var htmlPanel = { + type: 'htmlpanel', + html: '' + global$2.translate([ + 'You are using {0}', + changeLogLink + ]) + '
', + presets: 'document' + }; + return { + name: 'versions', + title: 'Version', + items: [htmlPanel] + }; + }; + + var parseHelpTabsSetting = function (tabsFromSettings, tabs) { + var newTabs = {}; + var names = map(tabsFromSettings, function (t) { + if (typeof t === 'string') { + if (has(tabs, t)) { + newTabs[t] = tabs[t]; + } + return t; + } else { + newTabs[t.name] = t; + return t.name; + } + }); + return { + tabs: newTabs, + names: names + }; + }; + var getNamesFromTabs = function (tabs) { + var names = keys(tabs); + var idx = names.indexOf('versions'); + if (idx !== -1) { + names.splice(idx, 1); + names.push('versions'); + } + return { + tabs: tabs, + names: names + }; + }; + var parseCustomTabs = function (editor, customTabs) { + var _a; + var shortcuts = tab$1(); + var nav = tab(); + var plugins = tab$2(editor); + var versions = tab$3(); + var tabs = __assign((_a = {}, _a[shortcuts.name] = shortcuts, _a[nav.name] = nav, _a[plugins.name] = plugins, _a[versions.name] = versions, _a), customTabs.get()); + return getHelpTabs(editor).fold(function () { + return getNamesFromTabs(tabs); + }, function (tabsFromSettings) { + return parseHelpTabsSetting(tabsFromSettings, tabs); + }); + }; + var init = function (editor, customTabs) { + return function () { + var _a = parseCustomTabs(editor, customTabs), tabs = _a.tabs, names = _a.names; + var foundTabs = map(names, function (name) { + return get$1(tabs, name); + }); + var dialogTabs = cat(foundTabs); + var body = { + type: 'tabpanel', + tabs: dialogTabs + }; + editor.windowManager.open({ + title: 'Help', + size: 'medium', + body: body, + buttons: [{ + type: 'cancel', + name: 'close', + text: 'Close', + primary: true + }], + initialData: {} + }); + }; + }; + + function Plugin () { + global.add('help', function (editor) { + var customTabs = Cell({}); + var api = get(customTabs); + var dialogOpener = init(editor, customTabs); + register$1(editor, dialogOpener); + register(editor, dialogOpener); + editor.shortcuts.add('Alt+0', 'Open help dialog', 'mceHelp'); + return api; + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/help/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/help/plugin.min.js new file mode 100644 index 0000000000..9a945df2c3 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/help/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var e,t,n,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),m=function(){return(m=Object.assign||function(e){for(var t,n=1,a=arguments.length;n'+e.name+""};return{name:"plugins",title:"Plugins",items:[{type:"htmlpanel",presets:"document",html:[null==(n=e)?"":''+function(a){var e,t,n,o=(t=f((e=a).plugins),(n=e.getParam("forced_plugins"))===undefined?t:function(e,t){for(var n=[],a=0,o=e.length;a",(t=p(["Accessibility Checker","Advanced Code Editor","Advanced Tables","Case Change","Checklist","Tiny Comments","Tiny Drive","Enhanced Media Embed","Format Painter","Link Checker","Mentions","MoxieManager","Page Embed","Permanent Pen","PowerPaste","Spell Checker Pro"],function(e){return""+(t=a,n=e,g(C,function(e){return e.key===n}).fold(function(){var e=t.plugins[n].getMetadata;return"function"==typeof e?l(e()):n},function(e){var t=e.slug||e.key;return l({name:e.name,url:"https://www.tiny.cloud/docs/plugins/"+t})}))+"";var t,n}),r=i.length,s=i.join("");return" "+A.translate(["Plugins installed ({0}):",r])+"
"+s+"
"}(n)+""+A.translate(e)+" "}).join(""),'")].join("")}]}},x=tinymce.util.Tools.resolve("tinymce.EditorManager"),P=function(e,t){var n,a,o,i,r,s={name:"shortcuts",title:"Handy Shortcuts",items:[{type:"table",header:["Action","Shortcut"],cells:p(w,function(e){var t=p(e.shortcuts,v).join(" or ");return[e.action,t]})}]},l={name:"keyboardnav",title:"Keyboard Navigation",items:[{type:"htmlpanel",presets:"document",html:"'+A.translate("Premium plugins:")+"
Editor UI keyboard navigation
\n\nActivating keyboard navigation
\n\nThe sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation:
\n\n
\n\n- Focus the menubar: Alt + F9 (Windows) or ⌥F9 (MacOS)
\n- Focus the toolbar: Alt + F10 (Windows) or ⌥F10 (MacOS)
\n- Focus the footer: Alt + F11 (Windows) or ⌥F11 (MacOS)
\nFocusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline.
\n\nMoving between UI sections
\n\nWhen keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are:
\n\n
\n\n- the menubar
\n- each group of the toolbar
\n- the sidebar
\n- the element path in the footer
\n- the wordcount toggle button in the footer
\n- the branding link in the footer
\nPressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last.
\n\nMoving within UI sections
\n\nKeyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes:
\n\n
\n\n- moving between menus in the menubar
\n- moving between buttons in a toolbar group
\n- moving between items in the element path
\nIn all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group.
\n\nExecuting buttons
\n\nTo execute a button, navigate the selection to the desired button and hit space or enter.
\n\nOpening, navigating and closing menus
\n\nWhen focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys.
\n\nTo close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus.
\n\nContext toolbars and menus
\n\nTo focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS).
\n\nContext toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation.
\n\nDialog navigation
\n\nThere are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs.
\n\nWhen a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards.
\n\nWhen a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons.
"}]},c=T(e),u=(i='TinyMCE '+(a=x.majorVersion,o=x.minorVersion,0===a.indexOf("@")?"X.X.X":a+"."+o)+"",{name:"versions",title:"Version",items:[{type:"htmlpanel",html:""+A.translate(["You are using {0}",i])+"
",presets:"document"}]}),h=m(((n={})[s.name]=s,n[l.name]=l,n[c.name]=c,n[u.name]=u,n),t.get());return r=e,d.from(r.getParam("help_tabs")).fold(function(){return t=f(e=h),-1!==(n=t.indexOf("versions"))&&(t.splice(n,1),t.push("versions")),{tabs:e,names:t};var e,t,n},function(e){return t=h,n={},a=p(e,function(e){return"string"==typeof e?(y(t,e)&&(n[e]=t[e]),e):(n[e.name]=e).name}),{tabs:n,names:a};var t,n,a})},M=function(o,i){return function(){var e=P(o,i),a=e.tabs,t=e.names,n={type:"tabpanel",tabs:function(e){for(var t=[],n=function(e){t.push(e)},a=0;a'); + }); + }; + + var register$1 = function (editor) { + editor.ui.registry.addButton('hr', { + icon: 'horizontal-rule', + tooltip: 'Horizontal line', + onAction: function () { + return editor.execCommand('InsertHorizontalRule'); + } + }); + editor.ui.registry.addMenuItem('hr', { + icon: 'horizontal-rule', + text: 'Horizontal line', + onAction: function () { + return editor.execCommand('InsertHorizontalRule'); + } + }); + }; + + function Plugin () { + global.add('hr', function (editor) { + register(editor); + register$1(editor); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/hr/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/hr/plugin.min.js new file mode 100644 index 0000000000..5901aa48d9 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/hr/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var n=tinymce.util.Tools.resolve("tinymce.PluginManager");n.add("hr",function(n){var o,t;(o=n).addCommand("InsertHorizontalRule",function(){o.execCommand("mceInsertContent",!1,"
")}),(t=n).ui.registry.addButton("hr",{icon:"horizontal-rule",tooltip:"Horizontal line",onAction:function(){return t.execCommand("InsertHorizontalRule")}}),t.ui.registry.addMenuItem("hr",{icon:"horizontal-rule",text:"Horizontal line",onAction:function(){return t.execCommand("InsertHorizontalRule")}})})}(); \ No newline at end of file diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.js new file mode 100644 index 0000000000..83c519ae07 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.js @@ -0,0 +1,1651 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +(function () { + 'use strict'; + + var global = tinymce.util.Tools.resolve('tinymce.PluginManager'); + + var __assign = function () { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + var typeOf = function (x) { + var t = typeof x; + if (x === null) { + return 'null'; + } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { + return 'array'; + } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { + return 'string'; + } else { + return t; + } + }; + var isType = function (type) { + return function (value) { + return typeOf(value) === type; + }; + }; + var isSimpleType = function (type) { + return function (value) { + return typeof value === type; + }; + }; + var eq = function (t) { + return function (a) { + return t === a; + }; + }; + var isString = isType('string'); + var isObject = isType('object'); + var isArray = isType('array'); + var isNull = eq(null); + var isBoolean = isSimpleType('boolean'); + var isNumber = isSimpleType('number'); + + var noop = function () { + }; + var constant = function (value) { + return function () { + return value; + }; + }; + var never = constant(false); + var always = constant(true); + + var none = function () { + return NONE; + }; + var NONE = function () { + var eq = function (o) { + return o.isNone(); + }; + var call = function (thunk) { + return thunk(); + }; + var id = function (n) { + return n; + }; + var me = { + fold: function (n, _s) { + return n(); + }, + is: never, + isSome: never, + isNone: always, + getOr: id, + getOrThunk: call, + getOrDie: function (msg) { + throw new Error(msg || 'error: getOrDie called on none.'); + }, + getOrNull: constant(null), + getOrUndefined: constant(undefined), + or: id, + orThunk: call, + map: none, + each: noop, + bind: none, + exists: never, + forall: always, + filter: none, + equals: eq, + equals_: eq, + toArray: function () { + return []; + }, + toString: constant('none()') + }; + return me; + }(); + var some = function (a) { + var constant_a = constant(a); + var self = function () { + return me; + }; + var bind = function (f) { + return f(a); + }; + var me = { + fold: function (n, s) { + return s(a); + }, + is: function (v) { + return a === v; + }, + isSome: always, + isNone: never, + getOr: constant_a, + getOrThunk: constant_a, + getOrDie: constant_a, + getOrNull: constant_a, + getOrUndefined: constant_a, + or: self, + orThunk: self, + map: function (f) { + return some(f(a)); + }, + each: function (f) { + f(a); + }, + bind: bind, + exists: bind, + forall: bind, + filter: function (f) { + return f(a) ? me : NONE; + }, + toArray: function () { + return [a]; + }, + toString: function () { + return 'some(' + a + ')'; + }, + equals: function (o) { + return o.is(a); + }, + equals_: function (o, elementEq) { + return o.fold(never, function (b) { + return elementEq(a, b); + }); + } + }; + return me; + }; + var from = function (value) { + return value === null || value === undefined ? NONE : some(value); + }; + var Optional = { + some: some, + none: none, + from: from + }; + + var nativePush = Array.prototype.push; + var flatten = function (xs) { + var r = []; + for (var i = 0, len = xs.length; i < len; ++i) { + if (!isArray(xs[i])) { + throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); + } + nativePush.apply(r, xs[i]); + } + return r; + }; + var head = function (xs) { + return xs.length === 0 ? Optional.none() : Optional.some(xs[0]); + }; + var findMap = function (arr, f) { + for (var i = 0; i < arr.length; i++) { + var r = f(arr[i], i); + if (r.isSome()) { + return r; + } + } + return Optional.none(); + }; + + var Global = typeof window !== 'undefined' ? window : Function('return this;')(); + + var rawSet = function (dom, key, value) { + if (isString(value) || isBoolean(value) || isNumber(value)) { + dom.setAttribute(key, value + ''); + } else { + console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom); + throw new Error('Attribute value was not simple'); + } + }; + var set = function (element, key, value) { + rawSet(element.dom, key, value); + }; + var remove = function (element, key) { + element.dom.removeAttribute(key); + }; + + var fromHtml = function (html, scope) { + var doc = scope || document; + var div = doc.createElement('div'); + div.innerHTML = html; + if (!div.hasChildNodes() || div.childNodes.length > 1) { + console.error('HTML does not have a single root node', html); + throw new Error('HTML must have a single root node'); + } + return fromDom(div.childNodes[0]); + }; + var fromTag = function (tag, scope) { + var doc = scope || document; + var node = doc.createElement(tag); + return fromDom(node); + }; + var fromText = function (text, scope) { + var doc = scope || document; + var node = doc.createTextNode(text); + return fromDom(node); + }; + var fromDom = function (node) { + if (node === null || node === undefined) { + throw new Error('Node cannot be null or undefined'); + } + return { dom: node }; + }; + var fromPoint = function (docElm, x, y) { + return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); + }; + var SugarElement = { + fromHtml: fromHtml, + fromTag: fromTag, + fromText: fromText, + fromDom: fromDom, + fromPoint: fromPoint + }; + + var global$1 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); + + var global$2 = tinymce.util.Tools.resolve('tinymce.util.Promise'); + + var global$3 = tinymce.util.Tools.resolve('tinymce.util.XHR'); + + var hasDimensions = function (editor) { + return editor.getParam('image_dimensions', true, 'boolean'); + }; + var hasAdvTab = function (editor) { + return editor.getParam('image_advtab', false, 'boolean'); + }; + var hasUploadTab = function (editor) { + return editor.getParam('image_uploadtab', true, 'boolean'); + }; + var getPrependUrl = function (editor) { + return editor.getParam('image_prepend_url', '', 'string'); + }; + var getClassList = function (editor) { + return editor.getParam('image_class_list'); + }; + var hasDescription = function (editor) { + return editor.getParam('image_description', true, 'boolean'); + }; + var hasImageTitle = function (editor) { + return editor.getParam('image_title', false, 'boolean'); + }; + var hasImageCaption = function (editor) { + return editor.getParam('image_caption', false, 'boolean'); + }; + var getImageList = function (editor) { + return editor.getParam('image_list', false); + }; + var hasUploadUrl = function (editor) { + return !!getUploadUrl(editor); + }; + var hasUploadHandler = function (editor) { + return !!getUploadHandler(editor); + }; + var getUploadUrl = function (editor) { + return editor.getParam('images_upload_url', '', 'string'); + }; + var getUploadHandler = function (editor) { + return editor.getParam('images_upload_handler', undefined, 'function'); + }; + var getUploadBasePath = function (editor) { + return editor.getParam('images_upload_base_path', undefined, 'string'); + }; + var getUploadCredentials = function (editor) { + return editor.getParam('images_upload_credentials', false, 'boolean'); + }; + var showAccessibilityOptions = function (editor) { + return editor.getParam('a11y_advanced_options', false, 'boolean'); + }; + var isAutomaticUploadsEnabled = function (editor) { + return editor.getParam('automatic_uploads', true, 'boolean'); + }; + + var parseIntAndGetMax = function (val1, val2) { + return Math.max(parseInt(val1, 10), parseInt(val2, 10)); + }; + var getImageSize = function (url) { + return new global$2(function (callback) { + var img = document.createElement('img'); + var done = function (dimensions) { + if (img.parentNode) { + img.parentNode.removeChild(img); + } + callback(dimensions); + }; + img.onload = function () { + var width = parseIntAndGetMax(img.width, img.clientWidth); + var height = parseIntAndGetMax(img.height, img.clientHeight); + var dimensions = { + width: width, + height: height + }; + done(global$2.resolve(dimensions)); + }; + img.onerror = function () { + done(global$2.reject('Failed to get image dimensions for: ' + url)); + }; + var style = img.style; + style.visibility = 'hidden'; + style.position = 'fixed'; + style.bottom = style.left = '0px'; + style.width = style.height = 'auto'; + document.body.appendChild(img); + img.src = url; + }); + }; + var removePixelSuffix = function (value) { + if (value) { + value = value.replace(/px$/, ''); + } + return value; + }; + var addPixelSuffix = function (value) { + if (value.length > 0 && /^[0-9]+$/.test(value)) { + value += 'px'; + } + return value; + }; + var mergeMargins = function (css) { + if (css.margin) { + var splitMargin = String(css.margin).split(' '); + switch (splitMargin.length) { + case 1: + css['margin-top'] = css['margin-top'] || splitMargin[0]; + css['margin-right'] = css['margin-right'] || splitMargin[0]; + css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; + css['margin-left'] = css['margin-left'] || splitMargin[0]; + break; + case 2: + css['margin-top'] = css['margin-top'] || splitMargin[0]; + css['margin-right'] = css['margin-right'] || splitMargin[1]; + css['margin-bottom'] = css['margin-bottom'] || splitMargin[0]; + css['margin-left'] = css['margin-left'] || splitMargin[1]; + break; + case 3: + css['margin-top'] = css['margin-top'] || splitMargin[0]; + css['margin-right'] = css['margin-right'] || splitMargin[1]; + css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; + css['margin-left'] = css['margin-left'] || splitMargin[1]; + break; + case 4: + css['margin-top'] = css['margin-top'] || splitMargin[0]; + css['margin-right'] = css['margin-right'] || splitMargin[1]; + css['margin-bottom'] = css['margin-bottom'] || splitMargin[2]; + css['margin-left'] = css['margin-left'] || splitMargin[3]; + } + delete css.margin; + } + return css; + }; + var createImageList = function (editor, callback) { + var imageList = getImageList(editor); + if (typeof imageList === 'string') { + global$3.send({ + url: imageList, + success: function (text) { + callback(JSON.parse(text)); + } + }); + } else if (typeof imageList === 'function') { + imageList(callback); + } else { + callback(imageList); + } + }; + var waitLoadImage = function (editor, data, imgElm) { + var selectImage = function () { + imgElm.onload = imgElm.onerror = null; + if (editor.selection) { + editor.selection.select(imgElm); + editor.nodeChanged(); + } + }; + imgElm.onload = function () { + if (!data.width && !data.height && hasDimensions(editor)) { + editor.dom.setAttribs(imgElm, { + width: String(imgElm.clientWidth), + height: String(imgElm.clientHeight) + }); + } + selectImage(); + }; + imgElm.onerror = selectImage; + }; + var blobToDataUri = function (blob) { + return new global$2(function (resolve, reject) { + var reader = new FileReader(); + reader.onload = function () { + resolve(reader.result); + }; + reader.onerror = function () { + reject(reader.error.message); + }; + reader.readAsDataURL(blob); + }); + }; + var isPlaceholderImage = function (imgElm) { + return imgElm.nodeName === 'IMG' && (imgElm.hasAttribute('data-mce-object') || imgElm.hasAttribute('data-mce-placeholder')); + }; + + var DOM = global$1.DOM; + var getHspace = function (image) { + if (image.style.marginLeft && image.style.marginRight && image.style.marginLeft === image.style.marginRight) { + return removePixelSuffix(image.style.marginLeft); + } else { + return ''; + } + }; + var getVspace = function (image) { + if (image.style.marginTop && image.style.marginBottom && image.style.marginTop === image.style.marginBottom) { + return removePixelSuffix(image.style.marginTop); + } else { + return ''; + } + }; + var getBorder = function (image) { + if (image.style.borderWidth) { + return removePixelSuffix(image.style.borderWidth); + } else { + return ''; + } + }; + var getAttrib = function (image, name) { + if (image.hasAttribute(name)) { + return image.getAttribute(name); + } else { + return ''; + } + }; + var getStyle = function (image, name) { + return image.style[name] ? image.style[name] : ''; + }; + var hasCaption = function (image) { + return image.parentNode !== null && image.parentNode.nodeName === 'FIGURE'; + }; + var updateAttrib = function (image, name, value) { + if (value === '') { + image.removeAttribute(name); + } else { + image.setAttribute(name, value); + } + }; + var wrapInFigure = function (image) { + var figureElm = DOM.create('figure', { class: 'image' }); + DOM.insertAfter(figureElm, image); + figureElm.appendChild(image); + figureElm.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption')); + figureElm.contentEditable = 'false'; + }; + var removeFigure = function (image) { + var figureElm = image.parentNode; + DOM.insertAfter(image, figureElm); + DOM.remove(figureElm); + }; + var toggleCaption = function (image) { + if (hasCaption(image)) { + removeFigure(image); + } else { + wrapInFigure(image); + } + }; + var normalizeStyle = function (image, normalizeCss) { + var attrValue = image.getAttribute('style'); + var value = normalizeCss(attrValue !== null ? attrValue : ''); + if (value.length > 0) { + image.setAttribute('style', value); + image.setAttribute('data-mce-style', value); + } else { + image.removeAttribute('style'); + } + }; + var setSize = function (name, normalizeCss) { + return function (image, name, value) { + if (image.style[name]) { + image.style[name] = addPixelSuffix(value); + normalizeStyle(image, normalizeCss); + } else { + updateAttrib(image, name, value); + } + }; + }; + var getSize = function (image, name) { + if (image.style[name]) { + return removePixelSuffix(image.style[name]); + } else { + return getAttrib(image, name); + } + }; + var setHspace = function (image, value) { + var pxValue = addPixelSuffix(value); + image.style.marginLeft = pxValue; + image.style.marginRight = pxValue; + }; + var setVspace = function (image, value) { + var pxValue = addPixelSuffix(value); + image.style.marginTop = pxValue; + image.style.marginBottom = pxValue; + }; + var setBorder = function (image, value) { + var pxValue = addPixelSuffix(value); + image.style.borderWidth = pxValue; + }; + var setBorderStyle = function (image, value) { + image.style.borderStyle = value; + }; + var getBorderStyle = function (image) { + return getStyle(image, 'borderStyle'); + }; + var isFigure = function (elm) { + return elm.nodeName === 'FIGURE'; + }; + var isImage = function (elm) { + return elm.nodeName === 'IMG'; + }; + var getIsDecorative = function (image) { + return DOM.getAttrib(image, 'alt').length === 0 && DOM.getAttrib(image, 'role') === 'presentation'; + }; + var getAlt = function (image) { + if (getIsDecorative(image)) { + return ''; + } else { + return getAttrib(image, 'alt'); + } + }; + var defaultData = function () { + return { + src: '', + alt: '', + title: '', + width: '', + height: '', + class: '', + style: '', + caption: false, + hspace: '', + vspace: '', + border: '', + borderStyle: '', + isDecorative: false + }; + }; + var getStyleValue = function (normalizeCss, data) { + var image = document.createElement('img'); + updateAttrib(image, 'style', data.style); + if (getHspace(image) || data.hspace !== '') { + setHspace(image, data.hspace); + } + if (getVspace(image) || data.vspace !== '') { + setVspace(image, data.vspace); + } + if (getBorder(image) || data.border !== '') { + setBorder(image, data.border); + } + if (getBorderStyle(image) || data.borderStyle !== '') { + setBorderStyle(image, data.borderStyle); + } + return normalizeCss(image.getAttribute('style')); + }; + var create = function (normalizeCss, data) { + var image = document.createElement('img'); + write(normalizeCss, __assign(__assign({}, data), { caption: false }), image); + setAlt(image, data.alt, data.isDecorative); + if (data.caption) { + var figure = DOM.create('figure', { class: 'image' }); + figure.appendChild(image); + figure.appendChild(DOM.create('figcaption', { contentEditable: 'true' }, 'Caption')); + figure.contentEditable = 'false'; + return figure; + } else { + return image; + } + }; + var read = function (normalizeCss, image) { + return { + src: getAttrib(image, 'src'), + alt: getAlt(image), + title: getAttrib(image, 'title'), + width: getSize(image, 'width'), + height: getSize(image, 'height'), + class: getAttrib(image, 'class'), + style: normalizeCss(getAttrib(image, 'style')), + caption: hasCaption(image), + hspace: getHspace(image), + vspace: getVspace(image), + border: getBorder(image), + borderStyle: getStyle(image, 'borderStyle'), + isDecorative: getIsDecorative(image) + }; + }; + var updateProp = function (image, oldData, newData, name, set) { + if (newData[name] !== oldData[name]) { + set(image, name, newData[name]); + } + }; + var setAlt = function (image, alt, isDecorative) { + if (isDecorative) { + DOM.setAttrib(image, 'role', 'presentation'); + var sugarImage = SugarElement.fromDom(image); + set(sugarImage, 'alt', ''); + } else { + if (isNull(alt)) { + var sugarImage = SugarElement.fromDom(image); + remove(sugarImage, 'alt'); + } else { + var sugarImage = SugarElement.fromDom(image); + set(sugarImage, 'alt', alt); + } + if (DOM.getAttrib(image, 'role') === 'presentation') { + DOM.setAttrib(image, 'role', ''); + } + } + }; + var updateAlt = function (image, oldData, newData) { + if (newData.alt !== oldData.alt || newData.isDecorative !== oldData.isDecorative) { + setAlt(image, newData.alt, newData.isDecorative); + } + }; + var normalized = function (set, normalizeCss) { + return function (image, name, value) { + set(image, value); + normalizeStyle(image, normalizeCss); + }; + }; + var write = function (normalizeCss, newData, image) { + var oldData = read(normalizeCss, image); + updateProp(image, oldData, newData, 'caption', function (image, _name, _value) { + return toggleCaption(image); + }); + updateProp(image, oldData, newData, 'src', updateAttrib); + updateProp(image, oldData, newData, 'title', updateAttrib); + updateProp(image, oldData, newData, 'width', setSize('width', normalizeCss)); + updateProp(image, oldData, newData, 'height', setSize('height', normalizeCss)); + updateProp(image, oldData, newData, 'class', updateAttrib); + updateProp(image, oldData, newData, 'style', normalized(function (image, value) { + return updateAttrib(image, 'style', value); + }, normalizeCss)); + updateProp(image, oldData, newData, 'hspace', normalized(setHspace, normalizeCss)); + updateProp(image, oldData, newData, 'vspace', normalized(setVspace, normalizeCss)); + updateProp(image, oldData, newData, 'border', normalized(setBorder, normalizeCss)); + updateProp(image, oldData, newData, 'borderStyle', normalized(setBorderStyle, normalizeCss)); + updateAlt(image, oldData, newData); + }; + + var normalizeCss = function (editor, cssText) { + var css = editor.dom.styles.parse(cssText); + var mergedCss = mergeMargins(css); + var compressed = editor.dom.styles.parse(editor.dom.styles.serialize(mergedCss)); + return editor.dom.styles.serialize(compressed); + }; + var getSelectedImage = function (editor) { + var imgElm = editor.selection.getNode(); + var figureElm = editor.dom.getParent(imgElm, 'figure.image'); + if (figureElm) { + return editor.dom.select('img', figureElm)[0]; + } + if (imgElm && (imgElm.nodeName !== 'IMG' || isPlaceholderImage(imgElm))) { + return null; + } + return imgElm; + }; + var splitTextBlock = function (editor, figure) { + var dom = editor.dom; + var textBlock = dom.getParent(figure.parentNode, function (node) { + return !!editor.schema.getTextBlockElements()[node.nodeName]; + }, editor.getBody()); + if (textBlock) { + return dom.split(textBlock, figure); + } else { + return figure; + } + }; + var readImageDataFromSelection = function (editor) { + var image = getSelectedImage(editor); + return image ? read(function (css) { + return normalizeCss(editor, css); + }, image) : defaultData(); + }; + var insertImageAtCaret = function (editor, data) { + var elm = create(function (css) { + return normalizeCss(editor, css); + }, data); + editor.dom.setAttrib(elm, 'data-mce-id', '__mcenew'); + editor.focus(); + editor.selection.setContent(elm.outerHTML); + var insertedElm = editor.dom.select('*[data-mce-id="__mcenew"]')[0]; + editor.dom.setAttrib(insertedElm, 'data-mce-id', null); + if (isFigure(insertedElm)) { + var figure = splitTextBlock(editor, insertedElm); + editor.selection.select(figure); + } else { + editor.selection.select(insertedElm); + } + }; + var syncSrcAttr = function (editor, image) { + editor.dom.setAttrib(image, 'src', image.getAttribute('src')); + }; + var deleteImage = function (editor, image) { + if (image) { + var elm = editor.dom.is(image.parentNode, 'figure.image') ? image.parentNode : image; + editor.dom.remove(elm); + editor.focus(); + editor.nodeChanged(); + if (editor.dom.isEmpty(editor.getBody())) { + editor.setContent(''); + editor.selection.setCursorLocation(); + } + } + }; + var writeImageDataToSelection = function (editor, data) { + var image = getSelectedImage(editor); + write(function (css) { + return normalizeCss(editor, css); + }, data, image); + syncSrcAttr(editor, image); + if (isFigure(image.parentNode)) { + var figure = image.parentNode; + splitTextBlock(editor, figure); + editor.selection.select(image.parentNode); + } else { + editor.selection.select(image); + waitLoadImage(editor, data, image); + } + }; + var insertOrUpdateImage = function (editor, partialData) { + var image = getSelectedImage(editor); + if (image) { + var selectedImageData = read(function (css) { + return normalizeCss(editor, css); + }, image); + var data = __assign(__assign({}, selectedImageData), partialData); + if (data.src) { + writeImageDataToSelection(editor, data); + } else { + deleteImage(editor, image); + } + } else if (partialData.src) { + insertImageAtCaret(editor, __assign(__assign({}, defaultData()), partialData)); + } + }; + + var hasOwnProperty = Object.prototype.hasOwnProperty; + var deep = function (old, nu) { + var bothObjects = isObject(old) && isObject(nu); + return bothObjects ? deepMerge(old, nu) : nu; + }; + var baseMerge = function (merger) { + return function () { + var objects = new Array(arguments.length); + for (var i = 0; i < objects.length; i++) { + objects[i] = arguments[i]; + } + if (objects.length === 0) { + throw new Error('Can\'t merge zero objects'); + } + var ret = {}; + for (var j = 0; j < objects.length; j++) { + var curObject = objects[j]; + for (var key in curObject) { + if (hasOwnProperty.call(curObject, key)) { + ret[key] = merger(ret[key], curObject[key]); + } + } + } + return ret; + }; + }; + var deepMerge = baseMerge(deep); + + var global$4 = tinymce.util.Tools.resolve('tinymce.util.Tools'); + + var getValue = function (item) { + return isString(item.value) ? item.value : ''; + }; + var sanitizeList = function (list, extractValue) { + var out = []; + global$4.each(list, function (item) { + var text = isString(item.text) ? item.text : isString(item.title) ? item.title : ''; + if (item.menu !== undefined) { + var items = sanitizeList(item.menu, extractValue); + out.push({ + text: text, + items: items + }); + } else { + var value = extractValue(item); + out.push({ + text: text, + value: value + }); + } + }); + return out; + }; + var sanitizer = function (extracter) { + if (extracter === void 0) { + extracter = getValue; + } + return function (list) { + if (list) { + return Optional.from(list).map(function (list) { + return sanitizeList(list, extracter); + }); + } else { + return Optional.none(); + } + }; + }; + var sanitize = function (list) { + return sanitizer(getValue)(list); + }; + var isGroup = function (item) { + return Object.prototype.hasOwnProperty.call(item, 'items'); + }; + var findEntryDelegate = function (list, value) { + return findMap(list, function (item) { + if (isGroup(item)) { + return findEntryDelegate(item.items, value); + } else if (item.value === value) { + return Optional.some(item); + } else { + return Optional.none(); + } + }); + }; + var findEntry = function (optList, value) { + return optList.bind(function (list) { + return findEntryDelegate(list, value); + }); + }; + var ListUtils = { + sanitizer: sanitizer, + sanitize: sanitize, + findEntry: findEntry + }; + + var pathJoin = function (path1, path2) { + if (path1) { + return path1.replace(/\/$/, '') + '/' + path2.replace(/^\//, ''); + } + return path2; + }; + function Uploader (settings) { + var defaultHandler = function (blobInfo, success, failure, progress) { + var xhr = new XMLHttpRequest(); + xhr.open('POST', settings.url); + xhr.withCredentials = settings.credentials; + xhr.upload.onprogress = function (e) { + progress(e.loaded / e.total * 100); + }; + xhr.onerror = function () { + failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status); + }; + xhr.onload = function () { + if (xhr.status < 200 || xhr.status >= 300) { + failure('HTTP Error: ' + xhr.status); + return; + } + var json = JSON.parse(xhr.responseText); + if (!json || typeof json.location !== 'string') { + failure('Invalid JSON: ' + xhr.responseText); + return; + } + success(pathJoin(settings.basePath, json.location)); + }; + var formData = new FormData(); + formData.append('file', blobInfo.blob(), blobInfo.filename()); + xhr.send(formData); + }; + var uploadBlob = function (blobInfo, handler) { + return new global$2(function (resolve, reject) { + try { + handler(blobInfo, resolve, reject, noop); + } catch (ex) { + reject(ex.message); + } + }); + }; + var isDefaultHandler = function (handler) { + return handler === defaultHandler; + }; + var upload = function (blobInfo) { + return !settings.url && isDefaultHandler(settings.handler) ? global$2.reject('Upload url missing from the settings.') : uploadBlob(blobInfo, settings.handler); + }; + settings = global$4.extend({ + credentials: false, + handler: defaultHandler + }, settings); + return { upload: upload }; + } + + var makeTab = function (_info) { + return { + title: 'Advanced', + name: 'advanced', + items: [ + { + type: 'input', + label: 'Style', + name: 'style' + }, + { + type: 'grid', + columns: 2, + items: [ + { + type: 'input', + label: 'Vertical space', + name: 'vspace', + inputMode: 'numeric' + }, + { + type: 'input', + label: 'Horizontal space', + name: 'hspace', + inputMode: 'numeric' + }, + { + type: 'input', + label: 'Border width', + name: 'border', + inputMode: 'numeric' + }, + { + type: 'listbox', + name: 'borderstyle', + label: 'Border style', + items: [ + { + text: 'Select...', + value: '' + }, + { + text: 'Solid', + value: 'solid' + }, + { + text: 'Dotted', + value: 'dotted' + }, + { + text: 'Dashed', + value: 'dashed' + }, + { + text: 'Double', + value: 'double' + }, + { + text: 'Groove', + value: 'groove' + }, + { + text: 'Ridge', + value: 'ridge' + }, + { + text: 'Inset', + value: 'inset' + }, + { + text: 'Outset', + value: 'outset' + }, + { + text: 'None', + value: 'none' + }, + { + text: 'Hidden', + value: 'hidden' + } + ] + } + ] + } + ] + }; + }; + var AdvTab = { makeTab: makeTab }; + + var collect = function (editor) { + var urlListSanitizer = ListUtils.sanitizer(function (item) { + return editor.convertURL(item.value || item.url, 'src'); + }); + var futureImageList = new global$2(function (completer) { + createImageList(editor, function (imageList) { + completer(urlListSanitizer(imageList).map(function (items) { + return flatten([ + [{ + text: 'None', + value: '' + }], + items + ]); + })); + }); + }); + var classList = ListUtils.sanitize(getClassList(editor)); + var hasAdvTab$1 = hasAdvTab(editor); + var hasUploadTab$1 = hasUploadTab(editor); + var hasUploadUrl$1 = hasUploadUrl(editor); + var hasUploadHandler$1 = hasUploadHandler(editor); + var image = readImageDataFromSelection(editor); + var hasDescription$1 = hasDescription(editor); + var hasImageTitle$1 = hasImageTitle(editor); + var hasDimensions$1 = hasDimensions(editor); + var hasImageCaption$1 = hasImageCaption(editor); + var hasAccessibilityOptions = showAccessibilityOptions(editor); + var url = getUploadUrl(editor); + var basePath = getUploadBasePath(editor); + var credentials = getUploadCredentials(editor); + var handler = getUploadHandler(editor); + var automaticUploads = isAutomaticUploadsEnabled(editor); + var prependURL = Optional.some(getPrependUrl(editor)).filter(function (preUrl) { + return isString(preUrl) && preUrl.length > 0; + }); + return futureImageList.then(function (imageList) { + return { + image: image, + imageList: imageList, + classList: classList, + hasAdvTab: hasAdvTab$1, + hasUploadTab: hasUploadTab$1, + hasUploadUrl: hasUploadUrl$1, + hasUploadHandler: hasUploadHandler$1, + hasDescription: hasDescription$1, + hasImageTitle: hasImageTitle$1, + hasDimensions: hasDimensions$1, + hasImageCaption: hasImageCaption$1, + url: url, + basePath: basePath, + credentials: credentials, + handler: handler, + prependURL: prependURL, + hasAccessibilityOptions: hasAccessibilityOptions, + automaticUploads: automaticUploads + }; + }); + }; + + var makeItems = function (info) { + var imageUrl = { + name: 'src', + type: 'urlinput', + filetype: 'image', + label: 'Source' + }; + var imageList = info.imageList.map(function (items) { + return { + name: 'images', + type: 'listbox', + label: 'Image list', + items: items + }; + }); + var imageDescription = { + name: 'alt', + type: 'input', + label: 'Alternative description', + disabled: info.hasAccessibilityOptions && info.image.isDecorative + }; + var imageTitle = { + name: 'title', + type: 'input', + label: 'Image title' + }; + var imageDimensions = { + name: 'dimensions', + type: 'sizeinput' + }; + var isDecorative = { + type: 'label', + label: 'Accessibility', + items: [{ + name: 'isDecorative', + type: 'checkbox', + label: 'Image is decorative' + }] + }; + var classList = info.classList.map(function (items) { + return { + name: 'classes', + type: 'listbox', + label: 'Class', + items: items + }; + }); + var caption = { + type: 'label', + label: 'Caption', + items: [{ + type: 'checkbox', + name: 'caption', + label: 'Show caption' + }] + }; + return flatten([ + [imageUrl], + imageList.toArray(), + info.hasAccessibilityOptions && info.hasDescription ? [isDecorative] : [], + info.hasDescription ? [imageDescription] : [], + info.hasImageTitle ? [imageTitle] : [], + info.hasDimensions ? [imageDimensions] : [], + [{ + type: 'grid', + columns: 2, + items: flatten([ + classList.toArray(), + info.hasImageCaption ? [caption] : [] + ]) + }] + ]); + }; + var makeTab$1 = function (info) { + return { + title: 'General', + name: 'general', + items: makeItems(info) + }; + }; + var MainTab = { + makeTab: makeTab$1, + makeItems: makeItems + }; + + var makeTab$2 = function (_info) { + var items = [{ + type: 'dropzone', + name: 'fileinput' + }]; + return { + title: 'Upload', + name: 'upload', + items: items + }; + }; + var UploadTab = { makeTab: makeTab$2 }; + + var createState = function (info) { + return { + prevImage: ListUtils.findEntry(info.imageList, info.image.src), + prevAlt: info.image.alt, + open: true + }; + }; + var fromImageData = function (image) { + return { + src: { + value: image.src, + meta: {} + }, + images: image.src, + alt: image.alt, + title: image.title, + dimensions: { + width: image.width, + height: image.height + }, + classes: image.class, + caption: image.caption, + style: image.style, + vspace: image.vspace, + border: image.border, + hspace: image.hspace, + borderstyle: image.borderStyle, + fileinput: [], + isDecorative: image.isDecorative + }; + }; + var toImageData = function (data, removeEmptyAlt) { + return { + src: data.src.value, + alt: data.alt.length === 0 && removeEmptyAlt ? null : data.alt, + title: data.title, + width: data.dimensions.width, + height: data.dimensions.height, + class: data.classes, + style: data.style, + caption: data.caption, + hspace: data.hspace, + vspace: data.vspace, + border: data.border, + borderStyle: data.borderstyle, + isDecorative: data.isDecorative + }; + }; + var addPrependUrl2 = function (info, srcURL) { + if (!/^(?:[a-zA-Z]+:)?\/\//.test(srcURL)) { + return info.prependURL.bind(function (prependUrl) { + if (srcURL.substring(0, prependUrl.length) !== prependUrl) { + return Optional.some(prependUrl + srcURL); + } + return Optional.none(); + }); + } + return Optional.none(); + }; + var addPrependUrl = function (info, api) { + var data = api.getData(); + addPrependUrl2(info, data.src.value).each(function (srcURL) { + api.setData({ + src: { + value: srcURL, + meta: data.src.meta + } + }); + }); + }; + var formFillFromMeta2 = function (info, data, meta) { + if (info.hasDescription && isString(meta.alt)) { + data.alt = meta.alt; + } + if (info.hasAccessibilityOptions) { + data.isDecorative = meta.isDecorative || data.isDecorative || false; + } + if (info.hasImageTitle && isString(meta.title)) { + data.title = meta.title; + } + if (info.hasDimensions) { + if (isString(meta.width)) { + data.dimensions.width = meta.width; + } + if (isString(meta.height)) { + data.dimensions.height = meta.height; + } + } + if (isString(meta.class)) { + ListUtils.findEntry(info.classList, meta.class).each(function (entry) { + data.classes = entry.value; + }); + } + if (info.hasImageCaption) { + if (isBoolean(meta.caption)) { + data.caption = meta.caption; + } + } + if (info.hasAdvTab) { + if (isString(meta.style)) { + data.style = meta.style; + } + if (isString(meta.vspace)) { + data.vspace = meta.vspace; + } + if (isString(meta.border)) { + data.border = meta.border; + } + if (isString(meta.hspace)) { + data.hspace = meta.hspace; + } + if (isString(meta.borderstyle)) { + data.borderstyle = meta.borderstyle; + } + } + }; + var formFillFromMeta = function (info, api) { + var data = api.getData(); + var meta = data.src.meta; + if (meta !== undefined) { + var newData = deepMerge({}, data); + formFillFromMeta2(info, newData, meta); + api.setData(newData); + } + }; + var calculateImageSize = function (helpers, info, state, api) { + var data = api.getData(); + var url = data.src.value; + var meta = data.src.meta || {}; + if (!meta.width && !meta.height && info.hasDimensions) { + helpers.imageSize(url).then(function (size) { + if (state.open) { + api.setData({ dimensions: size }); + } + }); + } + }; + var updateImagesDropdown = function (info, state, api) { + var data = api.getData(); + var image = ListUtils.findEntry(info.imageList, data.src.value); + state.prevImage = image; + api.setData({ + images: image.map(function (entry) { + return entry.value; + }).getOr('') + }); + }; + var changeSrc = function (helpers, info, state, api) { + addPrependUrl(info, api); + formFillFromMeta(info, api); + calculateImageSize(helpers, info, state, api); + updateImagesDropdown(info, state, api); + }; + var changeImages = function (helpers, info, state, api) { + var data = api.getData(); + var image = ListUtils.findEntry(info.imageList, data.images); + image.each(function (img) { + var updateAlt = data.alt === '' || state.prevImage.map(function (image) { + return image.text === data.alt; + }).getOr(false); + if (updateAlt) { + if (img.value === '') { + api.setData({ + src: img, + alt: state.prevAlt + }); + } else { + api.setData({ + src: img, + alt: img.text + }); + } + } else { + api.setData({ src: img }); + } + }); + state.prevImage = image; + changeSrc(helpers, info, state, api); + }; + var calcVSpace = function (css) { + var matchingTopBottom = css['margin-top'] && css['margin-bottom'] && css['margin-top'] === css['margin-bottom']; + return matchingTopBottom ? removePixelSuffix(String(css['margin-top'])) : ''; + }; + var calcHSpace = function (css) { + var matchingLeftRight = css['margin-right'] && css['margin-left'] && css['margin-right'] === css['margin-left']; + return matchingLeftRight ? removePixelSuffix(String(css['margin-right'])) : ''; + }; + var calcBorderWidth = function (css) { + return css['border-width'] ? removePixelSuffix(String(css['border-width'])) : ''; + }; + var calcBorderStyle = function (css) { + return css['border-style'] ? String(css['border-style']) : ''; + }; + var calcStyle = function (parseStyle, serializeStyle, css) { + return serializeStyle(parseStyle(serializeStyle(css))); + }; + var changeStyle2 = function (parseStyle, serializeStyle, data) { + var css = mergeMargins(parseStyle(data.style)); + var dataCopy = deepMerge({}, data); + dataCopy.vspace = calcVSpace(css); + dataCopy.hspace = calcHSpace(css); + dataCopy.border = calcBorderWidth(css); + dataCopy.borderstyle = calcBorderStyle(css); + dataCopy.style = calcStyle(parseStyle, serializeStyle, css); + return dataCopy; + }; + var changeStyle = function (helpers, api) { + var data = api.getData(); + var newData = changeStyle2(helpers.parseStyle, helpers.serializeStyle, data); + api.setData(newData); + }; + var changeAStyle = function (helpers, info, api) { + var data = deepMerge(fromImageData(info.image), api.getData()); + var style = getStyleValue(helpers.normalizeCss, toImageData(data, false)); + api.setData({ style: style }); + }; + var changeFileInput = function (helpers, info, state, api) { + var data = api.getData(); + api.block('Uploading image'); + head(data.fileinput).fold(function () { + api.unblock(); + }, function (file) { + var blobUri = URL.createObjectURL(file); + var uploader = Uploader({ + url: info.url, + basePath: info.basePath, + credentials: info.credentials, + handler: info.handler + }); + var finalize = function () { + api.unblock(); + URL.revokeObjectURL(blobUri); + }; + var updateSrcAndSwitchTab = function (url) { + api.setData({ + src: { + value: url, + meta: {} + } + }); + api.showTab('general'); + changeSrc(helpers, info, state, api); + }; + blobToDataUri(file).then(function (dataUrl) { + var blobInfo = helpers.createBlobCache(file, blobUri, dataUrl); + if (info.automaticUploads) { + uploader.upload(blobInfo).then(function (url) { + updateSrcAndSwitchTab(url); + finalize(); + }).catch(function (err) { + finalize(); + helpers.alertErr(err); + }); + } else { + helpers.addToBlobCache(blobInfo); + updateSrcAndSwitchTab(blobInfo.blobUri()); + api.unblock(); + } + }); + }); + }; + var changeHandler = function (helpers, info, state) { + return function (api, evt) { + if (evt.name === 'src') { + changeSrc(helpers, info, state, api); + } else if (evt.name === 'images') { + changeImages(helpers, info, state, api); + } else if (evt.name === 'alt') { + state.prevAlt = api.getData().alt; + } else if (evt.name === 'style') { + changeStyle(helpers, api); + } else if (evt.name === 'vspace' || evt.name === 'hspace' || evt.name === 'border' || evt.name === 'borderstyle') { + changeAStyle(helpers, info, api); + } else if (evt.name === 'fileinput') { + changeFileInput(helpers, info, state, api); + } else if (evt.name === 'isDecorative') { + if (api.getData().isDecorative) { + api.disable('alt'); + } else { + api.enable('alt'); + } + } + }; + }; + var closeHandler = function (state) { + return function () { + state.open = false; + }; + }; + var makeDialogBody = function (info) { + if (info.hasAdvTab || info.hasUploadUrl || info.hasUploadHandler) { + var tabPanel = { + type: 'tabpanel', + tabs: flatten([ + [MainTab.makeTab(info)], + info.hasAdvTab ? [AdvTab.makeTab(info)] : [], + info.hasUploadTab && (info.hasUploadUrl || info.hasUploadHandler) ? [UploadTab.makeTab(info)] : [] + ]) + }; + return tabPanel; + } else { + var panel = { + type: 'panel', + items: MainTab.makeItems(info) + }; + return panel; + } + }; + var makeDialog = function (helpers) { + return function (info) { + var state = createState(info); + return { + title: 'Insert/Edit Image', + size: 'normal', + body: makeDialogBody(info), + buttons: [ + { + type: 'cancel', + name: 'cancel', + text: 'Cancel' + }, + { + type: 'submit', + name: 'save', + text: 'Save', + primary: true + } + ], + initialData: fromImageData(info.image), + onSubmit: helpers.onSubmit(info), + onChange: changeHandler(helpers, info, state), + onClose: closeHandler(state) + }; + }; + }; + var submitHandler = function (editor) { + return function (info) { + return function (api) { + var data = deepMerge(fromImageData(info.image), api.getData()); + editor.execCommand('mceUpdateImage', false, toImageData(data, info.hasAccessibilityOptions)); + editor.editorUpload.uploadImagesAuto(); + api.close(); + }; + }; + }; + var imageSize = function (editor) { + return function (url) { + return getImageSize(editor.documentBaseURI.toAbsolute(url)).then(function (dimensions) { + return { + width: String(dimensions.width), + height: String(dimensions.height) + }; + }); + }; + }; + var createBlobCache = function (editor) { + return function (file, blobUri, dataUrl) { + return editor.editorUpload.blobCache.create({ + blob: file, + blobUri: blobUri, + name: file.name ? file.name.replace(/\.[^\.]+$/, '') : null, + base64: dataUrl.split(',')[1] + }); + }; + }; + var addToBlobCache = function (editor) { + return function (blobInfo) { + editor.editorUpload.blobCache.add(blobInfo); + }; + }; + var alertErr = function (editor) { + return function (message) { + editor.windowManager.alert(message); + }; + }; + var normalizeCss$1 = function (editor) { + return function (cssText) { + return normalizeCss(editor, cssText); + }; + }; + var parseStyle = function (editor) { + return function (cssText) { + return editor.dom.parseStyle(cssText); + }; + }; + var serializeStyle = function (editor) { + return function (stylesArg, name) { + return editor.dom.serializeStyle(stylesArg, name); + }; + }; + var Dialog = function (editor) { + var helpers = { + onSubmit: submitHandler(editor), + imageSize: imageSize(editor), + addToBlobCache: addToBlobCache(editor), + createBlobCache: createBlobCache(editor), + alertErr: alertErr(editor), + normalizeCss: normalizeCss$1(editor), + parseStyle: parseStyle(editor), + serializeStyle: serializeStyle(editor) + }; + var open = function () { + collect(editor).then(makeDialog(helpers)).then(editor.windowManager.open); + }; + return { open: open }; + }; + + var register = function (editor) { + editor.addCommand('mceImage', Dialog(editor).open); + editor.addCommand('mceUpdateImage', function (_ui, data) { + editor.undoManager.transact(function () { + return insertOrUpdateImage(editor, data); + }); + }); + }; + + var hasImageClass = function (node) { + var className = node.attr('class'); + return className && /\bimage\b/.test(className); + }; + var toggleContentEditableState = function (state) { + return function (nodes) { + var i = nodes.length; + var toggleContentEditable = function (node) { + node.attr('contenteditable', state ? 'true' : null); + }; + while (i--) { + var node = nodes[i]; + if (hasImageClass(node)) { + node.attr('contenteditable', state ? 'false' : null); + global$4.each(node.getAll('figcaption'), toggleContentEditable); + } + } + }; + }; + var setup = function (editor) { + editor.on('PreInit', function () { + editor.parser.addNodeFilter('figure', toggleContentEditableState(true)); + editor.serializer.addNodeFilter('figure', toggleContentEditableState(false)); + }); + }; + + var register$1 = function (editor) { + editor.ui.registry.addToggleButton('image', { + icon: 'image', + tooltip: 'Insert/edit image', + onAction: Dialog(editor).open, + onSetup: function (buttonApi) { + return editor.selection.selectorChangedWithUnbind('img:not([data-mce-object],[data-mce-placeholder]),figure.image', buttonApi.setActive).unbind; + } + }); + editor.ui.registry.addMenuItem('image', { + icon: 'image', + text: 'Image...', + onAction: Dialog(editor).open + }); + editor.ui.registry.addContextMenu('image', { + update: function (element) { + return isFigure(element) || isImage(element) && !isPlaceholderImage(element) ? ['image'] : []; + } + }); + }; + + function Plugin () { + global.add('image', function (editor) { + setup(editor); + register$1(editor); + register(editor); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js index fb8ee8fd7f..9e01ef9a50 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/image/plugin.min.js @@ -1 +1,9 @@ -tinymce.PluginManager.add("image",function(e){function t(e,t){function n(e,n){i.parentNode&&i.parentNode.removeChild(i),t({width:e,height:n})}var i=document.createElement("img");i.onload=function(){n(i.clientWidth,i.clientHeight)},i.onerror=function(){n()};var a=i.style;a.visibility="hidden",a.position="fixed",a.bottom=a.left=0,a.width=a.height="auto",document.body.appendChild(i),i.src=e}function n(t){return function(){var n=e.settings.image_list;"string"==typeof n?tinymce.util.XHR.send({url:n,success:function(e){t(tinymce.util.JSON.parse(e))}}):t(n)}}function i(n){function i(){var t=[{text:"None",value:""}];return tinymce.each(n,function(n){t.push({text:n.text||n.title,value:e.convertURL(n.value||n.url,"src"),menu:n.menu})}),t}function a(){var e,t,n,i;e=s.find("#width")[0],t=s.find("#height")[0],n=e.value(),i=t.value(),s.find("#constrain")[0].checked()&&d&&u&&n&&i&&(d!=n?(i=Math.round(n/d*i),t.value(i)):(n=Math.round(i/u*n),e.value(n))),d=n,u=i}function o(){function t(t){function i(){t.onload=t.onerror=null,e.selection.select(t),e.nodeChanged()}t.onload=function(){n.width||n.height||m.setAttribs(t,{width:t.clientWidth,height:t.clientHeight}),i()},t.onerror=i}c(),a();var n=s.toJSON();""===n.width&&(n.width=null),""===n.height&&(n.height=null),""===n.style&&(n.style=null),n={src:n.src,alt:n.alt,width:n.width,height:n.height,style:n.style},e.fire('SaveImage', n),e.undoManager.transact(function(){return n.src?(p?m.setAttribs(p,n):(n.id="__mcenew",e.focus(),e.selection.setContent(m.createHTML("img",n)),p=m.get("__mcenew"),m.setAttrib(p,"id",null)),void t(p)):void(p&&(m.remove(p),e.nodeChanged()))})}function l(e){return e&&(e=e.replace(/px$/,"")),e}function r(){h&&h.value(e.convertURL(this.value(),"src")),t(this.value(),function(e){e.width&&e.height&&(d=e.width,u=e.height,s.find("#width").value(d),s.find("#height").value(u))})}function c(){function t(e){return e.length>0&&/^[0-9]+$/.test(e)&&(e+="px"),e}if(e.settings.image_advtab){var n=s.toJSON(),i=m.parseStyle(n.style);delete i.margin,i["margin-top"]=i["margin-bottom"]=t(n.vspace),i["margin-left"]=i["margin-right"]=t(n.hspace),i["border-width"]=t(n.border),s.find("#style").value(m.serializeStyle(m.parseStyle(m.serializeStyle(i))))}}var s,d,u,h,g={},m=e.dom,p=e.selection.getNode();d=m.getAttrib(p,"width"),u=m.getAttrib(p,"height"),"IMG"!=p.nodeName||p.getAttribute("data-mce-object")||p.getAttribute("data-mce-placeholder")?p=null:g={src:m.getAttrib(p,"src"),alt:m.getAttrib(p,"alt"),width:d,height:u},n&&(h={type:"listbox",label:"Image list",values:i(),value:g.src&&e.convertURL(g.src,"src"),onselect:function(e){var t=s.find("#alt");(!t.value()||e.lastControl&&t.value()==e.lastControl.text())&&t.value(e.control.text()),s.find("#src").value(e.control.value())},onPostRender:function(){h=this}});var y=[{name:"src",type:"filepicker",filetype:"image",label:"Source",autofocus:!0,onchange:r},h,{name:"alt",type:"textbox",label:"Image description"},{type:"container",label:"Dimensions",layout:"flex",direction:"row",align:"center",spacing:5,items:[{name:"width",type:"textbox",maxLength:5,size:3,onchange:a},{type:"label",text:"x"},{name:"height",type:"textbox",maxLength:5,size:3,onchange:a},{name:"constrain",type:"checkbox",checked:!0,text:"Constrain proportions"}]}];e.fire('EditImage', g),e.settings.image_advtab?(p&&(g.hspace=l(p.style.marginLeft||p.style.marginRight),g.vspace=l(p.style.marginTop||p.style.marginBottom),g.border=l(p.style.borderWidth),g.style=e.dom.serializeStyle(e.dom.parseStyle(e.dom.getAttrib(p,"style")))),s=e.windowManager.open({title:"Insert/edit image",data:g,bodyType:"tabpanel",body:[{title:"General",type:"form",items:y},{title:"Advanced",type:"form",pack:"start",items:[{label:"Style",name:"style",type:"textbox"},{type:"form",layout:"grid",packV:"start",columns:2,padding:0,alignH:["left","right"],defaults:{type:"textbox",maxWidth:50,onchange:c},items:[{label:"Vertical space",name:"vspace"},{label:"Horizontal space",name:"hspace"},{label:"Border",name:"border"}]}]}],onSubmit:o})):s=e.windowManager.open({title:"Insert/edit image",data:g,body:y,onSubmit:o})}e.addButton("image",{icon:"image",tooltip:"Insert/edit image",onclick:n(i),stateSelector:"img:not([data-mce-object],[data-mce-placeholder])"}),e.addMenuItem("image",{icon:"image",text:"Insert image",onclick:n(i),context:"insert",prependToContext:!0})}); \ No newline at end of file +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var t,e,n,r,o,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),c=function(){return(c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n= 300; + }; + var requestServiceBlob = function (url, apiKey) { + var headers = { + 'Content-Type': 'application/json;charset=UTF-8', + 'tiny-api-key': apiKey + }; + return sendRequest(appendApiKey(url, apiKey), headers).then(function (result) { + return isError(result.status) ? handleServiceErrorResponse(result.status, result.blob) : Promise.resolve(result.blob); + }); + }; + var requestBlob = function (url, withCredentials) { + return sendRequest(url, {}, withCredentials).then(function (result) { + return isError(result.status) ? handleHttpError(result.status) : Promise.resolve(result.blob); + }); + }; + var getUrl = function (url, apiKey, withCredentials) { + if (withCredentials === void 0) { + withCredentials = false; + } + return apiKey ? requestServiceBlob(url, apiKey) : requestBlob(url, withCredentials); + }; + + var blobToImageResult = function (blob) { + return fromBlob(blob); + }; + + var ELEMENT = 1; + + var fromHtml = function (html, scope) { + var doc = scope || document; + var div = doc.createElement('div'); + div.innerHTML = html; + if (!div.hasChildNodes() || div.childNodes.length > 1) { + console.error('HTML does not have a single root node', html); + throw new Error('HTML must have a single root node'); + } + return fromDom(div.childNodes[0]); + }; + var fromTag = function (tag, scope) { + var doc = scope || document; + var node = doc.createElement(tag); + return fromDom(node); + }; + var fromText = function (text, scope) { + var doc = scope || document; + var node = doc.createTextNode(text); + return fromDom(node); + }; + var fromDom = function (node) { + if (node === null || node === undefined) { + throw new Error('Node cannot be null or undefined'); + } + return { dom: node }; + }; + var fromPoint = function (docElm, x, y) { + return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); + }; + var SugarElement = { + fromHtml: fromHtml, + fromTag: fromTag, + fromText: fromText, + fromDom: fromDom, + fromPoint: fromPoint + }; + + var is = function (element, selector) { + var dom = element.dom; + if (dom.nodeType !== ELEMENT) { + return false; + } else { + var elem = dom; + if (elem.matches !== undefined) { + return elem.matches(selector); + } else if (elem.msMatchesSelector !== undefined) { + return elem.msMatchesSelector(selector); + } else if (elem.webkitMatchesSelector !== undefined) { + return elem.webkitMatchesSelector(selector); + } else if (elem.mozMatchesSelector !== undefined) { + return elem.mozMatchesSelector(selector); + } else { + throw new Error('Browser lacks native selectors'); + } + } + }; + + var Global = typeof window !== 'undefined' ? window : Function('return this;')(); + + var child = function (scope, predicate) { + var pred = function (node) { + return predicate(SugarElement.fromDom(node)); + }; + var result = find(scope.dom.childNodes, pred); + return result.map(SugarElement.fromDom); + }; + + var child$1 = function (scope, selector) { + return child(scope, function (e) { + return is(e, selector); + }); + }; + + var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay'); + + var global$3 = tinymce.util.Tools.resolve('tinymce.util.Promise'); + + var global$4 = tinymce.util.Tools.resolve('tinymce.util.URI'); + + var getToolbarItems = function (editor) { + return editor.getParam('imagetools_toolbar', 'rotateleft rotateright flipv fliph editimage imageoptions'); + }; + var getProxyUrl = function (editor) { + return editor.getParam('imagetools_proxy'); + }; + var getCorsHosts = function (editor) { + return editor.getParam('imagetools_cors_hosts', [], 'string[]'); + }; + var getCredentialsHosts = function (editor) { + return editor.getParam('imagetools_credentials_hosts', [], 'string[]'); + }; + var getFetchImage = function (editor) { + return Optional.from(editor.getParam('imagetools_fetch_image', null, 'function')); + }; + var getApiKey = function (editor) { + return editor.getParam('api_key', editor.getParam('imagetools_api_key', '', 'string'), 'string'); + }; + var getUploadTimeout = function (editor) { + return editor.getParam('images_upload_timeout', 30000, 'number'); + }; + var shouldReuseFilename = function (editor) { + return editor.getParam('images_reuse_filename', false, 'boolean'); + }; + + function getImageSize(img) { + var width, height; + function isPxValue(value) { + return /^[0-9\.]+px$/.test(value); + } + width = img.style.width; + height = img.style.height; + if (width || height) { + if (isPxValue(width) && isPxValue(height)) { + return { + w: parseInt(width, 10), + h: parseInt(height, 10) + }; + } + return null; + } + width = img.width; + height = img.height; + if (width && height) { + return { + w: parseInt(width, 10), + h: parseInt(height, 10) + }; + } + return null; + } + function setImageSize(img, size) { + var width, height; + if (size) { + width = img.style.width; + height = img.style.height; + if (width || height) { + img.style.width = size.w + 'px'; + img.style.height = size.h + 'px'; + img.removeAttribute('data-mce-style'); + } + width = img.width; + height = img.height; + if (width || height) { + img.setAttribute('width', size.w); + img.setAttribute('height', size.h); + } + } + } + function getNaturalImageSize(img) { + return { + w: img.naturalWidth, + h: img.naturalHeight + }; + } + + var count = 0; + var getFigureImg = function (elem) { + return child$1(SugarElement.fromDom(elem), 'img'); + }; + var isFigure = function (editor, elem) { + return editor.dom.is(elem, 'figure'); + }; + var getEditableImage = function (editor, elem) { + var isImage = function (imgNode) { + return editor.dom.is(imgNode, 'img:not([data-mce-object],[data-mce-placeholder])'); + }; + var isEditable = function (imgNode) { + return isImage(imgNode) && (isLocalImage(editor, imgNode) || isCorsImage(editor, imgNode) || getProxyUrl(editor)); + }; + if (isFigure(editor, elem)) { + var imgOpt = getFigureImg(elem); + return imgOpt.map(function (img) { + return isEditable(img.dom) ? Optional.some(img.dom) : Optional.none(); + }); + } + return isEditable(elem) ? Optional.some(elem) : Optional.none(); + }; + var displayError = function (editor, error) { + editor.notificationManager.open({ + text: error, + type: 'error' + }); + }; + var getSelectedImage = function (editor) { + var elem = editor.selection.getNode(); + if (isFigure(editor, elem)) { + return getFigureImg(elem); + } else { + return Optional.some(SugarElement.fromDom(elem)); + } + }; + var extractFilename = function (editor, url) { + var m = url.match(/\/([^\/\?]+)?\.(?:jpeg|jpg|png|gif)(?:\?|$)/i); + if (m) { + return editor.dom.encode(m[1]); + } + return null; + }; + var createId = function () { + return 'imagetools' + count++; + }; + var isLocalImage = function (editor, img) { + var url = img.src; + return url.indexOf('data:') === 0 || url.indexOf('blob:') === 0 || new global$4(url).host === editor.documentBaseURI.host; + }; + var isCorsImage = function (editor, img) { + return global$1.inArray(getCorsHosts(editor), new global$4(img.src).host) !== -1; + }; + var isCorsWithCredentialsImage = function (editor, img) { + return global$1.inArray(getCredentialsHosts(editor), new global$4(img.src).host) !== -1; + }; + var defaultFetchImage = function (editor, img) { + if (isCorsImage(editor, img)) { + return getUrl(img.src, null, isCorsWithCredentialsImage(editor, img)); + } + if (!isLocalImage(editor, img)) { + var proxyUrl = getProxyUrl(editor); + var src = proxyUrl + (proxyUrl.indexOf('?') === -1 ? '?' : '&') + 'url=' + encodeURIComponent(img.src); + var apiKey = getApiKey(editor); + return getUrl(src, apiKey, false); + } + return imageToBlob$1(img); + }; + var imageToBlob$2 = function (editor, img) { + return getFetchImage(editor).fold(function () { + return defaultFetchImage(editor, img); + }, function (customFetchImage) { + return customFetchImage(img); + }); + }; + var findBlob = function (editor, img) { + var blobInfo = editor.editorUpload.blobCache.getByUri(img.src); + if (blobInfo) { + return global$3.resolve(blobInfo.blob()); + } + return imageToBlob$2(editor, img); + }; + var startTimedUpload = function (editor, imageUploadTimerState) { + var imageUploadTimer = global$2.setEditorTimeout(editor, function () { + editor.editorUpload.uploadImagesAuto(); + }, getUploadTimeout(editor)); + imageUploadTimerState.set(imageUploadTimer); + }; + var cancelTimedUpload = function (imageUploadTimerState) { + global$2.clearTimeout(imageUploadTimerState.get()); + }; + var updateSelectedImage = function (editor, ir, uploadImmediately, imageUploadTimerState, selectedImage, size) { + return ir.toBlob().then(function (blob) { + var uri, name, blobInfo; + var blobCache = editor.editorUpload.blobCache; + uri = selectedImage.src; + if (shouldReuseFilename(editor)) { + blobInfo = blobCache.getByUri(uri); + if (blobInfo) { + uri = blobInfo.uri(); + name = blobInfo.name(); + } else { + name = extractFilename(editor, uri); + } + } + blobInfo = blobCache.create({ + id: createId(), + blob: blob, + base64: ir.toBase64(), + uri: uri, + name: name + }); + blobCache.add(blobInfo); + editor.undoManager.transact(function () { + function imageLoadedHandler() { + editor.$(selectedImage).off('load', imageLoadedHandler); + editor.nodeChanged(); + if (uploadImmediately) { + editor.editorUpload.uploadImagesAuto(); + } else { + cancelTimedUpload(imageUploadTimerState); + startTimedUpload(editor, imageUploadTimerState); + } + } + editor.$(selectedImage).on('load', imageLoadedHandler); + if (size) { + editor.$(selectedImage).attr({ + width: size.w, + height: size.h + }); + } + editor.$(selectedImage).attr({ src: blobInfo.blobUri() }).removeAttr('data-mce-src'); + }); + return blobInfo; + }); + }; + var selectedImageOperation = function (editor, imageUploadTimerState, fn, size) { + return function () { + var imgOpt = getSelectedImage(editor); + return imgOpt.fold(function () { + displayError(editor, 'Could not find selected image'); + }, function (img) { + return editor._scanForImages().then(function () { + return findBlob(editor, img.dom); + }).then(blobToImageResult).then(fn).then(function (imageResult) { + return updateSelectedImage(editor, imageResult, false, imageUploadTimerState, img.dom, size); + }, function (error) { + displayError(editor, error); + }); + }); + }; + }; + var rotate$2 = function (editor, imageUploadTimerState, angle) { + return function () { + var imgOpt = getSelectedImage(editor); + var flippedSize = imgOpt.fold(function () { + return null; + }, function (img) { + var size = getImageSize(img.dom); + return size ? { + w: size.h, + h: size.w + } : null; + }); + return selectedImageOperation(editor, imageUploadTimerState, function (imageResult) { + return rotate$1(imageResult, angle); + }, flippedSize)(); + }; + }; + var flip$2 = function (editor, imageUploadTimerState, axis) { + return function () { + return selectedImageOperation(editor, imageUploadTimerState, function (imageResult) { + return flip$1(imageResult, axis); + })(); + }; + }; + var handleDialogBlob = function (editor, imageUploadTimerState, img, originalSize, blob) { + return blobToImage$1(blob).then(function (newImage) { + var newSize = getNaturalImageSize(newImage); + if (originalSize.w !== newSize.w || originalSize.h !== newSize.h) { + if (getImageSize(img)) { + setImageSize(img, newSize); + } + } + URL.revokeObjectURL(newImage.src); + return blob; + }).then(blobToImageResult).then(function (imageResult) { + return updateSelectedImage(editor, imageResult, true, imageUploadTimerState, img); + }, function () { + }); + }; + + var saveState = 'save-state'; + var disable = 'disable'; + var enable = 'enable'; + + var createState = function (blob) { + return { + blob: blob, + url: URL.createObjectURL(blob) + }; + }; + var makeOpen = function (editor, imageUploadTimerState) { + return function () { + var getLoadedSpec = function (currentState) { + return { + title: 'Edit Image', + size: 'large', + body: { + type: 'panel', + items: [{ + type: 'imagetools', + name: 'imagetools', + label: 'Edit Image', + currentState: currentState + }] + }, + buttons: [ + { + type: 'cancel', + name: 'cancel', + text: 'Cancel' + }, + { + type: 'submit', + name: 'save', + text: 'Save', + primary: true, + disabled: true + } + ], + onSubmit: function (api) { + var blob = api.getData().imagetools.blob; + originalImgOpt.each(function (originalImg) { + originalSizeOpt.each(function (originalSize) { + handleDialogBlob(editor, imageUploadTimerState, originalImg.dom, originalSize, blob); + }); + }); + api.close(); + }, + onCancel: function () { + }, + onAction: function (api, details) { + switch (details.name) { + case saveState: + if (details.value) { + api.enable('save'); + } else { + api.disable('save'); + } + break; + case disable: + api.disable('save'); + api.disable('cancel'); + break; + case enable: + api.enable('cancel'); + break; + } + } + }; + }; + var originalImgOpt = getSelectedImage(editor); + var originalSizeOpt = originalImgOpt.map(function (origImg) { + return getNaturalImageSize(origImg.dom); + }); + var imgOpt = getSelectedImage(editor); + imgOpt.each(function (img) { + getEditableImage(editor, img.dom).each(function (_) { + findBlob(editor, img.dom).then(function (blob) { + var state = createState(blob); + editor.windowManager.open(getLoadedSpec(state)); + }); + }); + }); + }; + }; + + var register = function (editor, imageUploadTimerState) { + global$1.each({ + mceImageRotateLeft: rotate$2(editor, imageUploadTimerState, -90), + mceImageRotateRight: rotate$2(editor, imageUploadTimerState, 90), + mceImageFlipVertical: flip$2(editor, imageUploadTimerState, 'v'), + mceImageFlipHorizontal: flip$2(editor, imageUploadTimerState, 'h'), + mceEditImage: makeOpen(editor, imageUploadTimerState) + }, function (fn, cmd) { + editor.addCommand(cmd, fn); + }); + }; + + var setup = function (editor, imageUploadTimerState, lastSelectedImageState) { + editor.on('NodeChange', function (e) { + var lastSelectedImage = lastSelectedImageState.get(); + if (lastSelectedImage && lastSelectedImage.src !== e.element.src) { + cancelTimedUpload(imageUploadTimerState); + editor.editorUpload.uploadImagesAuto(); + lastSelectedImageState.set(null); + } + getEditableImage(editor, e.element).each(lastSelectedImageState.set); + }); + }; + + var register$1 = function (editor) { + var cmd = function (command) { + return function () { + return editor.execCommand(command); + }; + }; + editor.ui.registry.addButton('rotateleft', { + tooltip: 'Rotate counterclockwise', + icon: 'rotate-left', + onAction: cmd('mceImageRotateLeft') + }); + editor.ui.registry.addButton('rotateright', { + tooltip: 'Rotate clockwise', + icon: 'rotate-right', + onAction: cmd('mceImageRotateRight') + }); + editor.ui.registry.addButton('flipv', { + tooltip: 'Flip vertically', + icon: 'flip-vertically', + onAction: cmd('mceImageFlipVertical') + }); + editor.ui.registry.addButton('fliph', { + tooltip: 'Flip horizontally', + icon: 'flip-horizontally', + onAction: cmd('mceImageFlipHorizontal') + }); + editor.ui.registry.addButton('editimage', { + tooltip: 'Edit image', + icon: 'edit-image', + onAction: cmd('mceEditImage'), + onSetup: function (buttonApi) { + var setDisabled = function () { + var elementOpt = getSelectedImage(editor); + elementOpt.each(function (element) { + var disabled = getEditableImage(editor, element.dom).isNone(); + buttonApi.setDisabled(disabled); + }); + }; + editor.on('NodeChange', setDisabled); + return function () { + editor.off('NodeChange', setDisabled); + }; + } + }); + editor.ui.registry.addButton('imageoptions', { + tooltip: 'Image options', + icon: 'image', + onAction: cmd('mceImage') + }); + editor.ui.registry.addContextMenu('imagetools', { + update: function (element) { + return getEditableImage(editor, element).fold(function () { + return []; + }, function (_) { + return [{ + text: 'Edit image', + icon: 'edit-image', + onAction: cmd('mceEditImage') + }]; + }); + } + }); + }; + + var register$2 = function (editor) { + editor.ui.registry.addContextToolbar('imagetools', { + items: getToolbarItems(editor), + predicate: function (elem) { + return getEditableImage(editor, elem).isSome(); + }, + position: 'node', + scope: 'node' + }); + }; + + function Plugin () { + global.add('imagetools', function (editor) { + var imageUploadTimerState = Cell(0); + var lastSelectedImageState = Cell(null); + register(editor, imageUploadTimerState); + register$1(editor); + register$2(editor); + setup(editor, imageUploadTimerState, lastSelectedImageState); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/imagetools/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/imagetools/plugin.min.js new file mode 100644 index 0000000000..44b4e8b7ff --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/imagetools/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var t,e,n,r,l=function(t){var e=t;return{get:function(){return e},set:function(t){e=t}}},o=tinymce.util.Tools.resolve("tinymce.PluginManager"),d=tinymce.util.Tools.resolve("tinymce.util.Tools"),i=function(){},u=function(t){return function(){return t}},a=u(!1),c=u(!0),s=function(){return f},f=(t=function(t){return t.isNone()},{fold:function(t,e){return t()},is:a,isSome:a,isNone:c,getOr:n=function(t){return t},getOrThunk:e=function(t){return t()},getOrDie:function(t){throw new Error(t||"error: getOrDie called on none.")},getOrNull:u(null),getOrUndefined:u(undefined),or:n,orThunk:e,map:s,each:i,bind:s,exists:a,forall:c,filter:s,equals:t,equals_:t,toArray:function(){return[]},toString:u("none()")}),m=function(n){var t=u(n),e=function(){return o},r=function(t){return t(n)},o={fold:function(t,e){return e(n)},is:function(t){return n===t},isSome:c,isNone:a,getOr:t,getOrThunk:t,getOrDie:t,getOrNull:t,getOrUndefined:t,or:e,orThunk:e,map:function(t){return m(t(n))},each:function(t){t(n)},bind:r,exists:r,forall:r,filter:function(t){return t(n)?o:f},toArray:function(){return[n]},toString:function(){return"some("+n+")"},equals:function(t){return t.is(n)},equals_:function(t,e){return t.fold(a,function(t){return e(n,t)})}};return o},g={some:m,none:s,from:function(t){return null===t||t===undefined?f:m(t)}},h=function(t){return!(null===(e=t)||e===undefined);var e},p=(r="function",function(t){return typeof t===r});function v(t,e){return b(document.createElement("canvas"),t,e)}function y(t){var e=v(t.width,t.height);return w(e).drawImage(t,0,0),e}function w(t){return t.getContext("2d")}function b(t,e,n){return t.width=e,t.height=n,t}var I,T,_,R,U=window.Promise?window.Promise:(I=function(t){if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof t)throw new TypeError("not a function");this._state=null,this._value=null,this._deferreds=[],C(t,A(j,this),A(x,this))},T=window,_=I.immediateFn||"function"==typeof T.setImmediate&&T.setImmediate||function(t){setTimeout(t,1)},R=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},I.prototype["catch"]=function(t){return this.then(null,t)},I.prototype.then=function(n,r){var o=this;return new I(function(t,e){E.call(o,new k(n,r,t,e))})},I.all=function(){for(var t=[],e=0;e 0) { + global$4.each(selectorGroups, function (group) { + var menuItem = processSelector(selector, group); + if (menuItem) { + model.addItemToGroup(group.title, menuItem); + } + }); + } else { + var menuItem = processSelector(selector, null); + if (menuItem) { + model.addItem(menuItem); + } + } + } + } + }); + var items = model.toFormats(); + editor.fire('addStyleModifications', { + items: items, + replace: !shouldAppend(editor) + }); + }); + }; + + var get = function (editor) { + var convertSelectorToFormat = function (selectorText) { + return defaultConvertSelectorToFormat(editor, selectorText); + }; + return { convertSelectorToFormat: convertSelectorToFormat }; + }; + + function Plugin () { + global.add('importcss', function (editor) { + setup(editor); + return get(editor); + }); + } + + Plugin(); + +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/importcss/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/importcss/plugin.min.js new file mode 100644 index 0000000000..d2cb80e898 --- /dev/null +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/importcss/plugin.min.js @@ -0,0 +1,9 @@ +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var n,t=tinymce.util.Tools.resolve("tinymce.PluginManager"),v=tinymce.util.Tools.resolve("tinymce.dom.DOMUtils"),f=tinymce.util.Tools.resolve("tinymce.EditorManager"),m=tinymce.util.Tools.resolve("tinymce.Env"),h=tinymce.util.Tools.resolve("tinymce.util.Tools"),d=function(t){return t.getParam("importcss_selector_converter")},o=(n="array",function(t){return r=typeof(e=t),(null===e?"null":"object"==r&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==r&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":r)===n;var e,r}),i=Array.prototype.push,l=function(t,e){return function(t){for(var e=[],r=0,n=t.length;r 0 ? formats[0] : getTimeFormat(editor); + }; + var shouldInsertTimeElement = function (editor) { + return editor.getParam('insertdatetime_element', false); + }; - function getDateTime(fmt, date) { - function addZeros(value, len) { - value = "" + value; + var daysShort = 'Sun Mon Tue Wed Thu Fri Sat Sun'.split(' '); + var daysLong = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '); + var monthsShort = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '); + var monthsLong = 'January February March April May June July August September October November December'.split(' '); + var addZeros = function (value, len) { + value = '' + value; + if (value.length < len) { + for (var i = 0; i < len - value.length; i++) { + value = '0' + value; + } + } + return value; + }; + var getDateTime = function (editor, fmt, date) { + date = date || new Date(); + fmt = fmt.replace('%D', '%m/%d/%Y'); + fmt = fmt.replace('%r', '%I:%M:%S %p'); + fmt = fmt.replace('%Y', '' + date.getFullYear()); + fmt = fmt.replace('%y', '' + date.getYear()); + fmt = fmt.replace('%m', addZeros(date.getMonth() + 1, 2)); + fmt = fmt.replace('%d', addZeros(date.getDate(), 2)); + fmt = fmt.replace('%H', '' + addZeros(date.getHours(), 2)); + fmt = fmt.replace('%M', '' + addZeros(date.getMinutes(), 2)); + fmt = fmt.replace('%S', '' + addZeros(date.getSeconds(), 2)); + fmt = fmt.replace('%I', '' + ((date.getHours() + 11) % 12 + 1)); + fmt = fmt.replace('%p', '' + (date.getHours() < 12 ? 'AM' : 'PM')); + fmt = fmt.replace('%B', '' + editor.translate(monthsLong[date.getMonth()])); + fmt = fmt.replace('%b', '' + editor.translate(monthsShort[date.getMonth()])); + fmt = fmt.replace('%A', '' + editor.translate(daysLong[date.getDay()])); + fmt = fmt.replace('%a', '' + editor.translate(daysShort[date.getDay()])); + fmt = fmt.replace('%%', '%'); + return fmt; + }; + var updateElement = function (editor, timeElm, computerTime, userTime) { + var newTimeElm = editor.dom.create('time', { datetime: computerTime }, userTime); + timeElm.parentNode.insertBefore(newTimeElm, timeElm); + editor.dom.remove(timeElm); + editor.selection.select(newTimeElm, true); + editor.selection.collapse(false); + }; + var insertDateTime = function (editor, format) { + if (shouldInsertTimeElement(editor)) { + var userTime = getDateTime(editor, format); + var computerTime = void 0; + if (/%[HMSIp]/.test(format)) { + computerTime = getDateTime(editor, '%Y-%m-%dT%H:%M'); + } else { + computerTime = getDateTime(editor, '%Y-%m-%d'); + } + var timeElm = editor.dom.getParent(editor.selection.getStart(), 'time'); + if (timeElm) { + updateElement(editor, timeElm, computerTime, userTime); + } else { + editor.insertContent(''); + } + } else { + editor.insertContent(getDateTime(editor, format)); + } + }; - if (value.length < len) { - for (var i = 0; i < (len - value.length); i++) { - value = "0" + value; - } - } + var register = function (editor) { + editor.addCommand('mceInsertDate', function () { + insertDateTime(editor, getDateFormat(editor)); + }); + editor.addCommand('mceInsertTime', function () { + insertDateTime(editor, getTimeFormat(editor)); + }); + }; - return value; - } + var Cell = function (initial) { + var value = initial; + var get = function () { + return value; + }; + var set = function (v) { + value = v; + }; + return { + get: get, + set: set + }; + }; - date = date || new Date(); + var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools'); - fmt = fmt.replace("%D", "%m/%d/%Y"); - fmt = fmt.replace("%r", "%I:%M:%S %p"); - fmt = fmt.replace("%Y", "" + date.getFullYear()); - fmt = fmt.replace("%y", "" + date.getYear()); - fmt = fmt.replace("%m", addZeros(date.getMonth() + 1, 2)); - fmt = fmt.replace("%d", addZeros(date.getDate(), 2)); - fmt = fmt.replace("%H", "" + addZeros(date.getHours(), 2)); - fmt = fmt.replace("%M", "" + addZeros(date.getMinutes(), 2)); - fmt = fmt.replace("%S", "" + addZeros(date.getSeconds(), 2)); - fmt = fmt.replace("%I", "" + ((date.getHours() + 11) % 12 + 1)); - fmt = fmt.replace("%p", "" + (date.getHours() < 12 ? "AM" : "PM")); - fmt = fmt.replace("%B", "" + editor.translate(monthsLong[date.getMonth()])); - fmt = fmt.replace("%b", "" + editor.translate(monthsShort[date.getMonth()])); - fmt = fmt.replace("%A", "" + editor.translate(daysLong[date.getDay()])); - fmt = fmt.replace("%a", "" + editor.translate(daysShort[date.getDay()])); - fmt = fmt.replace("%%", "%"); + var register$1 = function (editor) { + var formats = getFormats(editor); + var defaultFormat = Cell(getDefaultDateTime(editor)); + editor.ui.registry.addSplitButton('insertdatetime', { + icon: 'insert-time', + tooltip: 'Insert date/time', + select: function (value) { + return value === defaultFormat.get(); + }, + fetch: function (done) { + done(global$1.map(formats, function (format) { + return { + type: 'choiceitem', + text: getDateTime(editor, format), + value: format + }; + })); + }, + onAction: function (_api) { + insertDateTime(editor, defaultFormat.get()); + }, + onItemAction: function (_api, value) { + defaultFormat.set(value); + insertDateTime(editor, value); + } + }); + var makeMenuItemHandler = function (format) { + return function () { + defaultFormat.set(format); + insertDateTime(editor, format); + }; + }; + editor.ui.registry.addNestedMenuItem('insertdatetime', { + icon: 'insert-time', + text: 'Date/time', + getSubmenuItems: function () { + return global$1.map(formats, function (format) { + return { + type: 'menuitem', + text: getDateTime(editor, format), + onAction: makeMenuItemHandler(format) + }; + }); + } + }); + }; - return fmt; - } + function Plugin () { + global.add('insertdatetime', function (editor) { + register(editor); + register$1(editor); + }); + } - function insertDateTime(format) { - var html = getDateTime(format); + Plugin(); - if (editor.settings.insertdatetime_element) { - var computerTime; - - if (/%[HMSIp]/.test(format)) { - computerTime = getDateTime("%Y-%m-%dT%H:%M"); - } else { - computerTime = getDateTime("%Y-%m-%d"); - } - - html = ''; - - var timeElm = editor.dom.getParent(editor.selection.getStart(), 'time'); - if (timeElm) { - editor.dom.setOuterHTML(timeElm, html); - return; - } - } - - editor.insertContent(html); - } - - editor.addCommand('mceInsertDate', function() { - insertDateTime(editor.getParam("insertdatetime_dateformat", editor.translate("%Y-%m-%d"))); - }); - - editor.addCommand('mceInsertTime', function() { - insertDateTime(editor.getParam("insertdatetime_timeformat", editor.translate('%H:%M:%S'))); - }); - - editor.addButton('insertdatetime', { - type: 'splitbutton', - title: 'Insert date/time', - onclick: function() { - insertDateTime(lastFormat || defaultButtonTimeFormat); - }, - menu: menuItems - }); - - tinymce.each(editor.settings.insertdatetime_formats || [ - "%H:%M:%S", - "%Y-%m-%d", - "%I:%M:%S %p", - "%D" - ], function(fmt) { - if (!defaultButtonTimeFormat) { - defaultButtonTimeFormat = fmt; - } - - menuItems.push({ - text: getDateTime(fmt), - onclick: function() { - lastFormat = fmt; - insertDateTime(fmt); - } - }); - }); - - editor.addMenuItem('insertdatetime', { - icon: 'date', - text: 'Insert date/time', - menu: menuItems, - context: 'insert' - }); -}); +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/insertdatetime/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/insertdatetime/plugin.min.js index 6b170087a9..f70aadc35d 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/insertdatetime/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/insertdatetime/plugin.min.js @@ -1 +1,9 @@ -tinymce.PluginManager.add("insertdatetime",function(e){function t(t,a){function n(e,t){if(e=""+e,e.length '+n+"";var i=e.dom.getParent(e.selection.getStart(),"time");if(i)return void e.dom.setOuterHTML(i,n)}e.insertContent(n)}var n,r,i="Sun Mon Tue Wed Thu Fri Sat Sun".split(" "),d="Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "),c="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),m="January February March April May June July August September October November December".split(" "),u=[];e.addCommand("mceInsertDate",function(){a(e.getParam("insertdatetime_dateformat",e.translate("%Y-%m-%d")))}),e.addCommand("mceInsertTime",function(){a(e.getParam("insertdatetime_timeformat",e.translate("%H:%M:%S")))}),e.addButton("insertdatetime",{type:"splitbutton",title:"Insert date/time",onclick:function(){a(n||r)},menu:u}),tinymce.each(e.settings.insertdatetime_formats||["%H:%M:%S","%Y-%m-%d","%I:%M:%S %p","%D"],function(e){r||(r=e),u.push({text:t(e),onclick:function(){n=e,a(e)}})}),e.addMenuItem("insertdatetime",{icon:"date",text:"Insert date/time",menu:u,context:"insert"})}); \ No newline at end of file +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var e=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=function(e){return e.getParam("insertdatetime_timeformat",e.translate("%H:%M:%S"))},c=function(e){return e.getParam("insertdatetime_formats",["%H:%M:%S","%Y-%m-%d","%I:%M:%S %p","%D"])},r="Sun Mon Tue Wed Thu Fri Sat Sun".split(" "),a="Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" "),i="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),o="January February March April May June July August September October November December".split(" "),m=function(e,t){if((e=""+e).length '+n+"")):e.insertContent(s(e,t))},t=function(t){t.addCommand("mceInsertDate",function(){var e;l(t,(e=t).getParam("insertdatetime_dateformat",e.translate("%Y-%m-%d")))}),t.addCommand("mceInsertTime",function(){l(t,u(t))})},d=tinymce.util.Tools.resolve("tinymce.util.Tools"),n=function(n){var e,t,r,a,i=c(n),o=(a=c(r=n),e=0 -1; + }; + var map = function (xs, f) { + var len = xs.length; + var r = new Array(len); + for (var i = 0; i < len; i++) { + var x = xs[i]; + r[i] = f(x, i); + } + return r; + }; + var each = function (xs, f) { + for (var i = 0, len = xs.length; i < len; i++) { + var x = xs[i]; + f(x, i); + } + }; + var foldl = function (xs, f, acc) { + each(xs, function (x) { + acc = f(acc, x); + }); + return acc; + }; + var flatten = function (xs) { + var r = []; + for (var i = 0, len = xs.length; i < len; ++i) { + if (!isArray(xs[i])) { + throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); + } + nativePush.apply(r, xs[i]); + } + return r; + }; + var bind = function (xs, f) { + return flatten(map(xs, f)); + }; + var findMap = function (arr, f) { + for (var i = 0; i < arr.length; i++) { + var r = f(arr[i], i); + if (r.isSome()) { + return r; + } + } + return Optional.none(); + }; + + var cat = function (arr) { + var r = []; + var push = function (x) { + r.push(x); + }; + for (var i = 0; i < arr.length; i++) { + arr[i].each(push); + } + return r; + }; + var someIf = function (b, a) { + return b ? Optional.some(a) : Optional.none(); + }; + + var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools'); + + var getValue = function (item) { + return isString(item.value) ? item.value : ''; + }; + var sanitizeList = function (list, extractValue) { + var out = []; + global$2.each(list, function (item) { + var text = isString(item.text) ? item.text : isString(item.title) ? item.title : ''; + if (item.menu !== undefined) { + var items = sanitizeList(item.menu, extractValue); + out.push({ + text: text, + items: items + }); + } else { + var value = extractValue(item); + out.push({ + text: text, + value: value + }); + } + }); + return out; + }; + var sanitizeWith = function (extracter) { + if (extracter === void 0) { + extracter = getValue; + } + return function (list) { + return Optional.from(list).map(function (list) { + return sanitizeList(list, extracter); + }); + }; + }; + var sanitize = function (list) { + return sanitizeWith(getValue)(list); + }; + var createUi = function (name, label) { + return function (items) { + return { + name: name, + type: 'listbox', + label: label, + items: items + }; + }; + }; + var ListOptions = { + sanitize: sanitize, + sanitizeWith: sanitizeWith, + createUi: createUi, + getValue: getValue + }; + + var __assign = function () { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) + if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + var keys = Object.keys; + var hasOwnProperty = Object.hasOwnProperty; + var each$1 = function (obj, f) { + var props = keys(obj); + for (var k = 0, len = props.length; k < len; k++) { + var i = props[k]; + var x = obj[i]; + f(x, i); + } + }; + var objAcc = function (r) { + return function (x, i) { + r[i] = x; + }; + }; + var internalFilter = function (obj, pred, onTrue, onFalse) { + var r = {}; + each$1(obj, function (x, i) { + (pred(x, i) ? onTrue : onFalse)(x, i); + }); + return r; + }; + var filter = function (obj, pred) { + var t = {}; + internalFilter(obj, pred, objAcc(t), noop); + return t; + }; + var has = function (obj, key) { + return hasOwnProperty.call(obj, key); + }; + var hasNonNullableKey = function (obj, key) { + return has(obj, key) && obj[key] !== undefined && obj[key] !== null; + }; + + var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker'); + + var isAnchor = function (elm) { + return elm && elm.nodeName.toLowerCase() === 'a'; + }; + var isLink = function (elm) { + return isAnchor(elm) && !!getHref(elm); + }; + var collectNodesInRange = function (rng, predicate) { + if (rng.collapsed) { + return []; + } else { + var contents = rng.cloneContents(); + var walker = new global$3(contents.firstChild, contents); + var elements = []; + var current = contents.firstChild; + do { + if (predicate(current)) { + elements.push(current); + } + } while (current = walker.next()); + return elements; + } + }; + var hasProtocol = function (url) { + return /^\w+:/i.test(url); + }; + var getHref = function (elm) { + var href = elm.getAttribute('data-mce-href'); + return href ? href : elm.getAttribute('href'); + }; + var applyRelTargetRules = function (rel, isUnsafe) { + var rules = ['noopener']; + var rels = rel ? rel.split(/\s+/) : []; + var toString = function (rels) { + return global$2.trim(rels.sort().join(' ')); + }; + var addTargetRules = function (rels) { + rels = removeTargetRules(rels); + return rels.length > 0 ? rels.concat(rules) : rules; + }; + var removeTargetRules = function (rels) { + return rels.filter(function (val) { + return global$2.inArray(rules, val) === -1; + }); + }; + var newRels = isUnsafe ? addTargetRules(rels) : removeTargetRules(rels); + return newRels.length > 0 ? toString(newRels) : ''; + }; + var trimCaretContainers = function (text) { + return text.replace(/\uFEFF/g, ''); + }; + var getAnchorElement = function (editor, selectedElm) { + selectedElm = selectedElm || editor.selection.getNode(); + if (isImageFigure(selectedElm)) { + return editor.dom.select('a[href]', selectedElm)[0]; + } else { + return editor.dom.getParent(selectedElm, 'a[href]'); + } + }; + var getAnchorText = function (selection, anchorElm) { + var text = anchorElm ? anchorElm.innerText || anchorElm.textContent : selection.getContent({ format: 'text' }); + return trimCaretContainers(text); + }; + var hasLinks = function (elements) { + return global$2.grep(elements, isLink).length > 0; + }; + var hasLinksInSelection = function (rng) { + return collectNodesInRange(rng, isLink).length > 0; + }; + var isOnlyTextSelected = function (editor) { + var inlineTextElements = editor.schema.getTextInlineElements(); + var isElement = function (elm) { + return elm.nodeType === 1 && !isAnchor(elm) && !has(inlineTextElements, elm.nodeName.toLowerCase()); + }; + var elements = collectNodesInRange(editor.selection.getRng(), isElement); + return elements.length === 0; + }; + var isImageFigure = function (elm) { + return elm && elm.nodeName === 'FIGURE' && /\bimage\b/i.test(elm.className); + }; + var getLinkAttrs = function (data) { + return foldl([ + 'title', + 'rel', + 'class', + 'target' + ], function (acc, key) { + data[key].each(function (value) { + acc[key] = value.length > 0 ? value : null; + }); + return acc; + }, { href: data.href }); + }; + var handleExternalTargets = function (href, assumeExternalTargets) { + if ((assumeExternalTargets === 'http' || assumeExternalTargets === 'https') && !hasProtocol(href)) { + return assumeExternalTargets + '://' + href; + } + return href; + }; + var applyLinkOverrides = function (editor, linkAttrs) { + var newLinkAttrs = __assign({}, linkAttrs); + if (!(getRelList(editor).length > 0) && allowUnsafeLinkTarget(editor) === false) { + var newRel = applyRelTargetRules(newLinkAttrs.rel, newLinkAttrs.target === '_blank'); + newLinkAttrs.rel = newRel ? newRel : null; + } + if (Optional.from(newLinkAttrs.target).isNone() && getTargetList(editor) === false) { + newLinkAttrs.target = getDefaultLinkTarget(editor); + } + newLinkAttrs.href = handleExternalTargets(newLinkAttrs.href, assumeExternalTargets(editor)); + return newLinkAttrs; + }; + var updateLink = function (editor, anchorElm, text, linkAttrs) { + text.each(function (text) { + if (anchorElm.hasOwnProperty('innerText')) { + anchorElm.innerText = text; + } else { + anchorElm.textContent = text; + } + }); + editor.dom.setAttribs(anchorElm, linkAttrs); + editor.selection.select(anchorElm); + }; + var createLink = function (editor, selectedElm, text, linkAttrs) { + if (isImageFigure(selectedElm)) { + linkImageFigure(editor, selectedElm, linkAttrs); + } else { + text.fold(function () { + editor.execCommand('mceInsertLink', false, linkAttrs); + }, function (text) { + editor.insertContent(editor.dom.createHTML('a', linkAttrs, editor.dom.encode(text))); + }); + } + }; + var linkDomMutation = function (editor, attachState, data) { + var selectedElm = editor.selection.getNode(); + var anchorElm = getAnchorElement(editor, selectedElm); + var linkAttrs = applyLinkOverrides(editor, getLinkAttrs(data)); + editor.undoManager.transact(function () { + if (data.href === attachState.href) { + attachState.attach(); + } + if (anchorElm) { + editor.focus(); + updateLink(editor, anchorElm, data.text, linkAttrs); + } else { + createLink(editor, selectedElm, data.text, linkAttrs); + } + }); + }; + var unlinkSelection = function (editor) { + var dom = editor.dom, selection = editor.selection; + var bookmark = selection.getBookmark(); + var rng = selection.getRng().cloneRange(); + var startAnchorElm = dom.getParent(rng.startContainer, 'a[href]', editor.getBody()); + var endAnchorElm = dom.getParent(rng.endContainer, 'a[href]', editor.getBody()); + if (startAnchorElm) { + rng.setStartBefore(startAnchorElm); + } + if (endAnchorElm) { + rng.setEndAfter(endAnchorElm); + } + selection.setRng(rng); + editor.execCommand('unlink'); + selection.moveToBookmark(bookmark); + }; + var unlinkDomMutation = function (editor) { + editor.undoManager.transact(function () { + var node = editor.selection.getNode(); + if (isImageFigure(node)) { + unlinkImageFigure(editor, node); + } else { + unlinkSelection(editor); + } + editor.focus(); + }); + }; + var unwrapOptions = function (data) { + var cls = data.class, href = data.href, rel = data.rel, target = data.target, text = data.text, title = data.title; + return filter({ + class: cls.getOrNull(), + href: href, + rel: rel.getOrNull(), + target: target.getOrNull(), + text: text.getOrNull(), + title: title.getOrNull() + }, function (v, _k) { + return isNull(v) === false; + }); + }; + var link = function (editor, attachState, data) { + editor.hasPlugin('rtc', true) ? editor.execCommand('createlink', false, unwrapOptions(data)) : linkDomMutation(editor, attachState, data); + }; + var unlink = function (editor) { + editor.hasPlugin('rtc', true) ? editor.execCommand('unlink') : unlinkDomMutation(editor); + }; + var unlinkImageFigure = function (editor, fig) { + var img = editor.dom.select('img', fig)[0]; + if (img) { + var a = editor.dom.getParents(img, 'a[href]', fig)[0]; + if (a) { + a.parentNode.insertBefore(img, a); + editor.dom.remove(a); + } + } + }; + var linkImageFigure = function (editor, fig, attrs) { + var img = editor.dom.select('img', fig)[0]; + if (img) { + var a = editor.dom.create('a', attrs); + img.parentNode.insertBefore(a, img); + a.appendChild(img); + } + }; + + var isListGroup = function (item) { + return hasNonNullableKey(item, 'items'); + }; + var findTextByValue = function (value, catalog) { + return findMap(catalog, function (item) { + if (isListGroup(item)) { + return findTextByValue(value, item.items); + } else { + return someIf(item.value === value, item); + } + }); + }; + var getDelta = function (persistentText, fieldName, catalog, data) { + var value = data[fieldName]; + var hasPersistentText = persistentText.length > 0; + return value !== undefined ? findTextByValue(value, catalog).map(function (i) { + return { + url: { + value: i.value, + meta: { + text: hasPersistentText ? persistentText : i.text, + attach: noop + } + }, + text: hasPersistentText ? persistentText : i.text + }; + }) : Optional.none(); + }; + var findCatalog = function (catalogs, fieldName) { + if (fieldName === 'link') { + return catalogs.link; + } else if (fieldName === 'anchor') { + return catalogs.anchor; + } else { + return Optional.none(); + } + }; + var init = function (initialData, linkCatalog) { + var persistentData = { + text: initialData.text, + title: initialData.title + }; + var getTitleFromUrlChange = function (url) { + return someIf(persistentData.title.length <= 0, Optional.from(url.meta.title).getOr('')); + }; + var getTextFromUrlChange = function (url) { + return someIf(persistentData.text.length <= 0, Optional.from(url.meta.text).getOr(url.value)); + }; + var onUrlChange = function (data) { + var text = getTextFromUrlChange(data.url); + var title = getTitleFromUrlChange(data.url); + if (text.isSome() || title.isSome()) { + return Optional.some(__assign(__assign({}, text.map(function (text) { + return { text: text }; + }).getOr({})), title.map(function (title) { + return { title: title }; + }).getOr({}))); + } else { + return Optional.none(); + } + }; + var onCatalogChange = function (data, change) { + var catalog = findCatalog(linkCatalog, change.name).getOr([]); + return getDelta(persistentData.text, change.name, catalog, data); + }; + var onChange = function (getData, change) { + var name = change.name; + if (name === 'url') { + return onUrlChange(getData()); + } else if (contains([ + 'anchor', + 'link' + ], name)) { + return onCatalogChange(getData(), change); + } else if (name === 'text' || name === 'title') { + persistentData[name] = getData()[name]; + return Optional.none(); + } else { + return Optional.none(); + } + }; + return { onChange: onChange }; + }; + var DialogChanges = { + init: init, + getDelta: getDelta + }; + + var global$4 = tinymce.util.Tools.resolve('tinymce.util.Delay'); + + var global$5 = tinymce.util.Tools.resolve('tinymce.util.Promise'); + + var delayedConfirm = function (editor, message, callback) { + var rng = editor.selection.getRng(); + global$4.setEditorTimeout(editor, function () { + editor.windowManager.confirm(message, function (state) { + editor.selection.setRng(rng); + callback(state); + }); + }); + }; + var tryEmailTransform = function (data) { + var url = data.href; + var suggestMailTo = url.indexOf('@') > 0 && url.indexOf('/') === -1 && url.indexOf('mailto:') === -1; + return suggestMailTo ? Optional.some({ + message: 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?', + preprocess: function (oldData) { + return __assign(__assign({}, oldData), { href: 'mailto:' + url }); + } + }) : Optional.none(); + }; + var tryProtocolTransform = function (assumeExternalTargets, defaultLinkProtocol) { + return function (data) { + var url = data.href; + var suggestProtocol = assumeExternalTargets === 1 && !hasProtocol(url) || assumeExternalTargets === 0 && /^\s*www(\.|\d\.)/i.test(url); + return suggestProtocol ? Optional.some({ + message: 'The URL you entered seems to be an external link. Do you want to add the required ' + defaultLinkProtocol + ':// prefix?', + preprocess: function (oldData) { + return __assign(__assign({}, oldData), { href: defaultLinkProtocol + '://' + url }); + } + }) : Optional.none(); + }; + }; + var preprocess = function (editor, data) { + return findMap([ + tryEmailTransform, + tryProtocolTransform(assumeExternalTargets(editor), getDefaultLinkProtocol(editor)) + ], function (f) { + return f(data); + }).fold(function () { + return global$5.resolve(data); + }, function (transform) { + return new global$5(function (callback) { + delayedConfirm(editor, transform.message, function (state) { + callback(state ? transform.preprocess(data) : data); + }); + }); + }); + }; + var DialogConfirms = { preprocess: preprocess }; + + var getAnchors = function (editor) { + var anchorNodes = editor.dom.select('a:not([href])'); + var anchors = bind(anchorNodes, function (anchor) { + var id = anchor.name || anchor.id; + return id ? [{ + text: id, + value: '#' + id + }] : []; + }); + return anchors.length > 0 ? Optional.some([{ + text: 'None', + value: '' + }].concat(anchors)) : Optional.none(); + }; + var AnchorListOptions = { getAnchors: getAnchors }; + + var getClasses = function (editor) { + var list = getLinkClassList(editor); + if (list.length > 0) { + return ListOptions.sanitize(list); + } + return Optional.none(); + }; + var ClassListOptions = { getClasses: getClasses }; + + var global$6 = tinymce.util.Tools.resolve('tinymce.util.XHR'); + + var parseJson = function (text) { + try { + return Optional.some(JSON.parse(text)); + } catch (err) { + return Optional.none(); + } + }; + var getLinks = function (editor) { + var extractor = function (item) { + return editor.convertURL(item.value || item.url, 'href'); + }; + var linkList = getLinkList(editor); + return new global$5(function (callback) { + if (isString(linkList)) { + global$6.send({ + url: linkList, + success: function (text) { + return callback(parseJson(text)); + }, + error: function (_) { + return callback(Optional.none()); + } + }); + } else if (isFunction(linkList)) { + linkList(function (output) { + return callback(Optional.some(output)); + }); + } else { + callback(Optional.from(linkList)); + } + }).then(function (optItems) { + return optItems.bind(ListOptions.sanitizeWith(extractor)).map(function (items) { + if (items.length > 0) { + var noneItem = [{ + text: 'None', + value: '' + }]; + return noneItem.concat(items); + } else { + return items; + } + }); + }); + }; + var LinkListOptions = { getLinks: getLinks }; + + var getRels = function (editor, initialTarget) { + var list = getRelList(editor); + if (list.length > 0) { + var isTargetBlank_1 = initialTarget.is('_blank'); + var enforceSafe = allowUnsafeLinkTarget(editor) === false; + var safeRelExtractor = function (item) { + return applyRelTargetRules(ListOptions.getValue(item), isTargetBlank_1); + }; + var sanitizer = enforceSafe ? ListOptions.sanitizeWith(safeRelExtractor) : ListOptions.sanitize; + return sanitizer(list); + } + return Optional.none(); + }; + var RelOptions = { getRels: getRels }; + + var fallbacks = [ + { + text: 'Current window', + value: '' + }, + { + text: 'New window', + value: '_blank' + } + ]; + var getTargets = function (editor) { + var list = getTargetList(editor); + if (isArray(list)) { + return ListOptions.sanitize(list).orThunk(function () { + return Optional.some(fallbacks); + }); + } else if (list === false) { + return Optional.none(); + } + return Optional.some(fallbacks); + }; + var TargetOptions = { getTargets: getTargets }; + + var nonEmptyAttr = function (dom, elem, name) { + var val = dom.getAttrib(elem, name); + return val !== null && val.length > 0 ? Optional.some(val) : Optional.none(); + }; + var extractFromAnchor = function (editor, anchor) { + var dom = editor.dom; + var onlyText = isOnlyTextSelected(editor); + var text = onlyText ? Optional.some(getAnchorText(editor.selection, anchor)) : Optional.none(); + var url = anchor ? Optional.some(dom.getAttrib(anchor, 'href')) : Optional.none(); + var target = anchor ? Optional.from(dom.getAttrib(anchor, 'target')) : Optional.none(); + var rel = nonEmptyAttr(dom, anchor, 'rel'); + var linkClass = nonEmptyAttr(dom, anchor, 'class'); + var title = nonEmptyAttr(dom, anchor, 'title'); + return { + url: url, + text: text, + title: title, + target: target, + rel: rel, + linkClass: linkClass + }; + }; + var collect = function (editor, linkNode) { + return LinkListOptions.getLinks(editor).then(function (links) { + var anchor = extractFromAnchor(editor, linkNode); + return { + anchor: anchor, + catalogs: { + targets: TargetOptions.getTargets(editor), + rels: RelOptions.getRels(editor, anchor.target), + classes: ClassListOptions.getClasses(editor), + anchor: AnchorListOptions.getAnchors(editor), + link: links + }, + optNode: Optional.from(linkNode), + flags: { titleEnabled: shouldShowLinkTitle(editor) } + }; + }); + }; + var DialogInfo = { collect: collect }; + + var handleSubmit = function (editor, info) { + return function (api) { + var data = api.getData(); + if (!data.url.value) { + unlink(editor); + api.close(); + return; + } + var getChangedValue = function (key) { + return Optional.from(data[key]).filter(function (value) { + return !info.anchor[key].is(value); + }); + }; + var changedData = { + href: data.url.value, + text: getChangedValue('text'), + target: getChangedValue('target'), + rel: getChangedValue('rel'), + class: getChangedValue('linkClass'), + title: getChangedValue('title') + }; + var attachState = { + href: data.url.value, + attach: data.url.meta !== undefined && data.url.meta.attach ? data.url.meta.attach : function () { + } + }; + DialogConfirms.preprocess(editor, changedData).then(function (pData) { + link(editor, attachState, pData); + }); + api.close(); + }; + }; + var collectData = function (editor) { + var anchorNode = getAnchorElement(editor); + return DialogInfo.collect(editor, anchorNode); + }; + var getInitialData = function (info, defaultTarget) { + var anchor = info.anchor; + var url = anchor.url.getOr(''); + return { + url: { + value: url, + meta: { original: { value: url } } + }, + text: anchor.text.getOr(''), + title: anchor.title.getOr(''), + anchor: url, + link: url, + rel: anchor.rel.getOr(''), + target: anchor.target.or(defaultTarget).getOr(''), + linkClass: anchor.linkClass.getOr('') + }; + }; + var makeDialog = function (settings, onSubmit, editor) { + var urlInput = [{ + name: 'url', + type: 'urlinput', + filetype: 'file', + label: 'URL' + }]; + var displayText = settings.anchor.text.map(function () { + return { + name: 'text', + type: 'input', + label: 'Text to display' + }; + }).toArray(); + var titleText = settings.flags.titleEnabled ? [{ + name: 'title', + type: 'input', + label: 'Title' + }] : []; + var defaultTarget = Optional.from(getDefaultLinkTarget(editor)); + var initialData = getInitialData(settings, defaultTarget); + var catalogs = settings.catalogs; + var dialogDelta = DialogChanges.init(initialData, catalogs); + var body = { + type: 'panel', + items: flatten([ + urlInput, + displayText, + titleText, + cat([ + catalogs.anchor.map(ListOptions.createUi('anchor', 'Anchors')), + catalogs.rels.map(ListOptions.createUi('rel', 'Rel')), + catalogs.targets.map(ListOptions.createUi('target', 'Open link in...')), + catalogs.link.map(ListOptions.createUi('link', 'Link list')), + catalogs.classes.map(ListOptions.createUi('linkClass', 'Class')) + ]) + ]) + }; + return { + title: 'Insert/Edit Link', + size: 'normal', + body: body, + buttons: [ + { + type: 'cancel', + name: 'cancel', + text: 'Cancel' + }, + { + type: 'submit', + name: 'save', + text: 'Save', + primary: true + } + ], + initialData: initialData, + onChange: function (api, _a) { + var name = _a.name; + dialogDelta.onChange(api.getData, { name: name }).each(function (newData) { + api.setData(newData); + }); + }, + onSubmit: onSubmit + }; + }; + var open = function (editor) { + var data = collectData(editor); + data.then(function (info) { + var onSubmit = handleSubmit(editor, info); + return makeDialog(info, onSubmit, editor); + }).then(function (spec) { + editor.windowManager.open(spec); + }); + }; + + var appendClickRemove = function (link, evt) { + document.body.appendChild(link); + link.dispatchEvent(evt); + document.body.removeChild(link); + }; + var open$1 = function (url) { + var link = document.createElement('a'); + link.target = '_blank'; + link.href = url; + link.rel = 'noreferrer noopener'; + var evt = document.createEvent('MouseEvents'); + evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); + appendClickRemove(link, evt); + }; + + var getLink = function (editor, elm) { + return editor.dom.getParent(elm, 'a[href]'); + }; + var getSelectedLink = function (editor) { + return getLink(editor, editor.selection.getStart()); + }; + var hasOnlyAltModifier = function (e) { + return e.altKey === true && e.shiftKey === false && e.ctrlKey === false && e.metaKey === false; + }; + var gotoLink = function (editor, a) { + if (a) { + var href = getHref(a); + if (/^#/.test(href)) { + var targetEl = editor.$(href); + if (targetEl.length) { + editor.selection.scrollIntoView(targetEl[0], true); + } + } else { + open$1(a.href); + } + } + }; + var openDialog = function (editor) { + return function () { + open(editor); + }; + }; + var gotoSelectedLink = function (editor) { + return function () { + gotoLink(editor, getSelectedLink(editor)); + }; + }; + var setupGotoLinks = function (editor) { + editor.on('click', function (e) { + var link = getLink(editor, e.target); + if (link && global$1.metaKeyPressed(e)) { + e.preventDefault(); + gotoLink(editor, link); + } + }); + editor.on('keydown', function (e) { + var link = getSelectedLink(editor); + if (link && e.keyCode === 13 && hasOnlyAltModifier(e)) { + e.preventDefault(); + gotoLink(editor, link); + } + }); + }; + var toggleState = function (editor, toggler) { + editor.on('NodeChange', toggler); + return function () { + return editor.off('NodeChange', toggler); + }; + }; + var toggleActiveState = function (editor) { + return function (api) { + return toggleState(editor, function () { + api.setActive(!editor.mode.isReadOnly() && getAnchorElement(editor, editor.selection.getNode()) !== null); + }); + }; + }; + var toggleEnabledState = function (editor) { + return function (api) { + var updateState = function () { + return api.setDisabled(getAnchorElement(editor, editor.selection.getNode()) === null); + }; + updateState(); + return toggleState(editor, updateState); + }; + }; + var toggleUnlinkState = function (editor) { + return function (api) { + var hasLinks$1 = function (parents) { + return hasLinks(parents) || hasLinksInSelection(editor.selection.getRng()); + }; + var parents = editor.dom.getParents(editor.selection.getStart()); + api.setDisabled(!hasLinks$1(parents)); + return toggleState(editor, function (e) { + return api.setDisabled(!hasLinks$1(e.parents)); + }); + }; + }; + + var register = function (editor) { + editor.addCommand('mceLink', function () { + if (useQuickLink(editor)) { + editor.fire('contexttoolbar-show', { toolbarKey: 'quicklink' }); + } else { + openDialog(editor)(); + } + }); + }; + + var setup = function (editor) { + editor.addShortcut('Meta+K', '', function () { + editor.execCommand('mceLink'); + }); + }; + + var setupButtons = function (editor) { + editor.ui.registry.addToggleButton('link', { + icon: 'link', + tooltip: 'Insert/edit link', + onAction: openDialog(editor), + onSetup: toggleActiveState(editor) + }); + editor.ui.registry.addButton('openlink', { + icon: 'new-tab', + tooltip: 'Open link', + onAction: gotoSelectedLink(editor), + onSetup: toggleEnabledState(editor) + }); + editor.ui.registry.addButton('unlink', { + icon: 'unlink', + tooltip: 'Remove link', + onAction: function () { + return unlink(editor); + }, + onSetup: toggleUnlinkState(editor) + }); + }; + var setupMenuItems = function (editor) { + editor.ui.registry.addMenuItem('openlink', { + text: 'Open link', + icon: 'new-tab', + onAction: gotoSelectedLink(editor), + onSetup: toggleEnabledState(editor) + }); + editor.ui.registry.addMenuItem('link', { + icon: 'link', + text: 'Link...', + shortcut: 'Meta+K', + onAction: openDialog(editor) + }); + editor.ui.registry.addMenuItem('unlink', { + icon: 'unlink', + text: 'Remove link', + onAction: function () { + return unlink(editor); + }, + onSetup: toggleUnlinkState(editor) + }); + }; + var setupContextMenu = function (editor) { + var inLink = 'link unlink openlink'; + var noLink = 'link'; + editor.ui.registry.addContextMenu('link', { + update: function (element) { + return hasLinks(editor.dom.getParents(element, 'a')) ? inLink : noLink; + } + }); + }; + var setupContextToolbars = function (editor) { + var collapseSelectionToEnd = function (editor) { + editor.selection.collapse(false); + }; + var onSetupLink = function (buttonApi) { + var node = editor.selection.getNode(); + buttonApi.setDisabled(!getAnchorElement(editor, node)); + return function () { + }; + }; + editor.ui.registry.addContextForm('quicklink', { + launch: { + type: 'contextformtogglebutton', + icon: 'link', + tooltip: 'Link', + onSetup: toggleActiveState(editor) + }, + label: 'Link', + predicate: function (node) { + return !!getAnchorElement(editor, node) && hasContextToolbar(editor); + }, + initValue: function () { + var elm = getAnchorElement(editor); + return !!elm ? getHref(elm) : ''; + }, + commands: [ + { + type: 'contextformtogglebutton', + icon: 'link', + tooltip: 'Link', + primary: true, + onSetup: function (buttonApi) { + var node = editor.selection.getNode(); + buttonApi.setActive(!!getAnchorElement(editor, node)); + return toggleActiveState(editor)(buttonApi); + }, + onAction: function (formApi) { + var anchor = getAnchorElement(editor); + var value = formApi.getValue(); + if (!anchor) { + var attachState = { + href: value, + attach: function () { + } + }; + var onlyText = isOnlyTextSelected(editor); + var text = onlyText ? Optional.some(getAnchorText(editor.selection, anchor)).filter(function (t) { + return t.length > 0; + }).or(Optional.from(value)) : Optional.none(); + link(editor, attachState, { + href: value, + text: text, + title: Optional.none(), + rel: Optional.none(), + target: Optional.none(), + class: Optional.none() + }); + formApi.hide(); + } else { + editor.undoManager.transact(function () { + editor.dom.setAttrib(anchor, 'href', value); + collapseSelectionToEnd(editor); + formApi.hide(); + }); + } + } + }, + { + type: 'contextformbutton', + icon: 'unlink', + tooltip: 'Remove link', + onSetup: onSetupLink, + onAction: function (formApi) { + unlink(editor); + formApi.hide(); + } + }, + { + type: 'contextformbutton', + icon: 'new-tab', + tooltip: 'Open link', + onSetup: onSetupLink, + onAction: function (formApi) { + gotoSelectedLink(editor)(); + formApi.hide(); + } + } + ] + }); + }; + + function Plugin () { + global.add('link', function (editor) { + setupButtons(editor); + setupMenuItems(editor); + setupContextMenu(editor); + setupContextToolbars(editor); + setupGotoLinks(editor); + register(editor); + setup(editor); + }); } - function n(t) { - function n(e) { - var t = f.find("#text"); - (!t.value() || e.lastControl && t.value() == e.lastControl.text()) && t.value(e.control.text()), f.find("#href").value(e.control.value()) - } + Plugin(); - function l() { - var n = [{ - text: "None", - value: "" - }]; - return tinymce.each(t, function(t) { - n.push({ - text: t.text || t.title, - value: e.convertURL(t.value || t.url, "href"), - menu: t.menu - }) - }), n - } - - function i(t) { - var n = [{ - text: "None", - value: "" - }]; - return tinymce.each(e.settings.rel_list, function(e) { - n.push({ - text: e.text || e.title, - value: e.value, - selected: t === e.value - }) - }), n - } - - function r(t) { - var n = []; - return e.settings.target_list || (n.push({ - text: "None", - value: "" - }), n.push({ - text: "New window", - value: "_blank" - })), tinymce.each(e.settings.target_list, function(e) { - n.push({ - text: e.text || e.title, - value: e.value, - selected: t === e.value - }) - }), n - } - - function a(t) { - var l = []; - return tinymce.each(e.dom.select("a:not([href])"), function(e) { - var n = e.name || e.id; - n && l.push({ - text: n, - value: "#" + n, - selected: -1 != t.indexOf("#" + n) - }) - }), l.length ? (l.unshift({ - text: "None", - value: "" - }), { - name: "anchor", - type: "listbox", - label: "Anchors", - values: l, - onselect: n - }) : void 0 - } - - function o() { - h && h.value(e.convertURL(this.value(), "href")), !c && 0 === x.text.length && k && this.parent().parent().find("#text")[0].value(this.value()) - } - var u, s, c, f, d, h, v, g, x = {}, - m = e.selection, - p = e.dom; - u = m.getNode(), s = p.getParent(u, "a[href]"); - var k = !0; - if (/= 0; y--) - if (3 != b[y].nodeType) { - k = !1; - break - } - } - x.text = c = s ? s.innerText || s.textContent : m.getContent({ - format: "text" - }), x.href = s ? p.getAttrib(s, "href") : "", x.target = s ? p.getAttrib(s, "target") : e.settings.default_link_target || "", x.rel = s ? p.getAttrib(s, "rel") : "", e.fire('EditLink', x), k && (d = { - name: "text", - type: "textbox", - size: 40, - label: "Text to display", - onchange: function() { - x.text = this.value() - } - }), t && (h = { - type: "listbox", - label: "Link list", - values: l(), - onselect: n, - value: e.convertURL(x.href, "href"), - onPostRender: function() { - h = this - } - }), e.settings.target_list !== !1 && (g = { - name: "target", - type: "listbox", - label: "Target", - values: r(x.target) - }), e.settings.rel_list && (v = { - name: "rel", - type: "listbox", - label: "Rel", - values: i(x.rel) - }), f = e.windowManager.open({ - title: "Insert link", - data: x, - body: [{ - name: "href", - type: "filepicker", - filetype: "file", - size: 40, - autofocus: !0, - label: "Url", - onchange: o, - onkeyup: o - }, - d, a(x.href), h, v, g - ], - onSubmit: function(t) { - function n(t, n) { - var l = e.selection.getRng(); - window.setTimeout(function() { - e.windowManager.confirm(t, function(t) { - e.selection.setRng(l), n(t) - }) - }, 0) - } - - function l() { - s ? (e.focus(), k && i.text != c && (s.innerText = i.text), p.setAttribs(s, { - href: r, - target: i.target ? i.target : null, - rel: i.rel ? i.rel : null - }), m.select(s), e.undoManager.add()) : k ? e.insertContent(p.createHTML("a", { - href: r, - target: i.target ? i.target : null, - rel: i.rel ? i.rel : null - }, p.encode(i.text))) : e.execCommand("mceInsertLink", !1, { - href: r, - target: i.target, - rel: i.rel ? i.rel : null - }) - } - var i = t.data; - e.fire('SaveLink', i); - var r = i.href; - /* EDX - Change the email address detection, which mistakenly detected Split asset keys as email addresses. - Instead, if the link has a "@" sign *and* a colon, do not consider it an email address. */ - return r ? r.indexOf("@") > 0 && -1 == r.indexOf("//") && -1 == r.indexOf(":") ? void n("The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?", function(e) { - e && (r = "mailto:" + r), l() - }) : /^\s*www\./i.test(r) ? void n("The URL you entered seems to be an external link. Do you want to add the required http:// prefix?", function(e) { - e && (r = "http://" + r), l() - }) : void l() : void e.execCommand("unlink") - } - }) - } - e.addButton("link", { - icon: "link", - tooltip: "Insert/edit link", - shortcut: "Ctrl+K", - onclick: t(n), - stateSelector: "a[href]" - }), e.addButton("unlink", { - icon: "unlink", - tooltip: "Remove link", - cmd: "unlink", - stateSelector: "a[href]" - }), e.addShortcut("Ctrl+K", "", t(n)), this.showDialog = n, e.addMenuItem("link", { - icon: "link", - text: "Insert link", - shortcut: "Ctrl+K", - onclick: t(n), - stateSelector: "a[href]", - context: "insert", - prependToContext: !0 - }) -}); +}()); diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/link/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/link/plugin.min.js index 413eac55ae..9bca702167 100644 --- a/common/static/js/vendor/tinymce/js/tinymce/plugins/link/plugin.min.js +++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/link/plugin.min.js @@ -1 +1,9 @@ -tinymce.PluginManager.add("link",function(e){function t(t){return function(){var n=e.settings.link_list;"string"==typeof n?tinymce.util.XHR.send({url:n,success:function(e){t(tinymce.util.JSON.parse(e))}}):t(n)}}function n(t){function n(e){var t=f.find("#text");(!t.value()||e.lastControl&&t.value()==e.lastControl.text())&&t.value(e.control.text()),f.find("#href").value(e.control.value())}function l(){var n=[{text:"None",value:""}];return tinymce.each(t,function(t){n.push({text:t.text||t.title,value:e.convertURL(t.value||t.url,"href"),menu:t.menu})}),n}function i(t){var n=[{text:"None",value:""}];return tinymce.each(e.settings.rel_list,function(e){n.push({text:e.text||e.title,value:e.value,selected:t===e.value})}),n}function r(t){var n=[];return e.settings.target_list||(n.push({text:"None",value:""}),n.push({text:"New window",value:"_blank"})),tinymce.each(e.settings.target_list,function(e){n.push({text:e.text||e.title,value:e.value,selected:t===e.value})}),n}function a(t){var l=[];return tinymce.each(e.dom.select("a:not([href])"),function(e){var n=e.name||e.id;n&&l.push({text:n,value:"#"+n,selected:-1!=t.indexOf("#"+n)})}),l.length?(l.unshift({text:"None",value:""}),{name:"anchor",type:"listbox",label:"Anchors",values:l,onselect:n}):void 0}function o(){h&&h.value(e.convertURL(this.value(),"href")),!c&&0===x.text.length&&k&&this.parent().parent().find("#text")[0].value(this.value())}var u,s,c,f,d,h,v,g,x={},m=e.selection,p=e.dom;u=m.getNode(),s=p.getParent(u,"a[href]");var k=!0;if(/=0;y--)if(3!=b[y].nodeType){k=!1;break}}x.text=c=s?s.innerText||s.textContent:m.getContent({format:"text"}),x.href=s?p.getAttrib(s,"href"):"",x.target=s?p.getAttrib(s,"target"):e.settings.default_link_target||"",x.rel=s?p.getAttrib(s,"rel"):"",e.fire("EditLink",x),k&&(d={name:"text",type:"textbox",size:40,label:"Text to display",onchange:function(){x.text=this.value()}}),t&&(h={type:"listbox",label:"Link list",values:l(),onselect:n,value:e.convertURL(x.href,"href"),onPostRender:function(){h=this}}),e.settings.target_list!==!1&&(g={name:"target",type:"listbox",label:"Target",values:r(x.target)}),e.settings.rel_list&&(v={name:"rel",type:"listbox",label:"Rel",values:i(x.rel)}),f=e.windowManager.open({title:"Insert link",data:x,body:[{name:"href",type:"filepicker",filetype:"file",size:40,autofocus:!0,label:"Url",onchange:o,onkeyup:o},d,a(x.href),h,v,g],onSubmit:function(t){function n(t,n){var l=e.selection.getRng();window.setTimeout(function(){e.windowManager.confirm(t,function(t){e.selection.setRng(l),n(t)})},0)}function l(){s?(e.focus(),k&&i.text!=c&&(s.innerText=i.text),p.setAttribs(s,{href:r,target:i.target?i.target:null,rel:i.rel?i.rel:null}),m.select(s),e.undoManager.add()):k?e.insertContent(p.createHTML("a",{href:r,target:i.target?i.target:null,rel:i.rel?i.rel:null},p.encode(i.text))):e.execCommand("mceInsertLink",!1,{href:r,target:i.target,rel:i.rel?i.rel:null})}var i=t.data;e.fire("SaveLink",i);var r=i.href;return r?r.indexOf("@")>0&&-1==r.indexOf("//")&&-1==r.indexOf(":")?void n("The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?",function(e){e&&(r="mailto:"+r),l()}):/^\s*www\./i.test(r)?void n("The URL you entered seems to be an external link. Do you want to add the required http:// prefix?",function(e){e&&(r="http://"+r),l()}):void l():void e.execCommand("unlink")}})}e.addButton("link",{icon:"link",tooltip:"Insert/edit link",shortcut:"Ctrl+K",onclick:t(n),stateSelector:"a[href]"}),e.addButton("unlink",{icon:"unlink",tooltip:"Remove link",cmd:"unlink",stateSelector:"a[href]"}),e.addShortcut("Ctrl+K","",t(n)),this.showDialog=n,e.addMenuItem("link",{icon:"link",text:"Insert link",shortcut:"Ctrl+K",onclick:t(n),stateSelector:"a[href]",context:"insert",prependToContext:!0})}); \ No newline at end of file +/** + * 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/ + * + * Version: 5.5.1 (2020-10-01) + */ +!function(){"use strict";var n,t,e,r,o=tinymce.util.Tools.resolve("tinymce.PluginManager"),i=tinymce.util.Tools.resolve("tinymce.util.VK"),u=function(r){return function(t){return e=typeof(n=t),(null===n?"null":"object"==e&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==e&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":e)===r;var n,e}},a=function(n){return function(t){return typeof t===n}},l=u("string"),c=u("array"),f=function(t){return n===t},s=a("boolean"),m=a("function"),g=function(t){var n=t.getParam("link_assume_external_targets",!1);return s(n)&&n?1:!l(n)||"http"!==n&&"https"!==n?0:n},p=function(t){return t.getParam("default_link_target")},d=function(t){return t.getParam("target_list",!0)},h=function(t){return t.getParam("rel_list",[],"array")},v=function(t){return t.getParam("allow_unsafe_link_target",!1,"boolean")},y=function(){},k=function(t){return function(){return t}},x=k(!1),b=k(!(n=null)),O=function(){return w},w=(t=function(t){return t.isNone()},{fold:function(t,n){return t()},is:x,isSome:x,isNone:b,getOr:r=function(t){return t},getOrThunk:e=function(t){return t()},getOrDie:function(t){throw new Error(t||"error: getOrDie called on none.")},getOrNull:k(null),getOrUndefined:k(undefined),or:r,orThunk:e,map:O,each:y,bind:O,exists:x,forall:b,filter:O,equals:t,equals_:t,toArray:function(){return[]},toString:k("none()")}),C=function(e){var t=k(e),n=function(){return o},r=function(t){return t(e)},o={fold:function(t,n){return n(e)},is:function(t){return e===t},isSome:b,isNone:x,getOr:t,getOrThunk:t,getOrDie:t,getOrNull:t,getOrUndefined:t,or:n,orThunk:n,map:function(t){return C(t(e))},each:function(t){t(e)},bind:r,exists:r,forall:r,filter:function(t){return t(e)?o:w},toArray:function(){return[e]},toString:function(){return"some("+e+")"},equals:function(t){return t.is(e)},equals_:function(t,n){return t.fold(x,function(t){return n(e,t)})}};return o},N={some:C,none:O,from:function(t){return null===t||t===undefined?w:C(t)}},A=Array.prototype.indexOf,P=Array.prototype.push,T=function(t,n){return e=t,r=n,-1 || - * becomes: ||
- var forcedRootBlockName = editor.settings.forced_root_block;
- var forcedRootBlockStartHtml;
- if (forcedRootBlockName) {
- forcedRootBlockStartHtml = editor.dom.createHTML(forcedRootBlockName, editor.settings.forced_root_block_attrs);
- forcedRootBlockStartHtml = forcedRootBlockStartHtml.substr(0, forcedRootBlockStartHtml.length - 3) + '>';
- }
-
- if ((startBlock && /^(PRE|DIV)$/.test(startBlock.nodeName)) || !forcedRootBlockName) {
- text = Utils.filter(text, [
- [/\n/g, "
"]
- ]);
- } else {
- text = Utils.filter(text, [
- [/\n\n/g, "
)$/, forcedRootBlockStartHtml + '$1'],
- [/\n/g, "
"]
- ]);
-
- if (text.indexOf('
') != -1) {
- text = forcedRootBlockStartHtml + text;
- }
- }
-
- pasteHtml(text);
- }
-
- /**
- * Creates a paste bin element as close as possible to the current caret location and places the focus inside that element
- * so that when the real paste event occurs the contents gets inserted into this element
- * instead of the current editor selection element.
- */
- function createPasteBin() {
- var dom = editor.dom, body = editor.getBody();
- var viewport = editor.dom.getViewPort(editor.getWin()), scrollTop = viewport.y, top = 20;
- var scrollContainer;
-
- lastRng = editor.selection.getRng();
-
- if (editor.inline) {
- scrollContainer = editor.selection.getScrollContainer();
-
- if (scrollContainer) {
- scrollTop = scrollContainer.scrollTop;
- }
- }
-
- // Calculate top cordinate this is needed to avoid scrolling to top of document
- // We want the paste bin to be as close to the caret as possible to avoid scrolling
- if (lastRng.getClientRects) {
- var rects = lastRng.getClientRects();
-
- if (rects.length) {
- // Client rects gets us closes to the actual
- // caret location in for example a wrapped paragraph block
- top = scrollTop + (rects[0].top - dom.getPos(body).y);
- } else {
- top = scrollTop;
-
- // Check if we can find a closer location by checking the range element
- var container = lastRng.startContainer;
- if (container) {
- if (container.nodeType == 3 && container.parentNode != body) {
- container = container.parentNode;
- }
-
- if (container.nodeType == 1) {
- top = dom.getPos(container, scrollContainer || body).y;
- }
- }
- }
- }
-
- // Create a pastebin
- pasteBinElm = dom.add(editor.getBody(), 'div', {
- id: "mcepastebin",
- contentEditable: true,
- "data-mce-bogus": "1",
- style: 'position: absolute; top: ' + top + 'px;' +
- 'width: 10px; height: 10px; overflow: hidden; opacity: 0'
- }, pasteBinDefaultContent);
-
- // Move paste bin out of sight since the controlSelection rect gets displayed otherwise on IE and Gecko
- if (Env.ie || Env.gecko) {
- dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) == 'rtl' ? 0xFFFF : -0xFFFF);
- }
-
- // Prevent focus events from bubbeling fixed FocusManager issues
- dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function(e) {
- e.stopPropagation();
- });
-
- pasteBinElm.focus();
- editor.selection.select(pasteBinElm, true);
- }
-
- /**
- * Removes the paste bin if it exists.
- */
- function removePasteBin() {
- if (pasteBinElm) {
- var pasteBinClone;
-
- // WebKit/Blink might clone the div so
- // lets make sure we remove all clones
- // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
- while ((pasteBinClone = editor.dom.get('mcepastebin'))) {
- editor.dom.remove(pasteBinClone);
- editor.dom.unbind(pasteBinClone);
- }
-
- if (lastRng) {
- editor.selection.setRng(lastRng);
- }
- }
-
- keyboardPastePlainTextState = false;
- pasteBinElm = lastRng = null;
- }
-
- /**
- * Returns the contents of the paste bin as a HTML string.
- *
- * @return {String} Get the contents of the paste bin.
- */
- function getPasteBinHtml() {
- var html = pasteBinDefaultContent, pasteBinClones, i;
-
- // Since WebKit/Chrome might clone the paste bin when pasting
- // for example: a b a b we need to check if any of them contains some useful html.
- // TODO: Man o man is this ugly. WebKit is the new IE! Remove this if they ever fix it!
- pasteBinClones = editor.dom.select('div[id=mcepastebin]');
- i = pasteBinClones.length;
- while (i--) {
- var cloneHtml = pasteBinClones[i].innerHTML;
-
- if (html == pasteBinDefaultContent) {
- html = '';
- }
-
- if (cloneHtml.length > html.length) {
- html = cloneHtml;
- }
- }
-
- return html;
- }
-
- /**
- * Gets various content types out of a datatransfer object.
- *
- * @param {DataTransfer} dataTransfer Event fired on paste.
- * @return {Object} Object with mime types and data for those mime types.
- */
- function getDataTransferItems(dataTransfer) {
- var data = {};
-
- if (dataTransfer && dataTransfer.types) {
- // Use old WebKit API
- var legacyText = dataTransfer.getData('Text');
- if (legacyText && legacyText.length > 0) {
- data['text/plain'] = legacyText;
- }
-
- for (var i = 0; i < dataTransfer.types.length; i++) {
- var contentType = dataTransfer.types[i];
- data[contentType] = dataTransfer.getData(contentType);
- }
- }
-
- return data;
- }
-
- /**
- * Gets various content types out of the Clipboard API. It will also get the
- * plain text using older IE and WebKit API:s.
- *
- * @param {ClipboardEvent} clipboardEvent Event fired on paste.
- * @return {Object} Object with mime types and data for those mime types.
- */
- function getClipboardContent(clipboardEvent) {
- return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
- }
-
- /**
- * Checks if the clipboard contains image data if it does it will take that data
- * and convert it into a data url image and paste that image at the caret location.
- *
- * @param {ClipboardEvent} e Paste event object.
- * @param {Object} clipboardContent Collection of clipboard contents.
- * @return {Boolean} true/false if the image data was found or not.
- */
- function pasteImageData(e, clipboardContent) {
- function pasteImage(item) {
- if (items[i].type == 'image/png') {
- var reader = new FileReader();
-
- reader.onload = function() {
- pasteHtml('
');
- };
-
- reader.readAsDataURL(item.getAsFile());
-
- return true;
- }
- }
-
- // If paste data images are disabled or there is HTML or plain text
- // contents then proceed with the normal paste process
- if (!editor.settings.paste_data_images || "text/html" in clipboardContent || "text/plain" in clipboardContent) {
- return;
- }
-
- if (e.clipboardData) {
- var items = e.clipboardData.items;
-
- if (items) {
- for (var i = 0; i < items.length; i++) {
- if (pasteImage(items[i])) {
- return true;
- }
- }
- }
- }
- }
-
- function getCaretRangeFromEvent(e) {
- var doc = editor.getDoc(), rng;
-
- if (doc.caretPositionFromPoint) {
- var point = doc.caretPositionFromPoint(e.clientX, e.clientY);
- rng = doc.createRange();
- rng.setStart(point.offsetNode, point.offset);
- rng.collapse(true);
- } else if (doc.caretRangeFromPoint) {
- rng = doc.caretRangeFromPoint(e.clientX, e.clientY);
- }
-
- return rng;
- }
-
- function hasContentType(clipboardContent, mimeType) {
- return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
- }
-
- function registerEventHandlers() {
- editor.on('keydown', function(e) {
- if (e.isDefaultPrevented()) {
- return;
- }
-
- // Ctrl+V or Shift+Insert
- if ((VK.metaKeyPressed(e) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) {
- keyboardPastePlainTextState = e.shiftKey && e.keyCode == 86;
-
- // Prevent undoManager keydown handler from making an undo level with the pastebin in it
- e.stopImmediatePropagation();
-
- keyboardPasteTimeStamp = new Date().getTime();
-
- // IE doesn't support Ctrl+Shift+V and it doesn't even produce a paste event
- // so lets fake a paste event and let IE use the execCommand/dataTransfer methods
- if (Env.ie && keyboardPastePlainTextState) {
- e.preventDefault();
- editor.fire('paste', {ieFake: true});
- return;
- }
-
- removePasteBin();
- createPasteBin();
- }
- });
-
- editor.on('paste', function(e) {
- var clipboardContent = getClipboardContent(e);
- var isKeyBoardPaste = new Date().getTime() - keyboardPasteTimeStamp < 1000;
- var plainTextMode = self.pasteFormat == "text" || keyboardPastePlainTextState;
-
- if (e.isDefaultPrevented()) {
- removePasteBin();
- return;
- }
-
- if (pasteImageData(e, clipboardContent)) {
- removePasteBin();
- return;
- }
-
- // Not a keyboard paste prevent default paste and try to grab the clipboard contents using different APIs
- if (!isKeyBoardPaste) {
- e.preventDefault();
- }
-
- // Try IE only method if paste isn't a keyboard paste
- if (Env.ie && (!isKeyBoardPaste || e.ieFake)) {
- createPasteBin();
-
- editor.dom.bind(pasteBinElm, 'paste', function(e) {
- e.stopPropagation();
- });
-
- editor.getDoc().execCommand('Paste', false, null);
- clipboardContent["text/html"] = getPasteBinHtml();
- }
-
- setTimeout(function() {
- var html = getPasteBinHtml();
-
- // WebKit has a nice bug where it clones the paste bin if you paste from for example notepad
- if (pasteBinElm && pasteBinElm.firstChild && pasteBinElm.firstChild.id === 'mcepastebin') {
- plainTextMode = true;
- }
-
- removePasteBin();
-
- if (html == pasteBinDefaultContent || !isKeyBoardPaste) {
- html = clipboardContent['text/html'] || clipboardContent['text/plain'] || pasteBinDefaultContent;
-
- if (html == pasteBinDefaultContent) {
- if (!isKeyBoardPaste) {
- editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
- }
-
- return;
- }
- }
-
- // Force plain text mode if we only got a text/plain content type
- if (!hasContentType(clipboardContent, 'text/html') && hasContentType(clipboardContent, 'text/plain')) {
- plainTextMode = true;
- }
-
- if (plainTextMode) {
- pasteText(clipboardContent['text/plain'] || Utils.innerText(html));
- } else {
- pasteHtml(html);
- }
- }, 0);
- });
-
- editor.on('dragstart', function(e) {
- if (e.dataTransfer.types) {
- try {
- e.dataTransfer.setData('mce-internal', editor.selection.getContent());
- } catch (ex) {
- // IE 10 throws an error since it doesn't support custom data items
- }
- }
- });
-
- editor.on('drop', function(e) {
- var rng = getCaretRangeFromEvent(e);
-
- if (rng && !e.isDefaultPrevented()) {
- var dropContent = getDataTransferItems(e.dataTransfer);
- var content = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
-
- if (content) {
- e.preventDefault();
-
- editor.undoManager.transact(function() {
- if (dropContent['mce-internal']) {
- editor.execCommand('Delete');
- }
-
- editor.selection.setRng(rng);
-
- if (!dropContent['text/html']) {
- pasteText(content);
- } else {
- pasteHtml(content);
- }
- });
- }
- }
- });
- }
-
- self.pasteHtml = pasteHtml;
- self.pasteText = pasteText;
-
- editor.on('preInit', function() {
- registerEventHandlers();
-
- // Remove all data images from paste for example from Gecko
- // except internal images like video elements
- editor.parser.addNodeFilter('img', function(nodes) {
- if (!editor.settings.paste_data_images) {
- var i = nodes.length;
-
- while (i--) {
- var src = nodes[i].attributes.map.src;
- if (src && src.indexOf('data:image') === 0) {
- if (!nodes[i].attr('data-mce-object') && src !== Env.transparentSrc) {
- nodes[i].remove();
- }
- }
- }
- }
- });
- });
-
- // Fix for #6504 we need to remove the paste bin on IE if the user paste in a file
- editor.on('PreProcess', function() {
- editor.dom.remove(editor.dom.get('mcepastebin'));
- });
- };
-});
-
-// Included from: js/tinymce/plugins/paste/classes/WordFilter.js
-
-/**
- * WordFilter.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class parses word HTML into proper TinyMCE markup.
- *
- * @class tinymce.pasteplugin.Quirks
- * @private
- */
-define("tinymce/pasteplugin/WordFilter", [
- "tinymce/util/Tools",
- "tinymce/html/DomParser",
- "tinymce/html/Schema",
- "tinymce/html/Serializer",
- "tinymce/html/Node",
- "tinymce/pasteplugin/Utils"
-], function(Tools, DomParser, Schema, Serializer, Node, Utils) {
- function isWordContent(content) {
- return (/ 1) {
- currentListNode.attr('start', '' + start);
- }
-
- paragraphNode.wrap(currentListNode);
- } else {
- currentListNode.append(paragraphNode);
- }
-
- paragraphNode.name = 'li';
- listStartTextNode.value = '';
-
- var nextNode = listStartTextNode.next;
- if (nextNode && nextNode.type == 3) {
- nextNode.value = nextNode.value.replace(/^\u00a0+/, '');
- }
-
- // Append list to previous list if it exists
- if (level > lastLevel && prevListNode) {
- prevListNode.lastChild.append(currentListNode);
- }
-
- lastLevel = level;
- }
-
- var paragraphs = node.getAll('p');
-
- for (var i = 0; i < paragraphs.length; i++) {
- node = paragraphs[i];
-
- if (node.name == 'p' && node.firstChild) {
- // Find first text node in paragraph
- var nodeText = '';
- var listStartTextNode = node.firstChild;
-
- while (listStartTextNode) {
- nodeText = listStartTextNode.value;
- if (nodeText) {
- break;
- }
-
- listStartTextNode = listStartTextNode.firstChild;
- }
-
- // Detect unordered lists look for bullets
- if (/^\s*[\u2022\u00b7\u00a7\u00d8\u25CF]\s*$/.test(nodeText)) {
- convertParagraphToLi(node, listStartTextNode, 'ul');
- continue;
- }
-
- // Detect ordered lists 1., a. or ixv.
- if (/^\s*\w+\.$/.test(nodeText)) {
- // Parse OL start number
- var matches = /([0-9])\./.exec(nodeText);
- var start = 1;
- if (matches) {
- start = parseInt(matches[1], 10);
- }
-
- convertParagraphToLi(node, listStartTextNode, 'ol', start);
- continue;
- }
-
- currentListNode = null;
- }
- }
- }
-
- function filterStyles(node, styleValue) {
- // Parse out list indent level for lists
- if (node.name === 'p') {
- var matches = /mso-list:\w+ \w+([0-9]+)/.exec(styleValue);
-
- if (matches) {
- node._listLevel = parseInt(matches[1], 10);
- }
- }
-
- if (editor.getParam("paste_retain_style_properties", "none")) {
- var outputStyle = "";
-
- Tools.each(editor.dom.parseStyle(styleValue), function(value, name) {
- // Convert various MS styles to W3C styles
- switch (name) {
- case "horiz-align":
- name = "text-align";
- return;
-
- case "vert-align":
- name = "vertical-align";
- return;
-
- case "font-color":
- case "mso-foreground":
- name = "color";
- return;
-
- case "mso-background":
- case "mso-highlight":
- name = "background";
- break;
- }
-
- // Output only valid styles
- if (retainStyleProperties == "all" || (validStyles && validStyles[name])) {
- outputStyle += name + ':' + value + ';';
- }
- });
-
- if (outputStyle) {
- return outputStyle;
- }
- }
-
- return null;
- }
-
- if (settings.paste_enable_default_filters === false) {
- return;
- }
-
- // Detect is the contents is Word junk HTML
- if (isWordContent(e.content)) {
- e.wordContent = true; // Mark it for other processors
-
- // Remove basic Word junk
- content = Utils.filter(content, [
- // Word comments like conditional comments etc
- //gi,
-
- // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content,
- // MS Office namespaced tags, and a few other tags
- /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
-
- // Convert
into for line-though
- [/<(\/?)s>/gi, "<$1strike>"],
-
- // Replace nsbp entites to char since it's easier to handle
- [/ /gi, "\u00a0"],
-
- // Convert ___ to string of alternating
- // breaking/non-breaking spaces of same length
- [/([\s\u00a0]*)<\/span>/gi,
- function(str, spaces) {
- return (spaces.length > 0) ?
- spaces.replace(/./, " ").slice(Math.floor(spaces.length / 2)).split("").join("\u00a0") : "";
- }
- ]
- ]);
-
- var validElements = settings.paste_word_valid_elements;
- if (!validElements) {
- validElements = '@[style],-strong/b,-em/i,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' +
- '-table[width],-tr,-td[colspan|rowspan|width],-th,-thead,-tfoot,-tbody,-a[href|name],sub,sup,strike,br';
- }
-
- // Setup strict schema
- var schema = new Schema({
- valid_elements: validElements
- });
-
- // Parse HTML into DOM structure
- var domParser = new DomParser({}, schema);
-
- domParser.addAttributeFilter('style', function(nodes) {
- var i = nodes.length, node;
-
- while (i--) {
- node = nodes[i];
- node.attr('style', filterStyles(node, node.attr('style')));
-
- // Remove pointess spans
- if (node.name == 'span' && !node.attributes.length) {
- node.unwrap();
- }
- }
- });
-
- domParser.addNodeFilter('a', function(nodes) {
- var i = nodes.length, node, href, name;
-
- while (i--) {
- node = nodes[i];
- href = node.attr('href');
- name = node.attr('name');
-
- if (href && href.indexOf('file://') === 0) {
- href = href.split('#')[1];
- if (href) {
- href = '#' + href;
- }
- }
-
- if (!href && !name) {
- node.unwrap();
- } else {
- node.attr({
- href: href,
- name: name
- });
- }
- }
- });
- // Parse into DOM structure
- var rootNode = domParser.parse(content);
-
- // Process DOM
- convertFakeListsToProperLists(rootNode);
-
- // Serialize DOM back to HTML
- e.content = new Serializer({}, schema).serialize(rootNode);
- }
- });
- }
-
- WordFilter.isWordContent = isWordContent;
-
- return WordFilter;
-});
-
-// Included from: js/tinymce/plugins/paste/classes/Quirks.js
-
-/**
- * Quirks.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains various fixes for browsers. These issues can not be feature
- * detected since we have no direct control over the clipboard. However we might be able
- * to remove some of these fixes once the browsers gets updated/fixed.
- *
- * @class tinymce.pasteplugin.Quirks
- * @private
- */
-define("tinymce/pasteplugin/Quirks", [
- "tinymce/Env",
- "tinymce/util/Tools",
- "tinymce/pasteplugin/WordFilter",
- "tinymce/pasteplugin/Utils"
-], function(Env, Tools, WordFilter, Utils) {
- "use strict";
-
- return function(editor) {
- function addPreProcessFilter(filterFunc) {
- editor.on('BeforePastePreProcess', function(e) {
- e.content = filterFunc(e.content);
- });
- }
-
- /**
- * Removes WebKit fragment comments and converted-space spans.
- *
- * This:
- * a b
- *
- * Becomes:
- * a b
- */
- function removeWebKitFragments(html) {
- html = Utils.filter(html, [
- /^[\s\S]*|[\s\S]*$/g, // WebKit fragment
- [/\u00a0<\/span>/g, '\u00a0'], // WebKit
- /
$/i // Traling BR elements
- ]);
-
- return html;
- }
-
- /**
- * Removes BR elements after block elements. IE9 has a nasty bug where it puts a BR element after each
- * block element when pasting from word. This removes those elements.
- *
- * This:
- *
[\\s\\r\\n]+|
)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:
[\\s\\r\\n]+|
)*',
- 'g'
- );
-
- // Remove BR:s from:
- html = Utils.filter(html, [
- [explorerBlocksRegExp, '$1']
- ]);
-
- // IE9 also adds an extra BR element for each soft-linefeed and it also adds a BR for each word wrap break
- html = Utils.filter(html, [
- [/
/g, '
'], // Replace multiple BR elements with uppercase BR to keep them intact
- [/
/g, ' '], // Replace single br elements with space since they are word wrap BR:s
- [/
/g, '
'] // Replace back the double brs but into a single BR
- ]);
-
- return html;
- }
-
- /**
- * WebKit has a nasty bug where the all runtime styles gets added to style attributes when copy/pasting contents.
- * This fix solves that by simply removing the whole style attribute.
- *
- * Todo: This can be made smarter. Keeping styles that override existing ones etc.
- *
- * @param {String} content Content that needs to be processed.
- * @return {String} Processed contents.
- */
- function removeWebKitStyles(content) {
- if (editor.settings.paste_remove_styles || editor.settings.paste_remove_styles_if_webkit !== false) {
- content = content.replace(/ style=\"[^\"]+\"/g, '');
- }
-
- return content;
- }
-
- // Sniff browsers and apply fixes since we can't feature detect
- if (Env.webkit) {
- addPreProcessFilter(removeWebKitStyles);
- addPreProcessFilter(removeWebKitFragments);
- }
-
- if (Env.ie) {
- addPreProcessFilter(removeExplorerBrElementsAfterBlocks);
- }
- };
-});
-
-// Included from: js/tinymce/plugins/paste/classes/Plugin.js
-
-/**
- * Plugin.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains the tinymce plugin logic for the paste plugin.
- *
- * @class tinymce.pasteplugin.Plugin
- * @private
- */
-define("tinymce/pasteplugin/Plugin", [
- "tinymce/PluginManager",
- "tinymce/pasteplugin/Clipboard",
- "tinymce/pasteplugin/WordFilter",
- "tinymce/pasteplugin/Quirks"
-], function(PluginManager, Clipboard, WordFilter, Quirks) {
- var userIsInformed;
-
- PluginManager.add('paste', function(editor) {
- var self = this, clipboard, settings = editor.settings;
-
- function togglePlainTextPaste() {
- if (clipboard.pasteFormat == "text") {
- this.active(false);
- clipboard.pasteFormat = "html";
- } else {
- clipboard.pasteFormat = "text";
- this.active(true);
-
- if (!userIsInformed) {
- editor.windowManager.alert(
- 'Paste is now in plain text mode. Contents will now ' +
- 'be pasted as plain text until you toggle this option off.'
- );
-
- userIsInformed = true;
- }
- }
- }
-
- self.clipboard = clipboard = new Clipboard(editor);
- self.quirks = new Quirks(editor);
- self.wordFilter = new WordFilter(editor);
-
- if (editor.settings.paste_as_text) {
- self.clipboard.pasteFormat = "text";
- }
-
- if (settings.paste_preprocess) {
- editor.on('PastePreProcess', function(e) {
- settings.paste_preprocess.call(self, self, e);
- });
- }
-
- if (settings.paste_postprocess) {
- editor.on('PastePostProcess', function(e) {
- settings.paste_postprocess.call(self, self, e);
- });
- }
-
- editor.addCommand('mceInsertClipboardContent', function(ui, value) {
- if (value.content) {
- self.clipboard.pasteHtml(value.content);
- }
-
- if (value.text) {
- self.clipboard.pasteText(value.text);
- }
- });
-
- // Block all drag/drop events
- if (editor.paste_block_drop) {
- editor.on('dragend dragover draggesture dragdrop drop drag', function(e) {
- e.preventDefault();
- e.stopPropagation();
- });
- }
-
- // Prevent users from dropping data images on Gecko
- if (!editor.settings.paste_data_images) {
- editor.on('drop', function(e) {
- var dataTransfer = e.dataTransfer;
-
- if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
- e.preventDefault();
- }
- });
- }
-
- editor.addButton('pastetext', {
- icon: 'pastetext',
- tooltip: 'Paste as text',
- onclick: togglePlainTextPaste,
- active: self.clipboard.pasteFormat == "text"
- });
-
- editor.addMenuItem('pastetext', {
- text: 'Paste as text',
- selectable: true,
- active: clipboard.pasteFormat,
- onclick: togglePlainTextPaste
- });
- });
-});
-
-expose(["tinymce/pasteplugin/Utils","tinymce/pasteplugin/Clipboard","tinymce/pasteplugin/WordFilter","tinymce/pasteplugin/Quirks","tinymce/pasteplugin/Plugin"]);
-})(this);
\ No newline at end of file
+(function () {
+ 'use strict';
+
+ var Cell = function (initial) {
+ var value = initial;
+ var get = function () {
+ return value;
+ };
+ var set = function (v) {
+ value = v;
+ };
+ return {
+ get: get,
+ set: set
+ };
+ };
+
+ var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
+
+ var hasProPlugin = function (editor) {
+ if (editor.hasPlugin('powerpaste', true)) {
+ if (typeof window.console !== 'undefined' && window.console.log) {
+ window.console.log('PowerPaste is incompatible with Paste plugin! Remove \'paste\' from the \'plugins\' option.');
+ }
+ return true;
+ } else {
+ return false;
+ }
+ };
+
+ var get = function (clipboard, quirks) {
+ return {
+ clipboard: clipboard,
+ quirks: quirks
+ };
+ };
+
+ var noop = function () {
+ };
+ var constant = function (value) {
+ return function () {
+ return value;
+ };
+ };
+ var never = constant(false);
+ var always = constant(true);
+
+ var none = function () {
+ return NONE;
+ };
+ var NONE = function () {
+ var eq = function (o) {
+ return o.isNone();
+ };
+ var call = function (thunk) {
+ return thunk();
+ };
+ var id = function (n) {
+ return n;
+ };
+ var me = {
+ fold: function (n, _s) {
+ return n();
+ },
+ is: never,
+ isSome: never,
+ isNone: always,
+ getOr: id,
+ getOrThunk: call,
+ getOrDie: function (msg) {
+ throw new Error(msg || 'error: getOrDie called on none.');
+ },
+ getOrNull: constant(null),
+ getOrUndefined: constant(undefined),
+ or: id,
+ orThunk: call,
+ map: none,
+ each: noop,
+ bind: none,
+ exists: never,
+ forall: always,
+ filter: none,
+ equals: eq,
+ equals_: eq,
+ toArray: function () {
+ return [];
+ },
+ toString: constant('none()')
+ };
+ return me;
+ }();
+ var some = function (a) {
+ var constant_a = constant(a);
+ var self = function () {
+ return me;
+ };
+ var bind = function (f) {
+ return f(a);
+ };
+ var me = {
+ fold: function (n, s) {
+ return s(a);
+ },
+ is: function (v) {
+ return a === v;
+ },
+ isSome: always,
+ isNone: never,
+ getOr: constant_a,
+ getOrThunk: constant_a,
+ getOrDie: constant_a,
+ getOrNull: constant_a,
+ getOrUndefined: constant_a,
+ or: self,
+ orThunk: self,
+ map: function (f) {
+ return some(f(a));
+ },
+ each: function (f) {
+ f(a);
+ },
+ bind: bind,
+ exists: bind,
+ forall: bind,
+ filter: function (f) {
+ return f(a) ? me : NONE;
+ },
+ toArray: function () {
+ return [a];
+ },
+ toString: function () {
+ return 'some(' + a + ')';
+ },
+ equals: function (o) {
+ return o.is(a);
+ },
+ equals_: function (o, elementEq) {
+ return o.fold(never, function (b) {
+ return elementEq(a, b);
+ });
+ }
+ };
+ return me;
+ };
+ var from = function (value) {
+ return value === null || value === undefined ? NONE : some(value);
+ };
+ var Optional = {
+ some: some,
+ none: none,
+ from: from
+ };
+
+ var isSimpleType = function (type) {
+ return function (value) {
+ return typeof value === type;
+ };
+ };
+ var isFunction = isSimpleType('function');
+
+ var nativeSlice = Array.prototype.slice;
+ var map = function (xs, f) {
+ var len = xs.length;
+ var r = new Array(len);
+ for (var i = 0; i < len; i++) {
+ var x = xs[i];
+ r[i] = f(x, i);
+ }
+ return r;
+ };
+ var each = function (xs, f) {
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ f(x, i);
+ }
+ };
+ var filter = function (xs, pred) {
+ var r = [];
+ for (var i = 0, len = xs.length; i < len; i++) {
+ var x = xs[i];
+ if (pred(x, i)) {
+ r.push(x);
+ }
+ }
+ return r;
+ };
+ var foldl = function (xs, f, acc) {
+ each(xs, function (x) {
+ acc = f(acc, x);
+ });
+ return acc;
+ };
+ var from$1 = isFunction(Array.from) ? Array.from : function (x) {
+ return nativeSlice.call(x);
+ };
+
+ var value = function () {
+ var subject = Cell(Optional.none());
+ var clear = function () {
+ return subject.set(Optional.none());
+ };
+ var set = function (s) {
+ return subject.set(Optional.some(s));
+ };
+ var isSet = function () {
+ return subject.get().isSome();
+ };
+ var on = function (f) {
+ return subject.get().each(f);
+ };
+ return {
+ clear: clear,
+ set: set,
+ isSet: isSet,
+ on: on
+ };
+ };
+
+ var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
+
+ var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
+
+ var global$3 = tinymce.util.Tools.resolve('tinymce.util.Promise');
+
+ var global$4 = tinymce.util.Tools.resolve('tinymce.util.VK');
+
+ var firePastePreProcess = function (editor, html, internal, isWordHtml) {
+ return editor.fire('PastePreProcess', {
+ content: html,
+ internal: internal,
+ wordContent: isWordHtml
+ });
+ };
+ var firePastePostProcess = function (editor, node, internal, isWordHtml) {
+ return editor.fire('PastePostProcess', {
+ node: node,
+ internal: internal,
+ wordContent: isWordHtml
+ });
+ };
+ var firePastePlainTextToggle = function (editor, state) {
+ return editor.fire('PastePlainTextToggle', { state: state });
+ };
+ var firePaste = function (editor, ieFake) {
+ return editor.fire('paste', { ieFake: ieFake });
+ };
+
+ var shouldBlockDrop = function (editor) {
+ return editor.getParam('paste_block_drop', false);
+ };
+ var shouldPasteDataImages = function (editor) {
+ return editor.getParam('paste_data_images', false);
+ };
+ var shouldFilterDrop = function (editor) {
+ return editor.getParam('paste_filter_drop', true);
+ };
+ var getPreProcess = function (editor) {
+ return editor.getParam('paste_preprocess');
+ };
+ var getPostProcess = function (editor) {
+ return editor.getParam('paste_postprocess');
+ };
+ var getWebkitStyles = function (editor) {
+ return editor.getParam('paste_webkit_styles');
+ };
+ var shouldRemoveWebKitStyles = function (editor) {
+ return editor.getParam('paste_remove_styles_if_webkit', true);
+ };
+ var shouldMergeFormats = function (editor) {
+ return editor.getParam('paste_merge_formats', true);
+ };
+ var isSmartPasteEnabled = function (editor) {
+ return editor.getParam('smart_paste', true);
+ };
+ var isPasteAsTextEnabled = function (editor) {
+ return editor.getParam('paste_as_text', false);
+ };
+ var getRetainStyleProps = function (editor) {
+ return editor.getParam('paste_retain_style_properties');
+ };
+ var getWordValidElements = function (editor) {
+ var defaultValidElements = '-strong/b,-em/i,-u,-span,-p,-ol,-ul,-li,-h1,-h2,-h3,-h4,-h5,-h6,' + '-p/div,-a[href|name],sub,sup,strike,br,del,table[width],tr,' + 'td[colspan|rowspan|width],th[colspan|rowspan|width],thead,tfoot,tbody';
+ return editor.getParam('paste_word_valid_elements', defaultValidElements);
+ };
+ var shouldConvertWordFakeLists = function (editor) {
+ return editor.getParam('paste_convert_word_fake_lists', true);
+ };
+ var shouldUseDefaultFilters = function (editor) {
+ return editor.getParam('paste_enable_default_filters', true);
+ };
+ var getValidate = function (editor) {
+ return editor.getParam('validate');
+ };
+ var getAllowHtmlDataUrls = function (editor) {
+ return editor.getParam('allow_html_data_urls', false, 'boolean');
+ };
+ var getPasteDataImages = function (editor) {
+ return editor.getParam('paste_data_images', false, 'boolean');
+ };
+ var getImagesDataImgFilter = function (editor) {
+ return editor.getParam('images_dataimg_filter');
+ };
+ var getImagesReuseFilename = function (editor) {
+ return editor.getParam('images_reuse_filename');
+ };
+ var getForcedRootBlock = function (editor) {
+ return editor.getParam('forced_root_block');
+ };
+ var getForcedRootBlockAttrs = function (editor) {
+ return editor.getParam('forced_root_block_attrs');
+ };
+ var getTabSpaces = function (editor) {
+ return editor.getParam('paste_tab_spaces', 4, 'number');
+ };
+
+ var internalMimeType = 'x-tinymce/html';
+ var internalMark = '';
+ var mark = function (html) {
+ return internalMark + html;
+ };
+ var unmark = function (html) {
+ return html.replace(internalMark, '');
+ };
+ var isMarked = function (html) {
+ return html.indexOf(internalMark) !== -1;
+ };
+ var internalHtmlMime = function () {
+ return internalMimeType;
+ };
+
+ var global$5 = tinymce.util.Tools.resolve('tinymce.html.Entities');
+
+ var global$6 = tinymce.util.Tools.resolve('tinymce.util.Tools');
+
+ var isPlainText = function (text) {
+ return !/<(?:\/?(?!(?:div|p|br|span)>)\w+|(?:(?!(?:span style="white-space:\s?pre;?">)|br\s?\/>))\w+\s[^>]+)>/i.test(text);
+ };
+ var toBRs = function (text) {
+ return text.replace(/\r?\n/g, '
');
+ };
+ var openContainer = function (rootTag, rootAttrs) {
+ var key;
+ var attrs = [];
+ var tag = '<' + rootTag;
+ if (typeof rootAttrs === 'object') {
+ for (key in rootAttrs) {
+ if (rootAttrs.hasOwnProperty(key)) {
+ attrs.push(key + '="' + global$5.encodeAllRaw(rootAttrs[key]) + '"');
+ }
+ }
+ if (attrs.length) {
+ tag += ' ' + attrs.join(' ');
+ }
+ }
+ return tag + '>';
+ };
+ var toBlockElements = function (text, rootTag, rootAttrs) {
+ var blocks = text.split(/\n\n/);
+ var tagOpen = openContainer(rootTag, rootAttrs);
+ var tagClose = '' + rootTag + '>';
+ var paragraphs = global$6.map(blocks, function (p) {
+ return p.split(/\n/).join('
');
+ });
+ var stitch = function (p) {
+ return tagOpen + p + tagClose;
+ };
+ return paragraphs.length === 1 ? paragraphs[0] : global$6.map(paragraphs, stitch).join('');
+ };
+ var convert = function (text, rootTag, rootAttrs) {
+ return rootTag ? toBlockElements(text, rootTag === true ? 'p' : rootTag, rootAttrs) : toBRs(text);
+ };
+
+ var global$7 = tinymce.util.Tools.resolve('tinymce.html.DomParser');
+
+ var global$8 = tinymce.util.Tools.resolve('tinymce.html.Serializer');
+
+ var nbsp = '\xA0';
+
+ var global$9 = tinymce.util.Tools.resolve('tinymce.html.Node');
+
+ var global$a = tinymce.util.Tools.resolve('tinymce.html.Schema');
+
+ function filter$1(content, items) {
+ global$6.each(items, function (v) {
+ if (v.constructor === RegExp) {
+ content = content.replace(v, '');
+ } else {
+ content = content.replace(v[0], v[1]);
+ }
+ });
+ return content;
+ }
+ function innerText(html) {
+ var schema = global$a();
+ var domParser = global$7({}, schema);
+ var text = '';
+ var shortEndedElements = schema.getShortEndedElements();
+ var ignoreElements = global$6.makeMap('script noscript style textarea video audio iframe object', ' ');
+ var blockElements = schema.getBlockElements();
+ function walk(node) {
+ var name = node.name, currentNode = node;
+ if (name === 'br') {
+ text += '\n';
+ return;
+ }
+ if (name === 'wbr') {
+ return;
+ }
+ if (shortEndedElements[name]) {
+ text += ' ';
+ }
+ if (ignoreElements[name]) {
+ text += ' ';
+ return;
+ }
+ if (node.type === 3) {
+ text += node.value;
+ }
+ if (!node.shortEnded) {
+ if (node = node.firstChild) {
+ do {
+ walk(node);
+ } while (node = node.next);
+ }
+ }
+ if (blockElements[name] && currentNode.next) {
+ text += '\n';
+ if (name === 'p') {
+ text += '\n';
+ }
+ }
+ }
+ html = filter$1(html, [//g]);
+ walk(domParser.parse(html));
+ return text;
+ }
+ function trimHtml(html) {
+ function trimSpaces(all, s1, s2) {
+ if (!s1 && !s2) {
+ return ' ';
+ }
+ return nbsp;
+ }
+ html = filter$1(html, [
+ /^[\s\S]*]*>\s*|\s*<\/body[^>]*>[\s\S]*$/ig,
+ /|/g,
+ [
+ /( ?)\u00a0<\/span>( ?)/g,
+ trimSpaces
+ ],
+ /
/g,
+ /
$/i
+ ]);
+ return html;
+ }
+ function createIdGenerator(prefix) {
+ var count = 0;
+ return function () {
+ return prefix + count++;
+ };
+ }
+
+ function isWordContent(content) {
+ return / 1) {
+ currentListNode.attr('start', '' + start);
+ }
+ paragraphNode.wrap(currentListNode);
+ } else {
+ currentListNode.append(paragraphNode);
+ }
+ paragraphNode.name = 'li';
+ if (level > lastLevel && prevListNode) {
+ prevListNode.lastChild.append(currentListNode);
+ }
+ lastLevel = level;
+ removeIgnoredNodes(paragraphNode);
+ trimListStart(paragraphNode, /^\u00a0+/);
+ trimListStart(paragraphNode, /^\s*([\u2022\u00b7\u00a7\u25CF]|\w+\.)/);
+ trimListStart(paragraphNode, /^\u00a0+/);
+ }
+ var elements = [];
+ var child = node.firstChild;
+ while (typeof child !== 'undefined' && child !== null) {
+ elements.push(child);
+ child = child.walk();
+ if (child !== null) {
+ while (typeof child !== 'undefined' && child.parent !== node) {
+ child = child.walk();
+ }
+ }
+ }
+ for (var i = 0; i < elements.length; i++) {
+ node = elements[i];
+ if (node.name === 'p' && node.firstChild) {
+ var nodeText = getText(node);
+ if (isBulletList(nodeText)) {
+ convertParagraphToLi(node, 'ul');
+ continue;
+ }
+ if (isNumericList(nodeText)) {
+ var matches = /([0-9]+)\./.exec(nodeText);
+ var start = 1;
+ if (matches) {
+ start = parseInt(matches[1], 10);
+ }
+ convertParagraphToLi(node, 'ol', start);
+ continue;
+ }
+ if (node._listLevel) {
+ convertParagraphToLi(node, 'ul', 1);
+ continue;
+ }
+ currentListNode = null;
+ } else {
+ prevListNode = currentListNode;
+ currentListNode = null;
+ }
+ }
+ }
+ function filterStyles(editor, validStyles, node, styleValue) {
+ var outputStyles = {}, matches;
+ var styles = editor.dom.parseStyle(styleValue);
+ global$6.each(styles, function (value, name) {
+ switch (name) {
+ case 'mso-list':
+ matches = /\w+ \w+([0-9]+)/i.exec(styleValue);
+ if (matches) {
+ node._listLevel = parseInt(matches[1], 10);
+ }
+ if (/Ignore/i.test(value) && node.firstChild) {
+ node._listIgnore = true;
+ node.firstChild._listIgnore = true;
+ }
+ break;
+ case 'horiz-align':
+ name = 'text-align';
+ break;
+ case 'vert-align':
+ name = 'vertical-align';
+ break;
+ case 'font-color':
+ case 'mso-foreground':
+ name = 'color';
+ break;
+ case 'mso-background':
+ case 'mso-highlight':
+ name = 'background';
+ break;
+ case 'font-weight':
+ case 'font-style':
+ if (value !== 'normal') {
+ outputStyles[name] = value;
+ }
+ return;
+ case 'mso-element':
+ if (/^(comment|comment-list)$/i.test(value)) {
+ node.remove();
+ return;
+ }
+ break;
+ }
+ if (name.indexOf('mso-comment') === 0) {
+ node.remove();
+ return;
+ }
+ if (name.indexOf('mso-') === 0) {
+ return;
+ }
+ if (getRetainStyleProps(editor) === 'all' || validStyles && validStyles[name]) {
+ outputStyles[name] = value;
+ }
+ });
+ if (/(bold)/i.test(outputStyles['font-weight'])) {
+ delete outputStyles['font-weight'];
+ node.wrap(new global$9('b', 1));
+ }
+ if (/(italic)/i.test(outputStyles['font-style'])) {
+ delete outputStyles['font-style'];
+ node.wrap(new global$9('i', 1));
+ }
+ outputStyles = editor.dom.serializeStyle(outputStyles, node.name);
+ if (outputStyles) {
+ return outputStyles;
+ }
+ return null;
+ }
+ var filterWordContent = function (editor, content) {
+ var validStyles;
+ var retainStyleProperties = getRetainStyleProps(editor);
+ if (retainStyleProperties) {
+ validStyles = global$6.makeMap(retainStyleProperties.split(/[, ]/));
+ }
+ content = filter$1(content, [
+ /
/gi,
+ /]+id="?docs-internal-[^>]*>/gi,
+ //gi,
+ /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,
+ [
+ /<(\/?)s>/gi,
+ '<$1strike>'
+ ],
+ [
+ / /gi,
+ nbsp
+ ],
+ [
+ /([\s\u00a0]*)<\/span>/gi,
+ function (str, spaces) {
+ return spaces.length > 0 ? spaces.replace(/./, ' ').slice(Math.floor(spaces.length / 2)).split('').join(nbsp) : '';
+ }
+ ]
+ ]);
+ var validElements = getWordValidElements(editor);
+ var schema = global$a({
+ valid_elements: validElements,
+ valid_children: '-li[p]'
+ });
+ global$6.each(schema.elements, function (rule) {
+ if (!rule.attributes.class) {
+ rule.attributes.class = {};
+ rule.attributesOrder.push('class');
+ }
+ if (!rule.attributes.style) {
+ rule.attributes.style = {};
+ rule.attributesOrder.push('style');
+ }
+ });
+ var domParser = global$7({}, schema);
+ domParser.addAttributeFilter('style', function (nodes) {
+ var i = nodes.length, node;
+ while (i--) {
+ node = nodes[i];
+ node.attr('style', filterStyles(editor, validStyles, node, node.attr('style')));
+ if (node.name === 'span' && node.parent && !node.attributes.length) {
+ node.unwrap();
+ }
+ }
+ });
+ domParser.addAttributeFilter('class', function (nodes) {
+ var i = nodes.length, node, className;
+ while (i--) {
+ node = nodes[i];
+ className = node.attr('class');
+ if (/^(MsoCommentReference|MsoCommentText|msoDel)$/i.test(className)) {
+ node.remove();
+ }
+ node.attr('class', null);
+ }
+ });
+ domParser.addNodeFilter('del', function (nodes) {
+ var i = nodes.length;
+ while (i--) {
+ nodes[i].remove();
+ }
+ });
+ domParser.addNodeFilter('a', function (nodes) {
+ var i = nodes.length, node, href, name;
+ while (i--) {
+ node = nodes[i];
+ href = node.attr('href');
+ name = node.attr('name');
+ if (href && href.indexOf('#_msocom_') !== -1) {
+ node.remove();
+ continue;
+ }
+ if (href && href.indexOf('file://') === 0) {
+ href = href.split('#')[1];
+ if (href) {
+ href = '#' + href;
+ }
+ }
+ if (!href && !name) {
+ node.unwrap();
+ } else {
+ if (name && !/^_?(?:toc|edn|ftn)/i.test(name)) {
+ node.unwrap();
+ continue;
+ }
+ node.attr({
+ href: href,
+ name: name
+ });
+ }
+ }
+ });
+ var rootNode = domParser.parse(content);
+ if (shouldConvertWordFakeLists(editor)) {
+ convertFakeListsToProperLists(rootNode);
+ }
+ content = global$8({ validate: getValidate(editor) }, schema).serialize(rootNode);
+ return content;
+ };
+ var preProcess = function (editor, content) {
+ return shouldUseDefaultFilters(editor) ? filterWordContent(editor, content) : content;
+ };
+
+ var preProcess$1 = function (editor, html) {
+ var parser = global$7({}, editor.schema);
+ parser.addNodeFilter('meta', function (nodes) {
+ global$6.each(nodes, function (node) {
+ node.remove();
+ });
+ });
+ var fragment = parser.parse(html, {
+ forced_root_block: false,
+ isRootContent: true
+ });
+ return global$8({ validate: getValidate(editor) }, editor.schema).serialize(fragment);
+ };
+ var processResult = function (content, cancelled) {
+ return {
+ content: content,
+ cancelled: cancelled
+ };
+ };
+ var postProcessFilter = function (editor, html, internal, isWordHtml) {
+ var tempBody = editor.dom.create('div', { style: 'display:none' }, html);
+ var postProcessArgs = firePastePostProcess(editor, tempBody, internal, isWordHtml);
+ return processResult(postProcessArgs.node.innerHTML, postProcessArgs.isDefaultPrevented());
+ };
+ var filterContent = function (editor, content, internal, isWordHtml) {
+ var preProcessArgs = firePastePreProcess(editor, content, internal, isWordHtml);
+ var filteredContent = preProcess$1(editor, preProcessArgs.content);
+ if (editor.hasEventListeners('PastePostProcess') && !preProcessArgs.isDefaultPrevented()) {
+ return postProcessFilter(editor, filteredContent, internal, isWordHtml);
+ } else {
+ return processResult(filteredContent, preProcessArgs.isDefaultPrevented());
+ }
+ };
+ var process = function (editor, html, internal) {
+ var isWordHtml = isWordContent(html);
+ var content = isWordHtml ? preProcess(editor, html) : html;
+ return filterContent(editor, content, internal, isWordHtml);
+ };
+
+ var pasteHtml = function (editor, html) {
+ editor.insertContent(html, {
+ merge: shouldMergeFormats(editor),
+ paste: true
+ });
+ return true;
+ };
+ var isAbsoluteUrl = function (url) {
+ return /^https?:\/\/[\w\?\-\/+=.&%@~#]+$/i.test(url);
+ };
+ var isImageUrl = function (url) {
+ return isAbsoluteUrl(url) && /.(gif|jpe?g|png)$/.test(url);
+ };
+ var createImage = function (editor, url, pasteHtmlFn) {
+ editor.undoManager.extra(function () {
+ pasteHtmlFn(editor, url);
+ }, function () {
+ editor.insertContent('');
+ });
+ return true;
+ };
+ var createLink = function (editor, url, pasteHtmlFn) {
+ editor.undoManager.extra(function () {
+ pasteHtmlFn(editor, url);
+ }, function () {
+ editor.execCommand('mceInsertLink', false, url);
+ });
+ return true;
+ };
+ var linkSelection = function (editor, html, pasteHtmlFn) {
+ return editor.selection.isCollapsed() === false && isAbsoluteUrl(html) ? createLink(editor, html, pasteHtmlFn) : false;
+ };
+ var insertImage = function (editor, html, pasteHtmlFn) {
+ return isImageUrl(html) ? createImage(editor, html, pasteHtmlFn) : false;
+ };
+ var smartInsertContent = function (editor, html) {
+ global$6.each([
+ linkSelection,
+ insertImage,
+ pasteHtml
+ ], function (action) {
+ return action(editor, html, pasteHtml) !== true;
+ });
+ };
+ var insertContent = function (editor, html, pasteAsText) {
+ if (pasteAsText || isSmartPasteEnabled(editor) === false) {
+ pasteHtml(editor, html);
+ } else {
+ smartInsertContent(editor, html);
+ }
+ };
+
+ var repeat = function (s, count) {
+ return count <= 0 ? '' : new Array(count + 1).join(s);
+ };
+
+ var isCollapsibleWhitespace = function (c) {
+ return ' \f\t\x0B'.indexOf(c) !== -1;
+ };
+ var isNewLineChar = function (c) {
+ return c === '\n' || c === '\r';
+ };
+ var isNewline = function (text, idx) {
+ return idx < text.length && idx >= 0 ? isNewLineChar(text[idx]) : false;
+ };
+ var normalizeWhitespace = function (editor, text) {
+ var tabSpace = repeat(' ', getTabSpaces(editor));
+ var normalizedText = text.replace(/\t/g, tabSpace);
+ var result = foldl(normalizedText, function (acc, c) {
+ if (isCollapsibleWhitespace(c) || c === nbsp) {
+ if (acc.pcIsSpace || acc.str === '' || acc.str.length === normalizedText.length - 1 || isNewline(normalizedText, acc.str.length + 1)) {
+ return {
+ pcIsSpace: false,
+ str: acc.str + nbsp
+ };
+ } else {
+ return {
+ pcIsSpace: true,
+ str: acc.str + ' '
+ };
+ }
+ } else {
+ return {
+ pcIsSpace: isNewLineChar(c),
+ str: acc.str + c
+ };
+ }
+ }, {
+ pcIsSpace: false,
+ str: ''
+ });
+ return result.str;
+ };
+
+ var doPaste = function (editor, content, internal, pasteAsText) {
+ var args = process(editor, content, internal);
+ if (args.cancelled === false) {
+ insertContent(editor, args.content, pasteAsText);
+ }
+ };
+ var pasteHtml$1 = function (editor, html, internalFlag) {
+ var internal = internalFlag ? internalFlag : isMarked(html);
+ doPaste(editor, unmark(html), internal, false);
+ };
+ var pasteText = function (editor, text) {
+ var encodedText = editor.dom.encode(text).replace(/\r\n/g, '\n');
+ var normalizedText = normalizeWhitespace(editor, encodedText);
+ var html = convert(normalizedText, getForcedRootBlock(editor), getForcedRootBlockAttrs(editor));
+ doPaste(editor, html, false, true);
+ };
+ var getDataTransferItems = function (dataTransfer) {
+ var items = {};
+ var mceInternalUrlPrefix = 'data:text/mce-internal,';
+ if (dataTransfer) {
+ if (dataTransfer.getData) {
+ var legacyText = dataTransfer.getData('Text');
+ if (legacyText && legacyText.length > 0) {
+ if (legacyText.indexOf(mceInternalUrlPrefix) === -1) {
+ items['text/plain'] = legacyText;
+ }
+ }
+ }
+ if (dataTransfer.types) {
+ for (var i = 0; i < dataTransfer.types.length; i++) {
+ var contentType = dataTransfer.types[i];
+ try {
+ items[contentType] = dataTransfer.getData(contentType);
+ } catch (ex) {
+ items[contentType] = '';
+ }
+ }
+ }
+ }
+ return items;
+ };
+ var getClipboardContent = function (editor, clipboardEvent) {
+ return getDataTransferItems(clipboardEvent.clipboardData || editor.getDoc().dataTransfer);
+ };
+ var hasContentType = function (clipboardContent, mimeType) {
+ return mimeType in clipboardContent && clipboardContent[mimeType].length > 0;
+ };
+ var hasHtmlOrText = function (content) {
+ return hasContentType(content, 'text/html') || hasContentType(content, 'text/plain');
+ };
+ var parseDataUri = function (uri) {
+ var matches = /data:([^;]+);base64,([a-z0-9\+\/=]+)/i.exec(uri);
+ if (matches) {
+ return {
+ type: matches[1],
+ data: decodeURIComponent(matches[2])
+ };
+ } else {
+ return {
+ type: null,
+ data: null
+ };
+ }
+ };
+ var isValidDataUriImage = function (editor, imgElm) {
+ var filter = getImagesDataImgFilter(editor);
+ return filter ? filter(imgElm) : true;
+ };
+ var extractFilename = function (editor, str) {
+ var m = str.match(/([\s\S]+?)\.(?:jpeg|jpg|png|gif)$/i);
+ return m ? editor.dom.encode(m[1]) : null;
+ };
+ var uniqueId = createIdGenerator('mceclip');
+ var pasteImage = function (editor, imageItem) {
+ var _a = parseDataUri(imageItem.uri), base64 = _a.data, type = _a.type;
+ var id = uniqueId();
+ var name = getImagesReuseFilename(editor) && imageItem.blob.name ? extractFilename(editor, imageItem.blob.name) : id;
+ var img = new Image();
+ img.src = imageItem.uri;
+ if (isValidDataUriImage(editor, img)) {
+ var blobCache = editor.editorUpload.blobCache;
+ var blobInfo = void 0;
+ var existingBlobInfo = blobCache.getByData(base64, type);
+ if (!existingBlobInfo) {
+ blobInfo = blobCache.create(id, imageItem.blob, base64, name);
+ blobCache.add(blobInfo);
+ } else {
+ blobInfo = existingBlobInfo;
+ }
+ pasteHtml$1(editor, '
', false);
+ } else {
+ pasteHtml$1(editor, '
', false);
+ }
+ };
+ var isClipboardEvent = function (event) {
+ return event.type === 'paste';
+ };
+ var readBlobsAsDataUris = function (items) {
+ return global$3.all(map(items, function (item) {
+ return new global$3(function (resolve) {
+ var blob = item.getAsFile ? item.getAsFile() : item;
+ var reader = new window.FileReader();
+ reader.onload = function () {
+ resolve({
+ blob: blob,
+ uri: reader.result
+ });
+ };
+ reader.readAsDataURL(blob);
+ });
+ }));
+ };
+ var getImagesFromDataTransfer = function (dataTransfer) {
+ var items = dataTransfer.items ? map(from$1(dataTransfer.items), function (item) {
+ return item.getAsFile();
+ }) : [];
+ var files = dataTransfer.files ? from$1(dataTransfer.files) : [];
+ var images = filter(items.length > 0 ? items : files, function (file) {
+ return /^image\/(jpeg|png|gif|bmp)$/.test(file.type);
+ });
+ return images;
+ };
+ var pasteImageData = function (editor, e, rng) {
+ var dataTransfer = isClipboardEvent(e) ? e.clipboardData : e.dataTransfer;
+ if (getPasteDataImages(editor) && dataTransfer) {
+ var images = getImagesFromDataTransfer(dataTransfer);
+ if (images.length > 0) {
+ e.preventDefault();
+ readBlobsAsDataUris(images).then(function (blobResults) {
+ if (rng) {
+ editor.selection.setRng(rng);
+ }
+ each(blobResults, function (result) {
+ pasteImage(editor, result);
+ });
+ });
+ return true;
+ }
+ }
+ return false;
+ };
+ var isBrokenAndroidClipboardEvent = function (e) {
+ var clipboardData = e.clipboardData;
+ return navigator.userAgent.indexOf('Android') !== -1 && clipboardData && clipboardData.items && clipboardData.items.length === 0;
+ };
+ var isKeyboardPasteEvent = function (e) {
+ return global$4.metaKeyPressed(e) && e.keyCode === 86 || e.shiftKey && e.keyCode === 45;
+ };
+ var registerEventHandlers = function (editor, pasteBin, pasteFormat) {
+ var keyboardPasteEvent = value();
+ var keyboardPastePlainTextState;
+ editor.on('keydown', function (e) {
+ function removePasteBinOnKeyUp(e) {
+ if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
+ pasteBin.remove();
+ }
+ }
+ if (isKeyboardPasteEvent(e) && !e.isDefaultPrevented()) {
+ keyboardPastePlainTextState = e.shiftKey && e.keyCode === 86;
+ if (keyboardPastePlainTextState && global$1.webkit && navigator.userAgent.indexOf('Version/') !== -1) {
+ return;
+ }
+ e.stopImmediatePropagation();
+ keyboardPasteEvent.set(e);
+ window.setTimeout(function () {
+ keyboardPasteEvent.clear();
+ }, 100);
+ if (global$1.ie && keyboardPastePlainTextState) {
+ e.preventDefault();
+ firePaste(editor, true);
+ return;
+ }
+ pasteBin.remove();
+ pasteBin.create();
+ editor.once('keyup', removePasteBinOnKeyUp);
+ editor.once('paste', function () {
+ editor.off('keyup', removePasteBinOnKeyUp);
+ });
+ }
+ });
+ function insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal) {
+ var content;
+ if (hasContentType(clipboardContent, 'text/html')) {
+ content = clipboardContent['text/html'];
+ } else {
+ content = pasteBin.getHtml();
+ internal = internal ? internal : isMarked(content);
+ if (pasteBin.isDefaultContent(content)) {
+ plainTextMode = true;
+ }
+ }
+ content = trimHtml(content);
+ pasteBin.remove();
+ var isPlainTextHtml = internal === false && isPlainText(content);
+ var isImage = isImageUrl(content);
+ if (!content.length || isPlainTextHtml && !isImage) {
+ plainTextMode = true;
+ }
+ if (plainTextMode || isImage) {
+ if (hasContentType(clipboardContent, 'text/plain') && isPlainTextHtml) {
+ content = clipboardContent['text/plain'];
+ } else {
+ content = innerText(content);
+ }
+ }
+ if (pasteBin.isDefaultContent(content)) {
+ if (!isKeyBoardPaste) {
+ editor.windowManager.alert('Please use Ctrl+V/Cmd+V keyboard shortcuts to paste contents.');
+ }
+ return;
+ }
+ if (plainTextMode) {
+ pasteText(editor, content);
+ } else {
+ pasteHtml$1(editor, content, internal);
+ }
+ }
+ var getLastRng = function () {
+ return pasteBin.getLastRng() || editor.selection.getRng();
+ };
+ editor.on('paste', function (e) {
+ var isKeyBoardPaste = keyboardPasteEvent.isSet();
+ var clipboardContent = getClipboardContent(editor, e);
+ var plainTextMode = pasteFormat.get() === 'text' || keyboardPastePlainTextState;
+ var internal = hasContentType(clipboardContent, internalHtmlMime());
+ keyboardPastePlainTextState = false;
+ if (e.isDefaultPrevented() || isBrokenAndroidClipboardEvent(e)) {
+ pasteBin.remove();
+ return;
+ }
+ if (!hasHtmlOrText(clipboardContent) && pasteImageData(editor, e, getLastRng())) {
+ pasteBin.remove();
+ return;
+ }
+ if (!isKeyBoardPaste) {
+ e.preventDefault();
+ }
+ if (global$1.ie && (!isKeyBoardPaste || e.ieFake) && !hasContentType(clipboardContent, 'text/html')) {
+ pasteBin.create();
+ editor.dom.bind(pasteBin.getEl(), 'paste', function (e) {
+ e.stopPropagation();
+ });
+ editor.getDoc().execCommand('Paste', false, null);
+ clipboardContent['text/html'] = pasteBin.getHtml();
+ }
+ if (hasContentType(clipboardContent, 'text/html')) {
+ e.preventDefault();
+ if (!internal) {
+ internal = isMarked(clipboardContent['text/html']);
+ }
+ insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
+ } else {
+ global$2.setEditorTimeout(editor, function () {
+ insertClipboardContent(clipboardContent, isKeyBoardPaste, plainTextMode, internal);
+ }, 0);
+ }
+ });
+ };
+ var registerEventsAndFilters = function (editor, pasteBin, pasteFormat) {
+ registerEventHandlers(editor, pasteBin, pasteFormat);
+ var src;
+ editor.parser.addNodeFilter('img', function (nodes, name, args) {
+ var isPasteInsert = function (args) {
+ return args.data && args.data.paste === true;
+ };
+ var remove = function (node) {
+ if (!node.attr('data-mce-object') && src !== global$1.transparentSrc) {
+ node.remove();
+ }
+ };
+ var isWebKitFakeUrl = function (src) {
+ return src.indexOf('webkit-fake-url') === 0;
+ };
+ var isDataUri = function (src) {
+ return src.indexOf('data:') === 0;
+ };
+ if (!getPasteDataImages(editor) && isPasteInsert(args)) {
+ var i = nodes.length;
+ while (i--) {
+ src = nodes[i].attr('src');
+ if (!src) {
+ continue;
+ }
+ if (isWebKitFakeUrl(src)) {
+ remove(nodes[i]);
+ } else if (!getAllowHtmlDataUrls(editor) && isDataUri(src)) {
+ remove(nodes[i]);
+ }
+ }
+ }
+ });
+ };
+
+ var getPasteBinParent = function (editor) {
+ return global$1.ie && editor.inline ? document.body : editor.getBody();
+ };
+ var isExternalPasteBin = function (editor) {
+ return getPasteBinParent(editor) !== editor.getBody();
+ };
+ var delegatePasteEvents = function (editor, pasteBinElm, pasteBinDefaultContent) {
+ if (isExternalPasteBin(editor)) {
+ editor.dom.bind(pasteBinElm, 'paste keyup', function (_e) {
+ if (!isDefault(editor, pasteBinDefaultContent)) {
+ editor.fire('paste');
+ }
+ });
+ }
+ };
+ var create = function (editor, lastRngCell, pasteBinDefaultContent) {
+ var dom = editor.dom, body = editor.getBody();
+ lastRngCell.set(editor.selection.getRng());
+ var pasteBinElm = editor.dom.add(getPasteBinParent(editor), 'div', {
+ 'id': 'mcepastebin',
+ 'class': 'mce-pastebin',
+ 'contentEditable': true,
+ 'data-mce-bogus': 'all',
+ 'style': 'position: fixed; top: 50%; width: 10px; height: 10px; overflow: hidden; opacity: 0'
+ }, pasteBinDefaultContent);
+ if (global$1.ie || global$1.gecko) {
+ dom.setStyle(pasteBinElm, 'left', dom.getStyle(body, 'direction', true) === 'rtl' ? 65535 : -65535);
+ }
+ dom.bind(pasteBinElm, 'beforedeactivate focusin focusout', function (e) {
+ e.stopPropagation();
+ });
+ delegatePasteEvents(editor, pasteBinElm, pasteBinDefaultContent);
+ pasteBinElm.focus();
+ editor.selection.select(pasteBinElm, true);
+ };
+ var remove = function (editor, lastRngCell) {
+ if (getEl(editor)) {
+ var pasteBinClone = void 0;
+ var lastRng = lastRngCell.get();
+ while (pasteBinClone = editor.dom.get('mcepastebin')) {
+ editor.dom.remove(pasteBinClone);
+ editor.dom.unbind(pasteBinClone);
+ }
+ if (lastRng) {
+ editor.selection.setRng(lastRng);
+ }
+ }
+ lastRngCell.set(null);
+ };
+ var getEl = function (editor) {
+ return editor.dom.get('mcepastebin');
+ };
+ var getHtml = function (editor) {
+ var copyAndRemove = function (toElm, fromElm) {
+ toElm.appendChild(fromElm);
+ editor.dom.remove(fromElm, true);
+ };
+ var pasteBinClones = global$6.grep(getPasteBinParent(editor).childNodes, function (elm) {
+ return elm.id === 'mcepastebin';
+ });
+ var pasteBinElm = pasteBinClones.shift();
+ global$6.each(pasteBinClones, function (pasteBinClone) {
+ copyAndRemove(pasteBinElm, pasteBinClone);
+ });
+ var dirtyWrappers = editor.dom.select('div[id=mcepastebin]', pasteBinElm);
+ for (var i = dirtyWrappers.length - 1; i >= 0; i--) {
+ var cleanWrapper = editor.dom.create('div');
+ pasteBinElm.insertBefore(cleanWrapper, dirtyWrappers[i]);
+ copyAndRemove(cleanWrapper, dirtyWrappers[i]);
+ }
+ return pasteBinElm ? pasteBinElm.innerHTML : '';
+ };
+ var getLastRng = function (lastRng) {
+ return lastRng.get();
+ };
+ var isDefaultContent = function (pasteBinDefaultContent, content) {
+ return content === pasteBinDefaultContent;
+ };
+ var isPasteBin = function (elm) {
+ return elm && elm.id === 'mcepastebin';
+ };
+ var isDefault = function (editor, pasteBinDefaultContent) {
+ var pasteBinElm = getEl(editor);
+ return isPasteBin(pasteBinElm) && isDefaultContent(pasteBinDefaultContent, pasteBinElm.innerHTML);
+ };
+ var PasteBin = function (editor) {
+ var lastRng = Cell(null);
+ var pasteBinDefaultContent = '%MCEPASTEBIN%';
+ return {
+ create: function () {
+ return create(editor, lastRng, pasteBinDefaultContent);
+ },
+ remove: function () {
+ return remove(editor, lastRng);
+ },
+ getEl: function () {
+ return getEl(editor);
+ },
+ getHtml: function () {
+ return getHtml(editor);
+ },
+ getLastRng: function () {
+ return getLastRng(lastRng);
+ },
+ isDefault: function () {
+ return isDefault(editor, pasteBinDefaultContent);
+ },
+ isDefaultContent: function (content) {
+ return isDefaultContent(pasteBinDefaultContent, content);
+ }
+ };
+ };
+
+ var Clipboard = function (editor, pasteFormat) {
+ var pasteBin = PasteBin(editor);
+ editor.on('PreInit', function () {
+ return registerEventsAndFilters(editor, pasteBin, pasteFormat);
+ });
+ return {
+ pasteFormat: pasteFormat,
+ pasteHtml: function (html, internalFlag) {
+ return pasteHtml$1(editor, html, internalFlag);
+ },
+ pasteText: function (text) {
+ return pasteText(editor, text);
+ },
+ pasteImageData: function (e, rng) {
+ return pasteImageData(editor, e, rng);
+ },
+ getDataTransferItems: getDataTransferItems,
+ hasHtmlOrText: hasHtmlOrText,
+ hasContentType: hasContentType
+ };
+ };
+
+ var togglePlainTextPaste = function (editor, clipboard) {
+ if (clipboard.pasteFormat.get() === 'text') {
+ clipboard.pasteFormat.set('html');
+ firePastePlainTextToggle(editor, false);
+ } else {
+ clipboard.pasteFormat.set('text');
+ firePastePlainTextToggle(editor, true);
+ }
+ editor.focus();
+ };
+
+ var register = function (editor, clipboard) {
+ editor.addCommand('mceTogglePlainTextPaste', function () {
+ togglePlainTextPaste(editor, clipboard);
+ });
+ editor.addCommand('mceInsertClipboardContent', function (ui, value) {
+ if (value.content) {
+ clipboard.pasteHtml(value.content, value.internal);
+ }
+ if (value.text) {
+ clipboard.pasteText(value.text);
+ }
+ });
+ };
+
+ var hasWorkingClipboardApi = function (clipboardData) {
+ return global$1.iOS === false && typeof (clipboardData === null || clipboardData === void 0 ? void 0 : clipboardData.setData) === 'function';
+ };
+ var setHtml5Clipboard = function (clipboardData, html, text) {
+ if (hasWorkingClipboardApi(clipboardData)) {
+ try {
+ clipboardData.clearData();
+ clipboardData.setData('text/html', html);
+ clipboardData.setData('text/plain', text);
+ clipboardData.setData(internalHtmlMime(), html);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ } else {
+ return false;
+ }
+ };
+ var setClipboardData = function (evt, data, fallback, done) {
+ if (setHtml5Clipboard(evt.clipboardData, data.html, data.text)) {
+ evt.preventDefault();
+ done();
+ } else {
+ fallback(data.html, done);
+ }
+ };
+ var fallback = function (editor) {
+ return function (html, done) {
+ var markedHtml = mark(html);
+ var outer = editor.dom.create('div', {
+ 'contenteditable': 'false',
+ 'data-mce-bogus': 'all'
+ });
+ var inner = editor.dom.create('div', { contenteditable: 'true' }, markedHtml);
+ editor.dom.setStyles(outer, {
+ position: 'fixed',
+ top: '0',
+ left: '-3000px',
+ width: '1000px',
+ overflow: 'hidden'
+ });
+ outer.appendChild(inner);
+ editor.dom.add(editor.getBody(), outer);
+ var range = editor.selection.getRng();
+ inner.focus();
+ var offscreenRange = editor.dom.createRng();
+ offscreenRange.selectNodeContents(inner);
+ editor.selection.setRng(offscreenRange);
+ global$2.setTimeout(function () {
+ editor.selection.setRng(range);
+ outer.parentNode.removeChild(outer);
+ done();
+ }, 0);
+ };
+ };
+ var getData = function (editor) {
+ return {
+ html: editor.selection.getContent({ contextual: true }),
+ text: editor.selection.getContent({ format: 'text' })
+ };
+ };
+ var isTableSelection = function (editor) {
+ return !!editor.dom.getParent(editor.selection.getStart(), 'td[data-mce-selected],th[data-mce-selected]', editor.getBody());
+ };
+ var hasSelectedContent = function (editor) {
+ return !editor.selection.isCollapsed() || isTableSelection(editor);
+ };
+ var cut = function (editor) {
+ return function (evt) {
+ if (hasSelectedContent(editor)) {
+ setClipboardData(evt, getData(editor), fallback(editor), function () {
+ if (global$1.browser.isChrome()) {
+ var rng_1 = editor.selection.getRng();
+ global$2.setEditorTimeout(editor, function () {
+ editor.selection.setRng(rng_1);
+ editor.execCommand('Delete');
+ }, 0);
+ } else {
+ editor.execCommand('Delete');
+ }
+ });
+ }
+ };
+ };
+ var copy = function (editor) {
+ return function (evt) {
+ if (hasSelectedContent(editor)) {
+ setClipboardData(evt, getData(editor), fallback(editor), function () {
+ });
+ }
+ };
+ };
+ var register$1 = function (editor) {
+ editor.on('cut', cut(editor));
+ editor.on('copy', copy(editor));
+ };
+
+ var global$b = tinymce.util.Tools.resolve('tinymce.dom.RangeUtils');
+
+ var getCaretRangeFromEvent = function (editor, e) {
+ return global$b.getCaretRangeFromPoint(e.clientX, e.clientY, editor.getDoc());
+ };
+ var isPlainTextFileUrl = function (content) {
+ var plainTextContent = content['text/plain'];
+ return plainTextContent ? plainTextContent.indexOf('file://') === 0 : false;
+ };
+ var setFocusedRange = function (editor, rng) {
+ editor.focus();
+ editor.selection.setRng(rng);
+ };
+ var setup = function (editor, clipboard, draggingInternallyState) {
+ if (shouldBlockDrop(editor)) {
+ editor.on('dragend dragover draggesture dragdrop drop drag', function (e) {
+ e.preventDefault();
+ e.stopPropagation();
+ });
+ }
+ if (!shouldPasteDataImages(editor)) {
+ editor.on('drop', function (e) {
+ var dataTransfer = e.dataTransfer;
+ if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) {
+ e.preventDefault();
+ }
+ });
+ }
+ editor.on('drop', function (e) {
+ var rng = getCaretRangeFromEvent(editor, e);
+ if (e.isDefaultPrevented() || draggingInternallyState.get()) {
+ return;
+ }
+ var dropContent = clipboard.getDataTransferItems(e.dataTransfer);
+ var internal = clipboard.hasContentType(dropContent, internalHtmlMime());
+ if ((!clipboard.hasHtmlOrText(dropContent) || isPlainTextFileUrl(dropContent)) && clipboard.pasteImageData(e, rng)) {
+ return;
+ }
+ if (rng && shouldFilterDrop(editor)) {
+ var content_1 = dropContent['mce-internal'] || dropContent['text/html'] || dropContent['text/plain'];
+ if (content_1) {
+ e.preventDefault();
+ global$2.setEditorTimeout(editor, function () {
+ editor.undoManager.transact(function () {
+ if (dropContent['mce-internal']) {
+ editor.execCommand('Delete');
+ }
+ setFocusedRange(editor, rng);
+ content_1 = trimHtml(content_1);
+ if (!dropContent['text/html']) {
+ clipboard.pasteText(content_1);
+ } else {
+ clipboard.pasteHtml(content_1, internal);
+ }
+ });
+ });
+ }
+ }
+ });
+ editor.on('dragstart', function (_e) {
+ draggingInternallyState.set(true);
+ });
+ editor.on('dragover dragend', function (e) {
+ if (shouldPasteDataImages(editor) && draggingInternallyState.get() === false) {
+ e.preventDefault();
+ setFocusedRange(editor, getCaretRangeFromEvent(editor, e));
+ }
+ if (e.type === 'dragend') {
+ draggingInternallyState.set(false);
+ }
+ });
+ };
+
+ var setup$1 = function (editor) {
+ var plugin = editor.plugins.paste;
+ var preProcess = getPreProcess(editor);
+ if (preProcess) {
+ editor.on('PastePreProcess', function (e) {
+ preProcess.call(plugin, plugin, e);
+ });
+ }
+ var postProcess = getPostProcess(editor);
+ if (postProcess) {
+ editor.on('PastePostProcess', function (e) {
+ postProcess.call(plugin, plugin, e);
+ });
+ }
+ };
+
+ function addPreProcessFilter(editor, filterFunc) {
+ editor.on('PastePreProcess', function (e) {
+ e.content = filterFunc(editor, e.content, e.internal, e.wordContent);
+ });
+ }
+ function addPostProcessFilter(editor, filterFunc) {
+ editor.on('PastePostProcess', function (e) {
+ filterFunc(editor, e.node);
+ });
+ }
+ function removeExplorerBrElementsAfterBlocks(editor, html) {
+ if (!isWordContent(html)) {
+ return html;
+ }
+ var blockElements = [];
+ global$6.each(editor.schema.getBlockElements(), function (block, blockName) {
+ blockElements.push(blockName);
+ });
+ var explorerBlocksRegExp = new RegExp('(?:
[\\s\\r\\n]+|
)*(<\\/?(' + blockElements.join('|') + ')[^>]*>)(?:
[\\s\\r\\n]+|
)*', 'g');
+ html = filter$1(html, [[
+ explorerBlocksRegExp,
+ '$1'
+ ]]);
+ html = filter$1(html, [
+ [
+ /
/g,
+ '
'
+ ],
+ [
+ /
/g,
+ ' '
+ ],
+ [
+ /
/g,
+ '
'
+ ]
+ ]);
+ return html;
+ }
+ function removeWebKitStyles(editor, content, internal, isWordHtml) {
+ if (isWordHtml || internal) {
+ return content;
+ }
+ var webKitStylesSetting = getWebkitStyles(editor);
+ var webKitStyles;
+ if (shouldRemoveWebKitStyles(editor) === false || webKitStylesSetting === 'all') {
+ return content;
+ }
+ if (webKitStylesSetting) {
+ webKitStyles = webKitStylesSetting.split(/[, ]/);
+ }
+ if (webKitStyles) {
+ var dom_1 = editor.dom, node_1 = editor.selection.getNode();
+ content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, function (all, before, value, after) {
+ var inputStyles = dom_1.parseStyle(dom_1.decode(value));
+ var outputStyles = {};
+ if (webKitStyles === 'none') {
+ return before + after;
+ }
+ for (var i = 0; i < webKitStyles.length; i++) {
+ var inputValue = inputStyles[webKitStyles[i]], currentValue = dom_1.getStyle(node_1, webKitStyles[i], true);
+ if (/color/.test(webKitStyles[i])) {
+ inputValue = dom_1.toHex(inputValue);
+ currentValue = dom_1.toHex(currentValue);
+ }
+ if (currentValue !== inputValue) {
+ outputStyles[webKitStyles[i]] = inputValue;
+ }
+ }
+ outputStyles = dom_1.serializeStyle(outputStyles, 'span');
+ if (outputStyles) {
+ return before + ' style="' + outputStyles + '"' + after;
+ }
+ return before + after;
+ });
+ } else {
+ content = content.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi, '$1$3');
+ }
+ content = content.replace(/(<[^>]+) data-mce-style="([^"]+)"([^>]*>)/gi, function (all, before, value, after) {
+ return before + ' style="' + value + '"' + after;
+ });
+ return content;
+ }
+ function removeUnderlineAndFontInAnchor(editor, root) {
+ editor.$('a', root).find('font,u').each(function (i, node) {
+ editor.dom.remove(node, true);
+ });
+ }
+ var setup$2 = function (editor) {
+ if (global$1.webkit) {
+ addPreProcessFilter(editor, removeWebKitStyles);
+ }
+ if (global$1.ie) {
+ addPreProcessFilter(editor, removeExplorerBrElementsAfterBlocks);
+ addPostProcessFilter(editor, removeUnderlineAndFontInAnchor);
+ }
+ };
+
+ var makeSetupHandler = function (editor, clipboard) {
+ return function (api) {
+ api.setActive(clipboard.pasteFormat.get() === 'text');
+ var pastePlainTextToggleHandler = function (e) {
+ return api.setActive(e.state);
+ };
+ editor.on('PastePlainTextToggle', pastePlainTextToggleHandler);
+ return function () {
+ return editor.off('PastePlainTextToggle', pastePlainTextToggleHandler);
+ };
+ };
+ };
+ var register$2 = function (editor, clipboard) {
+ editor.ui.registry.addToggleButton('pastetext', {
+ active: false,
+ icon: 'paste-text',
+ tooltip: 'Paste as text',
+ onAction: function () {
+ return editor.execCommand('mceTogglePlainTextPaste');
+ },
+ onSetup: makeSetupHandler(editor, clipboard)
+ });
+ editor.ui.registry.addToggleMenuItem('pastetext', {
+ text: 'Paste as text',
+ icon: 'paste-text',
+ onAction: function () {
+ return editor.execCommand('mceTogglePlainTextPaste');
+ },
+ onSetup: makeSetupHandler(editor, clipboard)
+ });
+ };
+
+ function Plugin () {
+ global.add('paste', function (editor) {
+ if (hasProPlugin(editor) === false) {
+ var draggingInternallyState = Cell(false);
+ var pasteFormat = Cell(isPasteAsTextEnabled(editor) ? 'text' : 'html');
+ var clipboard = Clipboard(editor, pasteFormat);
+ var quirks = setup$2(editor);
+ register$2(editor, clipboard);
+ register(editor, clipboard);
+ setup$1(editor);
+ register$1(editor);
+ setup(editor, clipboard, draggingInternallyState);
+ return get(clipboard, quirks);
+ }
+ });
+ }
+
+ Plugin();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js
old mode 100755
new mode 100644
index 3cce5f864f..15160d421b
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/paste/plugin.min.js
@@ -1 +1,9 @@
-!function(e,t){"use strict";function n(e,t){for(var n,i=[],r=0;r
"]]):(e=n.filter(e,[[/\n\n/g,"
)$/,o+"$1"],[/\n/g,"
"]]),-1!=e.indexOf("
")&&(e=o+e)),r(e)}function o(){var t=i.dom,n=i.getBody(),r=i.dom.getViewPort(i.getWin()),a=r.y,o=20,s;if(h=i.selection.getRng(),i.inline&&(s=i.selection.getScrollContainer(),s&&(a=s.scrollTop)),h.getClientRects){var c=h.getClientRects();if(c.length)o=a+(c[0].top-t.getPos(n).y);else{o=a;var l=h.startContainer;l&&(3==l.nodeType&&l.parentNode!=n&&(l=l.parentNode),1==l.nodeType&&(o=t.getPos(l,s||n).y))}}v=t.add(i.getBody(),"div",{id:"mcepastebin",contentEditable:!0,"data-mce-bogus":"1",style:"position: absolute; top: "+o+"px;width: 10px; height: 10px; overflow: hidden; opacity: 0"},b),(e.ie||e.gecko)&&t.setStyle(v,"left","rtl"==t.getStyle(n,"direction",!0)?65535:-65535),t.bind(v,"beforedeactivate focusin focusout",function(e){e.stopPropagation()}),v.focus(),i.selection.select(v,!0)}function s(){if(v){for(var e;e=i.dom.get("mcepastebin");)i.dom.remove(e),i.dom.unbind(e);h&&i.selection.setRng(h)}x=!1,v=h=null}function c(){var e=b,t,n;for(t=i.dom.select("div[id=mcepastebin]"),n=t.length;n--;){var r=t[n].innerHTML;e==b&&(e=""),r.length>e.length&&(e=r)}return e}function l(e){var t={};if(e&&e.types){var n=e.getData("Text");n&&n.length>0&&(t["text/plain"]=n);for(var i=0;i texttexttexttexttext ' + htmlEscape(template.value.description) + '
$/i])}function s(e){if(!n.isWordContent(e))return e;var a=[];t.each(r.schema.getBlockElements(),function(e,t){a.push(t)});var o=new RegExp("(?:
[\\s\\r\\n]+|
)*(<\\/?("+a.join("|")+")[^>]*>)(?:
[\\s\\r\\n]+|
)*","g");return e=i.filter(e,[[o,"$1"]]),e=i.filter(e,[[/
/g,"
"],[/
/g," "],[/
/g,"
"]])}function c(e){return(r.settings.paste_remove_styles||r.settings.paste_remove_styles_if_webkit!==!1)&&(e=e.replace(/ style=\"[^\"]+\"/g,"")),e}e.webkit&&(a(c),a(o)),e.ie&&a(s)}}),i(b,[x,d,g,y],function(e,t,n,i){var r;e.add("paste",function(e){function a(){"text"==s.pasteFormat?(this.active(!1),s.pasteFormat="html"):(s.pasteFormat="text",this.active(!0),r||(e.windowManager.alert("Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off."),r=!0))}var o=this,s,c=e.settings;o.clipboard=s=new t(e),o.quirks=new i(e),o.wordFilter=new n(e),e.settings.paste_as_text&&(o.clipboard.pasteFormat="text"),c.paste_preprocess&&e.on("PastePreProcess",function(e){c.paste_preprocess.call(o,o,e)}),c.paste_postprocess&&e.on("PastePostProcess",function(e){c.paste_postprocess.call(o,o,e)}),e.addCommand("mceInsertClipboardContent",function(e,t){t.content&&o.clipboard.pasteHtml(t.content),t.text&&o.clipboard.pasteText(t.text)}),e.paste_block_drop&&e.on("dragend dragover draggesture dragdrop drop drag",function(e){e.preventDefault(),e.stopPropagation()}),e.settings.paste_data_images||e.on("drop",function(e){var t=e.dataTransfer;t&&t.files&&t.files.length>0&&e.preventDefault()}),e.addButton("pastetext",{icon:"pastetext",tooltip:"Paste as text",onclick:a,active:"text"==o.clipboard.pasteFormat}),e.addMenuItem("pastetext",{text:"Paste as text",selectable:!0,active:s.pasteFormat,onclick:a})})}),o([c,d,g,y,b])}(this);
\ No newline at end of file
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,t,n,r,m=function(e){var t=e;return{get:function(){return t},set:function(e){t=e}}},o=tinymce.util.Tools.resolve("tinymce.PluginManager"),a=function(e){return function(){return e}},i=a(!1),s=a(!0),u=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,t){return e()},is:i,isSome:i,isNone:s,getOr:n=function(e){return e},getOrThunk:t=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:a(null),getOrUndefined:a(undefined),or:n,orThunk:t,map:u,each:function(){},bind:u,exists:i,forall:s,filter:u,equals:e,equals_:e,toArray:function(){return[]},toString:a("none()")}),c=function(n){var e=a(n),t=function(){return o},r=function(e){return e(n)},o={fold:function(e,t){return t(n)},is:function(e){return n===e},isSome:s,isNone:i,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:t,orThunk:t,map:function(e){return c(e(n))},each:function(e){e(n)},bind:r,exists:r,forall:r,filter:function(e){return e(n)?o:l},toArray:function(){return[n]},toString:function(){return"some("+n+")"},equals:function(e){return e.is(n)},equals_:function(e,t){return e.fold(i,function(e){return t(n,e)})}};return o},p={some:c,none:u,from:function(e){return null===e||e===undefined?l:c(e)}},f=(r="function",function(e){return typeof e===r}),d=Array.prototype.slice,g=function(e,t){for(var n=e.length,r=new Array(n),o=0;o
")});return 1===i.length?i[0]:A.map(i,function(e){return o+e+a}).join("")},F=tinymce.util.Tools.resolve("tinymce.html.DomParser"),E=tinymce.util.Tools.resolve("tinymce.html.Serializer"),M="\xa0",N=tinymce.util.Tools.resolve("tinymce.html.Node"),B=tinymce.util.Tools.resolve("tinymce.html.Schema");function j(t,e){return A.each(e,function(e){t=e.constructor===RegExp?t.replace(e,""):t.replace(e[0],e[1])}),t}function H(e){var t=B(),n=F({},t),r="",o=t.getShortEndedElements(),a=A.makeMap("script noscript style textarea video audio iframe object"," "),i=t.getBlockElements();return e=j(e,[//g]),function s(e){var t=e.name,n=e;if("br"!==t){if("wbr"!==t)if(o[t]&&(r+=" "),a[t])r+=" ";else{if(3===e.type&&(r+=e.value),!e.shortEnded&&(e=e.firstChild))for(;s(e),e=e.next;);i[t]&&n.next&&(r+="\n","p"===t&&(r+="\n"))}}else r+="\n"}(n.parse(e)),r}function $(e){return e=j(e,[/^[\s\S]*]*>\s*|\s*<\/body[^>]*>[\s\S]*$/gi,/|/g,[/( ?)\u00a0<\/span>( ?)/g,function(e,t,n){return t||n?M:" "}],/
/g,/
$/i])}function L(e){return//gi,/]+id="?docs-internal-[^>]*>/gi,//gi,/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi,[/<(\/?)s>/gi,"<$1strike>"],[/ /gi,M],[/([\s\u00a0]*)<\/span>/gi,function(e,t){return 0',!1)},fe=function(t,e,n){var r,o,a,i,s="paste"===e.type?e.clipboardData:e.dataTransfer;if(D(t)&&s){var u=(a=(o=s).items?g(h(o.items),function(e){return e.getAsFile()}):[],i=o.files?h(o.files):[],function(e,t){for(var n=[],r=0,o=e.length;r
)*(<\\/?("+n.join("|")+")[^>]*>)(?:
[\\s\\r\\n]+|
)*","g"),"$1"]]),t=j(t,[[/
/g,"
"],[/
/g," "],[/
/g,"
"]])}function Ee(e,t,n,r){if(r||n)return t;var l,c,f,o=e.getParam("paste_webkit_styles");return!1===e.getParam("paste_remove_styles_if_webkit",!0)||"all"===o?t:(o&&(l=o.split(/[, ]/)),t=(t=l?(c=e.dom,f=e.selection.getNode(),t.replace(/(<[^>]+) style="([^"]*)"([^>]*>)/gi,function(e,t,n,r){var o=c.parseStyle(c.decode(n)),a={};if("none"===l)return t+r;for(var i=0;i
' : '\u00a0';
- tableElm.insertBefore(captionElm, tableElm.firstChild);
- }
-
- unApplyAlign(tableElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, tableElm);
- }
-
- editor.focus();
- editor.addVisual();
- });
- }
- });
- }
-
- function mergeDialog(grid, cell) {
- editor.windowManager.open({
- title: "Merge cells",
- body: [
- {label: 'Cols', name: 'cols', type: 'textbox', size: 10},
- {label: 'Rows', name: 'rows', type: 'textbox', size: 10}
- ],
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- grid.merge(cell, data.cols, data.rows);
- });
- }
- });
- }
-
- function cellDialog() {
- var dom = editor.dom, cellElm, data, cells = [];
-
- // Get selected cells or the current cell
- cells = editor.dom.select('td.mce-item-selected,th.mce-item-selected');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
- if (!cells.length && cellElm) {
- cells.push(cellElm);
- }
-
- cellElm = cellElm || cells[0];
-
- if (!cellElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- width: removePxSuffix(dom.getStyle(cellElm, 'width') || dom.getAttrib(cellElm, 'width')),
- height: removePxSuffix(dom.getStyle(cellElm, 'height') || dom.getAttrib(cellElm, 'height')),
- scope: dom.getAttrib(cellElm, 'scope')
- };
-
- data.type = cellElm.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(cellElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Cell properties",
- items: {
- type: 'form',
- data: data,
- layout: 'grid',
- columns: 2,
- defaults: {
- type: 'textbox',
- maxWidth: 50
- },
- items: [
- {label: 'Width', name: 'width'},
- {label: 'Height', name: 'height'},
- {
- label: 'Cell type',
- name: 'type',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'Cell', value: 'td'},
- {text: 'Header cell', value: 'th'}
- ]
- },
- {
- label: 'Scope',
- name: 'scope',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Row', value: 'row'},
- {text: 'Column', value: 'col'},
- {text: 'Row group', value: 'rowgroup'},
- {text: 'Column group', value: 'colgroup'}
- ]
- },
- {
- label: 'Alignment',
- name: 'align',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- }
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- each(cells, function(cellElm) {
- editor.dom.setAttrib(cellElm, 'scope', data.scope);
-
- editor.dom.setStyles(cellElm, {
- width: addSizeSuffix(data.width),
- height: addSizeSuffix(data.height)
- });
-
- // Switch cell type
- if (data.type && cellElm.nodeName.toLowerCase() != data.type) {
- cellElm = dom.rename(cellElm, data.type);
- }
-
- // Apply/remove alignment
- unApplyAlign(cellElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, cellElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function rowDialog() {
- var dom = editor.dom, tableElm, cellElm, rowElm, data, rows = [];
-
- tableElm = editor.dom.getParent(editor.selection.getStart(), 'table');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
-
- each(tableElm.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || cell == cellElm) {
- rows.push(row);
- return false;
- }
- });
- });
-
- rowElm = rows[0];
- if (!rowElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- height: removePxSuffix(dom.getStyle(rowElm, 'height') || dom.getAttrib(rowElm, 'height')),
- scope: dom.getAttrib(rowElm, 'scope')
- };
-
- data.type = rowElm.parentNode.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(rowElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Row properties",
- items: {
- type: 'form',
- data: data,
- columns: 2,
- defaults: {
- type: 'textbox'
- },
- items: [
- {
- type: 'listbox',
- name: 'type',
- label: 'Row type',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'Header', value: 'thead'},
- {text: 'Body', value: 'tbody'},
- {text: 'Footer', value: 'tfoot'}
- ]
- },
- {
- type: 'listbox',
- name: 'align',
- label: 'Alignment',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- },
- {label: 'Height', name: 'height'}
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON(), tableElm, oldParentElm, parentElm;
-
- editor.undoManager.transact(function() {
- var toType = data.type;
-
- each(rows, function(rowElm) {
- editor.dom.setAttrib(rowElm, 'scope', data.scope);
-
- editor.dom.setStyles(rowElm, {
- height: addSizeSuffix(data.height)
- });
-
- if (toType != rowElm.parentNode.nodeName.toLowerCase()) {
- tableElm = dom.getParent(rowElm, 'table');
-
- oldParentElm = rowElm.parentNode;
- parentElm = dom.select(toType, tableElm)[0];
- if (!parentElm) {
- parentElm = dom.create(toType);
- if (tableElm.firstChild) {
- tableElm.insertBefore(parentElm, tableElm.firstChild);
- } else {
- tableElm.appendChild(parentElm);
- }
- }
-
- parentElm.appendChild(rowElm);
-
- if (!oldParentElm.hasChildNodes()) {
- dom.remove(oldParentElm);
- }
- }
-
- // Apply/remove alignment
- unApplyAlign(rowElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, rowElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function cmd(command) {
- return function() {
- editor.execCommand(command);
- };
- }
-
- function insertTable(cols, rows) {
- var y, x, html;
-
- html = '';
-
- for (y = 0; y < rows; y++) {
- html += '
';
-
- editor.insertContent(html);
- }
-
- function handleDisabledState(ctrl, selector) {
- function bindStateListener() {
- ctrl.disabled(!editor.dom.getParent(editor.selection.getStart(), selector));
-
- editor.selection.selectorChanged(selector, function(state) {
- ctrl.disabled(!state);
- });
- }
-
- if (editor.initialized) {
- bindStateListener();
- } else {
- editor.on('init', bindStateListener);
- }
- }
-
- function postRender() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'table');
- }
-
- function postRenderCell() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'td,th');
- }
-
- function generateTableGrid() {
- var html = '';
-
- html = '';
-
- for (x = 0; x < cols; x++) {
- html += ' ';
- }
-
- html += '' + (Env.ie ? " " : ' ';
- }
-
- html += '
') + '';
-
- for (var y = 0; y < 10; y++) {
- html += '
';
-
- html += '';
-
- for (var x = 0; x < 10; x++) {
- html += ' ';
- }
-
- html += '';
- }
-
- html += '
'
- );
- } else {
- editor.dom.add(editor.getBody(), 'br', {'data-mce-bogus': '1'});
- }
- }
- });
-
- editor.on('PreProcess', function(o) {
- var last = o.node.lastChild;
-
- if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 &&
- (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) &&
- last.previousSibling && last.previousSibling.nodeName == "TABLE") {
- editor.dom.remove(last);
- }
- });
- }
-
- // this nasty hack is here to work around some WebKit selection bugs.
- function fixTableCellSelection() {
- function tableCellSelected(ed, rng, n, currentCell) {
- // The decision of when a table cell is selected is somewhat involved. The fact that this code is
- // required is actually a pointer to the root cause of this bug. A cell is selected when the start
- // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases)
- // or the parent of the table (in the case of the selection containing the last cell of a table).
- var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE');
- var tableParent, allOfCellSelected, tableCellSelection;
-
- if (table) {
- tableParent = table.parentNode;
- }
-
- allOfCellSelected = rng.startContainer.nodeType == TEXT_NODE &&
- rng.startOffset === 0 &&
- rng.endOffset === 0 &&
- currentCell &&
- (n.nodeName == "TR" || n == tableParent);
-
- tableCellSelection = (n.nodeName == "TD" || n.nodeName == "TH") && !currentCell;
-
- return allOfCellSelected || tableCellSelection;
- }
-
- function fixSelection() {
- var rng = editor.selection.getRng();
- var n = editor.selection.getNode();
- var currentCell = editor.dom.getParent(rng.startContainer, 'TD,TH');
-
- if (!tableCellSelected(editor, rng, n, currentCell)) {
- return;
- }
-
- if (!currentCell) {
- currentCell = n;
- }
-
- // Get the very last node inside the table cell
- var end = currentCell.lastChild;
- while (end.lastChild) {
- end = end.lastChild;
- }
-
- // Select the entire table cell. Nothing outside of the table cell should be selected.
- rng.setEnd(end, end.nodeValue.length);
- editor.selection.setRng(rng);
- }
-
- editor.on('KeyDown', function() {
- fixSelection();
- });
-
- editor.on('MouseDown', function(e) {
- if (e.button != 2) {
- fixSelection();
- }
- });
- }
-
- /**
- * Delete table if all cells are selected.
- */
- function deleteTable() {
- editor.on('keydown', function(e) {
- if ((e.keyCode == VK.DELETE || e.keyCode == VK.BACKSPACE) && !e.isDefaultPrevented()) {
- var table = editor.dom.getParent(editor.selection.getStart(), 'table');
-
- if (table) {
- var cells = editor.dom.select('td,th', table), i = cells.length;
- while (i--) {
- if (!editor.dom.hasClass(cells[i], 'mce-item-selected')) {
- return;
- }
- }
-
- e.preventDefault();
- editor.execCommand('mceTableDelete');
- }
- }
- });
- }
-
- deleteTable();
-
- if (Env.webkit) {
- moveWebKitSelection();
- fixTableCellSelection();
- }
-
- if (Env.gecko) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
-
- if (Env.ie > 10) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/classes/TableGrid.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/classes/TableGrid.js
deleted file mode 100755
index eea3cd23d9..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/classes/TableGrid.js
+++ /dev/null
@@ -1,833 +0,0 @@
-/**
- * TableGrid.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class creates a grid out of a table element. This
- * makes it a whole lot easier to handle complex tables with
- * col/row spans.
- *
- * @class tinymce.tableplugin.TableGrid
- * @private
- */
-define("tinymce/tableplugin/TableGrid", [
- "tinymce/util/Tools",
- "tinymce/Env"
-], function(Tools, Env) {
- var each = Tools.each;
-
- function getSpanVal(td, name) {
- return parseInt(td.getAttribute(name) || 1, 10);
- }
-
- return function(editor, table) {
- var grid, startPos, endPos, selectedCell, selection = editor.selection, dom = selection.dom;
-
- function buildGrid() {
- var startY = 0;
-
- grid = [];
-
- each(['thead', 'tbody', 'tfoot'], function(part) {
- var rows = dom.select('> ' + part + ' tr', table);
-
- each(rows, function(tr, y) {
- y += startY;
-
- each(dom.select('> td, > th', tr), function(td, x) {
- var x2, y2, rowspan, colspan;
-
- // Skip over existing cells produced by rowspan
- if (grid[y]) {
- while (grid[y][x]) {
- x++;
- }
- }
-
- // Get col/rowspan from cell
- rowspan = getSpanVal(td, 'rowspan');
- colspan = getSpanVal(td, 'colspan');
-
- // Fill out rowspan/colspan right and down
- for (y2 = y; y2 < y + rowspan; y2++) {
- if (!grid[y2]) {
- grid[y2] = [];
- }
-
- for (x2 = x; x2 < x + colspan; x2++) {
- grid[y2][x2] = {
- part: part,
- real: y2 == y && x2 == x,
- elm: td,
- rowspan: rowspan,
- colspan: colspan
- };
- }
- }
- });
- });
-
- startY += rows.length;
- });
- }
-
- function cloneNode(node, children) {
- node = node.cloneNode(children);
- node.removeAttribute('id');
-
- return node;
- }
-
- function getCell(x, y) {
- var row;
-
- row = grid[y];
- if (row) {
- return row[x];
- }
- }
-
- function setSpanVal(td, name, val) {
- if (td) {
- val = parseInt(val, 10);
-
- if (val === 1) {
- td.removeAttribute(name, 1);
- } else {
- td.setAttribute(name, val, 1);
- }
- }
- }
-
- function isCellSelected(cell) {
- return cell && (dom.hasClass(cell.elm, 'mce-item-selected') || cell == selectedCell);
- }
-
- function getSelectedRows() {
- var rows = [];
-
- each(table.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || (selectedCell && cell == selectedCell.elm)) {
- rows.push(row);
- return false;
- }
- });
- });
-
- return rows;
- }
-
- function deleteTable() {
- var rng = dom.createRng();
-
- rng.setStartAfter(table);
- rng.setEndAfter(table);
-
- selection.setRng(rng);
-
- dom.remove(table);
- }
-
- function cloneCell(cell) {
- var formatNode, cloneFormats = {};
-
- if (editor.settings.table_clone_elements !== false) {
- cloneFormats = Tools.makeMap(
- (editor.settings.table_clone_elements || 'strong em b i span font h1 h2 h3 h4 h5 h6 p div').toUpperCase(),
- /[ ,]/
- );
- }
-
- // Clone formats
- Tools.walk(cell, function(node) {
- var curNode;
-
- if (node.nodeType == 3) {
- each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) {
- if (!cloneFormats[node.nodeName]) {
- return;
- }
-
- node = cloneNode(node, false);
-
- if (!formatNode) {
- formatNode = curNode = node;
- } else if (curNode) {
- curNode.appendChild(node);
- }
-
- curNode = node;
- });
-
- // Add something to the inner node
- if (curNode) {
- curNode.innerHTML = Env.ie ? ' ' : '
';
- }
-
- return false;
- }
- }, 'childNodes');
-
- cell = cloneNode(cell, false);
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- if (formatNode) {
- cell.appendChild(formatNode);
- } else {
- if (!Env.ie) {
- cell.innerHTML = '
';
- }
- }
-
- return cell;
- }
-
- function cleanup() {
- var rng = dom.createRng(), row;
-
- // Empty rows
- each(dom.select('tr', table), function(tr) {
- if (tr.cells.length === 0) {
- dom.remove(tr);
- }
- });
-
- // Empty table
- if (dom.select('tr', table).length === 0) {
- rng.setStartBefore(table);
- rng.setEndBefore(table);
- selection.setRng(rng);
- dom.remove(table);
- return;
- }
-
- // Empty header/body/footer
- each(dom.select('thead,tbody,tfoot', table), function(part) {
- if (part.rows.length === 0) {
- dom.remove(part);
- }
- });
-
- // Restore selection to start position if it still exists
- buildGrid();
-
- // If we have a valid startPos object
- if (startPos) {
- // Restore the selection to the closest table position
- row = grid[Math.min(grid.length - 1, startPos.y)];
- if (row) {
- selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true);
- selection.collapse(true);
- }
- }
- }
-
- function fillLeftDown(x, y, rows, cols) {
- var tr, x2, r, c, cell;
-
- tr = grid[y][x].elm.parentNode;
- for (r = 1; r <= rows; r++) {
- tr = dom.getNext(tr, 'tr');
-
- if (tr) {
- // Loop left to find real cell
- for (x2 = x; x2 >= 0; x2--) {
- cell = grid[y + r][x2].elm;
-
- if (cell.parentNode == tr) {
- // Append clones after
- for (c = 1; c <= cols; c++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- break;
- }
- }
-
- if (x2 == -1) {
- // Insert nodes before first cell
- for (c = 1; c <= cols; c++) {
- tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]);
- }
- }
- }
- }
- }
-
- function split() {
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan, i;
-
- if (isCellSelected(cell)) {
- cell = cell.elm;
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan > 1 || rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- // Insert cells right
- for (i = 0; i < colSpan - 1; i++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- fillLeftDown(x, y, rowSpan - 1, colSpan);
- }
- }
- });
- });
- }
-
- function merge(cell, cols, rows) {
- var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count;
-
- // Use specified cell and cols/rows
- if (cell) {
- pos = getPos(cell);
- startX = pos.x;
- startY = pos.y;
- endX = startX + (cols - 1);
- endY = startY + (rows - 1);
- } else {
- startPos = endPos = null;
-
- // Calculate start/end pos by checking for selected cells in grid works better with context menu
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- if (!startPos) {
- startPos = {x: x, y: y};
- }
-
- endPos = {x: x, y: y};
- }
- });
- });
-
- // Use selection, but make sure startPos is valid before accessing
- if (startPos) {
- startX = startPos.x;
- startY = startPos.y;
- endX = endPos.x;
- endY = endPos.y;
- }
- }
-
- // Find start/end cells
- startCell = getCell(startX, startY);
- endCell = getCell(endX, endY);
-
- // Check if the cells exists and if they are of the same part for example tbody = tbody
- if (startCell && endCell && startCell.part == endCell.part) {
- // Split and rebuild grid
- split();
- buildGrid();
-
- // Set row/col span to start cell
- startCell = getCell(startX, startY).elm;
- setSpanVal(startCell, 'colSpan', (endX - startX) + 1);
- setSpanVal(startCell, 'rowSpan', (endY - startY) + 1);
-
- // Remove other cells and add it's contents to the start cell
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- if (!grid[y] || !grid[y][x]) {
- continue;
- }
-
- cell = grid[y][x].elm;
-
- /*jshint loopfunc:true */
- /*eslint loop-func:0 */
- if (cell != startCell) {
- // Move children to startCell
- children = Tools.grep(cell.childNodes);
- each(children, function(node) {
- startCell.appendChild(node);
- });
-
- // Remove bogus nodes if there is children in the target cell
- if (children.length) {
- children = Tools.grep(startCell.childNodes);
- count = 0;
- each(children, function(node) {
- if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) {
- startCell.removeChild(node);
- }
- });
- }
-
- dom.remove(cell);
- }
- }
- }
-
- // Remove empty rows etc and restore caret location
- cleanup();
- }
- }
-
- function insertRow(before) {
- var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan;
-
- // Find first/last row
- each(grid, function(row, y) {
- each(row, function(cell) {
- if (isCellSelected(cell)) {
- cell = cell.elm;
- rowElm = cell.parentNode;
- newRow = cloneNode(rowElm, false);
- posY = y;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posY;
- }
- });
-
- // If posY is undefined there is nothing for us to do here...just return to avoid crashing below
- if (posY === undefined) {
- return;
- }
-
- for (x = 0; x < grid[0].length; x++) {
- // Cell not found could be because of an invalid table structure
- if (!grid[posY][x]) {
- continue;
- }
-
- cell = grid[posY][x].elm;
-
- if (cell != lastCell) {
- if (!before) {
- rowSpan = getSpanVal(cell, 'rowspan');
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan + 1);
- continue;
- }
- } else {
- // Check if cell above can be expanded
- if (posY > 0 && grid[posY - 1][x]) {
- otherCell = grid[posY - 1][x].elm;
- rowSpan = getSpanVal(otherCell, 'rowSpan');
- if (rowSpan > 1) {
- setSpanVal(otherCell, 'rowSpan', rowSpan + 1);
- continue;
- }
- }
- }
-
- // Insert new cell into new row
- newCell = cloneCell(cell);
- setSpanVal(newCell, 'colSpan', cell.colSpan);
-
- newRow.appendChild(newCell);
-
- lastCell = cell;
- }
- }
-
- if (newRow.hasChildNodes()) {
- if (!before) {
- dom.insertAfter(newRow, rowElm);
- } else {
- rowElm.parentNode.insertBefore(newRow, rowElm);
- }
- }
- }
-
- function insertCol(before) {
- var posX, lastCell;
-
- // Find first/last column
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- posX = x;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posX;
- }
- });
-
- each(grid, function(row, y) {
- var cell, rowSpan, colSpan;
-
- if (!row[posX]) {
- return;
- }
-
- cell = row[posX].elm;
- if (cell != lastCell) {
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan == 1) {
- if (!before) {
- dom.insertAfter(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- } else {
- cell.parentNode.insertBefore(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- }
- } else {
- setSpanVal(cell, 'colSpan', cell.colSpan + 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- function deleteCols() {
- var cols = [];
-
- // Get selected column indexes
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) {
- each(grid, function(row) {
- var cell = row[x].elm, colSpan;
-
- colSpan = getSpanVal(cell, 'colSpan');
-
- if (colSpan > 1) {
- setSpanVal(cell, 'colSpan', colSpan - 1);
- } else {
- dom.remove(cell);
- }
- });
-
- cols.push(x);
- }
- });
- });
-
- cleanup();
- }
-
- function deleteRows() {
- var rows;
-
- function deleteRow(tr) {
- var nextTr, pos, lastCell;
-
- nextTr = dom.getNext(tr, 'tr');
-
- // Move down row spanned cells
- each(tr.cells, function(cell) {
- var rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- pos = getPos(cell);
- fillLeftDown(pos.x, pos.y, 1, 1);
- }
- });
-
- // Delete cells
- pos = getPos(tr.cells[0]);
- each(grid[pos.y], function(cell) {
- var rowSpan;
-
- cell = cell.elm;
-
- if (cell != lastCell) {
- rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan <= 1) {
- dom.remove(cell);
- } else {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- // Get selected rows and move selection out of scope
- rows = getSelectedRows();
-
- // Delete all selected rows
- each(rows.reverse(), function(tr) {
- deleteRow(tr);
- });
-
- cleanup();
- }
-
- function cutRows() {
- var rows = getSelectedRows();
-
- dom.remove(rows);
- cleanup();
-
- return rows;
- }
-
- function copyRows() {
- var rows = getSelectedRows();
-
- each(rows, function(row, i) {
- rows[i] = cloneNode(row, true);
- });
-
- return rows;
- }
-
- function pasteRows(rows, before) {
- var selectedRows = getSelectedRows(),
- targetRow = selectedRows[before ? 0 : selectedRows.length - 1],
- targetCellCount = targetRow.cells.length;
-
- // Nothing to paste
- if (!rows) {
- return;
- }
-
- // Calc target cell count
- each(grid, function(row) {
- var match;
-
- targetCellCount = 0;
- each(row, function(cell) {
- if (cell.real) {
- targetCellCount += cell.colspan;
- }
-
- if (cell.elm.parentNode == targetRow) {
- match = 1;
- }
- });
-
- if (match) {
- return false;
- }
- });
-
- if (!before) {
- rows.reverse();
- }
-
- each(rows, function(row) {
- var i, cellCount = row.cells.length, cell;
-
- // Remove col/rowspans
- for (i = 0; i < cellCount; i++) {
- cell = row.cells[i];
- setSpanVal(cell, 'colSpan', 1);
- setSpanVal(cell, 'rowSpan', 1);
- }
-
- // Needs more cells
- for (i = cellCount; i < targetCellCount; i++) {
- row.appendChild(cloneCell(row.cells[cellCount - 1]));
- }
-
- // Needs less cells
- for (i = targetCellCount; i < cellCount; i++) {
- dom.remove(row.cells[i]);
- }
-
- // Add before/after
- if (before) {
- targetRow.parentNode.insertBefore(row, targetRow);
- } else {
- dom.insertAfter(row, targetRow);
- }
- });
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
- }
-
- function getPos(target) {
- var pos;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (cell.elm == target) {
- pos = {x : x, y : y};
- return false;
- }
- });
-
- return !pos;
- });
-
- return pos;
- }
-
- function setStartCell(cell) {
- startPos = getPos(cell);
- }
-
- function findEndPos() {
- var maxX, maxY;
-
- maxX = maxY = 0;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan;
-
- if (isCellSelected(cell)) {
- cell = grid[y][x];
-
- if (x > maxX) {
- maxX = x;
- }
-
- if (y > maxY) {
- maxY = y;
- }
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- });
- });
-
- return {x : maxX, y : maxY};
- }
-
- function setEndCell(cell) {
- var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y;
-
- endPos = getPos(cell);
-
- if (startPos && endPos) {
- // Get start/end positions
- startX = Math.min(startPos.x, endPos.x);
- startY = Math.min(startPos.y, endPos.y);
- endX = Math.max(startPos.x, endPos.x);
- endY = Math.max(startPos.y, endPos.y);
-
- // Expand end positon to include spans
- maxX = endX;
- maxY = endY;
-
- // Expand startX
- for (y = startY; y <= maxY; y++) {
- cell = grid[y][startX];
-
- if (!cell.real) {
- if (startX - (cell.colspan - 1) < startX) {
- startX -= cell.colspan - 1;
- }
- }
- }
-
- // Expand startY
- for (x = startX; x <= maxX; x++) {
- cell = grid[startY][x];
-
- if (!cell.real) {
- if (startY - (cell.rowspan - 1) < startY) {
- startY -= cell.rowspan - 1;
- }
- }
- }
-
- // Find max X, Y
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- cell = grid[y][x];
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- }
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
-
- // Add new selection
- for (y = startY; y <= maxY; y++) {
- for (x = startX; x <= maxX; x++) {
- if (grid[y][x]) {
- dom.addClass(grid[y][x].elm, 'mce-item-selected');
- }
- }
- }
- }
- }
-
- table = table || dom.getParent(selection.getStart(), 'table');
-
- buildGrid();
-
- selectedCell = dom.getParent(selection.getStart(), 'th,td');
- if (selectedCell) {
- startPos = getPos(selectedCell);
- endPos = findEndPos();
- selectedCell = getCell(startPos.x, startPos.y);
- }
-
- Tools.extend(this, {
- deleteTable: deleteTable,
- split: split,
- merge: merge,
- insertRow: insertRow,
- insertCol: insertCol,
- deleteCols: deleteCols,
- deleteRows: deleteRows,
- cutRows: cutRows,
- copyRows: copyRows,
- pasteRows: pasteRows,
- getPos: getPos,
- setStartCell: setStartCell,
- setEndCell: setEndCell
- });
- };
-});
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.dev.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.dev.js
deleted file mode 100755
index 253bd3ecf6..0000000000
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.dev.js
+++ /dev/null
@@ -1,119 +0,0 @@
-/**
- * Inline development version. Only to be used while developing since it uses document.write to load scripts.
- */
-
-/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
-/*globals $code */
-
-(function(exports) {
- "use strict";
-
- var html = "", baseDir;
- var modules = {}, exposedModules = [], moduleCount = 0;
-
- var scripts = document.getElementsByTagName('script');
- for (var i = 0; i < scripts.length; i++) {
- var src = scripts[i].src;
-
- if (src.indexOf('/plugin.dev.js') != -1) {
- baseDir = src.substring(0, src.lastIndexOf('/'));
- }
- }
-
- function require(ids, callback) {
- var module, defs = [];
-
- for (var i = 0; i < ids.length; ++i) {
- module = modules[ids[i]] || resolve(ids[i]);
- if (!module) {
- throw 'module definition dependecy not found: ' + ids[i];
- }
-
- defs.push(module);
- }
-
- callback.apply(null, defs);
- }
-
- function resolve(id) {
- var target = exports;
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length; ++fi) {
- if (!target[fragments[fi]]) {
- return;
- }
-
- target = target[fragments[fi]];
- }
-
- return target;
- }
-
- function register(id) {
- var target = exports;
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length - 1; ++fi) {
- if (target[fragments[fi]] === undefined) {
- target[fragments[fi]] = {};
- }
-
- target = target[fragments[fi]];
- }
-
- target[fragments[fragments.length - 1]] = modules[id];
- }
-
- function define(id, dependencies, definition) {
- if (typeof id !== 'string') {
- throw 'invalid module definition, module id must be defined and be a string';
- }
-
- if (dependencies === undefined) {
- throw 'invalid module definition, dependencies must be specified';
- }
-
- if (definition === undefined) {
- throw 'invalid module definition, definition function must be specified';
- }
-
- require(dependencies, function() {
- modules[id] = definition.apply(null, arguments);
- });
-
- if (--moduleCount === 0) {
- for (var i = 0; i < exposedModules.length; i++) {
- register(exposedModules[i]);
- }
- }
- }
-
- function expose(ids) {
- exposedModules = ids;
- }
-
- function writeScripts() {
- document.write(html);
- }
-
- function load(path) {
- html += '\n';
- moduleCount++;
- }
-
- // Expose globally
- exports.define = define;
- exports.require = require;
-
- expose(["tinymce/tableplugin/TableGrid","tinymce/tableplugin/Quirks","tinymce/tableplugin/CellSelection","tinymce/tableplugin/Plugin"]);
-
- load('classes/TableGrid.js');
- load('classes/Quirks.js');
- load('classes/CellSelection.js');
- load('classes/Plugin.js');
-
- writeScripts();
-})(this);
-
-// $hash: 8a0327b8917332b89e69b02d5ba10c30
\ No newline at end of file
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js
old mode 100755
new mode 100644
index ff9bfe82f1..5273df8e3c
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.js
@@ -1,2260 +1,10260 @@
/**
- * Compiled inline version. (Library mode)
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
*/
-
-/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
-/*globals $code */
-
-(function(exports, undefined) {
- "use strict";
-
- var modules = {};
-
- function require(ids, callback) {
- var module, defs = [];
-
- for (var i = 0; i < ids.length; ++i) {
- module = modules[ids[i]] || resolve(ids[i]);
- if (!module) {
- throw 'module definition dependecy not found: ' + ids[i];
- }
-
- defs.push(module);
- }
-
- callback.apply(null, defs);
- }
-
- function define(id, dependencies, definition) {
- if (typeof id !== 'string') {
- throw 'invalid module definition, module id must be defined and be a string';
- }
-
- if (dependencies === undefined) {
- throw 'invalid module definition, dependencies must be specified';
- }
-
- if (definition === undefined) {
- throw 'invalid module definition, definition function must be specified';
- }
-
- require(dependencies, function() {
- modules[id] = definition.apply(null, arguments);
- });
- }
-
- function defined(id) {
- return !!modules[id];
- }
-
- function resolve(id) {
- var target = exports;
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length; ++fi) {
- if (!target[fragments[fi]]) {
- return;
- }
-
- target = target[fragments[fi]];
- }
-
- return target;
- }
-
- function expose(ids) {
- for (var i = 0; i < ids.length; i++) {
- var target = exports;
- var id = ids[i];
- var fragments = id.split(/[.\/]/);
-
- for (var fi = 0; fi < fragments.length - 1; ++fi) {
- if (target[fragments[fi]] === undefined) {
- target[fragments[fi]] = {};
- }
-
- target = target[fragments[fi]];
- }
-
- target[fragments[fragments.length - 1]] = modules[id];
- }
- }
-
-// Included from: js/tinymce/plugins/table/classes/TableGrid.js
-
-/**
- * TableGrid.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class creates a grid out of a table element. This
- * makes it a whole lot easier to handle complex tables with
- * col/row spans.
- *
- * @class tinymce.tableplugin.TableGrid
- * @private
- */
-define("tinymce/tableplugin/TableGrid", [
- "tinymce/util/Tools",
- "tinymce/Env"
-], function(Tools, Env) {
- var each = Tools.each;
-
- function getSpanVal(td, name) {
- return parseInt(td.getAttribute(name) || 1, 10);
- }
-
- return function(editor, table) {
- var grid, startPos, endPos, selectedCell, selection = editor.selection, dom = selection.dom;
-
- function buildGrid() {
- var startY = 0;
-
- grid = [];
-
- each(['thead', 'tbody', 'tfoot'], function(part) {
- var rows = dom.select('> ' + part + ' tr', table);
-
- each(rows, function(tr, y) {
- y += startY;
-
- each(dom.select('> td, > th', tr), function(td, x) {
- var x2, y2, rowspan, colspan;
-
- // Skip over existing cells produced by rowspan
- if (grid[y]) {
- while (grid[y][x]) {
- x++;
- }
- }
-
- // Get col/rowspan from cell
- rowspan = getSpanVal(td, 'rowspan');
- colspan = getSpanVal(td, 'colspan');
-
- // Fill out rowspan/colspan right and down
- for (y2 = y; y2 < y + rowspan; y2++) {
- if (!grid[y2]) {
- grid[y2] = [];
- }
-
- for (x2 = x; x2 < x + colspan; x2++) {
- grid[y2][x2] = {
- part: part,
- real: y2 == y && x2 == x,
- elm: td,
- rowspan: rowspan,
- colspan: colspan
- };
- }
- }
- });
- });
-
- startY += rows.length;
- });
- }
-
- function cloneNode(node, children) {
- node = node.cloneNode(children);
- node.removeAttribute('id');
-
- return node;
- }
-
- function getCell(x, y) {
- var row;
-
- row = grid[y];
- if (row) {
- return row[x];
- }
- }
-
- function setSpanVal(td, name, val) {
- if (td) {
- val = parseInt(val, 10);
-
- if (val === 1) {
- td.removeAttribute(name, 1);
- } else {
- td.setAttribute(name, val, 1);
- }
- }
- }
-
- function isCellSelected(cell) {
- return cell && (dom.hasClass(cell.elm, 'mce-item-selected') || cell == selectedCell);
- }
-
- function getSelectedRows() {
- var rows = [];
-
- each(table.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || (selectedCell && cell == selectedCell.elm)) {
- rows.push(row);
- return false;
- }
- });
- });
-
- return rows;
- }
-
- function deleteTable() {
- var rng = dom.createRng();
-
- rng.setStartAfter(table);
- rng.setEndAfter(table);
-
- selection.setRng(rng);
-
- dom.remove(table);
- }
-
- function cloneCell(cell) {
- var formatNode, cloneFormats = {};
-
- if (editor.settings.table_clone_elements !== false) {
- cloneFormats = Tools.makeMap(
- (editor.settings.table_clone_elements || 'strong em b i span font h1 h2 h3 h4 h5 h6 p div').toUpperCase(),
- /[ ,]/
- );
- }
-
- // Clone formats
- Tools.walk(cell, function(node) {
- var curNode;
-
- if (node.nodeType == 3) {
- each(dom.getParents(node.parentNode, null, cell).reverse(), function(node) {
- if (!cloneFormats[node.nodeName]) {
- return;
- }
-
- node = cloneNode(node, false);
-
- if (!formatNode) {
- formatNode = curNode = node;
- } else if (curNode) {
- curNode.appendChild(node);
- }
-
- curNode = node;
- });
-
- // Add something to the inner node
- if (curNode) {
- curNode.innerHTML = Env.ie ? ' ' : '
';
- }
-
- return false;
- }
- }, 'childNodes');
-
- cell = cloneNode(cell, false);
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- if (formatNode) {
- cell.appendChild(formatNode);
- } else {
- if (!Env.ie) {
- cell.innerHTML = '
';
- }
- }
-
- return cell;
- }
-
- function cleanup() {
- var rng = dom.createRng(), row;
-
- // Empty rows
- each(dom.select('tr', table), function(tr) {
- if (tr.cells.length === 0) {
- dom.remove(tr);
- }
- });
-
- // Empty table
- if (dom.select('tr', table).length === 0) {
- rng.setStartBefore(table);
- rng.setEndBefore(table);
- selection.setRng(rng);
- dom.remove(table);
- return;
- }
-
- // Empty header/body/footer
- each(dom.select('thead,tbody,tfoot', table), function(part) {
- if (part.rows.length === 0) {
- dom.remove(part);
- }
- });
-
- // Restore selection to start position if it still exists
- buildGrid();
-
- // If we have a valid startPos object
- if (startPos) {
- // Restore the selection to the closest table position
- row = grid[Math.min(grid.length - 1, startPos.y)];
- if (row) {
- selection.select(row[Math.min(row.length - 1, startPos.x)].elm, true);
- selection.collapse(true);
- }
- }
- }
-
- function fillLeftDown(x, y, rows, cols) {
- var tr, x2, r, c, cell;
-
- tr = grid[y][x].elm.parentNode;
- for (r = 1; r <= rows; r++) {
- tr = dom.getNext(tr, 'tr');
-
- if (tr) {
- // Loop left to find real cell
- for (x2 = x; x2 >= 0; x2--) {
- cell = grid[y + r][x2].elm;
-
- if (cell.parentNode == tr) {
- // Append clones after
- for (c = 1; c <= cols; c++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- break;
- }
- }
-
- if (x2 == -1) {
- // Insert nodes before first cell
- for (c = 1; c <= cols; c++) {
- tr.insertBefore(cloneCell(tr.cells[0]), tr.cells[0]);
- }
- }
- }
- }
- }
-
- function split() {
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan, i;
-
- if (isCellSelected(cell)) {
- cell = cell.elm;
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan > 1 || rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', 1);
- setSpanVal(cell, 'colSpan', 1);
-
- // Insert cells right
- for (i = 0; i < colSpan - 1; i++) {
- dom.insertAfter(cloneCell(cell), cell);
- }
-
- fillLeftDown(x, y, rowSpan - 1, colSpan);
- }
- }
- });
- });
- }
-
- function merge(cell, cols, rows) {
- var pos, startX, startY, endX, endY, x, y, startCell, endCell, children, count;
-
- // Use specified cell and cols/rows
- if (cell) {
- pos = getPos(cell);
- startX = pos.x;
- startY = pos.y;
- endX = startX + (cols - 1);
- endY = startY + (rows - 1);
- } else {
- startPos = endPos = null;
-
- // Calculate start/end pos by checking for selected cells in grid works better with context menu
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- if (!startPos) {
- startPos = {x: x, y: y};
- }
-
- endPos = {x: x, y: y};
- }
- });
- });
-
- // Use selection, but make sure startPos is valid before accessing
- if (startPos) {
- startX = startPos.x;
- startY = startPos.y;
- endX = endPos.x;
- endY = endPos.y;
- }
- }
-
- // Find start/end cells
- startCell = getCell(startX, startY);
- endCell = getCell(endX, endY);
-
- // Check if the cells exists and if they are of the same part for example tbody = tbody
- if (startCell && endCell && startCell.part == endCell.part) {
- // Split and rebuild grid
- split();
- buildGrid();
-
- // Set row/col span to start cell
- startCell = getCell(startX, startY).elm;
- setSpanVal(startCell, 'colSpan', (endX - startX) + 1);
- setSpanVal(startCell, 'rowSpan', (endY - startY) + 1);
-
- // Remove other cells and add it's contents to the start cell
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- if (!grid[y] || !grid[y][x]) {
- continue;
- }
-
- cell = grid[y][x].elm;
-
- /*jshint loopfunc:true */
- /*eslint loop-func:0 */
- if (cell != startCell) {
- // Move children to startCell
- children = Tools.grep(cell.childNodes);
- each(children, function(node) {
- startCell.appendChild(node);
- });
-
- // Remove bogus nodes if there is children in the target cell
- if (children.length) {
- children = Tools.grep(startCell.childNodes);
- count = 0;
- each(children, function(node) {
- if (node.nodeName == 'BR' && dom.getAttrib(node, 'data-mce-bogus') && count++ < children.length - 1) {
- startCell.removeChild(node);
- }
- });
- }
-
- dom.remove(cell);
- }
- }
- }
-
- // Remove empty rows etc and restore caret location
- cleanup();
- }
- }
-
- function insertRow(before) {
- var posY, cell, lastCell, x, rowElm, newRow, newCell, otherCell, rowSpan;
-
- // Find first/last row
- each(grid, function(row, y) {
- each(row, function(cell) {
- if (isCellSelected(cell)) {
- cell = cell.elm;
- rowElm = cell.parentNode;
- newRow = cloneNode(rowElm, false);
- posY = y;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posY;
- }
- });
-
- // If posY is undefined there is nothing for us to do here...just return to avoid crashing below
- if (posY === undefined) {
- return;
- }
-
- for (x = 0; x < grid[0].length; x++) {
- // Cell not found could be because of an invalid table structure
- if (!grid[posY][x]) {
- continue;
- }
-
- cell = grid[posY][x].elm;
-
- if (cell != lastCell) {
- if (!before) {
- rowSpan = getSpanVal(cell, 'rowspan');
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan + 1);
- continue;
- }
- } else {
- // Check if cell above can be expanded
- if (posY > 0 && grid[posY - 1][x]) {
- otherCell = grid[posY - 1][x].elm;
- rowSpan = getSpanVal(otherCell, 'rowSpan');
- if (rowSpan > 1) {
- setSpanVal(otherCell, 'rowSpan', rowSpan + 1);
- continue;
- }
- }
- }
-
- // Insert new cell into new row
- newCell = cloneCell(cell);
- setSpanVal(newCell, 'colSpan', cell.colSpan);
-
- newRow.appendChild(newCell);
-
- lastCell = cell;
- }
- }
-
- if (newRow.hasChildNodes()) {
- if (!before) {
- dom.insertAfter(newRow, rowElm);
- } else {
- rowElm.parentNode.insertBefore(newRow, rowElm);
- }
- }
- }
-
- function insertCol(before) {
- var posX, lastCell;
-
- // Find first/last column
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell)) {
- posX = x;
-
- if (before) {
- return false;
- }
- }
- });
-
- if (before) {
- return !posX;
- }
- });
-
- each(grid, function(row, y) {
- var cell, rowSpan, colSpan;
-
- if (!row[posX]) {
- return;
- }
-
- cell = row[posX].elm;
- if (cell != lastCell) {
- colSpan = getSpanVal(cell, 'colspan');
- rowSpan = getSpanVal(cell, 'rowspan');
-
- if (colSpan == 1) {
- if (!before) {
- dom.insertAfter(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- } else {
- cell.parentNode.insertBefore(cloneCell(cell), cell);
- fillLeftDown(posX, y, rowSpan - 1, colSpan);
- }
- } else {
- setSpanVal(cell, 'colSpan', cell.colSpan + 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- function deleteCols() {
- var cols = [];
-
- // Get selected column indexes
- each(grid, function(row) {
- each(row, function(cell, x) {
- if (isCellSelected(cell) && Tools.inArray(cols, x) === -1) {
- each(grid, function(row) {
- var cell = row[x].elm, colSpan;
-
- colSpan = getSpanVal(cell, 'colSpan');
-
- if (colSpan > 1) {
- setSpanVal(cell, 'colSpan', colSpan - 1);
- } else {
- dom.remove(cell);
- }
- });
-
- cols.push(x);
- }
- });
- });
-
- cleanup();
- }
-
- function deleteRows() {
- var rows;
-
- function deleteRow(tr) {
- var nextTr, pos, lastCell;
-
- nextTr = dom.getNext(tr, 'tr');
-
- // Move down row spanned cells
- each(tr.cells, function(cell) {
- var rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan > 1) {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- pos = getPos(cell);
- fillLeftDown(pos.x, pos.y, 1, 1);
- }
- });
-
- // Delete cells
- pos = getPos(tr.cells[0]);
- each(grid[pos.y], function(cell) {
- var rowSpan;
-
- cell = cell.elm;
-
- if (cell != lastCell) {
- rowSpan = getSpanVal(cell, 'rowSpan');
-
- if (rowSpan <= 1) {
- dom.remove(cell);
- } else {
- setSpanVal(cell, 'rowSpan', rowSpan - 1);
- }
-
- lastCell = cell;
- }
- });
- }
-
- // Get selected rows and move selection out of scope
- rows = getSelectedRows();
-
- // Delete all selected rows
- each(rows.reverse(), function(tr) {
- deleteRow(tr);
- });
-
- cleanup();
- }
-
- function cutRows() {
- var rows = getSelectedRows();
-
- dom.remove(rows);
- cleanup();
-
- return rows;
- }
-
- function copyRows() {
- var rows = getSelectedRows();
-
- each(rows, function(row, i) {
- rows[i] = cloneNode(row, true);
- });
-
- return rows;
- }
-
- function pasteRows(rows, before) {
- var selectedRows = getSelectedRows(),
- targetRow = selectedRows[before ? 0 : selectedRows.length - 1],
- targetCellCount = targetRow.cells.length;
-
- // Nothing to paste
- if (!rows) {
- return;
- }
-
- // Calc target cell count
- each(grid, function(row) {
- var match;
-
- targetCellCount = 0;
- each(row, function(cell) {
- if (cell.real) {
- targetCellCount += cell.colspan;
- }
-
- if (cell.elm.parentNode == targetRow) {
- match = 1;
- }
- });
-
- if (match) {
- return false;
- }
- });
-
- if (!before) {
- rows.reverse();
- }
-
- each(rows, function(row) {
- var i, cellCount = row.cells.length, cell;
-
- // Remove col/rowspans
- for (i = 0; i < cellCount; i++) {
- cell = row.cells[i];
- setSpanVal(cell, 'colSpan', 1);
- setSpanVal(cell, 'rowSpan', 1);
- }
-
- // Needs more cells
- for (i = cellCount; i < targetCellCount; i++) {
- row.appendChild(cloneCell(row.cells[cellCount - 1]));
- }
-
- // Needs less cells
- for (i = targetCellCount; i < cellCount; i++) {
- dom.remove(row.cells[i]);
- }
-
- // Add before/after
- if (before) {
- targetRow.parentNode.insertBefore(row, targetRow);
- } else {
- dom.insertAfter(row, targetRow);
- }
- });
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
- }
-
- function getPos(target) {
- var pos;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- if (cell.elm == target) {
- pos = {x : x, y : y};
- return false;
- }
- });
-
- return !pos;
- });
-
- return pos;
- }
-
- function setStartCell(cell) {
- startPos = getPos(cell);
- }
-
- function findEndPos() {
- var maxX, maxY;
-
- maxX = maxY = 0;
-
- each(grid, function(row, y) {
- each(row, function(cell, x) {
- var colSpan, rowSpan;
-
- if (isCellSelected(cell)) {
- cell = grid[y][x];
-
- if (x > maxX) {
- maxX = x;
- }
-
- if (y > maxY) {
- maxY = y;
- }
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- });
- });
-
- return {x : maxX, y : maxY};
- }
-
- function setEndCell(cell) {
- var startX, startY, endX, endY, maxX, maxY, colSpan, rowSpan, x, y;
-
- endPos = getPos(cell);
-
- if (startPos && endPos) {
- // Get start/end positions
- startX = Math.min(startPos.x, endPos.x);
- startY = Math.min(startPos.y, endPos.y);
- endX = Math.max(startPos.x, endPos.x);
- endY = Math.max(startPos.y, endPos.y);
-
- // Expand end positon to include spans
- maxX = endX;
- maxY = endY;
-
- // Expand startX
- for (y = startY; y <= maxY; y++) {
- cell = grid[y][startX];
-
- if (!cell.real) {
- if (startX - (cell.colspan - 1) < startX) {
- startX -= cell.colspan - 1;
- }
- }
- }
-
- // Expand startY
- for (x = startX; x <= maxX; x++) {
- cell = grid[startY][x];
-
- if (!cell.real) {
- if (startY - (cell.rowspan - 1) < startY) {
- startY -= cell.rowspan - 1;
- }
- }
- }
-
- // Find max X, Y
- for (y = startY; y <= endY; y++) {
- for (x = startX; x <= endX; x++) {
- cell = grid[y][x];
-
- if (cell.real) {
- colSpan = cell.colspan - 1;
- rowSpan = cell.rowspan - 1;
-
- if (colSpan) {
- if (x + colSpan > maxX) {
- maxX = x + colSpan;
- }
- }
-
- if (rowSpan) {
- if (y + rowSpan > maxY) {
- maxY = y + rowSpan;
- }
- }
- }
- }
- }
-
- // Remove current selection
- dom.removeClass(dom.select('td.mce-item-selected,th.mce-item-selected'), 'mce-item-selected');
-
- // Add new selection
- for (y = startY; y <= maxY; y++) {
- for (x = startX; x <= maxX; x++) {
- if (grid[y][x]) {
- dom.addClass(grid[y][x].elm, 'mce-item-selected');
- }
- }
- }
- }
- }
-
- table = table || dom.getParent(selection.getStart(), 'table');
-
- buildGrid();
-
- selectedCell = dom.getParent(selection.getStart(), 'th,td');
- if (selectedCell) {
- startPos = getPos(selectedCell);
- endPos = findEndPos();
- selectedCell = getCell(startPos.x, startPos.y);
- }
-
- Tools.extend(this, {
- deleteTable: deleteTable,
- split: split,
- merge: merge,
- insertRow: insertRow,
- insertCol: insertCol,
- deleteCols: deleteCols,
- deleteRows: deleteRows,
- cutRows: cutRows,
- copyRows: copyRows,
- pasteRows: pasteRows,
- getPos: getPos,
- setStartCell: setStartCell,
- setEndCell: setEndCell
- });
- };
-});
-
-// Included from: js/tinymce/plugins/table/classes/Quirks.js
-
-/**
- * Quirks.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class includes fixes for various browser quirks.
- *
- * @class tinymce.tableplugin.Quirks
- * @private
- */
-define("tinymce/tableplugin/Quirks", [
- "tinymce/util/VK",
- "tinymce/Env",
- "tinymce/util/Tools"
-], function(VK, Env, Tools) {
- var each = Tools.each;
-
- function getSpanVal(td, name) {
- return parseInt(td.getAttribute(name) || 1, 10);
- }
-
- return function(editor) {
- /**
- * Fixed caret movement around tables on WebKit.
- */
- function moveWebKitSelection() {
- function eventHandler(e) {
- var key = e.keyCode;
-
- function handle(upBool, sourceNode) {
- var siblingDirection = upBool ? 'previousSibling' : 'nextSibling';
- var currentRow = editor.dom.getParent(sourceNode, 'tr');
- var siblingRow = currentRow[siblingDirection];
-
- if (siblingRow) {
- moveCursorToRow(editor, sourceNode, siblingRow, upBool);
- e.preventDefault();
- return true;
- } else {
- var tableNode = editor.dom.getParent(currentRow, 'table');
- var middleNode = currentRow.parentNode;
- var parentNodeName = middleNode.nodeName.toLowerCase();
- if (parentNodeName === 'tbody' || parentNodeName === (upBool ? 'tfoot' : 'thead')) {
- var targetParent = getTargetParent(upBool, tableNode, middleNode, 'tbody');
- if (targetParent !== null) {
- return moveToRowInTarget(upBool, targetParent, sourceNode);
- }
- }
- return escapeTable(upBool, currentRow, siblingDirection, tableNode);
- }
- }
-
- function getTargetParent(upBool, topNode, secondNode, nodeName) {
- var tbodies = editor.dom.select('>' + nodeName, topNode);
- var position = tbodies.indexOf(secondNode);
- if (upBool && position === 0 || !upBool && position === tbodies.length - 1) {
- return getFirstHeadOrFoot(upBool, topNode);
- } else if (position === -1) {
- var topOrBottom = secondNode.tagName.toLowerCase() === 'thead' ? 0 : tbodies.length - 1;
- return tbodies[topOrBottom];
- } else {
- return tbodies[position + (upBool ? -1 : 1)];
- }
- }
-
- function getFirstHeadOrFoot(upBool, parent) {
- var tagName = upBool ? 'thead' : 'tfoot';
- var headOrFoot = editor.dom.select('>' + tagName, parent);
- return headOrFoot.length !== 0 ? headOrFoot[0] : null;
- }
-
- function moveToRowInTarget(upBool, targetParent, sourceNode) {
- var targetRow = getChildForDirection(targetParent, upBool);
-
- if (targetRow) {
- moveCursorToRow(editor, sourceNode, targetRow, upBool);
- }
-
- e.preventDefault();
- return true;
- }
-
- function escapeTable(upBool, currentRow, siblingDirection, table) {
- var tableSibling = table[siblingDirection];
-
- if (tableSibling) {
- moveCursorToStartOfElement(tableSibling);
- return true;
- } else {
- var parentCell = editor.dom.getParent(table, 'td,th');
- if (parentCell) {
- return handle(upBool, parentCell, e);
- } else {
- var backUpSibling = getChildForDirection(currentRow, !upBool);
- moveCursorToStartOfElement(backUpSibling);
- e.preventDefault();
- return false;
- }
- }
- }
-
- function getChildForDirection(parent, up) {
- var child = parent && parent[up ? 'lastChild' : 'firstChild'];
- // BR is not a valid table child to return in this case we return the table cell
- return child && child.nodeName === 'BR' ? editor.dom.getParent(child, 'td,th') : child;
- }
-
- function moveCursorToStartOfElement(n) {
- editor.selection.setCursorLocation(n, 0);
- }
-
- function isVerticalMovement() {
- return key == VK.UP || key == VK.DOWN;
- }
-
- function isInTable(editor) {
- var node = editor.selection.getNode();
- var currentRow = editor.dom.getParent(node, 'tr');
- return currentRow !== null;
- }
-
- function columnIndex(column) {
- var colIndex = 0;
- var c = column;
- while (c.previousSibling) {
- c = c.previousSibling;
- colIndex = colIndex + getSpanVal(c, "colspan");
- }
- return colIndex;
- }
-
- function findColumn(rowElement, columnIndex) {
- var c = 0, r = 0;
-
- each(rowElement.children, function(cell, i) {
- c = c + getSpanVal(cell, "colspan");
- r = i;
- if (c > columnIndex) {
- return false;
- }
- });
- return r;
- }
-
- function moveCursorToRow(ed, node, row, upBool) {
- var srcColumnIndex = columnIndex(editor.dom.getParent(node, 'td,th'));
- var tgtColumnIndex = findColumn(row, srcColumnIndex);
- var tgtNode = row.childNodes[tgtColumnIndex];
- var rowCellTarget = getChildForDirection(tgtNode, upBool);
- moveCursorToStartOfElement(rowCellTarget || tgtNode);
- }
-
- function shouldFixCaret(preBrowserNode) {
- var newNode = editor.selection.getNode();
- var newParent = editor.dom.getParent(newNode, 'td,th');
- var oldParent = editor.dom.getParent(preBrowserNode, 'td,th');
-
- return newParent && newParent !== oldParent && checkSameParentTable(newParent, oldParent);
- }
-
- function checkSameParentTable(nodeOne, NodeTwo) {
- return editor.dom.getParent(nodeOne, 'TABLE') === editor.dom.getParent(NodeTwo, 'TABLE');
- }
-
- if (isVerticalMovement() && isInTable(editor)) {
- var preBrowserNode = editor.selection.getNode();
- setTimeout(function() {
- if (shouldFixCaret(preBrowserNode)) {
- handle(!e.shiftKey && key === VK.UP, preBrowserNode, e);
- }
- }, 0);
- }
- }
-
- editor.on('KeyDown', function(e) {
- eventHandler(e);
- });
- }
-
- function fixBeforeTableCaretBug() {
- // Checks if the selection/caret is at the start of the specified block element
- function isAtStart(rng, par) {
- var doc = par.ownerDocument, rng2 = doc.createRange(), elm;
-
- rng2.setStartBefore(par);
- rng2.setEnd(rng.endContainer, rng.endOffset);
-
- elm = doc.createElement('body');
- elm.appendChild(rng2.cloneContents());
-
- // Check for text characters of other elements that should be treated as content
- return elm.innerHTML.replace(/<(br|img|object|embed|input|textarea)[^>]*>/gi, '-').replace(/<[^>]+>/g, '').length === 0;
- }
-
- // Fixes an bug where it's impossible to place the caret before a table in Gecko
- // this fix solves it by detecting when the caret is at the beginning of such a table
- // and then manually moves the caret infront of the table
- editor.on('KeyDown', function(e) {
- var rng, table, dom = editor.dom;
-
- // On gecko it's not possible to place the caret before a table
- if (e.keyCode == 37 || e.keyCode == 38) {
- rng = editor.selection.getRng();
- table = dom.getParent(rng.startContainer, 'table');
-
- if (table && editor.getBody().firstChild == table) {
- if (isAtStart(rng, table)) {
- rng = dom.createRng();
-
- rng.setStartBefore(table);
- rng.setEndBefore(table);
-
- editor.selection.setRng(rng);
-
- e.preventDefault();
- }
- }
- }
- });
- }
-
- // Fixes an issue on Gecko where it's impossible to place the caret behind a table
- // This fix will force a paragraph element after the table but only when the forced_root_block setting is enabled
- function fixTableCaretPos() {
- editor.on('KeyDown SetContent VisualAid', function() {
- var last;
-
- // Skip empty text nodes from the end
- for (last = editor.getBody().lastChild; last; last = last.previousSibling) {
- if (last.nodeType == 3) {
- if (last.nodeValue.length > 0) {
- break;
- }
- } else if (last.nodeType == 1 && !last.getAttribute('data-mce-bogus')) {
- break;
- }
- }
-
- if (last && last.nodeName == 'TABLE') {
- if (editor.settings.forced_root_block) {
- editor.dom.add(
- editor.getBody(),
- editor.settings.forced_root_block,
- editor.settings.forced_root_block_attrs,
- Env.ie && Env.ie < 11 ? ' ' : '
'
- );
- } else {
- editor.dom.add(editor.getBody(), 'br', {'data-mce-bogus': '1'});
- }
- }
- });
-
- editor.on('PreProcess', function(o) {
- var last = o.node.lastChild;
-
- if (last && (last.nodeName == "BR" || (last.childNodes.length == 1 &&
- (last.firstChild.nodeName == 'BR' || last.firstChild.nodeValue == '\u00a0'))) &&
- last.previousSibling && last.previousSibling.nodeName == "TABLE") {
- editor.dom.remove(last);
- }
- });
- }
-
- // this nasty hack is here to work around some WebKit selection bugs.
- function fixTableCellSelection() {
- function tableCellSelected(ed, rng, n, currentCell) {
- // The decision of when a table cell is selected is somewhat involved. The fact that this code is
- // required is actually a pointer to the root cause of this bug. A cell is selected when the start
- // and end offsets are 0, the start container is a text, and the selection node is either a TR (most cases)
- // or the parent of the table (in the case of the selection containing the last cell of a table).
- var TEXT_NODE = 3, table = ed.dom.getParent(rng.startContainer, 'TABLE');
- var tableParent, allOfCellSelected, tableCellSelection;
-
- if (table) {
- tableParent = table.parentNode;
- }
-
- allOfCellSelected = rng.startContainer.nodeType == TEXT_NODE &&
- rng.startOffset === 0 &&
- rng.endOffset === 0 &&
- currentCell &&
- (n.nodeName == "TR" || n == tableParent);
-
- tableCellSelection = (n.nodeName == "TD" || n.nodeName == "TH") && !currentCell;
-
- return allOfCellSelected || tableCellSelection;
- }
-
- function fixSelection() {
- var rng = editor.selection.getRng();
- var n = editor.selection.getNode();
- var currentCell = editor.dom.getParent(rng.startContainer, 'TD,TH');
-
- if (!tableCellSelected(editor, rng, n, currentCell)) {
- return;
- }
-
- if (!currentCell) {
- currentCell = n;
- }
-
- // Get the very last node inside the table cell
- var end = currentCell.lastChild;
- while (end.lastChild) {
- end = end.lastChild;
- }
-
- // Select the entire table cell. Nothing outside of the table cell should be selected.
- rng.setEnd(end, end.nodeValue.length);
- editor.selection.setRng(rng);
- }
-
- editor.on('KeyDown', function() {
- fixSelection();
- });
-
- editor.on('MouseDown', function(e) {
- if (e.button != 2) {
- fixSelection();
- }
- });
- }
-
- /**
- * Delete table if all cells are selected.
- */
- function deleteTable() {
- editor.on('keydown', function(e) {
- if ((e.keyCode == VK.DELETE || e.keyCode == VK.BACKSPACE) && !e.isDefaultPrevented()) {
- var table = editor.dom.getParent(editor.selection.getStart(), 'table');
-
- if (table) {
- var cells = editor.dom.select('td,th', table), i = cells.length;
- while (i--) {
- if (!editor.dom.hasClass(cells[i], 'mce-item-selected')) {
- return;
- }
- }
-
- e.preventDefault();
- editor.execCommand('mceTableDelete');
- }
- }
- });
- }
-
- deleteTable();
-
- if (Env.webkit) {
- moveWebKitSelection();
- fixTableCellSelection();
- }
-
- if (Env.gecko) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
-
- if (Env.ie > 10) {
- fixBeforeTableCaretBug();
- fixTableCaretPos();
- }
- };
-});
-
-// Included from: js/tinymce/plugins/table/classes/CellSelection.js
-
-/**
- * CellSelection.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class handles table cell selection by faking it using a css class that gets applied
- * to cells when dragging the mouse from one cell to another.
- *
- * @class tinymce.tableplugin.CellSelection
- * @private
- */
-define("tinymce/tableplugin/CellSelection", [
- "tinymce/tableplugin/TableGrid",
- "tinymce/dom/TreeWalker",
- "tinymce/util/Tools"
-], function(TableGrid, TreeWalker, Tools) {
- return function(editor) {
- var dom = editor.dom, tableGrid, startCell, startTable, hasCellSelection = true;
-
- function clear() {
- // Restore selection possibilities
- editor.getBody().style.webkitUserSelect = '';
-
- if (hasCellSelection) {
- editor.dom.removeClass(
- editor.dom.select('td.mce-item-selected,th.mce-item-selected'),
- 'mce-item-selected'
- );
-
- hasCellSelection = false;
- }
- }
-
- function cellSelectionHandler(e) {
- var sel, table, target = e.target;
-
- if (startCell && (tableGrid || target != startCell) && (target.nodeName == 'TD' || target.nodeName == 'TH')) {
- table = dom.getParent(target, 'table');
- if (table == startTable) {
- if (!tableGrid) {
- tableGrid = new TableGrid(editor, table);
- tableGrid.setStartCell(startCell);
-
- editor.getBody().style.webkitUserSelect = 'none';
- }
-
- tableGrid.setEndCell(target);
- hasCellSelection = true;
- }
-
- // Remove current selection
- sel = editor.selection.getSel();
-
- try {
- if (sel.removeAllRanges) {
- sel.removeAllRanges();
- } else {
- sel.empty();
- }
- } catch (ex) {
- // IE9 might throw errors here
- }
-
- e.preventDefault();
- }
- }
-
- // Add cell selection logic
- editor.on('MouseDown', function(e) {
- if (e.button != 2) {
- clear();
-
- startCell = dom.getParent(e.target, 'td,th');
- startTable = dom.getParent(startCell, 'table');
- }
- });
-
- editor.on('mouseover', cellSelectionHandler);
-
- editor.on('remove', function() {
- dom.unbind(editor.getDoc(), 'mouseover', cellSelectionHandler);
- });
-
- editor.on('MouseUp', function() {
- var rng, sel = editor.selection, selectedCells, walker, node, lastNode, endNode;
-
- function setPoint(node, start) {
- var walker = new TreeWalker(node, node);
-
- do {
- // Text node
- if (node.nodeType == 3 && Tools.trim(node.nodeValue).length !== 0) {
- if (start) {
- rng.setStart(node, 0);
- } else {
- rng.setEnd(node, node.nodeValue.length);
- }
-
- return;
- }
-
- // BR element
- if (node.nodeName == 'BR') {
- if (start) {
- rng.setStartBefore(node);
- } else {
- rng.setEndBefore(node);
- }
-
- return;
- }
- } while ((node = (start ? walker.next() : walker.prev())));
- }
-
- // Move selection to startCell
- if (startCell) {
- if (tableGrid) {
- editor.getBody().style.webkitUserSelect = '';
- }
-
- // Try to expand text selection as much as we can only Gecko supports cell selection
- selectedCells = dom.select('td.mce-item-selected,th.mce-item-selected');
- if (selectedCells.length > 0) {
- rng = dom.createRng();
- node = selectedCells[0];
- endNode = selectedCells[selectedCells.length - 1];
- rng.setStartBefore(node);
- rng.setEndAfter(node);
-
- setPoint(node, 1);
- walker = new TreeWalker(node, dom.getParent(selectedCells[0], 'table'));
-
- do {
- if (node.nodeName == 'TD' || node.nodeName == 'TH') {
- if (!dom.hasClass(node, 'mce-item-selected')) {
- break;
- }
-
- lastNode = node;
- }
- } while ((node = walker.next()));
-
- setPoint(lastNode);
-
- sel.setRng(rng);
- }
-
- editor.nodeChanged();
- startCell = tableGrid = startTable = null;
- }
- });
-
- editor.on('KeyUp', function() {
- clear();
- });
-
- return {
- clear: clear
- };
- };
-});
-
-// Included from: js/tinymce/plugins/table/classes/Plugin.js
-
-/**
- * Plugin.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/**
- * This class contains all core logic for the table plugin.
- *
- * @class tinymce.tableplugin.Plugin
- * @private
- */
-define("tinymce/tableplugin/Plugin", [
- "tinymce/tableplugin/TableGrid",
- "tinymce/tableplugin/Quirks",
- "tinymce/tableplugin/CellSelection",
- "tinymce/util/Tools",
- "tinymce/dom/TreeWalker",
- "tinymce/Env",
- "tinymce/PluginManager"
-], function(TableGrid, Quirks, CellSelection, Tools, TreeWalker, Env, PluginManager) {
- var each = Tools.each;
-
- function Plugin(editor) {
- var winMan, clipboardRows, self = this; // Might be selected cells on reload
-
- function removePxSuffix(size) {
- return size ? size.replace(/px$/, '') : "";
- }
-
- function addSizeSuffix(size) {
- if (/^[0-9]+$/.test(size)) {
- size += "px";
- }
-
- return size;
- }
-
- function unApplyAlign(elm) {
- each('left center right'.split(' '), function(name) {
- editor.formatter.remove('align' + name, {}, elm);
- });
- }
-
- function tableDialog() {
- var dom = editor.dom, tableElm, data;
-
- tableElm = dom.getParent(editor.selection.getStart(), 'table');
-
- data = {
- width: removePxSuffix(dom.getStyle(tableElm, 'width') || dom.getAttrib(tableElm, 'width')),
- height: removePxSuffix(dom.getStyle(tableElm, 'height') || dom.getAttrib(tableElm, 'height')),
- cellspacing: dom.getAttrib(tableElm, 'cellspacing'),
- cellpadding: dom.getAttrib(tableElm, 'cellpadding'),
- border: dom.getAttrib(tableElm, 'border'),
- caption: !!dom.select('caption', tableElm)[0]
- };
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(tableElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Table properties",
- items: {
- type: 'form',
- layout: 'grid',
- columns: 2,
- data: data,
- defaults: {
- type: 'textbox',
- maxWidth: 50
- },
- items: [
- {label: 'Width', name: 'width'},
- {label: 'Height', name: 'height'},
- {label: 'Cell spacing', name: 'cellspacing'},
- {label: 'Cell padding', name: 'cellpadding'},
- {label: 'Border', name: 'border'},
- {label: 'Caption', name: 'caption', type: 'checkbox'},
- {
- label: 'Alignment',
- minWidth: 90,
- name: 'align',
- type: 'listbox',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- }
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON(), captionElm;
-
- editor.undoManager.transact(function() {
- editor.dom.setAttribs(tableElm, {
- cellspacing: data.cellspacing,
- cellpadding: data.cellpadding,
- border: data.border
- });
-
- editor.dom.setStyles(tableElm, {
- width: addSizeSuffix(data.width),
- height: addSizeSuffix(data.height)
- });
-
- // Toggle caption on/off
- captionElm = dom.select('caption', tableElm)[0];
-
- if (captionElm && !data.caption) {
- dom.remove(captionElm);
- }
-
- if (!captionElm && data.caption) {
- captionElm = dom.create('caption');
- captionElm.innerHTML = !Env.ie ? '
' : '\u00a0';
- tableElm.insertBefore(captionElm, tableElm.firstChild);
- }
-
- unApplyAlign(tableElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, tableElm);
- }
-
- editor.focus();
- editor.addVisual();
- });
- }
- });
- }
-
- function mergeDialog(grid, cell) {
- editor.windowManager.open({
- title: "Merge cells",
- body: [
- {label: 'Cols', name: 'cols', type: 'textbox', size: 10},
- {label: 'Rows', name: 'rows', type: 'textbox', size: 10}
- ],
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- grid.merge(cell, data.cols, data.rows);
- });
- }
- });
- }
-
- function cellDialog() {
- var dom = editor.dom, cellElm, data, cells = [];
-
- // Get selected cells or the current cell
- cells = editor.dom.select('td.mce-item-selected,th.mce-item-selected');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
- if (!cells.length && cellElm) {
- cells.push(cellElm);
- }
-
- cellElm = cellElm || cells[0];
-
- if (!cellElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- width: removePxSuffix(dom.getStyle(cellElm, 'width') || dom.getAttrib(cellElm, 'width')),
- height: removePxSuffix(dom.getStyle(cellElm, 'height') || dom.getAttrib(cellElm, 'height')),
- scope: dom.getAttrib(cellElm, 'scope')
- };
-
- data.type = cellElm.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(cellElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Cell properties",
- items: {
- type: 'form',
- data: data,
- layout: 'grid',
- columns: 2,
- defaults: {
- type: 'textbox',
- maxWidth: 50
- },
- items: [
- {label: 'Width', name: 'width'},
- {label: 'Height', name: 'height'},
- {
- label: 'Cell type',
- name: 'type',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'Cell', value: 'td'},
- {text: 'Header cell', value: 'th'}
- ]
- },
- {
- label: 'Scope',
- name: 'scope',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Row', value: 'row'},
- {text: 'Column', value: 'col'},
- {text: 'Row group', value: 'rowgroup'},
- {text: 'Column group', value: 'colgroup'}
- ]
- },
- {
- label: 'Alignment',
- name: 'align',
- type: 'listbox',
- text: 'None',
- minWidth: 90,
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- }
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON();
-
- editor.undoManager.transact(function() {
- each(cells, function(cellElm) {
- editor.dom.setAttrib(cellElm, 'scope', data.scope);
-
- editor.dom.setStyles(cellElm, {
- width: addSizeSuffix(data.width),
- height: addSizeSuffix(data.height)
- });
-
- // Switch cell type
- if (data.type && cellElm.nodeName.toLowerCase() != data.type) {
- cellElm = dom.rename(cellElm, data.type);
- }
-
- // Apply/remove alignment
- unApplyAlign(cellElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, cellElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function rowDialog() {
- var dom = editor.dom, tableElm, cellElm, rowElm, data, rows = [];
-
- tableElm = editor.dom.getParent(editor.selection.getStart(), 'table');
- cellElm = editor.dom.getParent(editor.selection.getStart(), 'td,th');
-
- each(tableElm.rows, function(row) {
- each(row.cells, function(cell) {
- if (dom.hasClass(cell, 'mce-item-selected') || cell == cellElm) {
- rows.push(row);
- return false;
- }
- });
- });
-
- rowElm = rows[0];
- if (!rowElm) {
- // If this element is null, return now to avoid crashing.
- return;
- }
-
- data = {
- height: removePxSuffix(dom.getStyle(rowElm, 'height') || dom.getAttrib(rowElm, 'height')),
- scope: dom.getAttrib(rowElm, 'scope')
- };
-
- data.type = rowElm.parentNode.nodeName.toLowerCase();
-
- each('left center right'.split(' '), function(name) {
- if (editor.formatter.matchNode(rowElm, 'align' + name)) {
- data.align = name;
- }
- });
-
- editor.windowManager.open({
- title: "Row properties",
- items: {
- type: 'form',
- data: data,
- columns: 2,
- defaults: {
- type: 'textbox'
- },
- items: [
- {
- type: 'listbox',
- name: 'type',
- label: 'Row type',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'Header', value: 'thead'},
- {text: 'Body', value: 'tbody'},
- {text: 'Footer', value: 'tfoot'}
- ]
- },
- {
- type: 'listbox',
- name: 'align',
- label: 'Alignment',
- text: 'None',
- maxWidth: null,
- values: [
- {text: 'None', value: ''},
- {text: 'Left', value: 'left'},
- {text: 'Center', value: 'center'},
- {text: 'Right', value: 'right'}
- ]
- },
- {label: 'Height', name: 'height'}
- ]
- },
-
- onsubmit: function() {
- var data = this.toJSON(), tableElm, oldParentElm, parentElm;
-
- editor.undoManager.transact(function() {
- var toType = data.type;
-
- each(rows, function(rowElm) {
- editor.dom.setAttrib(rowElm, 'scope', data.scope);
-
- editor.dom.setStyles(rowElm, {
- height: addSizeSuffix(data.height)
- });
-
- if (toType != rowElm.parentNode.nodeName.toLowerCase()) {
- tableElm = dom.getParent(rowElm, 'table');
-
- oldParentElm = rowElm.parentNode;
- parentElm = dom.select(toType, tableElm)[0];
- if (!parentElm) {
- parentElm = dom.create(toType);
- if (tableElm.firstChild) {
- tableElm.insertBefore(parentElm, tableElm.firstChild);
- } else {
- tableElm.appendChild(parentElm);
- }
- }
-
- parentElm.appendChild(rowElm);
-
- if (!oldParentElm.hasChildNodes()) {
- dom.remove(oldParentElm);
- }
- }
-
- // Apply/remove alignment
- unApplyAlign(rowElm);
- if (data.align) {
- editor.formatter.apply('align' + data.align, {}, rowElm);
- }
- });
-
- editor.focus();
- });
- }
- });
- }
-
- function cmd(command) {
- return function() {
- editor.execCommand(command);
- };
- }
-
- function insertTable(cols, rows) {
- var y, x, html;
-
- html = '';
-
- for (y = 0; y < rows; y++) {
- html += '
';
-
- editor.insertContent(html);
- }
-
- function handleDisabledState(ctrl, selector) {
- function bindStateListener() {
- ctrl.disabled(!editor.dom.getParent(editor.selection.getStart(), selector));
-
- editor.selection.selectorChanged(selector, function(state) {
- ctrl.disabled(!state);
- });
- }
-
- if (editor.initialized) {
- bindStateListener();
- } else {
- editor.on('init', bindStateListener);
- }
- }
-
- function postRender() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'table');
- }
-
- function postRenderCell() {
- /*jshint validthis:true*/
- handleDisabledState(this, 'td,th');
- }
-
- function generateTableGrid() {
- var html = '';
-
- html = '';
-
- for (x = 0; x < cols; x++) {
- html += ' ';
- }
-
- html += '' + (Env.ie ? " " : ' ';
- }
-
- html += '
') + '';
-
- for (var y = 0; y < 10; y++) {
- html += '
';
-
- html += '';
-
- for (var x = 0; x < 10; x++) {
- html += ' ';
- }
-
- html += '';
- }
-
- html += '
' : nbsp;
+ tableElm.insertBefore(captionElm, tableElm.firstChild);
+ }
+ if (data.align === '') {
+ unApplyAlign(editor, tableElm);
+ } else {
+ applyAlign(editor, tableElm, data.align);
+ }
+ editor.focus();
+ editor.addVisual();
+ });
+ };
+ var open$2 = function (editor, insertNewTable) {
+ var dom = editor.dom;
+ var tableElm;
+ var data = extractDataFromSettings(editor, hasAdvancedTableTab(editor));
+ if (insertNewTable === false) {
+ tableElm = dom.getParent(editor.selection.getStart(), 'table');
+ if (tableElm) {
+ data = extractDataFromTableElement(editor, tableElm, hasAdvancedTableTab(editor));
+ } else {
+ if (hasAdvancedTableTab(editor)) {
+ data.borderstyle = '';
+ data.bordercolor = '';
+ data.backgroundcolor = '';
+ }
+ }
+ } else {
+ data.cols = '1';
+ data.rows = '1';
+ if (hasAdvancedTableTab(editor)) {
+ data.borderstyle = '';
+ data.bordercolor = '';
+ data.backgroundcolor = '';
+ }
+ }
+ var classes = buildListItems(getTableClassList(editor));
+ if (classes.length > 0) {
+ if (data.class) {
+ data.class = data.class.replace(/\s*mce\-item\-table\s*/g, '');
+ }
+ }
+ var generalPanel = {
+ type: 'grid',
+ columns: 2,
+ items: getItems$2(editor, classes, insertNewTable)
+ };
+ var nonAdvancedForm = function () {
+ return {
+ type: 'panel',
+ items: [generalPanel]
+ };
+ };
+ var advancedForm = function () {
+ return {
+ type: 'tabpanel',
+ tabs: [
+ {
+ title: 'General',
+ name: 'general',
+ items: [generalPanel]
+ },
+ getAdvancedTab('table')
+ ]
+ };
+ };
+ var dialogBody = hasAdvancedTableTab(editor) ? advancedForm() : nonAdvancedForm();
+ editor.windowManager.open({
+ title: 'Table Properties',
+ size: 'normal',
+ body: dialogBody,
+ onSubmit: curry(onSubmitTableForm, editor, tableElm),
+ buttons: [
+ {
+ type: 'cancel',
+ name: 'cancel',
+ text: 'Cancel'
+ },
+ {
+ type: 'submit',
+ name: 'save',
+ text: 'Save',
+ primary: true
+ }
+ ],
+ initialData: data
+ });
+ };
+
+ var getSelectionStartCellOrCaption$1 = function (editor) {
+ return getSelectionStartCellOrCaption(getSelectionStart(editor));
+ };
+ var getSelectionStartCell$1 = function (editor) {
+ return getSelectionStartCell(getSelectionStart(editor));
+ };
+ var registerCommands = function (editor, actions, cellSelection, selections, clipboard) {
+ var isRoot = getIsRoot(editor);
+ var eraseTable = function () {
+ return getSelectionStartCellOrCaption$1(editor).each(function (cellOrCaption) {
+ table(cellOrCaption, isRoot).filter(not(isRoot)).each(function (table) {
+ var cursor = SugarElement.fromText('');
+ after(table, cursor);
+ remove$2(table);
+ if (editor.dom.isEmpty(editor.getBody())) {
+ editor.setContent('');
+ editor.selection.setCursorLocation();
+ } else {
+ var rng = editor.dom.createRng();
+ rng.setStart(cursor.dom, 0);
+ rng.setEnd(cursor.dom, 0);
+ editor.selection.setRng(rng);
+ editor.nodeChanged();
+ }
+ });
+ });
+ };
+ var setSizingMode = function (sizing) {
+ return getSelectionStartCellOrCaption$1(editor).each(function (cellOrCaption) {
+ var isForcedSizing = isResponsiveForced(editor) || isPixelsForced(editor) || isPercentagesForced(editor);
+ if (!isForcedSizing) {
+ table(cellOrCaption, isRoot).each(function (table) {
+ if (sizing === 'relative' && !isPercentSizing$1(table)) {
+ enforcePercentage(editor, table);
+ } else if (sizing === 'fixed' && !isPixelSizing$1(table)) {
+ enforcePixels(editor, table);
+ } else if (sizing === 'responsive' && !isNoneSizing$1(table)) {
+ enforceNone(table);
+ }
+ removeDataStyle(table);
+ });
+ }
+ });
+ };
+ var getTableFromCell = function (cell) {
+ return table(cell, isRoot);
+ };
+ var actOnSelection = function (execute) {
+ return getSelectionStartCell$1(editor).each(function (cell) {
+ getTableFromCell(cell).each(function (table) {
+ var targets = forMenu(selections, table, cell);
+ execute(table, targets).each(function (rng) {
+ editor.selection.setRng(rng);
+ editor.focus();
+ cellSelection.clear(table);
+ removeDataStyle(table);
+ });
+ });
+ });
+ };
+ var copyRowSelection = function () {
+ return getSelectionStartCell$1(editor).map(function (cell) {
+ return getTableFromCell(cell).bind(function (table) {
+ var targets = forMenu(selections, table, cell);
+ var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), Optional.none());
+ return copyRows(table, targets, generators);
+ });
+ });
+ };
+ var copyColSelection = function () {
+ return getSelectionStartCell$1(editor).map(function (cell) {
+ return getTableFromCell(cell).bind(function (table) {
+ var targets = forMenu(selections, table, cell);
+ return copyCols(table, targets);
+ });
+ });
+ };
+ var pasteOnSelection = function (execute, getRows) {
+ return getRows().each(function (rows) {
+ var clonedRows = map(rows, function (row) {
+ return deep(row);
+ });
+ getSelectionStartCell$1(editor).each(function (cell) {
+ return getTableFromCell(cell).each(function (table) {
+ var generators = paste(SugarElement.fromDom(editor.getDoc()));
+ var targets = pasteRows(selections, cell, clonedRows, generators);
+ execute(table, targets).each(function (rng) {
+ editor.selection.setRng(rng);
+ editor.focus();
+ cellSelection.clear(table);
+ });
+ });
+ });
+ });
+ };
+ each$1({
+ mceTableSplitCells: function () {
+ return actOnSelection(actions.unmergeCells);
+ },
+ mceTableMergeCells: function () {
+ return actOnSelection(actions.mergeCells);
+ },
+ mceTableInsertRowBefore: function () {
+ return actOnSelection(actions.insertRowsBefore);
+ },
+ mceTableInsertRowAfter: function () {
+ return actOnSelection(actions.insertRowsAfter);
+ },
+ mceTableInsertColBefore: function () {
+ return actOnSelection(actions.insertColumnsBefore);
+ },
+ mceTableInsertColAfter: function () {
+ return actOnSelection(actions.insertColumnsAfter);
+ },
+ mceTableDeleteCol: function () {
+ return actOnSelection(actions.deleteColumn);
+ },
+ mceTableDeleteRow: function () {
+ return actOnSelection(actions.deleteRow);
+ },
+ mceTableCutCol: function (_grid) {
+ return copyColSelection().each(function (selection) {
+ clipboard.setColumns(selection);
+ actOnSelection(actions.deleteColumn);
+ });
+ },
+ mceTableCutRow: function (_grid) {
+ return copyRowSelection().each(function (selection) {
+ clipboard.setRows(selection);
+ actOnSelection(actions.deleteRow);
+ });
+ },
+ mceTableCopyCol: function (_grid) {
+ return copyColSelection().each(function (selection) {
+ return clipboard.setColumns(selection);
+ });
+ },
+ mceTableCopyRow: function (_grid) {
+ return copyRowSelection().each(function (selection) {
+ return clipboard.setRows(selection);
+ });
+ },
+ mceTablePasteColBefore: function (_grid) {
+ return pasteOnSelection(actions.pasteColsBefore, clipboard.getColumns);
+ },
+ mceTablePasteColAfter: function (_grid) {
+ return pasteOnSelection(actions.pasteColsAfter, clipboard.getColumns);
+ },
+ mceTablePasteRowBefore: function (_grid) {
+ return pasteOnSelection(actions.pasteRowsBefore, clipboard.getRows);
+ },
+ mceTablePasteRowAfter: function (_grid) {
+ return pasteOnSelection(actions.pasteRowsAfter, clipboard.getRows);
+ },
+ mceTableDelete: eraseTable,
+ mceTableSizingMode: function (ui, sizing) {
+ return setSizingMode(sizing);
+ }
+ }, function (func, name) {
+ return editor.addCommand(name, func);
+ });
+ each$1({
+ mceTableCellType: function (_ui, args) {
+ return actions.setTableCellType(editor, args);
+ },
+ mceTableRowType: function (_ui, args) {
+ return actions.setTableRowType(editor, args);
+ }
+ }, function (func, name) {
+ return editor.addCommand(name, func);
+ });
+ editor.addCommand('mceTableColType', function (_ui, args) {
+ return get(args, 'type').each(function (type) {
+ return actOnSelection(type === 'th' ? actions.makeColumnHeader : actions.unmakeColumnHeader);
+ });
+ });
+ each$1({
+ mceTableProps: curry(open$2, editor, false),
+ mceTableRowProps: curry(open$1, editor),
+ mceTableCellProps: curry(open, editor, selections)
+ }, function (func, name) {
+ return editor.addCommand(name, function () {
+ return func();
+ });
+ });
+ editor.addCommand('mceInsertTable', function (_ui, args) {
+ if (isObject(args) && keys(args).length > 0) {
+ insertTableWithDataValidation(editor, args.rows, args.columns, args.options, 'Invalid values for mceInsertTable - rows and columns values are required to insert a table.');
+ } else {
+ open$2(editor, true);
+ }
+ });
+ editor.addCommand('mceTableApplyCellStyle', function (_ui, args) {
+ if (!isObject(args)) {
+ return;
+ }
+ var cells = getCellsFromSelection(getSelectionStart(editor), selections);
+ if (cells.length === 0) {
+ return;
+ }
+ each$1(args, function (value, style) {
+ var formatName = 'tablecell' + style.toLowerCase().replace('-', '');
+ if (editor.formatter.has(formatName) && isString(value)) {
+ each(cells, function (cell) {
+ DomModifier.normal(editor, cell.dom).setFormat(formatName, value);
+ });
+ }
+ });
+ });
+ };
+
+ var registerQueryCommands = function (editor, actions, selections) {
+ var isRoot = getIsRoot(editor);
+ var getTableFromCell = function (cell) {
+ return table(cell, isRoot);
+ };
+ each$1({
+ mceTableRowType: function () {
+ return actions.getTableRowType(editor);
+ },
+ mceTableCellType: function () {
+ return actions.getTableCellType(editor);
+ },
+ mceTableColType: function () {
+ return getSelectionStartCell(getSelectionStart(editor)).bind(function (cell) {
+ return getTableFromCell(cell).map(function (table) {
+ var targets = forMenu(selections, table, cell);
+ return actions.getTableColType(table, targets);
+ });
+ }).getOr('');
+ }
+ }, function (func, name) {
+ return editor.addQueryValueHandler(name, func);
+ });
+ };
+
+ var Clipboard = function () {
+ var rows = Cell(Optional.none());
+ var cols = Cell(Optional.none());
+ var clearClipboard = function (clipboard) {
+ clipboard.set(Optional.none());
+ };
+ return {
+ getRows: rows.get,
+ setRows: function (r) {
+ rows.set(r);
+ clearClipboard(cols);
+ },
+ clearRows: function () {
+ return clearClipboard(rows);
+ },
+ getColumns: cols.get,
+ setColumns: function (c) {
+ cols.set(c);
+ clearClipboard(rows);
+ },
+ clearColumns: function () {
+ return clearClipboard(cols);
+ }
+ };
+ };
+
+ var cellFormats = {
+ tablecellbackgroundcolor: {
+ selector: 'td,th',
+ styles: { backgroundColor: '%value' },
+ remove_similar: true
+ },
+ tablecellbordercolor: {
+ selector: 'td,th',
+ styles: { borderColor: '%value' },
+ remove_similar: true
+ },
+ tablecellborderstyle: {
+ selector: 'td,th',
+ styles: { borderStyle: '%value' },
+ remove_similar: true
+ },
+ tablecellborderwidth: {
+ selector: 'td,th',
+ styles: { borderWidth: '%value' },
+ remove_similar: true
+ }
+ };
+ var registerFormats = function (editor) {
+ editor.formatter.register(cellFormats);
+ };
+
+ var adt$2 = Adt.generate([
+ { none: ['current'] },
+ { first: ['current'] },
+ {
+ middle: [
+ 'current',
+ 'target'
+ ]
+ },
+ { last: ['current'] }
+ ]);
+ var none$2 = function (current) {
+ if (current === void 0) {
+ current = undefined;
+ }
+ return adt$2.none(current);
+ };
+ var CellLocation = __assign(__assign({}, adt$2), { none: none$2 });
+
+ var detect$5 = function (current, isRoot) {
+ return table(current, isRoot).bind(function (table) {
+ var all = cells(table);
+ var index = findIndex(all, function (x) {
+ return eq(current, x);
+ });
+ return index.map(function (index) {
+ return {
+ index: index,
+ all: all
+ };
+ });
+ });
+ };
+ var next = function (current, isRoot) {
+ var detection = detect$5(current, isRoot);
+ return detection.fold(function () {
+ return CellLocation.none(current);
+ }, function (info) {
+ return info.index + 1 < info.all.length ? CellLocation.middle(current, info.all[info.index + 1]) : CellLocation.last(current);
+ });
+ };
+ var prev = function (current, isRoot) {
+ var detection = detect$5(current, isRoot);
+ return detection.fold(function () {
+ return CellLocation.none();
+ }, function (info) {
+ return info.index - 1 >= 0 ? CellLocation.middle(current, info.all[info.index - 1]) : CellLocation.first(current);
+ });
+ };
+
+ var create$2 = function (start, soffset, finish, foffset) {
+ return {
+ start: start,
+ soffset: soffset,
+ finish: finish,
+ foffset: foffset
+ };
+ };
+ var SimRange = { create: create$2 };
+
+ var adt$3 = Adt.generate([
+ { before: ['element'] },
+ {
+ on: [
+ 'element',
+ 'offset'
+ ]
+ },
+ { after: ['element'] }
+ ]);
+ var cata$1 = function (subject, onBefore, onOn, onAfter) {
+ return subject.fold(onBefore, onOn, onAfter);
+ };
+ var getStart = function (situ) {
+ return situ.fold(identity, identity, identity);
+ };
+ var before$2 = adt$3.before;
+ var on = adt$3.on;
+ var after$2 = adt$3.after;
+ var Situ = {
+ before: before$2,
+ on: on,
+ after: after$2,
+ cata: cata$1,
+ getStart: getStart
+ };
+
+ var adt$4 = Adt.generate([
+ { domRange: ['rng'] },
+ {
+ relative: [
+ 'startSitu',
+ 'finishSitu'
+ ]
+ },
+ {
+ exact: [
+ 'start',
+ 'soffset',
+ 'finish',
+ 'foffset'
+ ]
+ }
+ ]);
+ var exactFromRange = function (simRange) {
+ return adt$4.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
+ };
+ var getStart$1 = function (selection) {
+ return selection.match({
+ domRange: function (rng) {
+ return SugarElement.fromDom(rng.startContainer);
+ },
+ relative: function (startSitu, _finishSitu) {
+ return Situ.getStart(startSitu);
+ },
+ exact: function (start, _soffset, _finish, _foffset) {
+ return start;
+ }
+ });
+ };
+ var domRange = adt$4.domRange;
+ var relative = adt$4.relative;
+ var exact = adt$4.exact;
+ var getWin = function (selection) {
+ var start = getStart$1(selection);
+ return defaultView(start);
+ };
+ var range$1 = SimRange.create;
+ var SimSelection = {
+ domRange: domRange,
+ relative: relative,
+ exact: exact,
+ exactFromRange: exactFromRange,
+ getWin: getWin,
+ range: range$1
+ };
+
+ var selectNodeContents = function (win, element) {
+ var rng = win.document.createRange();
+ selectNodeContentsUsing(rng, element);
+ return rng;
+ };
+ var selectNodeContentsUsing = function (rng, element) {
+ return rng.selectNodeContents(element.dom);
+ };
+ var setStart = function (rng, situ) {
+ situ.fold(function (e) {
+ rng.setStartBefore(e.dom);
+ }, function (e, o) {
+ rng.setStart(e.dom, o);
+ }, function (e) {
+ rng.setStartAfter(e.dom);
+ });
+ };
+ var setFinish = function (rng, situ) {
+ situ.fold(function (e) {
+ rng.setEndBefore(e.dom);
+ }, function (e, o) {
+ rng.setEnd(e.dom, o);
+ }, function (e) {
+ rng.setEndAfter(e.dom);
+ });
+ };
+ var relativeToNative = function (win, startSitu, finishSitu) {
+ var range = win.document.createRange();
+ setStart(range, startSitu);
+ setFinish(range, finishSitu);
+ return range;
+ };
+ var exactToNative = function (win, start, soffset, finish, foffset) {
+ var rng = win.document.createRange();
+ rng.setStart(start.dom, soffset);
+ rng.setEnd(finish.dom, foffset);
+ return rng;
+ };
+ var toRect = function (rect) {
+ return {
+ left: rect.left,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom,
+ width: rect.width,
+ height: rect.height
+ };
+ };
+ var getFirstRect = function (rng) {
+ var rects = rng.getClientRects();
+ var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
+ return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none();
+ };
+
+ var adt$5 = Adt.generate([
+ {
+ ltr: [
+ 'start',
+ 'soffset',
+ 'finish',
+ 'foffset'
+ ]
+ },
+ {
+ rtl: [
+ 'start',
+ 'soffset',
+ 'finish',
+ 'foffset'
+ ]
+ }
+ ]);
+ var fromRange = function (win, type, range) {
+ return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
+ };
+ var getRanges = function (win, selection) {
+ return selection.match({
+ domRange: function (rng) {
+ return {
+ ltr: constant(rng),
+ rtl: Optional.none
+ };
+ },
+ relative: function (startSitu, finishSitu) {
+ return {
+ ltr: cached(function () {
+ return relativeToNative(win, startSitu, finishSitu);
+ }),
+ rtl: cached(function () {
+ return Optional.some(relativeToNative(win, finishSitu, startSitu));
+ })
+ };
+ },
+ exact: function (start, soffset, finish, foffset) {
+ return {
+ ltr: cached(function () {
+ return exactToNative(win, start, soffset, finish, foffset);
+ }),
+ rtl: cached(function () {
+ return Optional.some(exactToNative(win, finish, foffset, start, soffset));
+ })
+ };
+ }
+ });
+ };
+ var doDiagnose = function (win, ranges) {
+ var rng = ranges.ltr();
+ if (rng.collapsed) {
+ var reversed = ranges.rtl().filter(function (rev) {
+ return rev.collapsed === false;
+ });
+ return reversed.map(function (rev) {
+ return adt$5.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
+ }).getOrThunk(function () {
+ return fromRange(win, adt$5.ltr, rng);
+ });
+ } else {
+ return fromRange(win, adt$5.ltr, rng);
+ }
+ };
+ var diagnose = function (win, selection) {
+ var ranges = getRanges(win, selection);
+ return doDiagnose(win, ranges);
+ };
+ var asLtrRange = function (win, selection) {
+ var diagnosis = diagnose(win, selection);
+ return diagnosis.match({
+ ltr: function (start, soffset, finish, foffset) {
+ var rng = win.document.createRange();
+ rng.setStart(start.dom, soffset);
+ rng.setEnd(finish.dom, foffset);
+ return rng;
+ },
+ rtl: function (start, soffset, finish, foffset) {
+ var rng = win.document.createRange();
+ rng.setStart(finish.dom, foffset);
+ rng.setEnd(start.dom, soffset);
+ return rng;
+ }
+ });
+ };
+ var ltr$1 = adt$5.ltr;
+ var rtl$1 = adt$5.rtl;
+
+ var searchForPoint = function (rectForOffset, x, y, maxX, length) {
+ if (length === 0) {
+ return 0;
+ } else if (x === maxX) {
+ return length - 1;
+ }
+ var xDelta = maxX;
+ for (var i = 1; i < length; i++) {
+ var rect = rectForOffset(i);
+ var curDeltaX = Math.abs(x - rect.left);
+ if (y <= rect.bottom) {
+ if (y < rect.top || curDeltaX > xDelta) {
+ return i - 1;
+ } else {
+ xDelta = curDeltaX;
+ }
+ }
+ }
+ return 0;
+ };
+ var inRect = function (rect, x, y) {
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
+ };
+
+ var locateOffset = function (doc, textnode, x, y, rect) {
+ var rangeForOffset = function (o) {
+ var r = doc.dom.createRange();
+ r.setStart(textnode.dom, o);
+ r.collapse(true);
+ return r;
+ };
+ var rectForOffset = function (o) {
+ var r = rangeForOffset(o);
+ return r.getBoundingClientRect();
+ };
+ var length = get$3(textnode).length;
+ var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
+ return rangeForOffset(offset);
+ };
+ var locate = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ r.selectNode(node.dom);
+ var rects = r.getClientRects();
+ var foundRect = findMap(rects, function (rect) {
+ return inRect(rect, x, y) ? Optional.some(rect) : Optional.none();
+ });
+ return foundRect.map(function (rect) {
+ return locateOffset(doc, node, x, y, rect);
+ });
+ };
+
+ var searchInChildren = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ var nodes = children(node);
+ return findMap(nodes, function (n) {
+ r.selectNode(n.dom);
+ return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Optional.none();
+ });
+ };
+ var locateNode = function (doc, node, x, y) {
+ return isText(node) ? locate(doc, node, x, y) : searchInChildren(doc, node, x, y);
+ };
+ var locate$1 = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ r.selectNode(node.dom);
+ var rect = r.getBoundingClientRect();
+ var boundedX = Math.max(rect.left, Math.min(rect.right, x));
+ var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
+ return locateNode(doc, node, boundedX, boundedY);
+ };
+
+ var COLLAPSE_TO_LEFT = true;
+ var COLLAPSE_TO_RIGHT = false;
+ var getCollapseDirection = function (rect, x) {
+ return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
+ };
+ var createCollapsedNode = function (doc, target, collapseDirection) {
+ var r = doc.dom.createRange();
+ r.selectNode(target.dom);
+ r.collapse(collapseDirection);
+ return r;
+ };
+ var locateInElement = function (doc, node, x) {
+ var cursorRange = doc.dom.createRange();
+ cursorRange.selectNode(node.dom);
+ var rect = cursorRange.getBoundingClientRect();
+ var collapseDirection = getCollapseDirection(rect, x);
+ var f = collapseDirection === COLLAPSE_TO_LEFT ? first : last$1;
+ return f(node).map(function (target) {
+ return createCollapsedNode(doc, target, collapseDirection);
+ });
+ };
+ var locateInEmpty = function (doc, node, x) {
+ var rect = node.dom.getBoundingClientRect();
+ var collapseDirection = getCollapseDirection(rect, x);
+ return Optional.some(createCollapsedNode(doc, node, collapseDirection));
+ };
+ var search = function (doc, node, x) {
+ var f = children(node).length === 0 ? locateInEmpty : locateInElement;
+ return f(doc, node, x);
+ };
+
+ var caretPositionFromPoint = function (doc, x, y) {
+ return Optional.from(doc.dom.caretPositionFromPoint(x, y)).bind(function (pos) {
+ if (pos.offsetNode === null) {
+ return Optional.none();
+ }
+ var r = doc.dom.createRange();
+ r.setStart(pos.offsetNode, pos.offset);
+ r.collapse();
+ return Optional.some(r);
+ });
+ };
+ var caretRangeFromPoint = function (doc, x, y) {
+ return Optional.from(doc.dom.caretRangeFromPoint(x, y));
+ };
+ var searchTextNodes = function (doc, node, x, y) {
+ var r = doc.dom.createRange();
+ r.selectNode(node.dom);
+ var rect = r.getBoundingClientRect();
+ var boundedX = Math.max(rect.left, Math.min(rect.right, x));
+ var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
+ return locate$1(doc, node, boundedX, boundedY);
+ };
+ var searchFromPoint = function (doc, x, y) {
+ return SugarElement.fromPoint(doc, x, y).bind(function (elem) {
+ var fallback = function () {
+ return search(doc, elem, x);
+ };
+ return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
+ });
+ };
+ var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
+ var fromPoint$1 = function (win, x, y) {
+ var doc = SugarElement.fromDom(win.document);
+ return availableSearch(doc, x, y).map(function (rng) {
+ return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
+ });
+ };
+
+ var beforeSpecial = function (element, offset) {
+ var name$1 = name(element);
+ if ('input' === name$1) {
+ return Situ.after(element);
+ } else if (!contains([
+ 'br',
+ 'img'
+ ], name$1)) {
+ return Situ.on(element, offset);
+ } else {
+ return offset === 0 ? Situ.before(element) : Situ.after(element);
+ }
+ };
+ var preprocessRelative = function (startSitu, finishSitu) {
+ var start = startSitu.fold(Situ.before, beforeSpecial, Situ.after);
+ var finish = finishSitu.fold(Situ.before, beforeSpecial, Situ.after);
+ return SimSelection.relative(start, finish);
+ };
+ var preprocessExact = function (start, soffset, finish, foffset) {
+ var startSitu = beforeSpecial(start, soffset);
+ var finishSitu = beforeSpecial(finish, foffset);
+ return SimSelection.relative(startSitu, finishSitu);
+ };
+ var preprocess = function (selection) {
+ return selection.match({
+ domRange: function (rng) {
+ var start = SugarElement.fromDom(rng.startContainer);
+ var finish = SugarElement.fromDom(rng.endContainer);
+ return preprocessExact(start, rng.startOffset, finish, rng.endOffset);
+ },
+ relative: preprocessRelative,
+ exact: preprocessExact
+ });
+ };
+
+ var makeRange = function (start, soffset, finish, foffset) {
+ var doc = owner(start);
+ var rng = doc.dom.createRange();
+ rng.setStart(start.dom, soffset);
+ rng.setEnd(finish.dom, foffset);
+ return rng;
+ };
+ var after$3 = function (start, soffset, finish, foffset) {
+ var r = makeRange(start, soffset, finish, foffset);
+ var same = eq(start, finish) && soffset === foffset;
+ return r.collapsed && !same;
+ };
+
+ var getNativeSelection = function (win) {
+ return Optional.from(win.getSelection());
+ };
+ var doSetNativeRange = function (win, rng) {
+ getNativeSelection(win).each(function (selection) {
+ selection.removeAllRanges();
+ selection.addRange(rng);
+ });
+ };
+ var doSetRange = function (win, start, soffset, finish, foffset) {
+ var rng = exactToNative(win, start, soffset, finish, foffset);
+ doSetNativeRange(win, rng);
+ };
+ var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
+ selection.collapse(start.dom, soffset);
+ selection.extend(finish.dom, foffset);
+ };
+ var setRangeFromRelative = function (win, relative) {
+ return diagnose(win, relative).match({
+ ltr: function (start, soffset, finish, foffset) {
+ doSetRange(win, start, soffset, finish, foffset);
+ },
+ rtl: function (start, soffset, finish, foffset) {
+ getNativeSelection(win).each(function (selection) {
+ if (selection.setBaseAndExtent) {
+ selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
+ } else if (selection.extend) {
+ try {
+ setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
+ } catch (e) {
+ doSetRange(win, finish, foffset, start, soffset);
+ }
+ } else {
+ doSetRange(win, finish, foffset, start, soffset);
+ }
+ });
+ }
+ });
+ };
+ var setExact = function (win, start, soffset, finish, foffset) {
+ var relative = preprocessExact(start, soffset, finish, foffset);
+ setRangeFromRelative(win, relative);
+ };
+ var setRelative = function (win, startSitu, finishSitu) {
+ var relative = preprocessRelative(startSitu, finishSitu);
+ setRangeFromRelative(win, relative);
+ };
+ var toNative = function (selection) {
+ var win = SimSelection.getWin(selection).dom;
+ var getDomRange = function (start, soffset, finish, foffset) {
+ return exactToNative(win, start, soffset, finish, foffset);
+ };
+ var filtered = preprocess(selection);
+ return diagnose(win, filtered).match({
+ ltr: getDomRange,
+ rtl: getDomRange
+ });
+ };
+ var readRange = function (selection) {
+ if (selection.rangeCount > 0) {
+ var firstRng = selection.getRangeAt(0);
+ var lastRng = selection.getRangeAt(selection.rangeCount - 1);
+ return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
+ } else {
+ return Optional.none();
+ }
+ };
+ var doGetExact = function (selection) {
+ if (selection.anchorNode === null || selection.focusNode === null) {
+ return readRange(selection);
+ } else {
+ var anchor = SugarElement.fromDom(selection.anchorNode);
+ var focus_1 = SugarElement.fromDom(selection.focusNode);
+ return after$3(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
+ }
+ };
+ var setToElement = function (win, element) {
+ var rng = selectNodeContents(win, element);
+ doSetNativeRange(win, rng);
+ };
+ var getExact = function (win) {
+ return getNativeSelection(win).filter(function (sel) {
+ return sel.rangeCount > 0;
+ }).bind(doGetExact);
+ };
+ var get$b = function (win) {
+ return getExact(win).map(function (range) {
+ return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
+ });
+ };
+ var getFirstRect$1 = function (win, selection) {
+ var rng = asLtrRange(win, selection);
+ return getFirstRect(rng);
+ };
+ var getAtPoint = function (win, x, y) {
+ return fromPoint$1(win, x, y);
+ };
+ var clear = function (win) {
+ getNativeSelection(win).each(function (selection) {
+ return selection.removeAllRanges();
+ });
+ };
+
+ var global$3 = tinymce.util.Tools.resolve('tinymce.util.VK');
+
+ var forward = function (editor, isRoot, cell, actions) {
+ return go(editor, isRoot, next(cell), actions);
+ };
+ var backward = function (editor, isRoot, cell, actions) {
+ return go(editor, isRoot, prev(cell), actions);
+ };
+ var getCellFirstCursorPosition = function (editor, cell) {
+ var selection = SimSelection.exact(cell, 0, cell, 0);
+ return toNative(selection);
+ };
+ var getNewRowCursorPosition = function (editor, table) {
+ var rows = descendants$1(table, 'tr');
+ return last(rows).bind(function (last) {
+ return descendant$1(last, 'td,th').map(function (first) {
+ return getCellFirstCursorPosition(editor, first);
+ });
+ });
+ };
+ var go = function (editor, isRoot, cell, actions) {
+ return cell.fold(Optional.none, Optional.none, function (current, next) {
+ return first(next).map(function (cell) {
+ return getCellFirstCursorPosition(editor, cell);
+ });
+ }, function (current) {
+ return table(current, isRoot).bind(function (table) {
+ var targets = noMenu(current);
+ editor.undoManager.transact(function () {
+ actions.insertRowsAfter(table, targets);
+ });
+ return getNewRowCursorPosition(editor, table);
+ });
+ });
+ };
+ var rootElements = [
+ 'table',
+ 'li',
+ 'dl'
+ ];
+ var handle$1 = function (event, editor, actions) {
+ if (event.keyCode === global$3.TAB) {
+ var body_1 = getBody$1(editor);
+ var isRoot_1 = function (element) {
+ var name$1 = name(element);
+ return eq(element, body_1) || contains(rootElements, name$1);
+ };
+ var rng = editor.selection.getRng();
+ if (rng.collapsed) {
+ var start = SugarElement.fromDom(rng.startContainer);
+ cell(start, isRoot_1).each(function (cell) {
+ event.preventDefault();
+ var navigation = event.shiftKey ? backward : forward;
+ var rng = navigation(editor, isRoot_1, cell, actions);
+ rng.each(function (range) {
+ editor.selection.setRng(range);
+ });
+ });
+ }
+ }
+ };
+
+ var create$3 = function (selection, kill) {
+ return {
+ selection: selection,
+ kill: kill
+ };
+ };
+ var Response = { create: create$3 };
+
+ var create$4 = function (start, soffset, finish, foffset) {
+ return {
+ start: Situ.on(start, soffset),
+ finish: Situ.on(finish, foffset)
+ };
+ };
+ var Situs = { create: create$4 };
+
+ var convertToRange = function (win, selection) {
+ var rng = asLtrRange(win, selection);
+ return SimRange.create(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset);
+ };
+ var makeSitus = Situs.create;
+
+ var sync = function (container, isRoot, start, soffset, finish, foffset, selectRange) {
+ if (!(eq(start, finish) && soffset === foffset)) {
+ return closest$1(start, 'td,th', isRoot).bind(function (s) {
+ return closest$1(finish, 'td,th', isRoot).bind(function (f) {
+ return detect$6(container, isRoot, s, f, selectRange);
+ });
+ });
+ } else {
+ return Optional.none();
+ }
+ };
+ var detect$6 = function (container, isRoot, start, finish, selectRange) {
+ if (!eq(start, finish)) {
+ return identify(start, finish, isRoot).bind(function (cellSel) {
+ var boxes = cellSel.boxes.getOr([]);
+ if (boxes.length > 0) {
+ selectRange(container, boxes, cellSel.start, cellSel.finish);
+ return Optional.some(Response.create(Optional.some(makeSitus(start, 0, start, getEnd(start))), true));
+ } else {
+ return Optional.none();
+ }
+ });
+ } else {
+ return Optional.none();
+ }
+ };
+ var update = function (rows, columns, container, selected, annotations) {
+ var updateSelection = function (newSels) {
+ annotations.clearBeforeUpdate(container);
+ annotations.selectRange(container, newSels.boxes, newSels.start, newSels.finish);
+ return newSels.boxes;
+ };
+ return shiftSelection(selected, rows, columns, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(updateSelection);
+ };
+
+ var traverse = function (item, mode) {
+ return {
+ item: item,
+ mode: mode
+ };
+ };
+ var backtrack = function (universe, item, _direction, transition) {
+ if (transition === void 0) {
+ transition = sidestep;
+ }
+ return universe.property().parent(item).map(function (p) {
+ return traverse(p, transition);
+ });
+ };
+ var sidestep = function (universe, item, direction, transition) {
+ if (transition === void 0) {
+ transition = advance;
+ }
+ return direction.sibling(universe, item).map(function (p) {
+ return traverse(p, transition);
+ });
+ };
+ var advance = function (universe, item, direction, transition) {
+ if (transition === void 0) {
+ transition = advance;
+ }
+ var children = universe.property().children(item);
+ var result = direction.first(children);
+ return result.map(function (r) {
+ return traverse(r, transition);
+ });
+ };
+ var successors = [
+ {
+ current: backtrack,
+ next: sidestep,
+ fallback: Optional.none()
+ },
+ {
+ current: sidestep,
+ next: advance,
+ fallback: Optional.some(backtrack)
+ },
+ {
+ current: advance,
+ next: advance,
+ fallback: Optional.some(sidestep)
+ }
+ ];
+ var go$1 = function (universe, item, mode, direction, rules) {
+ if (rules === void 0) {
+ rules = successors;
+ }
+ var ruleOpt = find(rules, function (succ) {
+ return succ.current === mode;
+ });
+ return ruleOpt.bind(function (rule) {
+ return rule.current(universe, item, direction, rule.next).orThunk(function () {
+ return rule.fallback.bind(function (fb) {
+ return go$1(universe, item, fb, direction);
+ });
+ });
+ });
+ };
+
+ var left = function () {
+ var sibling = function (universe, item) {
+ return universe.query().prevSibling(item);
+ };
+ var first = function (children) {
+ return children.length > 0 ? Optional.some(children[children.length - 1]) : Optional.none();
+ };
+ return {
+ sibling: sibling,
+ first: first
+ };
+ };
+ var right = function () {
+ var sibling = function (universe, item) {
+ return universe.query().nextSibling(item);
+ };
+ var first = function (children) {
+ return children.length > 0 ? Optional.some(children[0]) : Optional.none();
+ };
+ return {
+ sibling: sibling,
+ first: first
+ };
+ };
+ var Walkers = {
+ left: left,
+ right: right
+ };
+
+ var hone = function (universe, item, predicate, mode, direction, isRoot) {
+ var next = go$1(universe, item, mode, direction);
+ return next.bind(function (n) {
+ if (isRoot(n.item)) {
+ return Optional.none();
+ } else {
+ return predicate(n.item) ? Optional.some(n.item) : hone(universe, n.item, predicate, n.mode, direction, isRoot);
+ }
+ });
+ };
+ var left$1 = function (universe, item, predicate, isRoot) {
+ return hone(universe, item, predicate, sidestep, Walkers.left(), isRoot);
+ };
+ var right$1 = function (universe, item, predicate, isRoot) {
+ return hone(universe, item, predicate, sidestep, Walkers.right(), isRoot);
+ };
+
+ var isLeaf = function (universe) {
+ return function (element) {
+ return universe.property().children(element).length === 0;
+ };
+ };
+ var before$3 = function (universe, item, isRoot) {
+ return seekLeft(universe, item, isLeaf(universe), isRoot);
+ };
+ var after$4 = function (universe, item, isRoot) {
+ return seekRight(universe, item, isLeaf(universe), isRoot);
+ };
+ var seekLeft = left$1;
+ var seekRight = right$1;
+
+ var universe$3 = DomUniverse();
+ var before$4 = function (element, isRoot) {
+ return before$3(universe$3, element, isRoot);
+ };
+ var after$5 = function (element, isRoot) {
+ return after$4(universe$3, element, isRoot);
+ };
+ var seekLeft$1 = function (element, predicate, isRoot) {
+ return seekLeft(universe$3, element, predicate, isRoot);
+ };
+ var seekRight$1 = function (element, predicate, isRoot) {
+ return seekRight(universe$3, element, predicate, isRoot);
+ };
+
+ var ancestor$2 = function (scope, predicate, isRoot) {
+ return ancestor(scope, predicate, isRoot).isSome();
+ };
+
+ var adt$6 = Adt.generate([
+ { none: ['message'] },
+ { success: [] },
+ { failedUp: ['cell'] },
+ { failedDown: ['cell'] }
+ ]);
+ var isOverlapping = function (bridge, before, after) {
+ var beforeBounds = bridge.getRect(before);
+ var afterBounds = bridge.getRect(after);
+ return afterBounds.right > beforeBounds.left && afterBounds.left < beforeBounds.right;
+ };
+ var isRow = function (elem) {
+ return closest$1(elem, 'tr');
+ };
+ var verify = function (bridge, before, beforeOffset, after, afterOffset, failure, isRoot) {
+ return closest$1(after, 'td,th', isRoot).bind(function (afterCell) {
+ return closest$1(before, 'td,th', isRoot).map(function (beforeCell) {
+ if (!eq(afterCell, beforeCell)) {
+ return sharedOne$1(isRow, [
+ afterCell,
+ beforeCell
+ ]).fold(function () {
+ return isOverlapping(bridge, beforeCell, afterCell) ? adt$6.success() : failure(beforeCell);
+ }, function (_sharedRow) {
+ return failure(beforeCell);
+ });
+ } else {
+ return eq(after, afterCell) && getEnd(afterCell) === afterOffset ? failure(beforeCell) : adt$6.none('in same cell');
+ }
+ });
+ }).getOr(adt$6.none('default'));
+ };
+ var cata$2 = function (subject, onNone, onSuccess, onFailedUp, onFailedDown) {
+ return subject.fold(onNone, onSuccess, onFailedUp, onFailedDown);
+ };
+ var BeforeAfter = __assign(__assign({}, adt$6), {
+ verify: verify,
+ cata: cata$2
+ });
+
+ var inParent = function (parent, children, element, index) {
+ return {
+ parent: parent,
+ children: children,
+ element: element,
+ index: index
+ };
+ };
+ var indexInParent = function (element) {
+ return parent(element).bind(function (parent) {
+ var children$1 = children(parent);
+ return indexOf(children$1, element).map(function (index) {
+ return inParent(parent, children$1, element, index);
+ });
+ });
+ };
+ var indexOf = function (elements, element) {
+ return findIndex(elements, curry(eq, element));
+ };
+
+ var isBr = function (elem) {
+ return name(elem) === 'br';
+ };
+ var gatherer = function (cand, gather, isRoot) {
+ return gather(cand, isRoot).bind(function (target) {
+ return isText(target) && get$3(target).trim().length === 0 ? gatherer(target, gather, isRoot) : Optional.some(target);
+ });
+ };
+ var handleBr = function (isRoot, element, direction) {
+ return direction.traverse(element).orThunk(function () {
+ return gatherer(element, direction.gather, isRoot);
+ }).map(direction.relative);
+ };
+ var findBr = function (element, offset) {
+ return child(element, offset).filter(isBr).orThunk(function () {
+ return child(element, offset - 1).filter(isBr);
+ });
+ };
+ var handleParent = function (isRoot, element, offset, direction) {
+ return findBr(element, offset).bind(function (br) {
+ return direction.traverse(br).fold(function () {
+ return gatherer(br, direction.gather, isRoot).map(direction.relative);
+ }, function (adjacent) {
+ return indexInParent(adjacent).map(function (info) {
+ return Situ.on(info.parent, info.index);
+ });
+ });
+ });
+ };
+ var tryBr = function (isRoot, element, offset, direction) {
+ var target = isBr(element) ? handleBr(isRoot, element, direction) : handleParent(isRoot, element, offset, direction);
+ return target.map(function (tgt) {
+ return {
+ start: tgt,
+ finish: tgt
+ };
+ });
+ };
+ var process = function (analysis) {
+ return BeforeAfter.cata(analysis, function (_message) {
+ return Optional.none();
+ }, function () {
+ return Optional.none();
+ }, function (cell) {
+ return Optional.some(point(cell, 0));
+ }, function (cell) {
+ return Optional.some(point(cell, getEnd(cell)));
+ });
+ };
+
+ var moveDown = function (caret, amount) {
+ return {
+ left: caret.left,
+ top: caret.top + amount,
+ right: caret.right,
+ bottom: caret.bottom + amount
+ };
+ };
+ var moveUp = function (caret, amount) {
+ return {
+ left: caret.left,
+ top: caret.top - amount,
+ right: caret.right,
+ bottom: caret.bottom - amount
+ };
+ };
+ var translate = function (caret, xDelta, yDelta) {
+ return {
+ left: caret.left + xDelta,
+ top: caret.top + yDelta,
+ right: caret.right + xDelta,
+ bottom: caret.bottom + yDelta
+ };
+ };
+ var getTop$1 = function (caret) {
+ return caret.top;
+ };
+ var getBottom = function (caret) {
+ return caret.bottom;
+ };
+
+ var getPartialBox = function (bridge, element, offset) {
+ if (offset >= 0 && offset < getEnd(element)) {
+ return bridge.getRangedRect(element, offset, element, offset + 1);
+ } else if (offset > 0) {
+ return bridge.getRangedRect(element, offset - 1, element, offset);
+ }
+ return Optional.none();
+ };
+ var toCaret = function (rect) {
+ return {
+ left: rect.left,
+ top: rect.top,
+ right: rect.right,
+ bottom: rect.bottom
+ };
+ };
+ var getElemBox = function (bridge, element) {
+ return Optional.some(bridge.getRect(element));
+ };
+ var getBoxAt = function (bridge, element, offset) {
+ if (isElement(element)) {
+ return getElemBox(bridge, element).map(toCaret);
+ } else if (isText(element)) {
+ return getPartialBox(bridge, element, offset).map(toCaret);
+ } else {
+ return Optional.none();
+ }
+ };
+ var getEntireBox = function (bridge, element) {
+ if (isElement(element)) {
+ return getElemBox(bridge, element).map(toCaret);
+ } else if (isText(element)) {
+ return bridge.getRangedRect(element, 0, element, getEnd(element)).map(toCaret);
+ } else {
+ return Optional.none();
+ }
+ };
+
+ var JUMP_SIZE = 5;
+ var NUM_RETRIES = 100;
+ var adt$7 = Adt.generate([
+ { none: [] },
+ { retry: ['caret'] }
+ ]);
+ var isOutside = function (caret, box) {
+ return caret.left < box.left || Math.abs(box.right - caret.left) < 1 || caret.left > box.right;
+ };
+ var inOutsideBlock = function (bridge, element, caret) {
+ return closest(element, isBlock$1).fold(never, function (cell) {
+ return getEntireBox(bridge, cell).exists(function (box) {
+ return isOutside(caret, box);
+ });
+ });
+ };
+ var adjustDown = function (bridge, element, guessBox, original, caret) {
+ var lowerCaret = moveDown(caret, JUMP_SIZE);
+ if (Math.abs(guessBox.bottom - original.bottom) < 1) {
+ return adt$7.retry(lowerCaret);
+ } else if (guessBox.top > caret.bottom) {
+ return adt$7.retry(lowerCaret);
+ } else if (guessBox.top === caret.bottom) {
+ return adt$7.retry(moveDown(caret, 1));
+ } else {
+ return inOutsideBlock(bridge, element, caret) ? adt$7.retry(translate(lowerCaret, JUMP_SIZE, 0)) : adt$7.none();
+ }
+ };
+ var adjustUp = function (bridge, element, guessBox, original, caret) {
+ var higherCaret = moveUp(caret, JUMP_SIZE);
+ if (Math.abs(guessBox.top - original.top) < 1) {
+ return adt$7.retry(higherCaret);
+ } else if (guessBox.bottom < caret.top) {
+ return adt$7.retry(higherCaret);
+ } else if (guessBox.bottom === caret.top) {
+ return adt$7.retry(moveUp(caret, 1));
+ } else {
+ return inOutsideBlock(bridge, element, caret) ? adt$7.retry(translate(higherCaret, JUMP_SIZE, 0)) : adt$7.none();
+ }
+ };
+ var upMovement = {
+ point: getTop$1,
+ adjuster: adjustUp,
+ move: moveUp,
+ gather: before$4
+ };
+ var downMovement = {
+ point: getBottom,
+ adjuster: adjustDown,
+ move: moveDown,
+ gather: after$5
+ };
+ var isAtTable = function (bridge, x, y) {
+ return bridge.elementFromPoint(x, y).filter(function (elm) {
+ return name(elm) === 'table';
+ }).isSome();
+ };
+ var adjustForTable = function (bridge, movement, original, caret, numRetries) {
+ return adjustTil(bridge, movement, original, movement.move(caret, JUMP_SIZE), numRetries);
+ };
+ var adjustTil = function (bridge, movement, original, caret, numRetries) {
+ if (numRetries === 0) {
+ return Optional.some(caret);
+ }
+ if (isAtTable(bridge, caret.left, movement.point(caret))) {
+ return adjustForTable(bridge, movement, original, caret, numRetries - 1);
+ }
+ return bridge.situsFromPoint(caret.left, movement.point(caret)).bind(function (guess) {
+ return guess.start.fold(Optional.none, function (element) {
+ return getEntireBox(bridge, element).bind(function (guessBox) {
+ return movement.adjuster(bridge, element, guessBox, original, caret).fold(Optional.none, function (newCaret) {
+ return adjustTil(bridge, movement, original, newCaret, numRetries - 1);
+ });
+ }).orThunk(function () {
+ return Optional.some(caret);
+ });
+ }, Optional.none);
+ });
+ };
+ var ieTryDown = function (bridge, caret) {
+ return bridge.situsFromPoint(caret.left, caret.bottom + JUMP_SIZE);
+ };
+ var ieTryUp = function (bridge, caret) {
+ return bridge.situsFromPoint(caret.left, caret.top - JUMP_SIZE);
+ };
+ var checkScroll = function (movement, adjusted, bridge) {
+ if (movement.point(adjusted) > bridge.getInnerHeight()) {
+ return Optional.some(movement.point(adjusted) - bridge.getInnerHeight());
+ } else if (movement.point(adjusted) < 0) {
+ return Optional.some(-movement.point(adjusted));
+ } else {
+ return Optional.none();
+ }
+ };
+ var retry = function (movement, bridge, caret) {
+ var moved = movement.move(caret, JUMP_SIZE);
+ var adjusted = adjustTil(bridge, movement, caret, moved, NUM_RETRIES).getOr(moved);
+ return checkScroll(movement, adjusted, bridge).fold(function () {
+ return bridge.situsFromPoint(adjusted.left, movement.point(adjusted));
+ }, function (delta) {
+ bridge.scrollBy(0, delta);
+ return bridge.situsFromPoint(adjusted.left, movement.point(adjusted) - delta);
+ });
+ };
+ var Retries = {
+ tryUp: curry(retry, upMovement),
+ tryDown: curry(retry, downMovement),
+ ieTryUp: ieTryUp,
+ ieTryDown: ieTryDown,
+ getJumpSize: constant(JUMP_SIZE)
+ };
+
+ var MAX_RETRIES = 20;
+ var findSpot = function (bridge, isRoot, direction) {
+ return bridge.getSelection().bind(function (sel) {
+ return tryBr(isRoot, sel.finish, sel.foffset, direction).fold(function () {
+ return Optional.some(point(sel.finish, sel.foffset));
+ }, function (brNeighbour) {
+ var range = bridge.fromSitus(brNeighbour);
+ var analysis = BeforeAfter.verify(bridge, sel.finish, sel.foffset, range.finish, range.foffset, direction.failure, isRoot);
+ return process(analysis);
+ });
+ });
+ };
+ var scan$1 = function (bridge, isRoot, element, offset, direction, numRetries) {
+ if (numRetries === 0) {
+ return Optional.none();
+ }
+ return tryCursor(bridge, isRoot, element, offset, direction).bind(function (situs) {
+ var range = bridge.fromSitus(situs);
+ var analysis = BeforeAfter.verify(bridge, element, offset, range.finish, range.foffset, direction.failure, isRoot);
+ return BeforeAfter.cata(analysis, function () {
+ return Optional.none();
+ }, function () {
+ return Optional.some(situs);
+ }, function (cell) {
+ if (eq(element, cell) && offset === 0) {
+ return tryAgain(bridge, element, offset, moveUp, direction);
+ } else {
+ return scan$1(bridge, isRoot, cell, 0, direction, numRetries - 1);
+ }
+ }, function (cell) {
+ if (eq(element, cell) && offset === getEnd(cell)) {
+ return tryAgain(bridge, element, offset, moveDown, direction);
+ } else {
+ return scan$1(bridge, isRoot, cell, getEnd(cell), direction, numRetries - 1);
+ }
+ });
+ });
+ };
+ var tryAgain = function (bridge, element, offset, move, direction) {
+ return getBoxAt(bridge, element, offset).bind(function (box) {
+ return tryAt(bridge, direction, move(box, Retries.getJumpSize()));
+ });
+ };
+ var tryAt = function (bridge, direction, box) {
+ var browser = detect$3().browser;
+ if (browser.isChrome() || browser.isSafari() || browser.isFirefox() || browser.isEdge()) {
+ return direction.otherRetry(bridge, box);
+ } else if (browser.isIE()) {
+ return direction.ieRetry(bridge, box);
+ } else {
+ return Optional.none();
+ }
+ };
+ var tryCursor = function (bridge, isRoot, element, offset, direction) {
+ return getBoxAt(bridge, element, offset).bind(function (box) {
+ return tryAt(bridge, direction, box);
+ });
+ };
+ var handle$2 = function (bridge, isRoot, direction) {
+ return findSpot(bridge, isRoot, direction).bind(function (spot) {
+ return scan$1(bridge, isRoot, spot.element, spot.offset, direction, MAX_RETRIES).map(bridge.fromSitus);
+ });
+ };
+
+ var inSameTable = function (elem, table) {
+ return ancestor$2(elem, function (e) {
+ return parent(e).exists(function (p) {
+ return eq(p, table);
+ });
+ });
+ };
+ var simulate = function (bridge, isRoot, direction, initial, anchor) {
+ return closest$1(initial, 'td,th', isRoot).bind(function (start) {
+ return closest$1(start, 'table', isRoot).bind(function (table) {
+ if (!inSameTable(anchor, table)) {
+ return Optional.none();
+ }
+ return handle$2(bridge, isRoot, direction).bind(function (range) {
+ return closest$1(range.finish, 'td,th', isRoot).map(function (finish) {
+ return {
+ start: start,
+ finish: finish,
+ range: range
+ };
+ });
+ });
+ });
+ });
+ };
+ var navigate = function (bridge, isRoot, direction, initial, anchor, precheck) {
+ if (detect$3().browser.isIE()) {
+ return Optional.none();
+ } else {
+ return precheck(initial, isRoot).orThunk(function () {
+ return simulate(bridge, isRoot, direction, initial, anchor).map(function (info) {
+ var range = info.range;
+ return Response.create(Optional.some(makeSitus(range.start, range.soffset, range.finish, range.foffset)), true);
+ });
+ });
+ }
+ };
+ var firstUpCheck = function (initial, isRoot) {
+ return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
+ return closest$1(startRow, 'table', isRoot).bind(function (table) {
+ var rows = descendants$1(table, 'tr');
+ if (eq(startRow, rows[0])) {
+ return seekLeft$1(table, function (element) {
+ return last$1(element).isSome();
+ }, isRoot).map(function (last) {
+ var lastOffset = getEnd(last);
+ return Response.create(Optional.some(makeSitus(last, lastOffset, last, lastOffset)), true);
+ });
+ } else {
+ return Optional.none();
+ }
+ });
+ });
+ };
+ var lastDownCheck = function (initial, isRoot) {
+ return closest$1(initial, 'tr', isRoot).bind(function (startRow) {
+ return closest$1(startRow, 'table', isRoot).bind(function (table) {
+ var rows = descendants$1(table, 'tr');
+ if (eq(startRow, rows[rows.length - 1])) {
+ return seekRight$1(table, function (element) {
+ return first(element).isSome();
+ }, isRoot).map(function (first) {
+ return Response.create(Optional.some(makeSitus(first, 0, first, 0)), true);
+ });
+ } else {
+ return Optional.none();
+ }
+ });
+ });
+ };
+ var select = function (bridge, container, isRoot, direction, initial, anchor, selectRange) {
+ return simulate(bridge, isRoot, direction, initial, anchor).bind(function (info) {
+ return detect$6(container, isRoot, info.start, info.finish, selectRange);
+ });
+ };
+
+ var value$1 = function () {
+ var subject = Cell(Optional.none());
+ var clear = function () {
+ return subject.set(Optional.none());
+ };
+ var set = function (s) {
+ return subject.set(Optional.some(s));
+ };
+ var isSet = function () {
+ return subject.get().isSome();
+ };
+ var on = function (f) {
+ return subject.get().each(f);
+ };
+ return {
+ clear: clear,
+ set: set,
+ isSet: isSet,
+ on: on
+ };
+ };
+
+ var findCell = function (target, isRoot) {
+ return closest$1(target, 'td,th', isRoot);
+ };
+ function MouseSelection (bridge, container, isRoot, annotations) {
+ var cursor = value$1();
+ var clearstate = cursor.clear;
+ var mousedown = function (event) {
+ annotations.clear(container);
+ findCell(event.target, isRoot).each(cursor.set);
+ };
+ var mouseover = function (event) {
+ cursor.on(function (start) {
+ annotations.clearBeforeUpdate(container);
+ findCell(event.target, isRoot).each(function (finish) {
+ identify(start, finish, isRoot).each(function (cellSel) {
+ var boxes = cellSel.boxes.getOr([]);
+ if (boxes.length > 1 || boxes.length === 1 && !eq(start, finish)) {
+ annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
+ bridge.selectContents(finish);
+ }
+ });
+ });
+ });
+ };
+ var mouseup = function (_event) {
+ clearstate();
+ };
+ return {
+ clearstate: clearstate,
+ mousedown: mousedown,
+ mouseover: mouseover,
+ mouseup: mouseup
+ };
+ }
+
+ var down = {
+ traverse: nextSibling,
+ gather: after$5,
+ relative: Situ.before,
+ otherRetry: Retries.tryDown,
+ ieRetry: Retries.ieTryDown,
+ failure: BeforeAfter.failedDown
+ };
+ var up = {
+ traverse: prevSibling,
+ gather: before$4,
+ relative: Situ.before,
+ otherRetry: Retries.tryUp,
+ ieRetry: Retries.ieTryUp,
+ failure: BeforeAfter.failedUp
+ };
+
+ var isKey = function (key) {
+ return function (keycode) {
+ return keycode === key;
+ };
+ };
+ var isUp = isKey(38);
+ var isDown = isKey(40);
+ var isNavigation = function (keycode) {
+ return keycode >= 37 && keycode <= 40;
+ };
+ var ltr$2 = {
+ isBackward: isKey(37),
+ isForward: isKey(39)
+ };
+ var rtl$2 = {
+ isBackward: isKey(39),
+ isForward: isKey(37)
+ };
+
+ var get$c = function (_DOC) {
+ var doc = _DOC !== undefined ? _DOC.dom : document;
+ var x = doc.body.scrollLeft || doc.documentElement.scrollLeft;
+ var y = doc.body.scrollTop || doc.documentElement.scrollTop;
+ return SugarPosition(x, y);
+ };
+ var by = function (x, y, _DOC) {
+ var doc = _DOC !== undefined ? _DOC.dom : document;
+ var win = doc.defaultView;
+ if (win) {
+ win.scrollBy(x, y);
+ }
+ };
+
+ var WindowBridge = function (win) {
+ var elementFromPoint = function (x, y) {
+ return SugarElement.fromPoint(SugarElement.fromDom(win.document), x, y);
+ };
+ var getRect = function (element) {
+ return element.dom.getBoundingClientRect();
+ };
+ var getRangedRect = function (start, soffset, finish, foffset) {
+ var sel = SimSelection.exact(start, soffset, finish, foffset);
+ return getFirstRect$1(win, sel);
+ };
+ var getSelection = function () {
+ return get$b(win).map(function (exactAdt) {
+ return convertToRange(win, exactAdt);
+ });
+ };
+ var fromSitus = function (situs) {
+ var relative = SimSelection.relative(situs.start, situs.finish);
+ return convertToRange(win, relative);
+ };
+ var situsFromPoint = function (x, y) {
+ return getAtPoint(win, x, y).map(function (exact) {
+ return Situs.create(exact.start, exact.soffset, exact.finish, exact.foffset);
+ });
+ };
+ var clearSelection = function () {
+ clear(win);
+ };
+ var collapseSelection = function (toStart) {
+ if (toStart === void 0) {
+ toStart = false;
+ }
+ get$b(win).each(function (sel) {
+ return sel.fold(function (rng) {
+ return rng.collapse(toStart);
+ }, function (startSitu, finishSitu) {
+ var situ = toStart ? startSitu : finishSitu;
+ setRelative(win, situ, situ);
+ }, function (start, soffset, finish, foffset) {
+ var node = toStart ? start : finish;
+ var offset = toStart ? soffset : foffset;
+ setExact(win, node, offset, node, offset);
+ });
+ });
+ };
+ var selectContents = function (element) {
+ setToElement(win, element);
+ };
+ var setSelection = function (sel) {
+ setExact(win, sel.start, sel.soffset, sel.finish, sel.foffset);
+ };
+ var setRelativeSelection = function (start, finish) {
+ setRelative(win, start, finish);
+ };
+ var getInnerHeight = function () {
+ return win.innerHeight;
+ };
+ var getScrollY = function () {
+ var pos = get$c(SugarElement.fromDom(win.document));
+ return pos.top;
+ };
+ var scrollBy = function (x, y) {
+ by(x, y, SugarElement.fromDom(win.document));
+ };
+ return {
+ elementFromPoint: elementFromPoint,
+ getRect: getRect,
+ getRangedRect: getRangedRect,
+ getSelection: getSelection,
+ fromSitus: fromSitus,
+ situsFromPoint: situsFromPoint,
+ clearSelection: clearSelection,
+ collapseSelection: collapseSelection,
+ setSelection: setSelection,
+ setRelativeSelection: setRelativeSelection,
+ selectContents: selectContents,
+ getInnerHeight: getInnerHeight,
+ getScrollY: getScrollY,
+ scrollBy: scrollBy
+ };
+ };
+
+ var rc = function (rows, cols) {
+ return {
+ rows: rows,
+ cols: cols
+ };
+ };
+ var mouse = function (win, container, isRoot, annotations) {
+ var bridge = WindowBridge(win);
+ var handlers = MouseSelection(bridge, container, isRoot, annotations);
+ return {
+ clearstate: handlers.clearstate,
+ mousedown: handlers.mousedown,
+ mouseover: handlers.mouseover,
+ mouseup: handlers.mouseup
+ };
+ };
+ var keyboard = function (win, container, isRoot, annotations) {
+ var bridge = WindowBridge(win);
+ var clearToNavigate = function () {
+ annotations.clear(container);
+ return Optional.none();
+ };
+ var keydown = function (event, start, soffset, finish, foffset, direction) {
+ var realEvent = event.raw;
+ var keycode = realEvent.which;
+ var shiftKey = realEvent.shiftKey === true;
+ var handler = retrieve(container, annotations.selectedSelector).fold(function () {
+ if (isDown(keycode) && shiftKey) {
+ return curry(select, bridge, container, isRoot, down, finish, start, annotations.selectRange);
+ } else if (isUp(keycode) && shiftKey) {
+ return curry(select, bridge, container, isRoot, up, finish, start, annotations.selectRange);
+ } else if (isDown(keycode)) {
+ return curry(navigate, bridge, isRoot, down, finish, start, lastDownCheck);
+ } else if (isUp(keycode)) {
+ return curry(navigate, bridge, isRoot, up, finish, start, firstUpCheck);
+ } else {
+ return Optional.none;
+ }
+ }, function (selected) {
+ var update$1 = function (attempts) {
+ return function () {
+ var navigation = findMap(attempts, function (delta) {
+ return update(delta.rows, delta.cols, container, selected, annotations);
+ });
+ return navigation.fold(function () {
+ return getEdges(container, annotations.firstSelectedSelector, annotations.lastSelectedSelector).map(function (edges) {
+ var relative = isDown(keycode) || direction.isForward(keycode) ? Situ.after : Situ.before;
+ bridge.setRelativeSelection(Situ.on(edges.first, 0), relative(edges.table));
+ annotations.clear(container);
+ return Response.create(Optional.none(), true);
+ });
+ }, function (_) {
+ return Optional.some(Response.create(Optional.none(), true));
+ });
+ };
+ };
+ if (isDown(keycode) && shiftKey) {
+ return update$1([rc(+1, 0)]);
+ } else if (isUp(keycode) && shiftKey) {
+ return update$1([rc(-1, 0)]);
+ } else if (direction.isBackward(keycode) && shiftKey) {
+ return update$1([
+ rc(0, -1),
+ rc(-1, 0)
+ ]);
+ } else if (direction.isForward(keycode) && shiftKey) {
+ return update$1([
+ rc(0, +1),
+ rc(+1, 0)
+ ]);
+ } else if (isNavigation(keycode) && shiftKey === false) {
+ return clearToNavigate;
+ } else {
+ return Optional.none;
+ }
+ });
+ return handler();
+ };
+ var keyup = function (event, start, soffset, finish, foffset) {
+ return retrieve(container, annotations.selectedSelector).fold(function () {
+ var realEvent = event.raw;
+ var keycode = realEvent.which;
+ var shiftKey = realEvent.shiftKey === true;
+ if (shiftKey === false) {
+ return Optional.none();
+ }
+ if (isNavigation(keycode)) {
+ return sync(container, isRoot, start, soffset, finish, foffset, annotations.selectRange);
+ } else {
+ return Optional.none();
+ }
+ }, Optional.none);
+ };
+ return {
+ keydown: keydown,
+ keyup: keyup
+ };
+ };
+ var external = function (win, container, isRoot, annotations) {
+ var bridge = WindowBridge(win);
+ return function (start, finish) {
+ annotations.clearBeforeUpdate(container);
+ identify(start, finish, isRoot).each(function (cellSel) {
+ var boxes = cellSel.boxes.getOr([]);
+ annotations.selectRange(container, boxes, cellSel.start, cellSel.finish);
+ bridge.selectContents(finish);
+ bridge.collapseSelection();
+ });
+ };
+ };
+
+ var remove$7 = function (element, classes) {
+ each(classes, function (x) {
+ remove$5(element, x);
+ });
+ };
+
+ var addClass = function (clazz) {
+ return function (element) {
+ add$3(element, clazz);
+ };
+ };
+ var removeClasses = function (classes) {
+ return function (element) {
+ remove$7(element, classes);
+ };
+ };
+
+ var byClass = function (ephemera) {
+ var addSelectionClass = addClass(ephemera.selected);
+ var removeSelectionClasses = removeClasses([
+ ephemera.selected,
+ ephemera.lastSelected,
+ ephemera.firstSelected
+ ]);
+ var clear = function (container) {
+ var sels = descendants$1(container, ephemera.selectedSelector);
+ each(sels, removeSelectionClasses);
+ };
+ var selectRange = function (container, cells, start, finish) {
+ clear(container);
+ each(cells, addSelectionClass);
+ add$3(start, ephemera.firstSelected);
+ add$3(finish, ephemera.lastSelected);
+ };
+ return {
+ clearBeforeUpdate: clear,
+ clear: clear,
+ selectRange: selectRange,
+ selectedSelector: ephemera.selectedSelector,
+ firstSelectedSelector: ephemera.firstSelectedSelector,
+ lastSelectedSelector: ephemera.lastSelectedSelector
+ };
+ };
+ var byAttr = function (ephemera, onSelection, onClear) {
+ var removeSelectionAttributes = function (element) {
+ remove(element, ephemera.selected);
+ remove(element, ephemera.firstSelected);
+ remove(element, ephemera.lastSelected);
+ };
+ var addSelectionAttribute = function (element) {
+ set(element, ephemera.selected, '1');
+ };
+ var clear = function (container) {
+ clearBeforeUpdate(container);
+ onClear();
+ };
+ var clearBeforeUpdate = function (container) {
+ var sels = descendants$1(container, ephemera.selectedSelector);
+ each(sels, removeSelectionAttributes);
+ };
+ var selectRange = function (container, cells, start, finish) {
+ clear(container);
+ each(cells, addSelectionAttribute);
+ set(start, ephemera.firstSelected, '1');
+ set(finish, ephemera.lastSelected, '1');
+ onSelection(cells, start, finish);
+ };
+ return {
+ clearBeforeUpdate: clearBeforeUpdate,
+ clear: clear,
+ selectRange: selectRange,
+ selectedSelector: ephemera.selectedSelector,
+ firstSelectedSelector: ephemera.firstSelectedSelector,
+ lastSelectedSelector: ephemera.lastSelectedSelector
+ };
+ };
+ var SelectionAnnotation = {
+ byClass: byClass,
+ byAttr: byAttr
+ };
+
+ var getUpOrLeftCells = function (grid, selectedCells, generators) {
+ var upGrid = grid.slice(0, selectedCells[selectedCells.length - 1].row + 1);
+ var upDetails = toDetailList(upGrid, generators);
+ return bind(upDetails, function (detail) {
+ var slicedCells = detail.cells.slice(0, selectedCells[selectedCells.length - 1].column + 1);
+ return map(slicedCells, function (cell) {
+ return cell.element;
+ });
+ });
+ };
+ var getDownOrRightCells = function (grid, selectedCells, generators) {
+ var downGrid = grid.slice(selectedCells[0].row + selectedCells[0].rowspan - 1, grid.length);
+ var downDetails = toDetailList(downGrid, generators);
+ return bind(downDetails, function (detail) {
+ var slicedCells = detail.cells.slice(selectedCells[0].column + selectedCells[0].colspan - 1, detail.cells.length);
+ return map(slicedCells, function (cell) {
+ return cell.element;
+ });
+ });
+ };
+ var getOtherCells = function (table, target, generators) {
+ var warehouse = Warehouse.fromTable(table);
+ var details = onCells(warehouse, target);
+ return details.map(function (selectedCells) {
+ var grid = toGrid(warehouse, generators, false);
+ var upOrLeftCells = getUpOrLeftCells(grid, selectedCells, generators);
+ var downOrRightCells = getDownOrRightCells(grid, selectedCells, generators);
+ return {
+ upOrLeftCells: upOrLeftCells,
+ downOrRightCells: downOrRightCells
+ };
+ });
+ };
+
+ var hasInternalTarget = function (e) {
+ return has$1(SugarElement.fromDom(e.target), 'ephox-snooker-resizer-bar') === false;
+ };
+ function CellSelection (editor, lazyResize, selectionTargets) {
+ var onSelection = function (cells, start, finish) {
+ selectionTargets.targets().each(function (targets) {
+ var tableOpt = table(start);
+ tableOpt.each(function (table) {
+ var cloneFormats = getCloneElements(editor);
+ var generators = cellOperations(noop, SugarElement.fromDom(editor.getDoc()), cloneFormats);
+ var otherCells = getOtherCells(table, targets, generators);
+ fireTableSelectionChange(editor, cells, start, finish, otherCells);
+ });
+ });
+ };
+ var onClear = function () {
+ return fireTableSelectionClear(editor);
+ };
+ var annotations = SelectionAnnotation.byAttr(ephemera, onSelection, onClear);
+ editor.on('init', function (_e) {
+ var win = editor.getWin();
+ var body = getBody$1(editor);
+ var isRoot = getIsRoot(editor);
+ var syncSelection = function () {
+ var sel = editor.selection;
+ var start = SugarElement.fromDom(sel.getStart());
+ var end = SugarElement.fromDom(sel.getEnd());
+ var shared = sharedOne$1(table, [
+ start,
+ end
+ ]);
+ shared.fold(function () {
+ return annotations.clear(body);
+ }, noop);
+ };
+ var mouseHandlers = mouse(win, body, isRoot, annotations);
+ var keyHandlers = keyboard(win, body, isRoot, annotations);
+ var external$1 = external(win, body, isRoot, annotations);
+ var hasShiftKey = function (event) {
+ return event.raw.shiftKey === true;
+ };
+ editor.on('TableSelectorChange', function (e) {
+ return external$1(e.start, e.finish);
+ });
+ var handleResponse = function (event, response) {
+ if (!hasShiftKey(event)) {
+ return;
+ }
+ if (response.kill) {
+ event.kill();
+ }
+ response.selection.each(function (ns) {
+ var relative = SimSelection.relative(ns.start, ns.finish);
+ var rng = asLtrRange(win, relative);
+ editor.selection.setRng(rng);
+ });
+ };
+ var keyup = function (event) {
+ var wrappedEvent = fromRawEvent$1(event);
+ if (wrappedEvent.raw.shiftKey && isNavigation(wrappedEvent.raw.which)) {
+ var rng = editor.selection.getRng();
+ var start = SugarElement.fromDom(rng.startContainer);
+ var end = SugarElement.fromDom(rng.endContainer);
+ keyHandlers.keyup(wrappedEvent, start, rng.startOffset, end, rng.endOffset).each(function (response) {
+ handleResponse(wrappedEvent, response);
+ });
+ }
+ };
+ var keydown = function (event) {
+ var wrappedEvent = fromRawEvent$1(event);
+ lazyResize().each(function (resize) {
+ return resize.hideBars();
+ });
+ var rng = editor.selection.getRng();
+ var start = SugarElement.fromDom(rng.startContainer);
+ var end = SugarElement.fromDom(rng.endContainer);
+ var direction = onDirection(ltr$2, rtl$2)(SugarElement.fromDom(editor.selection.getStart()));
+ keyHandlers.keydown(wrappedEvent, start, rng.startOffset, end, rng.endOffset, direction).each(function (response) {
+ handleResponse(wrappedEvent, response);
+ });
+ lazyResize().each(function (resize) {
+ return resize.showBars();
+ });
+ };
+ var isLeftMouse = function (raw) {
+ return raw.button === 0;
+ };
+ var isLeftButtonPressed = function (raw) {
+ if (raw.buttons === undefined) {
+ return true;
+ }
+ if (global$2.browser.isEdge() && raw.buttons === 0) {
+ return true;
+ }
+ return (raw.buttons & 1) !== 0;
+ };
+ var dragStart = function (_e) {
+ mouseHandlers.clearstate();
+ };
+ var mouseDown = function (e) {
+ if (isLeftMouse(e) && hasInternalTarget(e)) {
+ mouseHandlers.mousedown(fromRawEvent$1(e));
+ }
+ };
+ var mouseOver = function (e) {
+ if (isLeftButtonPressed(e) && hasInternalTarget(e)) {
+ mouseHandlers.mouseover(fromRawEvent$1(e));
+ }
+ };
+ var mouseUp = function (e) {
+ if (isLeftMouse(e) && hasInternalTarget(e)) {
+ mouseHandlers.mouseup(fromRawEvent$1(e));
+ }
+ };
+ var getDoubleTap = function () {
+ var lastTarget = Cell(SugarElement.fromDom(body));
+ var lastTimeStamp = Cell(0);
+ var touchEnd = function (t) {
+ var target = SugarElement.fromDom(t.target);
+ if (name(target) === 'td' || name(target) === 'th') {
+ var lT = lastTarget.get();
+ var lTS = lastTimeStamp.get();
+ if (eq(lT, target) && t.timeStamp - lTS < 300) {
+ t.preventDefault();
+ external$1(target, target);
+ }
+ }
+ lastTarget.set(target);
+ lastTimeStamp.set(t.timeStamp);
+ };
+ return { touchEnd: touchEnd };
+ };
+ var doubleTap = getDoubleTap();
+ editor.on('dragstart', dragStart);
+ editor.on('mousedown', mouseDown);
+ editor.on('mouseover', mouseOver);
+ editor.on('mouseup', mouseUp);
+ editor.on('touchend', doubleTap.touchEnd);
+ editor.on('keyup', keyup);
+ editor.on('keydown', keydown);
+ editor.on('NodeChange', syncSelection);
+ });
+ return { clear: annotations.clear };
+ }
+
+ var getSelectionTargets = function (editor, selections) {
+ var targets = Cell(Optional.none());
+ var changeHandlers = Cell([]);
+ var findTargets = function () {
+ return getSelectionStartCellOrCaption(getSelectionStart(editor)).bind(function (cellOrCaption) {
+ var table$1 = table(cellOrCaption);
+ var isCaption = function (elem) {
+ return name(elem) === 'caption';
+ };
+ return table$1.map(function (table) {
+ if (isCaption(cellOrCaption)) {
+ return noMenu(cellOrCaption);
+ } else {
+ return forMenu(selections, table, cellOrCaption);
+ }
+ });
+ });
+ };
+ var resetTargets = function () {
+ targets.set(cached(findTargets)());
+ each(changeHandlers.get(), function (handler) {
+ return handler();
+ });
+ };
+ var onSetup = function (api, isDisabled) {
+ var handler = function () {
+ return targets.get().fold(function () {
+ api.setDisabled(true);
+ }, function (targets) {
+ api.setDisabled(isDisabled(targets));
+ });
+ };
+ handler();
+ changeHandlers.set(changeHandlers.get().concat([handler]));
+ return function () {
+ changeHandlers.set(filter(changeHandlers.get(), function (h) {
+ return h !== handler;
+ }));
+ };
+ };
+ var onSetupTable = function (api) {
+ return onSetup(api, function (_) {
+ return false;
+ });
+ };
+ var onSetupCellOrRow = function (api) {
+ return onSetup(api, function (targets) {
+ return name(targets.element) === 'caption';
+ });
+ };
+ var onSetupPasteable = function (getClipboardData) {
+ return function (api) {
+ return onSetup(api, function (targets) {
+ return name(targets.element) === 'caption' || getClipboardData().isNone();
+ });
+ };
+ };
+ var onSetupMergeable = function (api) {
+ return onSetup(api, function (targets) {
+ return targets.mergable.isNone();
+ });
+ };
+ var onSetupUnmergeable = function (api) {
+ return onSetup(api, function (targets) {
+ return targets.unmergable.isNone();
+ });
+ };
+ editor.on('NodeChange ExecCommand TableSelectorChange', resetTargets);
+ return {
+ onSetupTable: onSetupTable,
+ onSetupCellOrRow: onSetupCellOrRow,
+ onSetupPasteable: onSetupPasteable,
+ onSetupMergeable: onSetupMergeable,
+ onSetupUnmergeable: onSetupUnmergeable,
+ resetTargets: resetTargets,
+ targets: function () {
+ return targets.get();
+ }
+ };
+ };
+
+ var addButtons = function (editor, selectionTargets, clipboard) {
+ editor.ui.registry.addMenuButton('table', {
+ tooltip: 'Table',
+ icon: 'table',
+ fetch: function (callback) {
+ return callback('inserttable | cell row column | advtablesort | tableprops deletetable');
+ }
+ });
+ var cmd = function (command) {
+ return function () {
+ return editor.execCommand(command);
+ };
+ };
+ editor.ui.registry.addButton('tableprops', {
+ tooltip: 'Table properties',
+ onAction: cmd('mceTableProps'),
+ icon: 'table',
+ onSetup: selectionTargets.onSetupTable
+ });
+ editor.ui.registry.addButton('tabledelete', {
+ tooltip: 'Delete table',
+ onAction: cmd('mceTableDelete'),
+ icon: 'table-delete-table',
+ onSetup: selectionTargets.onSetupTable
+ });
+ editor.ui.registry.addButton('tablecellprops', {
+ tooltip: 'Cell properties',
+ onAction: cmd('mceTableCellProps'),
+ icon: 'table-cell-properties',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablemergecells', {
+ tooltip: 'Merge cells',
+ onAction: cmd('mceTableMergeCells'),
+ icon: 'table-merge-cells',
+ onSetup: selectionTargets.onSetupMergeable
+ });
+ editor.ui.registry.addButton('tablesplitcells', {
+ tooltip: 'Split cell',
+ onAction: cmd('mceTableSplitCells'),
+ icon: 'table-split-cells',
+ onSetup: selectionTargets.onSetupUnmergeable
+ });
+ editor.ui.registry.addButton('tableinsertrowbefore', {
+ tooltip: 'Insert row before',
+ onAction: cmd('mceTableInsertRowBefore'),
+ icon: 'table-insert-row-above',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tableinsertrowafter', {
+ tooltip: 'Insert row after',
+ onAction: cmd('mceTableInsertRowAfter'),
+ icon: 'table-insert-row-after',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tabledeleterow', {
+ tooltip: 'Delete row',
+ onAction: cmd('mceTableDeleteRow'),
+ icon: 'table-delete-row',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablerowprops', {
+ tooltip: 'Row properties',
+ onAction: cmd('mceTableRowProps'),
+ icon: 'table-row-properties',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tableinsertcolbefore', {
+ tooltip: 'Insert column before',
+ onAction: cmd('mceTableInsertColBefore'),
+ icon: 'table-insert-column-before',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tableinsertcolafter', {
+ tooltip: 'Insert column after',
+ onAction: cmd('mceTableInsertColAfter'),
+ icon: 'table-insert-column-after',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tabledeletecol', {
+ tooltip: 'Delete column',
+ onAction: cmd('mceTableDeleteCol'),
+ icon: 'table-delete-column',
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablecutrow', {
+ tooltip: 'Cut row',
+ icon: 'cut-row',
+ onAction: cmd('mceTableCutRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablecopyrow', {
+ tooltip: 'Copy row',
+ icon: 'duplicate-row',
+ onAction: cmd('mceTableCopyRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablepasterowbefore', {
+ tooltip: 'Paste row before',
+ icon: 'paste-row-before',
+ onAction: cmd('mceTablePasteRowBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ editor.ui.registry.addButton('tablepasterowafter', {
+ tooltip: 'Paste row after',
+ icon: 'paste-row-after',
+ onAction: cmd('mceTablePasteRowAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ editor.ui.registry.addButton('tablecutcol', {
+ tooltip: 'Cut column',
+ icon: 'cut-column',
+ onAction: cmd('mceTableCutCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablecopycol', {
+ tooltip: 'Copy column',
+ icon: 'duplicate-column',
+ onAction: cmd('mceTableCopyCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addButton('tablepastecolbefore', {
+ tooltip: 'Paste column before',
+ icon: 'paste-column-before',
+ onAction: cmd('mceTablePasteColBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ editor.ui.registry.addButton('tablepastecolafter', {
+ tooltip: 'Paste column after',
+ icon: 'paste-column-after',
+ onAction: cmd('mceTablePasteColAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ editor.ui.registry.addButton('tableinsertdialog', {
+ tooltip: 'Insert table',
+ onAction: cmd('mceInsertTable'),
+ icon: 'table'
+ });
+ };
+ var addToolbars = function (editor) {
+ var isTable = function (table) {
+ return editor.dom.is(table, 'table') && editor.getBody().contains(table);
+ };
+ var toolbar = getToolbar(editor);
+ if (toolbar.length > 0) {
+ editor.ui.registry.addContextToolbar('table', {
+ predicate: isTable,
+ items: toolbar,
+ scope: 'node',
+ position: 'node'
+ });
+ }
+ };
+
+ var addMenuItems = function (editor, selectionTargets, clipboard) {
+ var cmd = function (command) {
+ return function () {
+ return editor.execCommand(command);
+ };
+ };
+ var insertTableAction = function (_a) {
+ var numRows = _a.numRows, numColumns = _a.numColumns;
+ editor.undoManager.transact(function () {
+ insert$1(editor, numColumns, numRows, 0, 0);
+ });
+ editor.addVisual();
+ };
+ var tableProperties = {
+ text: 'Table properties',
+ onSetup: selectionTargets.onSetupTable,
+ onAction: cmd('mceTableProps')
+ };
+ var deleteTable = {
+ text: 'Delete table',
+ icon: 'table-delete-table',
+ onSetup: selectionTargets.onSetupTable,
+ onAction: cmd('mceTableDelete')
+ };
+ editor.ui.registry.addMenuItem('tableinsertrowbefore', {
+ text: 'Insert row before',
+ icon: 'table-insert-row-above',
+ onAction: cmd('mceTableInsertRowBefore'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tableinsertrowafter', {
+ text: 'Insert row after',
+ icon: 'table-insert-row-after',
+ onAction: cmd('mceTableInsertRowAfter'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tabledeleterow', {
+ text: 'Delete row',
+ icon: 'table-delete-row',
+ onAction: cmd('mceTableDeleteRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablerowprops', {
+ text: 'Row properties',
+ icon: 'table-row-properties',
+ onAction: cmd('mceTableRowProps'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecutrow', {
+ text: 'Cut row',
+ icon: 'cut-row',
+ onAction: cmd('mceTableCutRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecopyrow', {
+ text: 'Copy row',
+ icon: 'duplicate-row',
+ onAction: cmd('mceTableCopyRow'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablepasterowbefore', {
+ text: 'Paste row before',
+ icon: 'paste-row-before',
+ onAction: cmd('mceTablePasteRowBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ editor.ui.registry.addMenuItem('tablepasterowafter', {
+ text: 'Paste row after',
+ icon: 'paste-row-after',
+ onAction: cmd('mceTablePasteRowAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getRows)
+ });
+ var row = {
+ type: 'nestedmenuitem',
+ text: 'Row',
+ getSubmenuItems: function () {
+ return 'tableinsertrowbefore tableinsertrowafter tabledeleterow tablerowprops | tablecutrow tablecopyrow tablepasterowbefore tablepasterowafter';
+ }
+ };
+ editor.ui.registry.addMenuItem('tableinsertcolumnbefore', {
+ text: 'Insert column before',
+ icon: 'table-insert-column-before',
+ onAction: cmd('mceTableInsertColBefore'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tableinsertcolumnafter', {
+ text: 'Insert column after',
+ icon: 'table-insert-column-after',
+ onAction: cmd('mceTableInsertColAfter'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tabledeletecolumn', {
+ text: 'Delete column',
+ icon: 'table-delete-column',
+ onAction: cmd('mceTableDeleteCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecutcolumn', {
+ text: 'Cut column',
+ icon: 'cut-column',
+ onAction: cmd('mceTableCutCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablecopycolumn', {
+ text: 'Copy column',
+ icon: 'duplicate-column',
+ onAction: cmd('mceTableCopyCol'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablepastecolumnbefore', {
+ text: 'Paste column before',
+ icon: 'paste-column-before',
+ onAction: cmd('mceTablePasteColBefore'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ editor.ui.registry.addMenuItem('tablepastecolumnafter', {
+ text: 'Paste column after',
+ icon: 'paste-column-after',
+ onAction: cmd('mceTablePasteColAfter'),
+ onSetup: selectionTargets.onSetupPasteable(clipboard.getColumns)
+ });
+ var column = {
+ type: 'nestedmenuitem',
+ text: 'Column',
+ getSubmenuItems: function () {
+ return 'tableinsertcolumnbefore tableinsertcolumnafter tabledeletecolumn | tablecutcolumn tablecopycolumn tablepastecolumnbefore tablepastecolumnafter';
+ }
+ };
+ editor.ui.registry.addMenuItem('tablecellprops', {
+ text: 'Cell properties',
+ icon: 'table-cell-properties',
+ onAction: cmd('mceTableCellProps'),
+ onSetup: selectionTargets.onSetupCellOrRow
+ });
+ editor.ui.registry.addMenuItem('tablemergecells', {
+ text: 'Merge cells',
+ icon: 'table-merge-cells',
+ onAction: cmd('mceTableMergeCells'),
+ onSetup: selectionTargets.onSetupMergeable
+ });
+ editor.ui.registry.addMenuItem('tablesplitcells', {
+ text: 'Split cell',
+ icon: 'table-split-cells',
+ onAction: cmd('mceTableSplitCells'),
+ onSetup: selectionTargets.onSetupUnmergeable
+ });
+ var cell = {
+ type: 'nestedmenuitem',
+ text: 'Cell',
+ getSubmenuItems: function () {
+ return 'tablecellprops tablemergecells tablesplitcells';
+ }
+ };
+ if (hasTableGrid(editor) === false) {
+ editor.ui.registry.addMenuItem('inserttable', {
+ text: 'Table',
+ icon: 'table',
+ onAction: cmd('mceInsertTable')
+ });
+ } else {
+ editor.ui.registry.addNestedMenuItem('inserttable', {
+ text: 'Table',
+ icon: 'table',
+ getSubmenuItems: function () {
+ return [{
+ type: 'fancymenuitem',
+ fancytype: 'inserttable',
+ onAction: insertTableAction
+ }];
+ }
+ });
+ }
+ editor.ui.registry.addMenuItem('inserttabledialog', {
+ text: 'Insert table',
+ icon: 'table',
+ onAction: cmd('mceInsertTable')
+ });
+ editor.ui.registry.addMenuItem('tableprops', tableProperties);
+ editor.ui.registry.addMenuItem('deletetable', deleteTable);
+ editor.ui.registry.addNestedMenuItem('row', row);
+ editor.ui.registry.addNestedMenuItem('column', column);
+ editor.ui.registry.addNestedMenuItem('cell', cell);
+ editor.ui.registry.addContextMenu('table', {
+ update: function () {
+ selectionTargets.resetTargets();
+ return selectionTargets.targets().fold(function () {
+ return '';
+ }, function (targets) {
+ if (name(targets.element) === 'caption') {
+ return 'tableprops deletetable';
+ } else {
+ return 'cell row column | advtablesort | tableprops deletetable';
+ }
+ });
+ }
+ });
+ };
+
+ function Plugin(editor) {
+ var selections = Selections(function () {
+ return getBody$1(editor);
+ }, function () {
+ return getSelectionStartCellOrCaption(getSelectionStart(editor));
+ }, ephemera.selectedSelector);
+ var selectionTargets = getSelectionTargets(editor, selections);
+ var resizeHandler = getResizeHandler(editor);
+ var cellSelection = CellSelection(editor, resizeHandler.lazyResize, selectionTargets);
+ var actions = TableActions(editor, resizeHandler.lazyWire, selections);
+ var clipboard = Clipboard();
+ registerCommands(editor, actions, cellSelection, selections, clipboard);
+ registerQueryCommands(editor, actions, selections);
+ registerEvents(editor, selections, actions, cellSelection);
+ addMenuItems(editor, selectionTargets, clipboard);
+ addButtons(editor, selectionTargets, clipboard);
+ addToolbars(editor);
+ editor.on('PreInit', function () {
+ editor.serializer.addTempAttr(ephemera.firstSelected);
+ editor.serializer.addTempAttr(ephemera.lastSelected);
+ registerFormats(editor);
+ });
+ if (hasTabNavigation(editor)) {
+ editor.on('keydown', function (e) {
+ handle$1(e, editor, actions);
+ });
+ }
+ editor.on('remove', function () {
+ resizeHandler.destroy();
+ });
+ return getApi(editor, clipboard, resizeHandler, selectionTargets);
+ }
+ function Plugin$1 () {
+ global.add('table', Plugin);
+ }
+
+ Plugin$1();
+
+}());
diff --git a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js
old mode 100755
new mode 100644
index a2aac1e06f..17330b459a
--- a/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js
+++ b/common/static/js/vendor/tinymce/js/tinymce/plugins/table/plugin.min.js
@@ -1 +1,9 @@
-!function(e,t){"use strict";function n(e,t){for(var n,o=[],i=0;i
'),!1):void 0},"childNodes"),t=s(t,!1),d(t,"rowSpan",1),d(t,"colSpan",1),o?t.appendChild(o):n.ie||(t.innerHTML='
'),t}function g(){var e=I.createRng(),t;return i(I.select("tr",a),function(e){0===e.cells.length&&I.remove(e)}),0===I.select("tr",a).length?(e.setStartBefore(a),e.setEndBefore(a),E.setRng(e),void I.remove(a)):(i(I.select("thead,tbody,tfoot",a),function(e){0===e.rows.length&&I.remove(e)}),l(),void(B&&(t=A[Math.min(A.length-1,B.y)],t&&(E.select(t[Math.min(t.length-1,B.x)].elm,!0),E.collapse(!0)))))}function h(e,t,n,o){var i,r,a,l,s;for(i=A[t][e].elm.parentNode,a=1;n>=a;a++)if(i=I.getNext(i,"tr")){for(r=e;r>=0;r--)if(s=A[t+a][r].elm,s.parentNode==i){for(l=1;o>=l;l++)I.insertAfter(p(s),s);break}if(-1==r)for(l=1;o>=l;l++)i.insertBefore(p(i.cells[0]),i.cells[0])}}function v(){i(A,function(e,t){i(e,function(e,n){var i,r,a;if(u(e)&&(e=e.elm,i=o(e,"colspan"),r=o(e,"rowspan"),i>1||r>1)){for(d(e,"rowSpan",1),d(e,"colSpan",1),a=0;i-1>a;a++)I.insertAfter(p(e),e);h(n,t,r-1,i)}})})}function b(t,n,o){var r,a,s,f,m,p,h,b,y,w,x;if(t?(r=S(t),a=r.x,s=r.y,f=a+(n-1),m=s+(o-1)):(B=_=null,i(A,function(e,t){i(e,function(e,n){u(e)&&(B||(B={x:n,y:t}),_={x:n,y:t})})}),B&&(a=B.x,s=B.y,f=_.x,m=_.y)),b=c(a,s),y=c(f,m),b&&y&&b.part==y.part){for(v(),l(),b=c(a,s).elm,d(b,"colSpan",f-a+1),d(b,"rowSpan",m-s+1),h=s;m>=h;h++)for(p=a;f>=p;p++)A[h]&&A[h][p]&&(t=A[h][p].elm,t!=b&&(w=e.grep(t.childNodes),i(w,function(e){b.appendChild(e)}),w.length&&(w=e.grep(b.childNodes),x=0,i(w,function(e){"BR"==e.nodeName&&I.getAttrib(e,"data-mce-bogus")&&x++
'):n.dom.add(n.getBody(),"br",{"data-mce-bogus":"1"}))}),n.on("PreProcess",function(e){var t=e.node.lastChild;t&&("BR"==t.nodeName||1==t.childNodes.length&&("BR"==t.firstChild.nodeName||"\xa0"==t.firstChild.nodeValue))&&t.previousSibling&&"TABLE"==t.previousSibling.nodeName&&n.dom.remove(t)})}function s(){function e(e,t,n,o){var i=3,r=e.dom.getParent(t.startContainer,"TABLE"),a,l,s;return r&&(a=r.parentNode),l=t.startContainer.nodeType==i&&0===t.startOffset&&0===t.endOffset&&o&&("TR"==n.nodeName||n==a),s=("TD"==n.nodeName||"TH"==n.nodeName)&&!o,l||s}function t(){var t=n.selection.getRng(),o=n.selection.getNode(),i=n.dom.getParent(t.startContainer,"TD,TH");if(e(n,t,o,i)){i||(i=o);for(var r=i.lastChild;r.lastChild;)r=r.lastChild;t.setEnd(r,r.nodeValue.length),n.selection.setRng(t)}}n.on("KeyDown",function(){t()}),n.on("MouseDown",function(e){2!=e.button&&t()})}function c(){n.on("keydown",function(t){if((t.keyCode==e.DELETE||t.keyCode==e.BACKSPACE)&&!t.isDefaultPrevented()){var o=n.dom.getParent(n.selection.getStart(),"table");if(o){for(var i=n.dom.select("td,th",o),r=i.length;r--;)if(!n.dom.hasClass(i[r],"mce-item-selected"))return;t.preventDefault(),n.execCommand("mceTableDelete")}}})}c(),t.webkit&&(r(),s()),t.gecko&&(a(),l()),t.ie>10&&(a(),l())}}),o(m,[s,p,c],function(e,t,n){return function(o){function i(){o.getBody().style.webkitUserSelect="",d&&(o.dom.removeClass(o.dom.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"),d=!1)}function r(t){var n,i,r=t.target;if(s&&(l||r!=s)&&("TD"==r.nodeName||"TH"==r.nodeName)){i=a.getParent(r,"table"),i==c&&(l||(l=new e(o,i),l.setStartCell(s),o.getBody().style.webkitUserSelect="none"),l.setEndCell(r),d=!0),n=o.selection.getSel();try{n.removeAllRanges?n.removeAllRanges():n.empty()}catch(u){}t.preventDefault()}}var a=o.dom,l,s,c,d=!0;return o.on("MouseDown",function(e){2!=e.button&&(i(),s=a.getParent(e.target,"td,th"),c=a.getParent(s,"table"))}),o.on("mouseover",r),o.on("remove",function(){a.unbind(o.getDoc(),"mouseover",r)}),o.on("MouseUp",function(){function e(e,o){var r=new t(e,e);do{if(3==e.nodeType&&0!==n.trim(e.nodeValue).length)return void(o?i.setStart(e,0):i.setEnd(e,e.nodeValue.length));if("BR"==e.nodeName)return void(o?i.setStartBefore(e):i.setEndBefore(e))}while(e=o?r.next():r.prev())}var i,r=o.selection,d,u,f,m,p;if(s){if(l&&(o.getBody().style.webkitUserSelect=""),d=a.select("td.mce-item-selected,th.mce-item-selected"),d.length>0){i=a.createRng(),f=d[0],p=d[d.length-1],i.setStartBefore(f),i.setEndAfter(f),e(f,1),u=new t(f,a.getParent(d[0],"table"));do if("TD"==f.nodeName||"TH"==f.nodeName){if(!a.hasClass(f,"mce-item-selected"))break;m=f}while(f=u.next());e(m),r.setRng(i)}o.nodeChanged(),s=l=c=null}}),o.on("KeyUp",function(){i()}),{clear:i}}}),o(g,[s,u,m,c,p,d,h],function(e,t,n,o,i,r,a){function l(o){function i(e){return e?e.replace(/px$/,""):""}function a(e){return/^[0-9]+$/.test(e)&&(e+="px"),e}function l(e){s("left center right".split(" "),function(t){o.formatter.remove("align"+t,{},e)})}function c(){var e=o.dom,t,n;t=e.getParent(o.selection.getStart(),"table"),n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),cellspacing:e.getAttrib(t,"cellspacing"),cellpadding:e.getAttrib(t,"cellpadding"),border:e.getAttrib(t,"border"),caption:!!e.select("caption",t)[0]},s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Table properties",items:{type:"form",layout:"grid",columns:2,data:n,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell spacing",name:"cellspacing"},{label:"Cell padding",name:"cellpadding"},{label:"Border",name:"border"},{label:"Caption",name:"caption",type:"checkbox"},{label:"Alignment",minWidth:90,name:"align",type:"listbox",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var n=this.toJSON(),i;o.undoManager.transact(function(){o.dom.setAttribs(t,{cellspacing:n.cellspacing,cellpadding:n.cellpadding,border:n.border}),o.dom.setStyles(t,{width:a(n.width),height:a(n.height)}),i=e.select("caption",t)[0],i&&!n.caption&&e.remove(i),!i&&n.caption&&(i=e.create("caption"),i.innerHTML=r.ie?"\xa0":'
',t.insertBefore(i,t.firstChild)),l(t),n.align&&o.formatter.apply("align"+n.align,{},t),o.focus(),o.addVisual()})}})}function d(e,t){o.windowManager.open({title:"Merge cells",body:[{label:"Cols",name:"cols",type:"textbox",size:10},{label:"Rows",name:"rows",type:"textbox",size:10}],onsubmit:function(){var n=this.toJSON();o.undoManager.transact(function(){e.merge(t,n.cols,n.rows)})}})}function u(){var e=o.dom,t,n,r=[];r=o.dom.select("td.mce-item-selected,th.mce-item-selected"),t=o.dom.getParent(o.selection.getStart(),"td,th"),!r.length&&t&&r.push(t),t=t||r[0],t&&(n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),scope:e.getAttrib(t,"scope")},n.type=t.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Cell properties",items:{type:"form",data:n,layout:"grid",columns:2,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell type",name:"type",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"Cell",value:"td"},{text:"Header cell",value:"th"}]},{label:"Scope",name:"scope",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Row",value:"row"},{text:"Column",value:"col"},{text:"Row group",value:"rowgroup"},{text:"Column group",value:"colgroup"}]},{label:"Alignment",name:"align",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var t=this.toJSON();o.undoManager.transact(function(){s(r,function(n){o.dom.setAttrib(n,"scope",t.scope),o.dom.setStyles(n,{width:a(t.width),height:a(t.height)}),t.type&&n.nodeName.toLowerCase()!=t.type&&(n=e.rename(n,t.type)),l(n),t.align&&o.formatter.apply("align"+t.align,{},n)}),o.focus()})}}))}function f(){var e=o.dom,t,n,r,c,d=[];t=o.dom.getParent(o.selection.getStart(),"table"),n=o.dom.getParent(o.selection.getStart(),"td,th"),s(t.rows,function(t){s(t.cells,function(o){return e.hasClass(o,"mce-item-selected")||o==n?(d.push(t),!1):void 0})}),r=d[0],r&&(c={height:i(e.getStyle(r,"height")||e.getAttrib(r,"height")),scope:e.getAttrib(r,"scope")},c.type=r.parentNode.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(r,"align"+e)&&(c.align=e)}),o.windowManager.open({title:"Row properties",items:{type:"form",data:c,columns:2,defaults:{type:"textbox"},items:[{type:"listbox",name:"type",label:"Row type",text:"None",maxWidth:null,values:[{text:"Header",value:"thead"},{text:"Body",value:"tbody"},{text:"Footer",value:"tfoot"}]},{type:"listbox",name:"align",label:"Alignment",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{label:"Height",name:"height"}]},onsubmit:function(){var t=this.toJSON(),n,i,r;o.undoManager.transact(function(){var c=t.type;s(d,function(s){o.dom.setAttrib(s,"scope",t.scope),o.dom.setStyles(s,{height:a(t.height)}),c!=s.parentNode.nodeName.toLowerCase()&&(n=e.getParent(s,"table"),i=s.parentNode,r=e.select(c,n)[0],r||(r=e.create(c),n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r)),r.appendChild(s),i.hasChildNodes()||e.remove(i)),l(s),t.align&&o.formatter.apply("align"+t.align,{},s)}),o.focus()})}}))}function m(e){return function(){o.execCommand(e)}}function p(e,t){var n,i,a;for(a="",n=0;t>n;n++){for(a+="
",o.insertContent(a)}function g(e,t){function n(){e.disabled(!o.dom.getParent(o.selection.getStart(),t)),o.selection.selectorChanged(t,function(t){e.disabled(!t)})}o.initialized?n():o.on("init",n)}function h(){g(this,"table")}function v(){g(this,"td,th")}function b(){var e="";e='",i=0;e>i;i++)a+=" "}a+=""+(r.ie?" ":" ";a+="
")+"';for(var t=0;10>t;t++){e+="
",e+='";for(var n=0;10>n;n++)e+=' "}return e+="";e+="
"+t,e.removeChild(e.firstChild)}catch(r){var i=n.create("div");i.innerHTML="
"+t,d(p(i.childNodes),function(t,n){n&&e.canHaveHTML&&e.appendChild(t)})}}else e.innerHTML=t;return t})},getOuterHTML:function(e){var t,n=this;return(e=n.get(e))?1===e.nodeType&&n.hasOuterHTML?e.outerHTML:(t=(e.ownerDocument||n.doc).createElement("body"),t.appendChild(e.cloneNode(!0)),t.innerHTML):null},setOuterHTML:function(e,t,n){var r=this;return r.run(e,function(e){function i(){var i,o;for(o=n.createElement("body"),o.innerHTML=t,i=o.lastChild;i;)r.insertAfter(i.cloneNode(!0),e),i=i.previousSibling;r.remove(e)}if(1==e.nodeType)if(n=n||e.ownerDocument||r.doc,v)try{1==e.nodeType&&r.hasOuterHTML?e.outerHTML=t:i()}catch(o){i()}else i()})},decode:a.decode,encode:a.encodeAllRaw,insertAfter:function(e,t){return t=this.get(t),this.run(e,function(e){var n,r;return n=t.parentNode,r=t.nextSibling,r?n.insertBefore(e,r):n.appendChild(e),e})},replace:function(e,t,n){var r=this;return r.run(t,function(t){return f(t,"array")&&(e=e.cloneNode(!0)),n&&d(p(t.childNodes),function(t){e.appendChild(t)}),t.parentNode.replaceChild(e,t)})},rename:function(e,t){var n=this,r;return e.nodeName!=t.toUpperCase()&&(r=n.create(t),d(n.getAttribs(e),function(t){n.setAttrib(r,t.nodeName,n.getAttrib(e,t.nodeName))}),n.replace(r,e,1)),r||e},findCommonAncestor:function(e,t){for(var n=e,r;n;){for(r=t;r&&n!=r;)r=r.parentNode;if(n==r)break;n=n.parentNode}return!n&&e.ownerDocument?e.ownerDocument.documentElement:n},toHex:function(e){return this.styles.toHex(l.trim(e))},run:function(e,t,n){var r=this,i;return"string"==typeof e&&(e=r.get(e)),e?(n=n||this,e.nodeType||!e.length&&0!==e.length?t.call(n,e):(i=[],d(e,function(e,o){e&&("string"==typeof e&&(e=r.get(e)),i.push(t.call(n,e,o)))}),i)):!1},getAttribs:function(e){var t;if(e=this.get(e),!e)return[];if(v){if(t=[],"OBJECT"==e.nodeName)return e.attributes;"OPTION"===e.nodeName&&this.getAttrib(e,"selected")&&t.push({specified:1,nodeName:"selected"});var n=/<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi;return e.cloneNode(!1).outerHTML.replace(n,"").replace(/[\w:\-]+/gi,function(e){t.push({specified:1,nodeName:e})}),t}return e.attributes},isEmpty:function(e,t){var n=this,r,o,a,s,l,c=0;if(e=e.firstChild){s=new i(e,e.parentNode),t=t||n.schema?n.schema.getNonEmptyElements():null;do{if(a=e.nodeType,1===a){if(e.getAttribute("data-mce-bogus"))continue;if(l=e.nodeName.toLowerCase(),t&&t[l]){if("br"===l){c++;continue}return!1}for(o=n.getAttribs(e),r=e.attributes.length;r--;)if(l=e.attributes[r].nodeName,"name"===l||"data-mce-bookmark"===l)return!1}if(8==a)return!1;if(3===a&&!b.test(e.nodeValue))return!1}while(e=s.next())}return 1>=c},createRng:function(){var e=this.doc;return e.createRange?e.createRange():new o(this)},nodeIndex:function(e,t){var n=0,r,i;if(e)for(r=e.nodeType,e=e.previousSibling;e;e=e.previousSibling)i=e.nodeType,(!t||3!=i||i!=r&&e.nodeValue.length)&&(n++,r=i);return n},split:function(e,t,n){function r(e){function t(e){var t=e.previousSibling&&"SPAN"==e.previousSibling.nodeName,n=e.nextSibling&&"SPAN"==e.nextSibling.nodeName;return t&&n}var n,o=e.childNodes,a=e.nodeType;if(1!=a||"bookmark"!=e.getAttribute("data-mce-type")){for(n=o.length-1;n>=0;n--)r(o[n]);if(9!=a){if(3==a&&e.nodeValue.length>0){var s=m(e.nodeValue).length;if(!i.isBlock(e.parentNode)||s>0||0===s&&t(e))return}else if(1==a&&(o=e.childNodes,1==o.length&&o[0]&&1==o[0].nodeType&&"bookmark"==o[0].getAttribute("data-mce-type")&&e.parentNode.insertBefore(o[0],e),o.length||/^(br|hr|input|img)$/i.test(e.nodeName)))return;i.remove(e)}return e}}var i=this,o=i.createRng(),a,s,l;return e&&t?(o.setStart(e.parentNode,i.nodeIndex(e)),o.setEnd(t.parentNode,i.nodeIndex(t)),a=o.extractContents(),o=i.createRng(),o.setStart(t.parentNode,i.nodeIndex(t)+1),o.setEnd(e.parentNode,i.nodeIndex(e)+1),s=o.extractContents(),l=e.parentNode,l.insertBefore(r(a),e),n?l.replaceChild(n,t):l.insertBefore(t,e),l.insertBefore(r(s),e),i.remove(e),n||t):void 0},bind:function(e,t,n,r){var i=this;if(l.isArray(e)){for(var o=e.length;o--;)e[o]=i.bind(e[o],t,n,r);return e}return!i.settings.collect||e!==i.doc&&e!==i.win||i.boundEvents.push([e,t,n,r]),i.events.bind(e,t,n,r||i)},unbind:function(e,t,n){var r=this,i;if(l.isArray(e)){for(i=e.length;i--;)e[i]=r.unbind(e[i],t,n);return e}if(r.boundEvents&&(e===r.doc||e===r.win))for(i=r.boundEvents.length;i--;){var o=r.boundEvents[i];e!=o[0]||t&&t!=o[1]||n&&n!=o[2]||this.events.unbind(o[0],o[1],o[2])}return this.events.unbind(e,t,n)},fire:function(e,t,n){return this.events.fire(e,t,n)},getContentEditable:function(e){var t;return 1!=e.nodeType?null:(t=e.getAttribute("data-mce-contenteditable"),t&&"inherit"!==t?t:"inherit"!==e.contentEditable?e.contentEditable:null)},destroy:function(){var t=this;if(t.boundEvents){for(var n=t.boundEvents.length;n--;){var r=t.boundEvents[n];this.events.unbind(r[0],r[1],r[2])}t.boundEvents=null}e.setDocument&&e.setDocument(),t.win=t.doc=t.root=t.events=t.frag=null},dumpRng:function(e){return"startContainer: "+e.startContainer.nodeName+", startOffset: "+e.startOffset+", endContainer: "+e.endContainer.nodeName+", endOffset: "+e.endOffset},_findSib:function(e,t,n){var r=this,i=t;if(e)for("string"==typeof i&&(i=function(e){return r.is(e,t)}),e=e[n];e;e=e[n])if(i(e))return e;return null}},u.DOM=new u(document),u}),r(b,[y,p],function(e,t){function n(){function e(e,t){function n(){o.remove(s),a&&(a.onreadystatechange=a.onload=a=null),t()
-}function i(){"undefined"!=typeof console&&console.log&&console.log("Failed to load: "+e)}var o=r,a,s;s=o.uniqueId(),a=document.createElement("script"),a.id=s,a.type="text/javascript",a.src=e,"onreadystatechange"in a?a.onreadystatechange=function(){/loaded|complete/.test(a.readyState)&&n()}:a.onload=n,a.onerror=i,(document.getElementsByTagName("head")[0]||document.body).appendChild(a)}var t=0,n=1,a=2,s={},l=[],c={},u=[],d=0,f;this.isDone=function(e){return s[e]==a},this.markDone=function(e){s[e]=a},this.add=this.load=function(e,n,r){var i=s[e];i==f&&(l.push(e),s[e]=t),n&&(c[e]||(c[e]=[]),c[e].push({func:n,scope:r||this}))},this.loadQueue=function(e,t){this.loadScripts(l,e,t)},this.loadScripts=function(t,r,l){function p(e){i(c[e],function(e){e.func.call(e.scope)}),c[e]=f}var m;u.push({func:r,scope:l||this}),(m=function(){var r=o(t);t.length=0,i(r,function(t){return s[t]==a?void p(t):void(s[t]!=n&&(s[t]=n,d++,e(t,function(){s[t]=a,d--,p(t),m()})))}),d||(i(u,function(e){e.func.call(e.scope)}),u.length=0)})()}}var r=e.DOM,i=t.each,o=t.grep;return n.ScriptLoader=new n,n}),r(C,[b,p],function(e,n){function r(){var e=this;e.items=[],e.urls={},e.lookup={}}var i=n.each;return r.prototype={get:function(e){return this.lookup[e]?this.lookup[e].instance:t},dependencies:function(e){var t;return this.lookup[e]&&(t=this.lookup[e].dependencies),t||[]},requireLangPack:function(t,n){if(r.language&&r.languageLoad!==!1){if(n&&new RegExp("([, ]|\\b)"+r.language+"([, ]|\\b)").test(n)===!1)return;e.ScriptLoader.add(this.urls[t]+"/langs/"+r.language+".js")}},add:function(e,t,n){return this.items.push(t),this.lookup[e]={instance:t,dependencies:n},t},createUrl:function(e,t){return"object"==typeof t?t:{prefix:e.prefix,resource:t,suffix:e.suffix}},addComponents:function(t,n){var r=this.urls[t];i(n,function(t){e.ScriptLoader.add(r+"/"+t)})},load:function(n,o,a,s){function l(){var r=c.dependencies(n);i(r,function(e){var n=c.createUrl(o,e);c.load(n.resource,n,t,t)}),a&&a.call(s?s:e)}var c=this,u=o;c.urls[n]||("object"==typeof o&&(u=o.prefix+o.resource+o.suffix),0!==u.indexOf("/")&&-1==u.indexOf("://")&&(u=r.baseURL+"/"+u),c.urls[n]=u.substring(0,u.lastIndexOf("/")),c.lookup[n]?l():e.ScriptLoader.add(u,l,s))}},r.PluginManager=new r,r.ThemeManager=new r,r}),r(x,[],function(){function e(e,t,n){var r,i,o=n?"lastChild":"firstChild",a=n?"prev":"next";if(e[o])return e[o];if(e!==t){if(r=e[a])return r;for(i=e.parent;i&&i!==t;i=i.parent)if(r=i[a])return r}}function t(e,t){this.name=e,this.type=t,1===t&&(this.attributes=[],this.attributes.map={})}var n=/^[ \t\r\n]*$/,r={"#text":3,"#comment":8,"#cdata":4,"#pi":7,"#doctype":10,"#document-fragment":11};return t.prototype={replace:function(e){var t=this;return e.parent&&e.remove(),t.insert(e,t),t.remove(),t},attr:function(e,t){var n=this,r,i,o;if("string"!=typeof e){for(i in e)n.attr(i,e[i]);return n}if(r=n.attributes){if(t!==o){if(null===t){if(e in r.map)for(delete r.map[e],i=r.length;i--;)if(r[i].name===e)return r=r.splice(i,1),n;return n}if(e in r.map){for(i=r.length;i--;)if(r[i].name===e){r[i].value=t;break}}else r.push({name:e,value:t});return r.map[e]=t,n}return r.map[e]}},clone:function(){var e=this,n=new t(e.name,e.type),r,i,o,a,s;if(o=e.attributes){for(s=[],s.map={},r=0,i=o.length;i>r;r++)a=o[r],"id"!==a.name&&(s[s.length]={name:a.name,value:a.value},s.map[a.name]=a.value);n.attributes=s}return n.value=e.value,n.shortEnded=e.shortEnded,n},wrap:function(e){var t=this;return t.parent.insert(e,t),e.append(t),t},unwrap:function(){var e=this,t,n;for(t=e.firstChild;t;)n=t.next,e.insert(t,e,!0),t=n;e.remove()},remove:function(){var e=this,t=e.parent,n=e.next,r=e.prev;return t&&(t.firstChild===e?(t.firstChild=n,n&&(n.prev=null)):r.next=n,t.lastChild===e?(t.lastChild=r,r&&(r.next=null)):n.prev=r,e.parent=e.next=e.prev=null),e},append:function(e){var t=this,n;return e.parent&&e.remove(),n=t.lastChild,n?(n.next=e,e.prev=n,t.lastChild=e):t.lastChild=t.firstChild=e,e.parent=t,e},insert:function(e,t,n){var r;return e.parent&&e.remove(),r=t.parent||this,n?(t===r.firstChild?r.firstChild=e:t.prev.next=e,e.prev=t.prev,e.next=t,t.prev=e):(t===r.lastChild?r.lastChild=e:t.next.prev=e,e.next=t.next,e.prev=t,t.next=e),e.parent=r,e},getAll:function(t){var n=this,r,i=[];for(r=n.firstChild;r;r=e(r,n))r.name===t&&i.push(r);return i},empty:function(){var t=this,n,r,i;if(t.firstChild){for(n=[],i=t.firstChild;i;i=e(i,t))n.push(i);for(r=n.length;r--;)i=n[r],i.parent=i.firstChild=i.lastChild=i.next=i.prev=null}return t.firstChild=t.lastChild=null,t},isEmpty:function(t){var r=this,i=r.firstChild,o,a;if(i)do{if(1===i.type){if(i.attributes.map["data-mce-bogus"])continue;if(t[i.name])return!1;for(o=i.attributes.length;o--;)if(a=i.attributes[o].name,"name"===a||0===a.indexOf("data-mce-"))return!1}if(8===i.type)return!1;if(3===i.type&&!n.test(i.value))return!1}while(i=e(i,r));return!0},walk:function(t){return e(this,null,t)}},t.create=function(e,n){var i,o;if(i=new t(e,r[e]||1),n)for(o in n)i.attr(o,n[o]);return i},t}),r(w,[p],function(e){function t(e,t){return e?e.split(t||" "):[]}function n(e){function n(e,n,r){function i(e){var t={},n,r;for(n=0,r=e.length;r>n;n++)t[e[n]]={};return t}var o,l,c,u=arguments;for(r=r||[],n=n||"","string"==typeof r&&(r=t(r)),l=3;l
"+(r.item?r.item(0).outerHTML:r.htmlText),i.removeChild(i.firstChild)):i.innerHTML=r.toString(),/^\s/.test(i.innerHTML)&&(a=" "),/\s+$/.test(i.innerHTML)&&(s=" "),e.getInner=!0,e.content=n.isCollapsed()?"":a+n.serializer.serialize(i,e)+s,n.editor.fire("GetContent",e),e.content)},setContent:function(e,t){var n=this,r=n.getRng(),i,o=n.win.document,a,s;if(t=t||{format:"html"},t.set=!0,t.selection=!0,e=t.content=e,t.no_events||n.editor.fire("BeforeSetContent",t),e=t.content,r.insertNode){e+='_',r.startContainer==o&&r.endContainer==o?o.body.innerHTML=e:(r.deleteContents(),0===o.body.childNodes.length?o.body.innerHTML=e:r.createContextualFragment?r.insertNode(r.createContextualFragment(e)):(a=o.createDocumentFragment(),s=o.createElement("div"),a.appendChild(s),s.outerHTML=e,r.insertNode(a))),i=n.dom.get("__caret"),r=o.createRange(),r.setStartBefore(i),r.setEndBefore(i),n.setRng(r),n.dom.remove("__caret");try{n.setRng(r)}catch(l){}}else r.item&&(o.execCommand("Delete",!1,null),r=n.getRng()),/^\s+/.test(e)?(r.pasteHTML('_'+e),n.dom.remove("__mce_tmp")):r.pasteHTML(e);t.no_events||n.editor.fire("SetContent",t)},getStart:function(){var e=this,t=e.getRng(),n,r,i,o;if(t.duplicate||t.item){if(t.item)return t.item(0);for(i=t.duplicate(),i.collapse(1),n=i.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),r=o=t.parentElement();o=o.parentNode;)if(o==n){n=r;break}return n}return n=t.startContainer,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[Math.min(n.childNodes.length-1,t.startOffset)]),n&&3==n.nodeType?n.parentNode:n},getEnd:function(){var e=this,t=e.getRng(),n,r;return t.duplicate||t.item?t.item?t.item(0):(t=t.duplicate(),t.collapse(0),n=t.parentElement(),n.ownerDocument!==e.dom.doc&&(n=e.dom.getRoot()),n&&"BODY"==n.nodeName?n.lastChild||n:n):(n=t.endContainer,r=t.endOffset,1==n.nodeType&&n.hasChildNodes()&&(n=n.childNodes[r>0?r-1:r]),n&&3==n.nodeType?n.parentNode:n)},getBookmark:function(e,t){function n(e,t){var n=0;return l(a.select(e),function(e,r){e==t&&(n=r)}),n}function r(e){function t(t){var n,r,i,o=t?"start":"end";n=e[o+"Container"],r=e[o+"Offset"],1==n.nodeType&&"TR"==n.nodeName&&(i=n.childNodes,n=i[Math.min(t?r:r-1,i.length-1)],n&&(r=t?0:n.childNodes.length,e["set"+(t?"Start":"End")](n,r)))}return t(!0),t(),e}function i(){function e(e,n){var i=e[n?"startContainer":"endContainer"],a=e[n?"startOffset":"endOffset"],s=[],l,c,u=0;if(3==i.nodeType){if(t)for(l=i.previousSibling;l&&3==l.nodeType;l=l.previousSibling)a+=l.nodeValue.length;s.push(a)}else c=i.childNodes,a>=c.length&&c.length&&(u=1,a=Math.max(0,c.length-1)),s.push(o.dom.nodeIndex(c[a],t)+u);for(;i&&i!=r;i=i.parentNode)s.push(o.dom.nodeIndex(i,t));return s}var n=o.getRng(!0),r=a.getRoot(),i={};return i.start=e(n,!0),o.isCollapsed()||(i.end=e(n)),i}var o=this,a=o.dom,s,c,u,d,f,p,m="",h;if(2==e)return p=o.getNode(),f=p?p.nodeName:null,"IMG"==f?{name:f,index:n(f,p)}:o.tridentSel?o.tridentSel.getBookmark(e):i();if(e)return{rng:o.getRng()};if(s=o.getRng(),u=a.uniqueId(),d=o.isCollapsed(),h="overflow:hidden;line-height:0px",s.duplicate||s.item){if(s.item)return p=s.item(0),f=p.nodeName,{name:f,index:n(f,p)};c=s.duplicate();try{s.collapse(),s.pasteHTML(''+m+""),d||(c.collapse(!1),s.moveToElementText(c.parentElement()),0===s.compareEndPoints("StartToEnd",c)&&c.move("character",-1),c.pasteHTML(''+m+""))}catch(g){return null}}else{if(p=o.getNode(),f=p.nodeName,"IMG"==f)return{name:f,index:n(f,p)};c=r(s.cloneRange()),d||(c.collapse(!1),c.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_end",style:h},m))),s=r(s),s.collapse(!0),s.insertNode(a.create("span",{"data-mce-type":"bookmark",id:u+"_start",style:h},m))}return o.moveToBookmark({id:u,keep:1}),{id:u}},moveToBookmark:function(e){function t(t){var n=e[t?"start":"end"],r,i,o,l;if(n){for(o=n[0],i=s,r=n.length-1;r>=1;r--){if(l=i.childNodes,n[r]>l.length-1)return;i=l[n[r]]}3===i.nodeType&&(o=Math.min(n[0],i.nodeValue.length)),1===i.nodeType&&(o=Math.min(n[0],i.childNodes.length)),t?a.setStart(i,o):a.setEnd(i,o)}return!0}function n(t){var n=o.get(e.id+"_"+t),r,i,a,s,d=e.keep;if(n&&(r=n.parentNode,"start"==t?(d?(r=n.firstChild,i=1):i=o.nodeIndex(n),u=p=r,m=h=i):(d?(r=n.firstChild,i=1):i=o.nodeIndex(n),p=r,h=i),!d)){for(s=n.previousSibling,a=n.nextSibling,l(c(n.childNodes),function(e){3==e.nodeType&&(e.nodeValue=e.nodeValue.replace(/\uFEFF/g,""))});n=o.get(e.id+"_"+t);)o.remove(n,1);s&&a&&s.nodeType==a.nodeType&&3==s.nodeType&&!f&&(i=s.nodeValue.length,s.appendData(a.nodeValue),o.remove(a),"start"==t?(u=p=s,m=h=i):(p=s,h=i))}}function r(e){return!o.isBlock(e)||e.innerHTML||d||(e.innerHTML='
'),e}var i=this,o=i.dom,a,s,u,p,m,h;if(e)if(e.start){if(a=o.createRng(),s=o.getRoot(),i.tridentSel)return i.tridentSel.moveToBookmark(e);t(!0)&&t()&&i.setRng(a)}else e.id?(n("start"),n("end"),u&&(a=o.createRng(),a.setStart(r(u),m),a.setEnd(r(p),h),i.setRng(a))):e.name?i.select(o.select(e.name)[e.index]):e.rng&&i.setRng(e.rng)},select:function(e,t){var n=this,r=n.dom,i=r.createRng(),o;if(n.lastFocusBookmark=null,e){if(!t&&n.controlSelection.controlSelect(e))return;o=r.nodeIndex(e),i.setStart(e.parentNode,o),i.setEnd(e.parentNode,o+1),t&&(n._moveEndPoint(i,e,!0),n._moveEndPoint(i,e)),n.setRng(i)}return e},isCollapsed:function(){var e=this,t=e.getRng(),n=e.getSel();return!t||t.item?!1:t.compareEndPoints?0===t.compareEndPoints("StartToEnd",t):!n||t.collapsed},collapse:function(e){var t=this,n=t.getRng(),r;n.item&&(r=n.item(0),n=t.win.document.body.createTextRange(),n.moveToElementText(r)),n.collapse(!!e),t.setRng(n)},getSel:function(){var e=this.win;return e.getSelection?e.getSelection():e.document.selection},getRng:function(e){function t(e,t,n){try{return t.compareBoundaryPoints(e,n)}catch(r){return-1}}var n=this,r,i,o,a=n.win.document,s;if(!e&&n.lastFocusBookmark){var l=n.lastFocusBookmark;return l.startContainer?(i=a.createRange(),i.setStart(l.startContainer,l.startOffset),i.setEnd(l.endContainer,l.endOffset)):i=l,i}if(e&&n.tridentSel)return n.tridentSel.getRangeAt(0);try{(r=n.getSel())&&(i=r.rangeCount>0?r.getRangeAt(0):r.createRange?r.createRange():a.createRange())}catch(c){}if(d&&i&&i.setStart&&a.selection){try{s=a.selection.createRange()}catch(c){}s&&s.item&&(o=s.item(0),i=a.createRange(),i.setStartBefore(o),i.setEndAfter(o))}return i||(i=a.createRange?a.createRange():a.body.createTextRange()),i.setStart&&9===i.startContainer.nodeType&&i.collapsed&&(o=n.dom.getRoot(),i.setStart(o,0),i.setEnd(o,0)),n.selectedRange&&n.explicitRange&&(0===t(i.START_TO_START,i,n.selectedRange)&&0===t(i.END_TO_END,i,n.selectedRange)?i=n.explicitRange:(n.selectedRange=null,n.explicitRange=null)),i},setRng:function(e,t){var n=this,r;if(e.select)try{e.select()}catch(i){}else if(n.tridentSel){if(e.cloneRange)try{return void n.tridentSel.addRange(e)}catch(i){}}else if(r=n.getSel()){n.explicitRange=e;try{r.removeAllRanges(),r.addRange(e)}catch(i){}t===!1&&r.extend&&(r.collapse(e.endContainer,e.endOffset),r.extend(e.startContainer,e.startOffset)),n.selectedRange=r.rangeCount>0?r.getRangeAt(0):null}},setNode:function(e){var t=this;return t.setContent(t.dom.getOuterHTML(e)),e},getNode:function(){function e(e,t){for(var n=e;e&&3===e.nodeType&&0===e.length;)e=t?e.nextSibling:e.previousSibling;return e||n}var t=this,n=t.getRng(),r,i=n.startContainer,o=n.endContainer,a=n.startOffset,s=n.endOffset,l=t.dom.getRoot();return n?n.setStart?(r=n.commonAncestorContainer,!n.collapsed&&(i==o&&2>s-a&&i.hasChildNodes()&&(r=i.childNodes[a]),3===i.nodeType&&3===o.nodeType&&(i=i.length===a?e(i.nextSibling,!0):i.parentNode,o=0===s?e(o.previousSibling,!1):o.parentNode,i&&i===o))?i:r&&3==r.nodeType?r.parentNode:r):(r=n.item?n.item(0):n.parentElement(),r.ownerDocument!==t.win.document&&(r=l),r):l},getSelectedBlocks:function(t,n){var r=this,i=r.dom,o,a,s=[];if(a=i.getRoot(),t=i.getParent(t||r.getStart(),i.isBlock),n=i.getParent(n||r.getEnd(),i.isBlock),t&&t!=a&&s.push(t),t&&n&&t!=n){o=t;for(var l=new e(t,a);(o=l.next())&&o!=n;)i.isBlock(o)&&s.push(o)}return n&&t!=n&&n!=a&&s.push(n),s},isForward:function(){var e=this.dom,t=this.getSel(),n,r;return t&&t.anchorNode&&t.focusNode?(n=e.createRng(),n.setStart(t.anchorNode,t.anchorOffset),n.collapse(!0),r=e.createRng(),r.setStart(t.focusNode,t.focusOffset),r.collapse(!0),n.compareBoundaryPoints(n.START_TO_START,r)<=0):!0},normalize:function(){var e=this,t=e.getRng();return!d&&new i(e.dom).normalize(t)&&e.setRng(t,e.isForward()),t},selectorChanged:function(e,t){var n=this,r;return n.selectorChangedData||(n.selectorChangedData={},r={},n.editor.on("NodeChange",function(e){var t=e.element,i=n.dom,o=i.getParents(t,null,i.getRoot()),a={};l(n.selectorChangedData,function(e,t){l(o,function(n){return i.is(n,t)?(r[t]||(l(e,function(e){e(!0,{node:n,selector:t,parents:o})}),r[t]=e),a[t]=e,!1):void 0})}),l(r,function(e,n){a[n]||(delete r[n],l(e,function(e){e(!1,{node:t,selector:n,parents:o})}))})})),n.selectorChangedData[e]||(n.selectorChangedData[e]=[]),n.selectorChangedData[e].push(t),n},getScrollContainer:function(){for(var e,t=this.dom.getRoot();t&&"BODY"!=t.nodeName;){if(t.scrollHeight>t.clientHeight){e=t;break}t=t.parentNode}return e},scrollIntoView:function(e){function t(e){for(var t=0,n=0,r=e;r&&r.nodeType;)t+=r.offsetLeft||0,n+=r.offsetTop||0,r=r.offsetParent;return{x:t,y:n}}var n,r,i=this,o=i.dom,a=o.getRoot(),s,l;if("BODY"!=a.nodeName){var c=i.getScrollContainer();if(c)return n=t(e).y-t(c).y,l=c.clientHeight,s=c.scrollTop,void((s>n||n+25>s+l)&&(c.scrollTop=s>n?n:n-l+25))}r=o.getViewPort(i.editor.getWin()),n=o.getPos(e).y,s=r.y,l=r.h,(n
'),n}function y(t){var n,r,i;if(3==R.nodeType&&(t?A>0:A
|)$/," "))),e}var a,s,l,c,d,f,p,m,h,g,v;/^ | $/.test(i)&&(i=o(i)),a=r.parser,s=new e({},r.schema),v='ÈB;',f={content:i,format:"html",selection:!0},r.fire("BeforeSetContent",f),i=f.content,-1==i.indexOf("{$caret}")&&(i+="{$caret}"),i=i.replace(/\{\$caret\}/,v),m=_.getRng();var y=m.startContainer||(m.parentElement?m.parentElement():null),b=r.getBody();y===b&&_.isCollapsed()&&w.isBlock(b.firstChild)&&w.isEmpty(b.firstChild)&&(m=w.createRng(),m.setStart(b.firstChild,0),m.setEnd(b.firstChild,0),_.setRng(m)),_.isCollapsed()||r.getDoc().execCommand("Delete",!1,null),l=_.getNode();var C={context:l.nodeName.toLowerCase()};if(d=a.parse(i,C),h=d.lastChild,"mce_marker"==h.attr("id"))for(p=h,h=h.prev;h;h=h.walk(!0))if(3==h.type||!w.isBlock(h.name)){h.parent.insert(p,h,"br"===h.name);break}if(C.invalid){for(_.setContent(v),l=_.getNode(),c=r.getBody(),9==l.nodeType?l=h=c:h=l;h!==c;)l=h,h=h.parentNode;i=l==c?c.innerHTML:w.getOuterHTML(l),i=s.serialize(a.parse(i.replace(//i,function(){return s.serialize(d)}))),l==c?w.setHTML(c,i):w.setOuterHTML(l,i)}else i=s.serialize(d),h=l.firstChild,g=l.lastChild,!h||h===g&&"BR"===h.nodeName?w.setHTML(l,i):_.setContent(i);p=w.get("mce_marker"),_.scrollIntoView(p),m=w.createRng(),h=p.previousSibling,h&&3==h.nodeType?(m.setStart(h,h.nodeValue.length),u||(g=p.nextSibling,g&&3==g.nodeType&&(h.appendData(g.data),g.parentNode.removeChild(g)))):(m.setStartBefore(p),m.setEndBefore(p)),w.remove(p),_.setRng(m),r.fire("SetContent",f),r.addVisual()},mceInsertRawHTML:function(e,t,n){_.setContent("tiny_mce_marker"),r.setContent(r.getContent().replace(/tiny_mce_marker/g,function(){return n}))},mceToggleFormat:function(e,t,n){b(n)},mceSetContent:function(e,t,n){r.setContent(n)},"Indent,Outdent":function(e){var t,n,o;t=E.indentation,n=/[a-z%]+$/i.exec(t),t=parseInt(t,10),m("InsertUnorderedList")||m("InsertOrderedList")?v(e):(E.forced_root_block||w.getParent(_.getNode(),w.isBlock)||S.apply("div"),i(_.getSelectedBlocks(),function(i){if("LI"!=i.nodeName){var a=r.getParam("indent_use_margin",!1)?"margin":"padding";a+="rtl"==w.getStyle(i,"direction",!0)?"Right":"Left","outdent"==e?(o=Math.max(0,parseInt(i.style[a]||0,10)-t),w.setStyle(i,a,o?o+n:"")):(o=parseInt(i.style[a]||0,10)+t+n,w.setStyle(i,a,o))}}))},mceRepaint:function(){if(c)try{C(d),_.getSel()&&_.getSel().selectAllChildren(r.getBody()),_.collapse(d),x()}catch(e){}},InsertHorizontalRule:function(){r.execCommand("mceInsertContent",!1,"
")},mceToggleVisualAid:function(){r.hasVisual=!r.hasVisual,r.addVisual()},mceReplaceContent:function(e,t,n){r.execCommand("mceInsertContent",!1,n.replace(/\{\$selection\}/g,_.getContent({format:"text"})))},mceInsertLink:function(e,t,n){var r;"string"==typeof n&&(n={href:n}),r=w.getParent(_.getNode(),"a"),n.href=n.href.replace(" ","%20"),r&&n.href||S.remove("link"),n.href&&S.apply("link",n,r)},selectAll:function(){var e=w.getRoot(),t;_.getRng().setStart?(t=w.createRng(),t.setStart(e,0),t.setEnd(e,e.childNodes.length),_.setRng(t)):(t=_.getRng(),t.item||(t.moveToElementText(e),t.select()))},"delete":function(){v("Delete");var e=r.getBody();w.isEmpty(e)&&(r.setContent(""),e.firstChild&&w.isBlock(e.firstChild)?r.selection.setCursorLocation(e.firstChild,0):r.selection.setCursorLocation(e,0))},mceNewDocument:function(){r.setContent("")}}),g({"JustifyLeft,JustifyCenter,JustifyRight,JustifyFull":function(e){var t="align"+e.substring(7),n=_.isCollapsed()?[w.getParent(_.getNode(),w.isBlock)]:_.getSelectedBlocks(),r=a(n,function(e){return!!S.matchNode(e,t)});return-1!==s(r,d)},"Bold,Italic,Underline,Strikethrough,Superscript,Subscript":function(e){return y(e)},mceBlockQuote:function(){return y("blockquote")},Outdent:function(){var e;if(E.inline_styles){if((e=w.getParent(_.getStart(),w.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d;if((e=w.getParent(_.getEnd(),w.isBlock))&&parseInt(e.style.paddingLeft,10)>0)return d}return m("InsertUnorderedList")||m("InsertOrderedList")||!E.inline_styles&&!!w.getParent(_.getNode(),"BLOCKQUOTE")},"InsertUnorderedList,InsertOrderedList":function(e){var t=w.getParent(_.getNode(),"ul,ol");return t&&("insertunorderedlist"===e&&"UL"===t.tagName||"insertorderedlist"===e&&"OL"===t.tagName)}},"state"),g({"FontSize,FontName":function(e){var t=0,n;return(n=w.getParent(_.getNode(),"span"))&&(t="fontsize"==e?n.style.fontSize:n.style.fontFamily.replace(/, /g,",").replace(/[\'\"]/g,"").toLowerCase()),t}},"value"),g({Undo:function(){r.undoManager.undo()},Redo:function(){r.undoManager.redo()}})}}),r(I,[p],function(e){function t(e,i){var o=this,a,s;if(e=r(e),i=o.settings=i||{},/^([\w\-]+):([^\/]{2})/i.test(e)||/^\s*#/.test(e))return void(o.source=e);var l=0===e.indexOf("//");0!==e.indexOf("/")||l||(e=(i.base_uri?i.base_uri.protocol||"http":"http")+"://mce_host"+e),/^[\w\-]*:?\/\//.test(e)||(s=i.base_uri?i.base_uri.path:new t(location.href).directory,e=""===i.base_uri.protocol?"//mce_host"+o.toAbsPath(s,e):(i.base_uri&&i.base_uri.protocol||"http")+"://mce_host"+o.toAbsPath(s,e)),e=e.replace(/@@/g,"(mce_at)"),e=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(e),n(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],function(t,n){var r=e[n];r&&(r=r.replace(/\(mce_at\)/g,"@@")),o[t]=r}),a=i.base_uri,a&&(o.protocol||(o.protocol=a.protocol),o.userInfo||(o.userInfo=a.userInfo),o.port||"mce_host"!==o.host||(o.port=a.port),o.host&&"mce_host"!==o.host||(o.host=a.host),o.source=""),l&&(o.protocol="")}var n=e.each,r=e.trim;return t.prototype={setPath:function(e){var t=this;e=/^(.*?)\/?(\w+)?$/.exec(e),t.path=e[0],t.directory=e[1],t.file=e[2],t.source="",t.getURI()},toRelative:function(e){var n=this,r;if("./"===e)return e;if(e=new t(e,{base_uri:n}),"mce_host"!=e.host&&n.host!=e.host&&e.host||n.port!=e.port||n.protocol!=e.protocol&&""!==e.protocol)return e.getURI();var i=n.getURI(),o=e.getURI();return i==o||"/"==i.charAt(i.length-1)&&i.substr(0,i.length-1)==o?i:(r=n.toRelPath(n.path,e.path),e.query&&(r+="?"+e.query),e.anchor&&(r+="#"+e.anchor),r)},toAbsolute:function(e,n){return e=new t(e,{base_uri:this}),e.getURI(this.host==e.host&&this.protocol==e.protocol?n:0)},toRelPath:function(e,t){var n,r=0,i="",o,a;if(e=e.substring(0,e.lastIndexOf("/")),e=e.split("/"),n=t.split("/"),e.length>=n.length)for(o=0,a=e.length;a>o;o++)if(o>=n.length||e[o]!=n[o]){r=o+1;break}if(e.length
]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/,"")}),n.load({initial:!0,format:"html"}),n.startContent=n.getContent({format:"raw"}),n.initialized=!0,R(n._pendingNativeEvents,function(e){n.dom.bind(_(n,e),e,function(e){n.fire(e.type,e)})}),n.fire("init"),n.focus(!0),n.nodeChanged({initial:!0}),n.execCallback("init_instance_callback",n),n.contentStyles.length>0&&(h="",R(n.contentStyles,function(e){h+=e+"\r\n"}),n.dom.addStyle(h)),R(n.contentCSS,function(e){n.loadedCSS[e]||(n.dom.loadCSS(e),n.loadedCSS[e]=!0)}),o.auto_focus&&setTimeout(function(){var e=n.editorManager.get(o.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),f=p=m=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||(o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||(b.opera||n.getBody().focus(),n.getWin().focus()),(H||i)&&(l=n.getBody(),l.setActive&&b.ie<11?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?D(r):0,n=D(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n.data[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n.data[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n.data[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.split(r.indexOf("=")>0?/[;,](?![^=;,]*(?:[;,]|$))/:","),function(e){e=e.split("="),i[L(e[0])]=L(e.length>1?e[1]:e)}):i=r,i):r},nodeChanged:function(){var e=this,t=e.selection,n,r,i;!e.initialized||e.settings.disable_nodechange||e.settings.readonly||(i=e.getBody(),n=t.getStart()||i,n=P&&n.ownerDocument!=e.getDoc()?e.getBody():n,"IMG"==n.nodeName&&t.isCollapsed()&&(n=n.parentNode),r=[],e.dom.getParent(n,function(e){return e===i?!0:void r.push(e)
-}),e.fire("NodeChange",{element:n,parents:r}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),t.text||t.icon||(t.icon=e),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,t,n,r){var i=this,o=0,a;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||r&&r.skip_focus||i.focus(),r=T({},r),r=i.fire("BeforeExecCommand",{command:e,ui:t,value:n}),r.isDefaultPrevented()?!1:(a=i.execCommands[e])&&a.func.call(a.scope,t,n)!==!0?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(R(i.plugins,function(r){return r.execCommand&&r.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),o=!0,!1):void 0}),o?o:i.theme&&i.theme.execCommand&&i.theme.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):i.editorCommands.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(i.getDoc().execCommand(e,t,n),void i.fire("ExecCommand",{command:e,ui:t,value:n})))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;E.show(e.getContainer()),E.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),E.hide(e.getContainer()),E.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!E.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):void 0},save:function(e){var t=this,n=t.getElement(),r,i;if(n&&t.initialized)return e=e||{},e.save=!0,e.element=n,r=e.content=t.getContent(e),e.no_events||t.fire("SaveContent",e),r=e.content,/TEXTAREA|INPUT/i.test(n.nodeName)?n.value=r:(t.inline||(n.innerHTML=r),(i=E.getParent(t.id,"form"))&&R(i.elements,function(e){return e.name==t.id?(e.value=r,!1):void 0})),e.element=n=null,e.set_dirty!==!1&&(t.isNotDirty=!0),r},setContent:function(e,t){var n=this,r=n.getBody(),i;return t=t||{},t.format=t.format||"html",t.set=!0,t.content=e,t.no_events||n.fire("BeforeSetContent",t),e=t.content,0===e.length||/^\s+$/.test(e)?(i=n.settings.forced_root_block,i&&n.schema.isValidChild(r.nodeName.toLowerCase(),i.toLowerCase())?(e=P&&11>P?"":'
',e=n.dom.createHTML(i,n.settings.forced_root_block_attrs,e)):P||(e='
'),r.innerHTML=e,n.fire("SetContent",t)):("raw"!==t.format&&(e=new o({},n.schema).serialize(n.parser.parse(e,{isRootContent:!0}))),t.content=L(e),n.dom.setHTML(r,t.content),t.no_events||n.fire("SetContent",t)),t.content},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty},getContainer:function(){var e=this;return e.container||(e.container=E.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return E.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=E.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",t=i.getAttrib(e,"border"),void(t&&"0"!=t||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)));case"A":return void(i.getAttrib(e,"href",!1)||(t=i.getAttrib(e,"name")||e.id,o=r.visual_anchor_class||"mce-item-anchor",t&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))))}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this;if(!e.removed){e.save(),e.fire("remove"),e.off(),e.removed=1,e.hasHiddenInput&&E.remove(e.getElement().nextSibling),E.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc()));var t=e.getContainer();M.unbind(e.getBody()),M.unbind(t),e.editorManager.remove(e),E.remove(t),e.destroy()}},bindNative:function(e){var t=this;t.settings.readonly||(t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e])},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;if(!t.destroyed){if(!e&&!t.removed)return void t.remove();e&&H&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off("beforeunload",t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n._mceOldSubmit&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null),E.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=t.editorContainer=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1}},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return H?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(at,[],function(){var e={};return{rtl:!1,add:function(t,n){for(var r in n)e[r]=n[r];this.rtl=this.rtl||"rtl"===e._dir},translate:function(t){if("undefined"==typeof t)return t;if("string"!=typeof t&&t.raw)return t.raw;if(t.push){var n=t.slice(1);t=(e[t[0]]||t[0]).replace(/\{([^\}]+)\}/g,function(e,t){return n[t]})}return e[t]||t},data:e}}),r(st,[y,g],function(e,t){function n(e){function a(){try{return document.activeElement}catch(e){return document.body}}function s(e){return e&&e.startContainer?{startContainer:e.startContainer,startOffset:e.startOffset,endContainer:e.endContainer,endOffset:e.endOffset}:e}function l(e,t){var n;return t.startContainer?(n=e.getDoc().createRange(),n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset)):n=t,n}function c(e){return!!o.getParent(e,n.isEditorUIElement)}function u(e,t){for(var n=t.getBody();e;){if(e==n)return!0;e=e.parentNode}}function d(n){var d=n.editor;d.on("init",function(){(d.inline||t.ie)&&(d.on("nodechange keyup",function(){var e=document.activeElement;e&&e.id==d.id+"_ifr"&&(e=d.getBody()),u(e,d)&&(d.lastRng=d.selection.getRng())}),t.webkit&&!r&&(r=function(){var t=e.activeEditor;if(t&&t.selection){var n=t.selection.getRng();n&&!n.collapsed&&(d.lastRng=n)}},o.bind(document,"selectionchange",r)))}),d.on("setcontent",function(){d.lastRng=null}),d.on("mousedown",function(){d.selection.lastFocusBookmark=null}),d.on("focusin",function(){var t=e.focusedEditor;d.selection.lastFocusBookmark&&(d.selection.setRng(l(d,d.selection.lastFocusBookmark)),d.selection.lastFocusBookmark=null),t!=d&&(t&&t.fire("blur",{focusedEditor:d}),e.activeEditor=d,e.focusedEditor=d,d.fire("focus",{blurredEditor:t}),d.focus(!0)),d.lastRng=null}),d.on("focusout",function(){window.setTimeout(function(){var t=e.focusedEditor;c(a())||t!=d||(d.fire("blur",{focusedEditor:null}),e.focusedEditor=null,d.selection&&(d.selection.lastFocusBookmark=null))},0)}),i||(i=function(t){var n=e.activeEditor;n&&t.target.ownerDocument==document&&(n.selection&&(n.selection.lastFocusBookmark=s(n.lastRng)),c(t.target)||e.focusedEditor!=n||(n.fire("blur",{focusedEditor:null}),e.focusedEditor=null))},o.bind(document,"focusin",i))}function f(t){e.focusedEditor==t.editor&&(e.focusedEditor=null),e.activeEditor||(o.unbind(document,"selectionchange",r),o.unbind(document,"focusin",i),r=i=null)}e.on("AddEditor",d),e.on("RemoveEditor",f)}var r,i,o=e.DOM;return n.isEditorUIElement=function(e){return-1!==e.className.toString().indexOf("mce-")},n}),r(lt,[ot,y,I,g,p,rt,at,st],function(e,n,r,i,o,a,s,l){var c=n.DOM,u=o.explode,d=o.each,f=o.extend,p=0,m,h={majorVersion:"4",minorVersion:"0.20",releaseDate:"2014-03-18",editors:[],i18n:s,activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;s
)$/,o+"$1"],[/\n/g,"
"]]),-1!=e.indexOf("
")&&(e=o+e)),r(e)}function o(){var t=i.dom,n=i.getBody(),r=i.dom.getViewPort(i.getWin()),a=r.y,o=20,s;if(h=i.selection.getRng(),i.inline&&(s=i.selection.getScrollContainer(),s&&(a=s.scrollTop)),h.getClientRects){var c=h.getClientRects();if(c.length)o=a+(c[0].top-t.getPos(n).y);else{o=a;var l=h.startContainer;l&&(3==l.nodeType&&l.parentNode!=n&&(l=l.parentNode),1==l.nodeType&&(o=t.getPos(l,s||n).y))}}v=t.add(i.getBody(),"div",{id:"mcepastebin",contentEditable:!0,"data-mce-bogus":"1",style:"position: absolute; top: "+o+"px;width: 10px; height: 10px; overflow: hidden; opacity: 0"},b),(e.ie||e.gecko)&&t.setStyle(v,"left","rtl"==t.getStyle(n,"direction",!0)?65535:-65535),t.bind(v,"beforedeactivate focusin focusout",function(e){e.stopPropagation()}),v.focus(),i.selection.select(v,!0)}function s(){if(v){for(var e;e=i.dom.get("mcepastebin");)i.dom.remove(e),i.dom.unbind(e);h&&i.selection.setRng(h)}x=!1,v=h=null}function c(){var e=b,t,n;for(t=i.dom.select("div[id=mcepastebin]"),n=t.length;n--;){var r=t[n].innerHTML;e==b&&(e=""),r.length>e.length&&(e=r)}return e}function l(e){var t={};if(e&&e.types){var n=e.getData("Text");n&&n.length>0&&(t["text/plain"]=n);for(var i=0;i \xa0 /gi,""),o(/<\/p>/gi,"\n"),o(/ |\u00a0/gi," "),o(/"/gi,'"'),o(/</gi,"<"),o(/>/gi,">"),o(/&/gi,"&"),t}(o.content))})})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,n,r,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),s=function(e,n){var r,t=(r=n,e.fire("insertCustomChar",{chr:r}).chr);e.execCommand("mceInsertContent",!1,t)},i=function(e){return function(){return e}},o=i(!1),c=i(!0),u=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:o,isSome:o,isNone:c,getOr:r=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:r,orThunk:n,map:u,each:function(){},bind:u,exists:o,forall:c,filter:u,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),g=function(r){var e=i(r),n=function(){return a},t=function(e){return e(r)},a={fold:function(e,n){return n(r)},is:function(e){return r===e},isSome:c,isNone:o,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return g(e(r))},each:function(e){e(r)},bind:t,exists:t,forall:t,filter:function(e){return e(r)?a:l},toArray:function(){return[r]},toString:function(){return"some("+r+")"},equals:function(e){return e.is(r)},equals_:function(e,n){return e.fold(o,function(e){return n(r,e)})}};return a},m={some:g,none:u,from:function(e){return null===e||e===undefined?l:g(e)}},f=(t="array",function(e){return r=typeof(n=e),(null===n?"null":"object"==r&&(Array.prototype.isPrototypeOf(n)||n.constructor&&"Array"===n.constructor.name)?"array":"object"==r&&(String.prototype.isPrototypeOf(n)||n.constructor&&"String"===n.constructor.name)?"string":r)===t;var n,r}),h=Array.prototype.push,p=function(e,n){for(var r=e.length,t=new Array(r),a=0;a
$/i])}function s(e){if(!n.isWordContent(e))return e;var a=[];t.each(r.schema.getBlockElements(),function(e,t){a.push(t)});var o=new RegExp("(?:
[\\s\\r\\n]+|
)*(<\\/?("+a.join("|")+")[^>]*>)(?:
[\\s\\r\\n]+|
)*","g");return e=i.filter(e,[[o,"$1"]]),e=i.filter(e,[[/
/g,"
"],[/
/g," "],[/
/g,"
"]])}function c(e){return(r.settings.paste_remove_styles||r.settings.paste_remove_styles_if_webkit!==!1)&&(e=e.replace(/ style=\"[^\"]+\"/g,"")),e}e.webkit&&(a(c),a(o)),e.ie&&a(s)}}),i(b,[x,d,g,y],function(e,t,n,i){var r;e.add("paste",function(e){function a(){"text"==s.pasteFormat?(this.active(!1),s.pasteFormat="html"):(s.pasteFormat="text",this.active(!0),r||(e.windowManager.alert("Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off."),r=!0))}var o=this,s,c=e.settings;o.clipboard=s=new t(e),o.quirks=new i(e),o.wordFilter=new n(e),e.settings.paste_as_text&&(o.clipboard.pasteFormat="text"),c.paste_preprocess&&e.on("PastePreProcess",function(e){c.paste_preprocess.call(o,o,e)}),c.paste_postprocess&&e.on("PastePostProcess",function(e){c.paste_postprocess.call(o,o,e)}),e.addCommand("mceInsertClipboardContent",function(e,t){t.content&&o.clipboard.pasteHtml(t.content),t.text&&o.clipboard.pasteText(t.text)}),e.paste_block_drop&&e.on("dragend dragover draggesture dragdrop drop drag",function(e){e.preventDefault(),e.stopPropagation()}),e.settings.paste_data_images||e.on("drop",function(e){var t=e.dataTransfer;t&&t.files&&t.files.length>0&&e.preventDefault()}),e.addButton("pastetext",{icon:"pastetext",tooltip:"Paste as text",onclick:a,active:"text"==o.clipboard.pasteFormat}),e.addMenuItem("pastetext",{text:"Paste as text",selectable:!0,active:s.pasteFormat,onclick:a})})}),o([c,d,g,y,b])}(this);
-;tinymce.PluginManager.add("print",function(t){t.addCommand("mcePrint",function(){t.getWin().print()}),t.addButton("print",{title:"Print",cmd:"mcePrint"}),t.addShortcut("Ctrl+P","","mcePrint"),t.addMenuItem("print",{text:"Print",cmd:"mcePrint",icon:"print",shortcut:"Ctrl+P",context:"file"})});
-;tinymce.PluginManager.add("save",function(e){function a(){var a;if(a=tinymce.DOM.getParent(e.id,"form"),!e.getParam("save_enablewhendirty",!0)||e.isDirty())return tinymce.triggerSave(),e.getParam("save_onsavecallback")?void(e.execCallback("save_onsavecallback",e)&&(e.startContent=tinymce.trim(e.getContent({format:"raw"})),e.nodeChanged())):void(a?(e.isNotDirty=!0,a.onsubmit&&!a.onsubmit()||("function"==typeof a.submit?a.submit():e.windowManager.alert("Error: Form submit field collision.")),e.nodeChanged()):e.windowManager.alert("Error: No form element found."))}function n(){var a=tinymce.trim(e.startContent);return e.getParam("save_oncancelcallback")?void e.execCallback("save_oncancelcallback",e):(e.setContent(a),e.undoManager.clear(),void e.nodeChanged())}function t(){var a=this;e.on("nodeChange",function(){a.disabled(e.getParam("save_enablewhendirty",!0)&&!e.isDirty())})}e.addCommand("mceSave",a),e.addCommand("mceCancel",n),e.addButton("save",{icon:"save",text:"Save",cmd:"mceSave",disabled:!0,onPostRender:t}),e.addButton("cancel",{text:"Cancel",icon:!1,cmd:"mceCancel",disabled:!0,onPostRender:t}),e.addShortcut("ctrl+s","","mceSave")});
-;!function(){function e(e,t,n,a,r){function i(e,t){if(t=t||0,!e[0])throw"findAndReplaceDOMText cannot handle zero-length matches";var n=e.index;if(t>0){var a=e[t];if(!a)throw"Invalid capture group";n+=e[0].indexOf(a),e[0]=a}return[n,n+e[0].length,[e[0]]]}function d(e){var t;if(3===e.nodeType)return e.data;if(h[e.nodeName]&&!u[e.nodeName])return"";if(t="",(u[e.nodeName]||m[e.nodeName])&&(t+="\n"),e=e.firstChild)do t+=d(e);while(e=e.nextSibling);return t}function o(e,t,n){var a,r,i,d,o=[],l=0,c=e,s=t.shift(),f=0;e:for(;;){if((u[c.nodeName]||m[c.nodeName])&&l++,3===c.nodeType&&(!r&&c.length+l>=s[1]?(r=c,d=s[1]-l):a&&o.push(c),!a&&c.length+l>s[0]&&(a=c,i=s[0]-l),l+=c.length),a&&r){if(c=n({startNode:a,startNodeIndex:i,endNode:r,endNodeIndex:d,innerNodes:o,match:s[2],matchIndex:f}),l-=r.length-d,a=null,r=null,o=[],s=t.shift(),f++,!s)break}else{if((!h[c.nodeName]||u[c.nodeName])&&c.firstChild){c=c.firstChild;continue}if(c.nextSibling){c=c.nextSibling;continue}}for(;;){if(c.nextSibling){c=c.nextSibling;break}if(c.parentNode===e)break e;c=c.parentNode}}}function l(e){var t;if("function"!=typeof e){var n=e.nodeType?e:f.createElement(e);t=function(e,t){var a=n.cloneNode(!1);return a.setAttribute("data-mce-index",t),e&&a.appendChild(f.createTextNode(e)),a}}else t=e;return function(e){var n,a,r,i=e.startNode,d=e.endNode,o=e.matchIndex;if(i===d){var l=i;r=l.parentNode,e.startNodeIndex>0&&(n=f.createTextNode(l.data.substring(0,e.startNodeIndex)),r.insertBefore(n,l));var c=t(e.match[0],o);return r.insertBefore(c,l),e.endNodeIndex
'),!1):void 0},"childNodes"),t=s(t,!1),d(t,"rowSpan",1),d(t,"colSpan",1),o?t.appendChild(o):n.ie||(t.innerHTML='
'),t}function g(){var e=I.createRng(),t;return i(I.select("tr",a),function(e){0===e.cells.length&&I.remove(e)}),0===I.select("tr",a).length?(e.setStartBefore(a),e.setEndBefore(a),E.setRng(e),void I.remove(a)):(i(I.select("thead,tbody,tfoot",a),function(e){0===e.rows.length&&I.remove(e)}),l(),void(B&&(t=A[Math.min(A.length-1,B.y)],t&&(E.select(t[Math.min(t.length-1,B.x)].elm,!0),E.collapse(!0)))))}function h(e,t,n,o){var i,r,a,l,s;for(i=A[t][e].elm.parentNode,a=1;n>=a;a++)if(i=I.getNext(i,"tr")){for(r=e;r>=0;r--)if(s=A[t+a][r].elm,s.parentNode==i){for(l=1;o>=l;l++)I.insertAfter(p(s),s);break}if(-1==r)for(l=1;o>=l;l++)i.insertBefore(p(i.cells[0]),i.cells[0])}}function v(){i(A,function(e,t){i(e,function(e,n){var i,r,a;if(u(e)&&(e=e.elm,i=o(e,"colspan"),r=o(e,"rowspan"),i>1||r>1)){for(d(e,"rowSpan",1),d(e,"colSpan",1),a=0;i-1>a;a++)I.insertAfter(p(e),e);h(n,t,r-1,i)}})})}function b(t,n,o){var r,a,s,f,m,p,h,b,y,w,x;if(t?(r=S(t),a=r.x,s=r.y,f=a+(n-1),m=s+(o-1)):(B=_=null,i(A,function(e,t){i(e,function(e,n){u(e)&&(B||(B={x:n,y:t}),_={x:n,y:t})})}),B&&(a=B.x,s=B.y,f=_.x,m=_.y)),b=c(a,s),y=c(f,m),b&&y&&b.part==y.part){for(v(),l(),b=c(a,s).elm,d(b,"colSpan",f-a+1),d(b,"rowSpan",m-s+1),h=s;m>=h;h++)for(p=a;f>=p;p++)A[h]&&A[h][p]&&(t=A[h][p].elm,t!=b&&(w=e.grep(t.childNodes),i(w,function(e){b.appendChild(e)}),w.length&&(w=e.grep(b.childNodes),x=0,i(w,function(e){"BR"==e.nodeName&&I.getAttrib(e,"data-mce-bogus")&&x++
'):n.dom.add(n.getBody(),"br",{"data-mce-bogus":"1"}))}),n.on("PreProcess",function(e){var t=e.node.lastChild;t&&("BR"==t.nodeName||1==t.childNodes.length&&("BR"==t.firstChild.nodeName||"\xa0"==t.firstChild.nodeValue))&&t.previousSibling&&"TABLE"==t.previousSibling.nodeName&&n.dom.remove(t)})}function s(){function e(e,t,n,o){var i=3,r=e.dom.getParent(t.startContainer,"TABLE"),a,l,s;return r&&(a=r.parentNode),l=t.startContainer.nodeType==i&&0===t.startOffset&&0===t.endOffset&&o&&("TR"==n.nodeName||n==a),s=("TD"==n.nodeName||"TH"==n.nodeName)&&!o,l||s}function t(){var t=n.selection.getRng(),o=n.selection.getNode(),i=n.dom.getParent(t.startContainer,"TD,TH");if(e(n,t,o,i)){i||(i=o);for(var r=i.lastChild;r.lastChild;)r=r.lastChild;t.setEnd(r,r.nodeValue.length),n.selection.setRng(t)}}n.on("KeyDown",function(){t()}),n.on("MouseDown",function(e){2!=e.button&&t()})}function c(){n.on("keydown",function(t){if((t.keyCode==e.DELETE||t.keyCode==e.BACKSPACE)&&!t.isDefaultPrevented()){var o=n.dom.getParent(n.selection.getStart(),"table");if(o){for(var i=n.dom.select("td,th",o),r=i.length;r--;)if(!n.dom.hasClass(i[r],"mce-item-selected"))return;t.preventDefault(),n.execCommand("mceTableDelete")}}})}c(),t.webkit&&(r(),s()),t.gecko&&(a(),l()),t.ie>10&&(a(),l())}}),o(m,[s,p,c],function(e,t,n){return function(o){function i(){o.getBody().style.webkitUserSelect="",d&&(o.dom.removeClass(o.dom.select("td.mce-item-selected,th.mce-item-selected"),"mce-item-selected"),d=!1)}function r(t){var n,i,r=t.target;if(s&&(l||r!=s)&&("TD"==r.nodeName||"TH"==r.nodeName)){i=a.getParent(r,"table"),i==c&&(l||(l=new e(o,i),l.setStartCell(s),o.getBody().style.webkitUserSelect="none"),l.setEndCell(r),d=!0),n=o.selection.getSel();try{n.removeAllRanges?n.removeAllRanges():n.empty()}catch(u){}t.preventDefault()}}var a=o.dom,l,s,c,d=!0;return o.on("MouseDown",function(e){2!=e.button&&(i(),s=a.getParent(e.target,"td,th"),c=a.getParent(s,"table"))}),o.on("mouseover",r),o.on("remove",function(){a.unbind(o.getDoc(),"mouseover",r)}),o.on("MouseUp",function(){function e(e,o){var r=new t(e,e);do{if(3==e.nodeType&&0!==n.trim(e.nodeValue).length)return void(o?i.setStart(e,0):i.setEnd(e,e.nodeValue.length));if("BR"==e.nodeName)return void(o?i.setStartBefore(e):i.setEndBefore(e))}while(e=o?r.next():r.prev())}var i,r=o.selection,d,u,f,m,p;if(s){if(l&&(o.getBody().style.webkitUserSelect=""),d=a.select("td.mce-item-selected,th.mce-item-selected"),d.length>0){i=a.createRng(),f=d[0],p=d[d.length-1],i.setStartBefore(f),i.setEndAfter(f),e(f,1),u=new t(f,a.getParent(d[0],"table"));do if("TD"==f.nodeName||"TH"==f.nodeName){if(!a.hasClass(f,"mce-item-selected"))break;m=f}while(f=u.next());e(m),r.setRng(i)}o.nodeChanged(),s=l=c=null}}),o.on("KeyUp",function(){i()}),{clear:i}}}),o(g,[s,u,m,c,p,d,h],function(e,t,n,o,i,r,a){function l(o){function i(e){return e?e.replace(/px$/,""):""}function a(e){return/^[0-9]+$/.test(e)&&(e+="px"),e}function l(e){s("left center right".split(" "),function(t){o.formatter.remove("align"+t,{},e)})}function c(){var e=o.dom,t,n;t=e.getParent(o.selection.getStart(),"table"),n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),cellspacing:e.getAttrib(t,"cellspacing"),cellpadding:e.getAttrib(t,"cellpadding"),border:e.getAttrib(t,"border"),caption:!!e.select("caption",t)[0]},s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Table properties",items:{type:"form",layout:"grid",columns:2,data:n,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell spacing",name:"cellspacing"},{label:"Cell padding",name:"cellpadding"},{label:"Border",name:"border"},{label:"Caption",name:"caption",type:"checkbox"},{label:"Alignment",minWidth:90,name:"align",type:"listbox",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var n=this.toJSON(),i;o.undoManager.transact(function(){o.dom.setAttribs(t,{cellspacing:n.cellspacing,cellpadding:n.cellpadding,border:n.border}),o.dom.setStyles(t,{width:a(n.width),height:a(n.height)}),i=e.select("caption",t)[0],i&&!n.caption&&e.remove(i),!i&&n.caption&&(i=e.create("caption"),i.innerHTML=r.ie?"\xa0":'
',t.insertBefore(i,t.firstChild)),l(t),n.align&&o.formatter.apply("align"+n.align,{},t),o.focus(),o.addVisual()})}})}function d(e,t){o.windowManager.open({title:"Merge cells",body:[{label:"Cols",name:"cols",type:"textbox",size:10},{label:"Rows",name:"rows",type:"textbox",size:10}],onsubmit:function(){var n=this.toJSON();o.undoManager.transact(function(){e.merge(t,n.cols,n.rows)})}})}function u(){var e=o.dom,t,n,r=[];r=o.dom.select("td.mce-item-selected,th.mce-item-selected"),t=o.dom.getParent(o.selection.getStart(),"td,th"),!r.length&&t&&r.push(t),t=t||r[0],t&&(n={width:i(e.getStyle(t,"width")||e.getAttrib(t,"width")),height:i(e.getStyle(t,"height")||e.getAttrib(t,"height")),scope:e.getAttrib(t,"scope")},n.type=t.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(t,"align"+e)&&(n.align=e)}),o.windowManager.open({title:"Cell properties",items:{type:"form",data:n,layout:"grid",columns:2,defaults:{type:"textbox",maxWidth:50},items:[{label:"Width",name:"width"},{label:"Height",name:"height"},{label:"Cell type",name:"type",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"Cell",value:"td"},{text:"Header cell",value:"th"}]},{label:"Scope",name:"scope",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Row",value:"row"},{text:"Column",value:"col"},{text:"Row group",value:"rowgroup"},{text:"Column group",value:"colgroup"}]},{label:"Alignment",name:"align",type:"listbox",text:"None",minWidth:90,maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]},onsubmit:function(){var t=this.toJSON();o.undoManager.transact(function(){s(r,function(n){o.dom.setAttrib(n,"scope",t.scope),o.dom.setStyles(n,{width:a(t.width),height:a(t.height)}),t.type&&n.nodeName.toLowerCase()!=t.type&&(n=e.rename(n,t.type)),l(n),t.align&&o.formatter.apply("align"+t.align,{},n)}),o.focus()})}}))}function f(){var e=o.dom,t,n,r,c,d=[];t=o.dom.getParent(o.selection.getStart(),"table"),n=o.dom.getParent(o.selection.getStart(),"td,th"),s(t.rows,function(t){s(t.cells,function(o){return e.hasClass(o,"mce-item-selected")||o==n?(d.push(t),!1):void 0})}),r=d[0],r&&(c={height:i(e.getStyle(r,"height")||e.getAttrib(r,"height")),scope:e.getAttrib(r,"scope")},c.type=r.parentNode.nodeName.toLowerCase(),s("left center right".split(" "),function(e){o.formatter.matchNode(r,"align"+e)&&(c.align=e)}),o.windowManager.open({title:"Row properties",items:{type:"form",data:c,columns:2,defaults:{type:"textbox"},items:[{type:"listbox",name:"type",label:"Row type",text:"None",maxWidth:null,values:[{text:"Header",value:"thead"},{text:"Body",value:"tbody"},{text:"Footer",value:"tfoot"}]},{type:"listbox",name:"align",label:"Alignment",text:"None",maxWidth:null,values:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{label:"Height",name:"height"}]},onsubmit:function(){var t=this.toJSON(),n,i,r;o.undoManager.transact(function(){var c=t.type;s(d,function(s){o.dom.setAttrib(s,"scope",t.scope),o.dom.setStyles(s,{height:a(t.height)}),c!=s.parentNode.nodeName.toLowerCase()&&(n=e.getParent(s,"table"),i=s.parentNode,r=e.select(c,n)[0],r||(r=e.create(c),n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r)),r.appendChild(s),i.hasChildNodes()||e.remove(i)),l(s),t.align&&o.formatter.apply("align"+t.align,{},s)}),o.focus()})}}))}function m(e){return function(){o.execCommand(e)}}function p(e,t){var n,i,a;for(a="",n=0;t>n;n++){for(a+="
",o.insertContent(a)}function g(e,t){function n(){e.disabled(!o.dom.getParent(o.selection.getStart(),t)),o.selection.selectorChanged(t,function(t){e.disabled(!t)})}o.initialized?n():o.on("init",n)}function h(){g(this,"table")}function v(){g(this,"td,th")}function b(){var e="";e='",i=0;e>i;i++)a+=" "}a+=""+(r.ie?" ":" ";a+="
")+"';for(var t=0;10>t;t++){e+="
",e+='";for(var n=0;10>n;n++)e+=' "}return e+="";e+=" ",n=0;i>n;n++)d=F*i+n,d>a?l+=" "}return l+=""}function r(t){var o,r=this.parent();(o=t.target.getAttribute("data-mce-color"))&&(this.lastId&&document.getElementById(this.lastId).setAttribute("aria-selected",!1),t.target.setAttribute("aria-selected",!0),this.lastId=t.target.id,r.hidePanel(),o="#"+o,r.color(o),e.execCommand(r.settings.selectcmd,!1,o))}function l(){var t=this;t._color&&e.execCommand(t.settings.selectcmd,!1,t._color)}e.addButton("forecolor",{type:"colorbutton",tooltip:"Text color",selectcmd:"ForeColor",panel:{role:"application",ariaRemember:!0,html:o,onclick:r},onclick:l}),e.addButton("backcolor",{type:"colorbutton",tooltip:"Background color",selectcmd:"HiliteColor",panel:{role:"application",ariaRemember:!0,html:o,onclick:r},onclick:l})});
-;tinymce.PluginManager.add("visualblocks",function(e,s){function o(){var s=this;s.active(a),e.on("VisualBlocks",function(){s.active(e.dom.hasClass(e.getBody(),"mce-visualblocks"))})}var l,t,a;window.NodeList&&(e.addCommand("mceVisualBlocks",function(){var o,c=e.dom;l||(l=c.uniqueId(),o=c.create("link",{id:l,rel:"stylesheet",href:s+"/css/visualblocks.css"}),e.getDoc().getElementsByTagName("head")[0].appendChild(o)),e.on("PreviewFormats AfterPreviewFormats",function(s){a&&c.toggleClass(e.getBody(),"mce-visualblocks","afterpreviewformats"==s.type)}),c.toggleClass(e.getBody(),"mce-visualblocks"),a=e.dom.hasClass(e.getBody(),"mce-visualblocks"),t&&t.active(c.hasClass(e.getBody(),"mce-visualblocks")),e.fire("VisualBlocks")}),e.addButton("visualblocks",{title:"Show blocks",cmd:"mceVisualBlocks",onPostRender:o}),e.addMenuItem("visualblocks",{text:"Show blocks",cmd:"mceVisualBlocks",onPostRender:o,selectable:!0,context:"view",prependToContext:!0}),e.on("init",function(){e.settings.visualblocks_default_state&&e.execCommand("mceVisualBlocks",!1,null,{skip_focus:!0})}),e.on("remove",function(){e.dom.removeClass(e.getBody(),"mce-visualblocks")}))});
\ No newline at end of file
+/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var r=function(e){if(null===e)return"null";if(e===undefined)return"undefined";var t=typeof e;return"object"==t&&(Array.prototype.isPrototypeOf(e)||e.constructor&&"Array"===e.constructor.name)?"array":"object"==t&&(String.prototype.isPrototypeOf(e)||e.constructor&&"String"===e.constructor.name)?"string":t},t=function(e){return{eq:e}},s=t(function(e,t){return e===t}),i=function(o){return t(function(e,t){if(e.length!==t.length)return!1;for(var n=e.length,r=0;r":(r=o[d],l+=' ');l+="
"+r).contents().slice(1).appendTo(t)}return r}}):t.html(r)},A=function(e,n,r,o,i){return _(e,function(e){var t="string"==typeof n?a.createElement(n):n;return R(t,r),o&&("string"!=typeof o&&o.nodeType?t.appendChild(o):"string"==typeof o&&T(t,o)),i?t:e.appendChild(t)})},D=function(e,t,n){return A(a.createElement(e),e,t,n,!0)},e=ri.decode,O=ri.encodeAllRaw,B=function(e,t){var n=h(e);return t?n.each(function(){for(var e;e=this.firstChild;)3===e.nodeType&&0===e.data.length?this.removeChild(e):this.parentNode.insertBefore(e,this)}).remove():n.remove(),1
|)<\\/"+u+">[\r\n]*|
[\r\n]*)$"),o=a.replace(s,"")}return"text"===t.format||no(Nt.fromDom(r))?t.content=o:t.content=xt.trim(o),t.no_events||e.fire("GetContent",t),t.content},Um=xt.each,zm=function(o){this.compare=function(e,t){if(e.nodeName!==t.nodeName)return!1;var n=function(n){var r={};return Um(o.getAttribs(n),function(e){var t=e.nodeName.toLowerCase();0!==t.indexOf("_")&&"style"!==t&&0!==t.indexOf("data-")&&(r[t]=o.getAttrib(n,t))}),r},r=function(e,t){var n,r;for(r in e)if(e.hasOwnProperty(r)){if(void 0===(n=t[r]))return!1;if(e[r]!==n)return!1;delete t[r]}for(r in t)if(t.hasOwnProperty(r))return!1;return!0};return!!r(n(e),n(t))&&(!!r(o.parseStyle(o.getAttrib(e,"style")),o.parseStyle(o.getAttrib(t,"style")))&&(!$l(e)&&!$l(t)))}},jm=function(n,r,o){return U.from(o.container()).filter(On).exists(function(e){var t=n?0:-1;return r(e.data.charAt(o.offset()+t))})},Hm=E(jm,!0,Kl),Vm=E(jm,!1,Kl),qm=function(e){var t=e.container();return On(t)&&(0===t.data.length||ao(t.data)&&Kf.isBookmarkNode(t.parentNode))},$m=function(t,n){return function(e){return U.from(Zc(t?0:-1,e)).filter(n).isSome()}},Wm=function(e){return Mn(e)&&"block"===Yn(Nt.fromDom(e),"display")},Km=function(e){return Un(e)&&!(Nn(t=e)&&"all"===t.getAttribute("data-mce-bogus"));var t},Xm=$m(!0,Wm),Ym=$m(!1,Wm),Gm=$m(!0,jn),Jm=$m(!1,jn),Qm=$m(!0,Tn),Zm=$m(!1,Tn),ep=$m(!0,Km),tp=$m(!1,Km),np=function(e){var t=qu(e,"br"),n=j(function(e){for(var t=[],n=e.dom;n;)t.push(Nt.fromDom(n)),n=n.lastChild;return t}(e).slice(-1),Gr);t.length===n.length&&$(n,ln)},rp=function(e){cn(e),un(e,Nt.fromHtml('
'))},op=function(n){Yt(n).each(function(t){Ht(t).each(function(e){Xr(n)&&Gr(t)&&Xr(e)&&ln(t)})})},ip=function(e,t,n){return At(t,e)?function(e,t){for(var n=A(t)?t:p,r=e.dom,o=[];null!==r.parentNode&&r.parentNode!==undefined;){var i=r.parentNode,a=Nt.fromDom(i);if(o.push(a),!0===n(a))break;r=i}return o}(e,function(e){return n(e)||Rt(e,t)}).slice(0,-1):[]},ap=function(e,t){return ip(e,t,p)},up=function(e,t){return[e].concat(ap(e,t))},sp=function(e,t,n){return Rl(e,t,n,qm)},cp=function(e,t){return K(up(Nt.fromDom(t.container()),e),Xr)},lp=function(e,n,r){return sp(e,n.dom,r).forall(function(t){return cp(n,r).fold(function(){return!1===Qc(t,r,n.dom)},function(e){return!1===Qc(t,r,n.dom)&&At(e,Nt.fromDom(t.container()))})})},fp=function(t,n,r){return cp(n,r).fold(function(){return sp(t,n.dom,r).forall(function(e){return!1===Qc(e,r,n.dom)})},function(e){return sp(t,e.dom,r).isNone()})},dp=E(fp,!1),mp=E(fp,!0),pp=E(lp,!1),gp=E(lp,!0),hp=function(e){return ul(e).exists(Gr)},vp=function(e,t,n){var r=j(up(Nt.fromDom(n.container()),t),Xr),o=Z(r).getOr(t);return kl(e,o.dom,n).filter(hp)},yp=function(e,t){return ul(t).exists(Gr)||vp(!0,e,t).isSome()},bp=function(e,t){return n=t,U.from(n.getNode(!0)).map(Nt.fromDom).exists(Gr)||vp(!1,e,t).isSome();var n},Cp=E(vp,!1),wp=E(vp,!0),xp=function(e){return Is.isTextPosition(e)&&!e.isAtStart()&&!e.isAtEnd()},Sp=function(e,t){var n=j(up(Nt.fromDom(t.container()),e),Xr);return Z(n).getOr(e)},Np=function(e,t){return xp(t)?Vm(t):Vm(t)||Dl(Sp(e,t).dom,t).exists(Vm)},Ep=function(e,t){return xp(t)?Hm(t):Hm(t)||Al(Sp(e,t).dom,t).exists(Hm)},kp=function(e){return ul(e).bind(function(e){return Sr(e,Pt)}).exists(function(e){return t=Yn(e,"white-space"),I(["pre","pre-wrap"],t);var t})},_p=function(e,t){return r=t,Dl(e.dom,r).isNone()||(n=t,Al(e.dom,n).isNone())||dp(e,t)||mp(e,t)||bp(e,t)||yp(e,t);var n,r},Rp=function(e,t){return!kp(t)&&(dp(e,t)||pp(e,t)||bp(e,t)||Np(e,t))},Tp=function(e,t){return!kp(t)&&(mp(e,t)||gp(e,t)||yp(e,t)||Ep(e,t))},Ap=function(e,t){return Rp(e,t)||Tp(e,(r=(n=t).container(),o=n.offset(),On(r)&&o
');return cn(e),un(e,t),U.some(Us.before(t.dom))}return U.none()},Yp=function(e,t,a){var n,r,o,i,u=Ht(e).filter(Lt),s=Vt(e).filter(Lt);return ln(e),r=s,o=t,i=function(e,t,n){var r=e.dom,o=t.dom,i=r.data.length;return Up(r,o,a),n.container()===o?Us(r,i):n},((n=u).isSome()&&r.isSome()&&o.isSome()?U.some(i(n.getOrDie(),r.getOrDie(),o.getOrDie())):U.none()).orThunk(function(){return a&&(u.each(function(e){return Fp(e.dom,e.dom.length)}),s.each(function(e){return Mp(e.dom,0)})),t})},Gp=function(t,n,e,r){void 0===r&&(r=!0);var o,i,a=$p(n,t.getBody(),e.dom),u=xr(e,E(Kp,t),(o=t.getBody(),function(e){return e.dom===o})),s=Yp(e,a,(i=e,me(t.schema.getTextInlineElements(),Dt(i))));t.dom.isEmpty(t.getBody())?(t.setContent(""),t.selection.setCursorLocation()):u.bind(Xp).fold(function(){r&&Wp(t,n,s)},function(e){r&&Wp(t,n,U.some(e))})},Jp=function(e,t){return{start:e,end:t}},Qp=gr([{removeTable:["element"]},{emptyCells:["cells"]},{deleteCellSelection:["rng","cell"]}]),Zp=function(e,t){return kr(Nt.fromDom(e),"td,th",t)},eg=function(e,t){return Nr(e,"table",t)},tg=function(e){return!Rt(e.start,e.end)},ng=function(e,t){return eg(e.start,t).bind(function(r){return eg(e.end,t).bind(function(e){return t=Rt(r,e),n=r,t?U.some(n):U.none();var t,n})})},rg=function(e){return qu(e,"td,th")},og=function(r,e){var t=Zp(e.startContainer,r),n=Zp(e.endContainer,r);return e.collapsed?U.none():as(t,n,Jp).fold(function(){return t.fold(function(){return n.bind(function(t){return eg(t,r).bind(function(e){return Z(rg(e)).map(function(e){return Jp(e,t)})})})},function(t){return eg(t,r).bind(function(e){return ee(rg(e)).map(function(e){return Jp(t,e)})})})},function(e){return ig(r,e)?U.none():(n=r,eg((t=e).start,n).bind(function(e){return ee(rg(e)).map(function(e){return Jp(t.start,e)})}));var t,n})},ig=function(e,t){return ng(t,e).isSome()},ag=function(e,t,n){return e.filter(function(e){return tg(e)&&ig(n,e)}).orThunk(function(){return og(n,t)}).bind(function(e){return ng(t=e,n).map(function(e){return{rng:t,table:e,cells:rg(e)}});var t})},ug=function(e,t){return X(e,function(e){return Rt(e,t)})},sg=function(e,r,o){return e.filter(function(e){return n=o,!tg(t=e)&&ng(t,n).exists(function(e){var t=e.dom.rows;return 1===t.length&&1===t[0].cells.length})&&Af(e.start,r);var t,n}).map(function(e){return e.start})},cg=function(n){return as(ug((r=n).cells,r.rng.start),ug(r.cells,r.rng.end),function(e,t){return r.cells.slice(e,t+1)}).map(function(e){var t=n.cells;return e.length===t.length?Qp.removeTable(n.table):Qp.emptyCells(e)});var r},lg=function(e,t){var n,r,o,i,a,u=(n=e,function(e){return Rt(n,e)}),s=(o=u,i=Zp((r=t).startContainer,o),a=Zp(r.endContainer,o),as(i,a,Jp));return sg(s,t,u).map(function(e){return Qp.deleteCellSelection(t,e)}).orThunk(function(){return ag(s,t,u).bind(cg)})},fg=function(e){var t;return(8===Ot(t=e)||"#comment"===Dt(t)?Ht:Yt)(e).bind(fg).orThunk(function(){return U.some(e)})},dg=function(e,t){return $(t,rp),e.selection.setCursorLocation(t[0].dom,0),!0},mg=function(e,t,n){t.deleteContents();var r,o,i=fg(n).getOr(n),a=Nt.fromDom(e.dom.getParent(i.dom,e.dom.isBlock));return Uo(a)&&(rp(a),e.selection.setCursorLocation(a.dom,0)),Rt(n,a)||(r=jt(a).is(n)?[]:jt(o=a).map(Wt).map(function(e){return j(e,function(e){return!Rt(o,e)})}).getOr([]),$(r.concat(Wt(n)),function(e){Rt(e,a)||At(e,a)||ln(e)})),!0},pg=function(e,t){return Gp(e,!1,t),!0},gg=function(n,e,r,t){return vg(e,t).fold(function(){return t=n,lg(e,r).map(function(e){return e.fold(E(pg,t),E(dg,t),E(mg,t))});var t},function(e){return yg(n,e)}).getOr(!1)},hg=function(e,t){return K(up(t,e),to)},vg=function(e,t){return K(up(t,e),function(e){return"caption"===Dt(e)})},yg=function(e,t){return rp(t),e.selection.setCursorLocation(t.dom,0),U.some(!0)},bg=function(u,s,c,l,f){return _l(c,u.getBody(),f).bind(function(e){return o=c,i=f,a=e,Ol((r=l).dom).bind(function(t){return Bl(r.dom).map(function(e){return o?i.isEqual(t)&&a.isEqual(e):i.isEqual(e)&&a.isEqual(t)})}).getOr(!0)?yg(u,l):(t=l,n=e,vg(s,Nt.fromDom(n.getNode())).map(function(e){return!1===Rt(e,t)}));var t,n,r,o,i,a}).or(U.some(!0))},Cg=function(o,i,a,e){var u=Us.fromRangeStart(o.selection.getRng());return hg(a,e).bind(function(e){return Uo(e)?yg(o,e):(t=a,n=e,r=u,_l(i,o.getBody(),r).bind(function(e){return hg(t,Nt.fromDom(e.getNode())).map(function(e){return!1===Rt(e,n)})}));var t,n,r}).getOr(!1)},wg=function(e,t){return(e?Qm:Zm)(t)},xg=function(a,u,r){var s=Nt.fromDom(a.getBody());return vg(s,r).fold(function(){return Cg(a,u,s,r)||(e=a,t=u,n=Us.fromRangeStart(e.selection.getRng()),wg(t,n)||kl(t,e.getBody(),n).exists(function(e){return wg(t,e)}));var e,t,n},function(e){return t=a,n=u,r=s,o=e,i=Us.fromRangeStart(t.selection.getRng()),(Uo(o)?yg(t,o):bg(t,r,n,o,i)).getOr(!1);var t,n,r,o,i})},Sg=function(e,t){var n,r,o,i,a,u=Nt.fromDom(e.selection.getStart(!0)),s=_f(e);return e.selection.isCollapsed()&&0===s.length?xg(e,t,u):(n=e,r=u,o=Nt.fromDom(n.getBody()),i=n.selection.getRng(),0!==(a=_f(n)).length?dg(n,a):gg(n,o,i,r))},Ng=function(a){var u=Us.fromRangeStart(a),s=Us.fromRangeEnd(a),c=a.commonAncestorContainer;return kl(!1,c,s).map(function(e){return!Qc(u,s,c)&&Qc(u,e,c)?(t=u.container(),n=u.offset(),r=e.container(),o=e.offset(),(i=document.createRange()).setStart(t,n),i.setEnd(r,o),i):a;var t,n,r,o,i}).getOr(a)},Eg=function(e){return e.collapsed?e:Ng(e)},kg=function(e,t){var n,r;return e.getBlockElements()[t.name]&&((r=t).firstChild&&r.firstChild===r.lastChild)&&("br"===(n=t.firstChild).name||n.value===oo)},_g=function(e,t){var n,r,o,i=t.firstChild,a=t.lastChild;return i&&"meta"===i.name&&(i=i.next),a&&"mce_marker"===a.attr("id")&&(a=a.prev),r=a,o=(n=e).getNonEmptyElements(),r&&(r.isEmpty(o)||kg(n,r))&&(a=a.prev),!(!i||i!==a)&&("ul"===i.name||"ol"===i.name)},Rg=function(e){return e&&e.firstChild&&e.firstChild===e.lastChild&&((t=e.firstChild).data===oo||In(t));var t},Tg=function(e){return 0
)?$/," "));var p=e.parser,g=n.merge,h=Tm({validate:e.getParam("validate")},e.schema),v='',y={content:t,format:"html",selection:!0,paste:n.paste};if((y=e.fire("BeforeSetContent",y)).isDefaultPrevented())e.fire("SetContent",{content:y.content,format:"html",selection:!0,paste:n.paste});else{-1===(t=y.content).indexOf("{$caret}")&&(t+="{$caret}"),t=t.replace(/\{\$caret\}/,v);var b,C,w=(a=d.getRng()).startContainer||(a.parentElement?a.parentElement():null),x=e.getBody();w===x&&d.isCollapsed()&&m.isBlock(x.firstChild)&&(b=e,(C=x.firstChild)&&!b.schema.getShortEndedElements()[C.nodeName])&&m.isEmpty(x.firstChild)&&((a=m.createRng()).setStart(x.firstChild,0),a.setEnd(x.firstChild,0),d.setRng(a)),d.isCollapsed()||Lg(e);var S,N,E,k,_,R,T,A,D,O,B,P,L,I,M={context:(r=d.getNode()).nodeName.toLowerCase(),data:n.data,insert:!0},F=p.parse(t,M);if(!0===n.paste&&_g(e.schema,F)&&Ag(m,r))return a=Bg(h,m,d.getRng(),F),d.setRng(a),void e.fire("SetContent",y);if(!function(e){for(var t=e;t=t.walk();)1===t.type&&t.attr("data-mce-fragment","1")}(F),"mce_marker"===(u=F.lastChild).attr("id"))for(u=(i=u).prev;u;u=u.walk(!0))if(3===u.type||!m.isBlock(u.name)){e.schema.isValidChild(u.parent.name,"span")&&u.parent.insert(i,u,"br"===u.name);break}if(e._selectionOverrides.showBlockCaretContainer(r),M.invalid){for(e.selection.setContent(v),r=d.getNode(),o=e.getBody(),9===r.nodeType?r=u=o:u=r;u!==o;)u=(r=u).parentNode;t=r===o?o.innerHTML:m.getOuterHTML(r),t=h.serialize(p.parse(t.replace(//i,function(){return h.serialize(F)}))),r===o?m.setHTML(o,t):m.setOuterHTML(r,t)}else t=h.serialize(F),S=e,N=t,"all"===(E=r).getAttribute("data-mce-bogus")?E.parentNode.insertBefore(S.dom.createFragment(N),E):(k=E.firstChild,_=E.lastChild,!k||k===_&&"BR"===k.nodeName?S.dom.setHTML(E,N):S.selection.setContent(N));T=g,O=(R=e).schema.getTextInlineElements(),B=R.dom,T&&(A=R.getBody(),D=new zm(B),xt.each(B.select("*[data-mce-fragment]"),function(e){for(var t=e.parentNode;t&&t!==A;t=t.parentNode)O[e.nodeName.toLowerCase()]&&D.compare(t,e)&&B.remove(e,!0)})),function(n,e){var t,r,o=n.dom,i=n.selection;if(e){i.scrollIntoView(e);var a=function(e){for(var t=n.getBody();e&&e!==t;e=e.parentNode)if("false"===o.getContentEditable(e))return e;return null}(e);if(a)return o.remove(e),i.select(a);var u=o.createRng(),s=e.previousSibling;s&&3===s.nodeType?(u.setStart(s,s.nodeValue.length),vt.ie||(r=e.nextSibling)&&3===r.nodeType&&(s.appendData(r.data),r.parentNode.removeChild(r))):(u.setStartBefore(e),u.setEndBefore(e));var c=o.getParent(e,o.isBlock);o.remove(e),c&&o.isEmpty(c)&&(n.$(c).empty(),u.setStart(c,0),u.setEnd(c,0),Pg(c)||c.getAttribute("data-mce-fragment")||!(t=function(e){var t=Us.fromRangeStart(e);if(t=wl(n.getBody()).next(t))return t.toRange()}(u))?o.add(c,o.create("br",{"data-mce-bogus":"1"})):(u=t,o.remove(c))),i.setRng(u)}}(e,m.get("mce_marker")),P=e.getBody(),xt.each(P.getElementsByTagName("*"),function(e){e.removeAttribute("data-mce-fragment")}),L=m,I=d.getStart(),U.from(L.getParent(I,"td,th")).map(Nt.fromDom).each(op),e.fire("SetContent",y),e.addVisual()}},Mg=function(e,t){t(e),e.firstChild&&Mg(e.firstChild,t),e.next&&Mg(e.next,t)},Fg=function(e,t,n){var r=function(e,n,t){var r={},o={},i=[];for(var a in t.firstChild&&Mg(t.firstChild,function(t){$(e,function(e){e.name===t.name&&(r[e.name]?r[e.name].nodes.push(t):r[e.name]={filter:e,nodes:[t]})}),$(n,function(e){"string"==typeof t.attr(e.name)&&(o[e.name]?o[e.name].nodes.push(t):o[e.name]={filter:e,nodes:[t]})})}),r)r.hasOwnProperty(a)&&i.push(r[a]);for(var u in o)o.hasOwnProperty(u)&&i.push(o[u]);return i}(e,t,n);$(r,function(t){$(t.filter.callbacks,function(e){e(t.nodes,t.filter.name,{})})})},Ug=function(e){return e instanceof Em},zg=function(e,t){var r;e.dom.setHTML(e.getBody(),t),pm(r=e)&&Ol(r.getBody()).each(function(e){var t=e.getNode(),n=Tn(t)?Ol(t).getOr(e):e;r.selection.setRng(n.toRange())})},jg=function(u,s,c){return c.format=c.format?c.format:"html",c.set=!0,c.content=Ug(s)?"":s,Ug(s)||c.no_events||(u.fire("BeforeSetContent",c),s=c.content),U.from(u.getBody()).fold(N(s),function(e){return Ug(s)?function(e,t,n,r){Fg(e.parser.getNodeFilters(),e.parser.getAttributeFilters(),n);var o=Tm({validate:e.validate},e.schema).serialize(n);return r.content=no(Nt.fromDom(t))?o:xt.trim(o),zg(e,r.content),r.no_events||e.fire("SetContent",r),n}(u,e,s,c):(t=u,n=e,o=c,0===(r=s).length||/^\s+$/.test(r)?(a='
',"TABLE"===n.nodeName?r=" ":/^(UL|OL)$/.test(n.nodeName)&&(r=""+a+"
',zg(t,r),t.fire("SetContent",o)):("raw"!==o.format&&(r=Tm({validate:t.validate},t.schema).serialize(t.parser.parse(r,{isRootContent:!0,insert:!0}))),o.content=no(Nt.fromDom(n))?r:xt.trim(r),zg(t,o.content),o.no_events||t.fire("SetContent",o)),o.content);var t,n,r,o,i,a})},Hg=nf,Vg=function(e,t,n){var r=e.formatter.get(n);if(r)for(var o=0;o
").append(n.childNodes)}))},lh[Bm="pre"]||(lh[Bm]=[]),lh[Bm].push(Pm);var mh=xt.each,ph=function(e){return Nn(e)&&!$l(e)&&!Ll(e)&&!Rn(e)},gh=function(e,t){for(var n=e;n;n=n[t]){if(On(n)&&0!==n.nodeValue.length)return e;if(Nn(n)&&!$l(n))return n}return e},hh=function(e,t,n){var r,o,i=new zm(e);if(t&&n&&(t=gh(t,"previousSibling"),n=gh(n,"nextSibling"),i.compare(t,n))){for(r=t.nextSibling;r&&r!==n;)r=(o=r).nextSibling,t.appendChild(o);return e.remove(n),xt.each(xt.grep(n.childNodes),function(e){t.appendChild(e)}),t}return n},vh=function(e,t,n,r){var o;r&&!1!==t.merge_siblings&&(o=hh(e,Jl(r),r),hh(e,o,Jl(o,!0)))},yh=function(e,t,n){mh(e.childNodes,function(e){ph(e)&&(t(e)&&n(e),e.hasChildNodes()&&yh(e,t,n))})},bh=function(t,n){return function(e){return!(!e||!of(t,e,n))}},Ch=function(r,o,i){return function(e){var t,n;r.setStyle(e,o,i),""===e.getAttribute("style")&&e.removeAttribute("style"),t=r,"SPAN"===(n=e).nodeName&&0===t.getAttribs(n).length&&t.remove(n,!0)}},wh=gr([{keep:[]},{rename:["name"]},{removed:[]}]),xh=/^(src|href|style)$/,Sh=xt.each,Nh=nf,Eh=function(e,t,n){return e.isChildOf(t,n)&&t!==n&&!e.isBlock(n)},kh=function(e,t,n){var r,o=t[n?"startContainer":"endContainer"],i=t[n?"startOffset":"endOffset"];return Nn(o)&&(r=o.childNodes.length-1,!n&&i&&i--,o=o.childNodes[r=o.nodeValue.length&&(o=new Hr(o,e.getBody()).next()||o),On(o)&&!n&&0===i&&(o=new Hr(o,e.getBody()).prev()||o),o},_h=function(e,t){var n=t?"firstChild":"lastChild";if(/^(TR|TH|TD)$/.test(e.nodeName)&&e[n]){var r=e[n];return"TR"===e.nodeName&&r[n]||r}return e},Rh=function(e,t,n,r){var o=e.create(n,r);return t.parentNode.insertBefore(o,t),o.appendChild(t),o},Th=function(e,t,n,r,o){var i=Nt.fromDom(t),a=Nt.fromDom(e.create(r,o)),u=(n?$t:qt)(i);return sn(a,u),n?(rn(i,a),an(a,i)):(on(i,a),un(a,i)),a.dom},Ah=function(e,t,n,r){return!(t=Jl(t,n,r))||"BR"===t.nodeName||e.isBlock(t)},Dh=function(e,r,o,t,i){var n,a,u,s,c,l=e.dom;if(u=l,!(Nh(s=t,(c=r).inline)||Nh(s,c.block)||c.selector&&(Nn(s)&&u.is(s,c.selector))||(a=t,r.links&&"A"===a.nodeName)))return wh.keep();var f,d,m,p,g,h,v,y=t;if(r.inline&&"all"===r.remove&&S(r.preserve_attributes)){var b=j(l.getAttribs(y),function(e){return I(r.preserve_attributes,e.name.toLowerCase())});if(l.removeAllAttribs(y),$(b,function(e){return l.setAttrib(y,e.name,e.value)}),0
'},qx=function(e,t){return e.nodeName===t||e.previousSibling&&e.previousSibling.nodeName===t},$x=function(e,t){return t&&e.isBlock(t)&&!/^(TD|TH|CAPTION|FORM)$/.test(t.nodeName)&&!/^(fixed|absolute)/i.test(t.style.position)&&"true"!==e.getContentEditable(t)},Wx=function(e,t,n){return!1===On(t)?n:e?1===n&&t.data.charAt(n-1)===io?0:n:n===t.data.length-1&&t.data.charAt(n)===io?t.data.length:n},Kx=function(e,t){for(var n,r=e.getRoot(),o=t;o!==r&&"false"!==e.getContentEditable(o);)"true"===e.getContentEditable(o)&&(n=o),o=o.parentNode;return o!==r?n:r},Xx=function(e,t){var n=fc(e);n&&n.toLowerCase()===t.tagName.toLowerCase()&&function(e,o,t){var i=e.dom;U.from(t.style).map(i.parseStyle).each(function(e){var t=Qn(Nt.fromDom(o)),n=xe(xe({},t),e);i.setStyles(o,n)});var n=U.from(t["class"]).map(function(e){return e.split(/\s+/)}),r=U.from(o.className).map(function(e){return j(e.split(/\s+/),function(e){return""!==e})});as(n,r,function(t,e){var n=j(e,function(e){return!I(t,e)}),r=Se(t,n);i.setAttrib(o,"class",r.join(" "))});var a=["style","class"],u=le(t,function(e,t){return!I(a,t)});i.setAttribs(o,u)}(e,t,dc(e))},Yx=function(a,e){var t,u,i,s,n,r,o,c,l,f=a.dom,d=a.schema,m=d.getNonEmptyElements(),p=a.selection.getRng(),g=function(e){var t,n=u,r=d.getTextInlineElements(),o=e||"TABLE"===c||"HR"===c?f.create(e||N):s.cloneNode(!1),i=o;if(!1===a.getParam("keep_styles",!0))f.setAttrib(o,"style",null),f.setAttrib(o,"class",null);else do{if(r[n.nodeName]){if(Ll(n)||$l(n))continue;t=n.cloneNode(!1),f.setAttrib(t,"id",""),o.hasChildNodes()?t.appendChild(o.firstChild):i=t,o.appendChild(t)}}while((n=n.parentNode)&&n!==E);return Xx(a,o),Vx(i),o},h=function(e){var t,n,r=Wx(e,u,i);if(On(u)&&(e?0
'},uN=function(e,t){var n,r,o,i,a=e.editorManager.translate("Rich Text Area. Press ALT-0 for help."),u=(n=e.id,r=a,t.height,o=e.getParam("iframe_attrs",{}),i=Nt.fromTag("iframe"),$n(i,o),$n(i,{id:n+"_ifr",frameBorder:"0",allowTransparency:"true",title:r}),zu(i,"tox-edit-area__iframe"),i.dom);u.onload=function(){u.onload=null,e.fire("load")};var s=function(e,t){if(document.domain!==window.location.hostname&&vt.browser.isIE()){var n=Gy("mce");e[n]=function(){oN(e)};var r='javascript:(function(){document.open();document.domain="'+document.domain+'";var ed = window.parent.tinymce.get("'+e.id+'");document.write(ed.iframeHTML);document.close();ed.'+n+"(true);})()";return iN.setAttrib(t,"src",r),!0}return!1}(e,u);return e.contentAreaContainer=t.iframeContainer,e.iframeElement=u,e.iframeHTML=aN(e),iN.add(t.iframeContainer,u),s},sN=bu.DOM,cN=function(t,n,e){var r=Fy.get(e),o=Fy.urls[e]||t.documentBaseUrl.replace(/\/$/,"");if(e=xt.trim(e),r&&-1===xt.inArray(n,e)){if(xt.each(Fy.dependencies(e),function(e){cN(t,n,e)}),t.plugins[e])return;try{var i=new r(t,o,t.$);(t.plugins[e]=i).init&&(i.init(t,o),n.push(e))}catch(pk){!function(e,t,n){var r=Au.translate(["Failed to initialize plugin: {0}",t]);Wy(r,n),Hy(e,r)}(t,e,pk)}}},lN=function(e){return e.replace(/^\-/,"")},fN=function(e){return{editorContainer:e,iframeContainer:e,api:{}}},dN=function(e){var t,n,r=e.getElement();return e.inline?fN(null):(t=r,n=sN.create("div"),sN.insertAfter(n,t),fN(n))},mN=function(e){var t,n,r,o=e.getElement();return e.orgDisplay=o.style.display,q(Cc(e))?e.theme.renderUI():A(Cc(e))?(n=(t=e).getElement(),(r=Cc(t)(t,n)).editorContainer.nodeType&&(r.editorContainer.id=r.editorContainer.id||t.id+"_parent"),r.iframeContainer&&r.iframeContainer.nodeType&&(r.iframeContainer.id=r.iframeContainer.id||t.id+"_iframecontainer"),r.height=r.iframeHeight?r.iframeHeight:n.offsetHeight,r):dN(e)},pN=function(e){var n,t,r,o,i,a,u,s,c;e.fire("ScriptsLoaded"),n=e,t=xt.trim(pc(n)),r=n.ui.registry.getAll().icons,o=xe(xe({},Ry.get("default").icons),Ry.get(t).icons),oe(o,function(e,t){me(r,t)||n.ui.registry.addIcon(t,e)}),u=Cc(i=e),q(u)?(i.settings.theme=lN(u),a=Uy.get(u),i.theme=new a(i,Uy.urls[u]),i.theme.init&&i.theme.init(i,Uy.urls[u]||i.documentBaseUrl.replace(/\/$/,""),i.$)):i.theme={},s=e,c=[],xt.each(xc(s).split(/[ ,]/),function(e){cN(s,c,lN(e))});var l=mN(e);e.ui=xe(xe({},e.ui),l.api);var f,d,m,p,g={editorContainer:l.editorContainer,iframeContainer:l.iframeContainer};return e.editorContainer=g.editorContainer?g.editorContainer:null,(f=e).contentCSS=f.contentCSS.concat(Ky(f)),e.inline?oN(e):(p=uN(d=e,m=g),m.editorContainer&&(iN.get(m.editorContainer).style.display=d.orgDisplay,d.hidden=iN.isHidden(m.editorContainer)),d.getElement().style.display="none",iN.setAttrib(d.id,"aria-hidden","true"),void(p||oN(d)))},gN=bu.DOM,hN=function(e){return"-"===e.charAt(0)},vN=function(e,t){var n,r=hc(t),o=t.getParam("language_url","","string");!1===Au.hasCode(r)&&"en"!==r&&(n=""!==o?o:t.editorManager.baseURL+"/langs/"+r+".js",e.add(n,V,undefined,function(){Vy(t,"LanguageLoadError",qy("language",n,r))}))},yN=function(t,e,n){return U.from(e).filter(function(e){return 0
"),o(/\[b\]/gi,""),o(/\[\/b\]/gi,""),o(/\[i\]/gi,""),o(/\[\/i\]/gi,""),o(/\[u\]/gi,""),o(/\[\/u\]/gi,""),o(/\[url=([^\]]+)\](.*?)\[\/url\]/gi,'$2'),o(/\[url\](.*?)\[\/url\]/gi,'$1'),o(/\[img\](.*?)\[\/img\]/gi,''),o(/\[color=(.*?)\](.*?)\[\/color\]/gi,'$2'),o(/\[code\](.*?)\[\/code\]/gi,'$1 '),o(/\[quote.*?\](.*?)\[\/quote\]/gi,'$1 '),t};o.add("bbcode",function(o){o.on("BeforeSetContent",function(o){o.content=t(o.content)}),o.on("PostProcess",function(o){o.set&&(o.content=t(o.content)),o.get&&(o.content=function(t){t=e.trim(t);var o=function(o,e){t=t.replace(o,e)};return o(/
]*>/gi,"[quote]"),o(/<\/blockquote>/gi,"[/quote]"),o(/
')}var c;var e=tinyMCE.baseURL.indexOf("/static/");if(e>0){c=tinyMCE.baseURL.substring(0,e)}else{c=window.location.origin}var t="?CodeMirrorPath="+l.settings.codemirror.path+"&ParentOrigin="+window.location.origin;var o=800;if(l.settings.codemirror.width){o=l.settings.codemirror.width}var n=550;if(l.settings.codemirror.height){n=l.settings.codemirror.height}var i=tinymce.majorVersion<5?[{text:"Ok",subtype:"primary",onclick:function(){var e=document.querySelectorAll(".mce-container-body>iframe")[0];e.contentWindow.submit();a.close()}},{text:"Cancel",onclick:"close"}]:[{type:"custom",text:"Ok",name:"codemirrorOk",primary:true},{type:"cancel",text:"Cancel",name:"codemirrorCancel"}];var r={title:"HTML source code",url:m+"/source.html"+t,width:o,height:n,resizable:true,maximizable:true,fullScreen:l.settings.codemirror.fullscreen,saveCursorPosition:false,buttons:i,onClose:function(){window.removeEventListener("message",d)}};if(tinymce.majorVersion>=5){r.onAction=function(e,t){if(t.name==="codemirrorOk"){s({type:"save"})}else if(t.name==="codemirrorCancel"){s({type:"cancel"});a.close()}}}var a=tinymce.majorVersion<5?l.windowManager.open(r):l.windowManager.openUrl(r);var s=function(e){a.sendMessage(e)};var d=function(e){if(c!==e.origin){return}var t;if(e.data.type==="init"){t={content:l.getContent({source_view:true})};l.fire("ShowCodeEditor",t);s({type:"init",content:t.content});l.dom.remove(l.dom.select(".CmCaReT"))}else if(e.data.type==="setText"){t={content:e.data.text};var o=e.data.isDirty;l.fire("SaveCodeEditor",t);l.setContent(t.content);var n=l.dom.select("span#CmCaReT")[0];if(n){l.selection.scrollIntoView(n);l.selection.setCursorLocation(n,0);l.dom.remove(n)}else{var i=l.getContent();var r=i.replace('',"");if(i!==r){l.setContent(r)}}l.isNotDirty=!o;if(o){l.nodeChanged()}}else if(e.data.type==="closeWindow"){a.close()}};window.addEventListener("message",d,false)}if(tinymce.majorVersion<5){l.addButton("code",{title:"Source code",icon:"code",onclick:e});l.addMenuItem("code",{icon:"code",text:"Source code",context:"tools",onclick:e})}else{l.ui.registry.addButton("code",{text:"HTML",tooltip:"Edit HTML",onAction:e});l.ui.registry.addMenuItem("code",{icon:"sourcecode",text:"Edit HTML",onAction:e,context:"tools"})}});/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e=tinymce.util.Tools.resolve("tinymce.PluginManager"),o=function(o){var e=o.getContent({source_view:!0});o.windowManager.open({title:"Source Code",size:"large",body:{type:"panel",items:[{type:"textarea",name:"code"}]},buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:{code:e},onSubmit:function(e){var t,n;t=o,n=e.getData().code,t.focus(),t.undoManager.transact(function(){t.setContent(n)}),t.selection.setCursorLocation(),t.nodeChanged(),e.close()}})};e.add("code",function(e){var t,n;return(t=e).addCommand("mceCodeEditor",function(){o(t)}),(n=e).ui.registry.addButton("code",{icon:"sourcecode",tooltip:"Source code",onAction:function(){return o(n)}}),n.ui.registry.addMenuItem("code",{icon:"sourcecode",text:"Source code",onAction:function(){return o(n)}}),{}})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var e,n,t,a=tinymce.util.Tools.resolve("tinymce.PluginManager"),i=function(e){return function(){return e}},s=i(!1),o=i(!0),r=function(){return l},l=(e=function(e){return e.isNone()},{fold:function(e,n){return e()},is:s,isSome:s,isNone:o,getOr:t=function(e){return e},getOrThunk:n=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:i(null),getOrUndefined:i(undefined),or:t,orThunk:n,map:r,each:function(){},bind:r,exists:s,forall:o,filter:r,equals:e,equals_:e,toArray:function(){return[]},toString:i("none()")}),u=function(t){var e=i(t),n=function(){return r},a=function(e){return e(t)},r={fold:function(e,n){return n(t)},is:function(e){return t===e},isSome:o,isNone:s,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:n,orThunk:n,map:function(e){return u(e(t))},each:function(e){e(t)},bind:a,exists:a,forall:a,filter:function(e){return e(t)?r:l},toArray:function(){return[t]},toString:function(){return"some("+t+")"},equals:function(e){return e.is(t)},equals_:function(e,n){return e.fold(s,function(e){return n(t,e)})}};return r},c={some:u,none:r,from:function(e){return null===e||e===undefined?l:u(e)}},d=tinymce.util.Tools.resolve("tinymce.dom.DOMUtils");function p(e){return e&&"PRE"===e.nodeName&&-1!==e.className.indexOf("language-")}function g(t){return function(e,n){return t(n)}}var m="undefined"!=typeof window?window:Function("return this;")(),f={},h={exports:f},b={};!function(n,t,a,d){var e=window.Prism;window.Prism={manual:!0},function(e){"object"==typeof t&&void 0!==a?a.exports=e():"function"==typeof n&&n.amd?n([],e):("undefined"!=typeof window?window:void 0!==b?b:"undefined"!=typeof self?self:this).EphoxContactWrapper=e()}(function(){return function c(i,s,o){function l(n,e){if(!s[n]){if(!i[n]){var t="function"==typeof d&&d;if(!e&&t)return t(n,!0);if(u)return u(n,!0);var a=new Error("Cannot find module '"+n+"'");throw a.code="MODULE_NOT_FOUND",a}var r=s[n]={exports:{}};i[n][0].call(r.exports,function(e){return l(i[n][1][e]||e)},r,r.exports,c,i,s,o)}return s[n].exports}for(var u="function"==typeof d&&d,e=0;e
/gi,"\n"),o(/
/gi,"\n"),o(/
/gi,"\n"),o(/'+a+"
"),n.selection.select(n.$("#__new").removeAttr("id")[0])},function(e){n.dom.setAttrib(e,"class","language-"+t),e.innerHTML=a,w(n).highlightElement(e),n.selection.select(e)})}),e.close()}})},x=function(a){a.ui.registry.addToggleButton("codesample",{icon:"code-sample",tooltip:"Insert/edit code sample",onAction:function(){return k(a)},onSetup:function(t){var e=function(){var e,n;t.setActive((n=(e=a).selection.getStart(),e.dom.is(n,'pre[class*="language-"]')))};return a.on("NodeChange",e),function(){return a.off("NodeChange",e)}}}),a.ui.registry.addMenuItem("codesample",{text:"Code sample...",icon:"code-sample",onAction:function(){return k(a)}})};a.add("codesample",function(n){var t,r,a;r=(t=n).$,t.on("PreProcess",function(e){r("pre[contenteditable=false]",e.node).filter(g(p)).each(function(e,n){var t=r(n),a=n.textContent;t.attr("class",r.trim(t.attr("class"))),t.removeAttr("contentEditable"),t.empty().append(r("").each(function(){this.textContent=a}))})}),t.on("SetContent",function(){var e=r("pre").filter(g(p)).filter(function(e,n){return"false"!==n.contentEditable});e.length&&t.undoManager.transact(function(){e.each(function(e,n){r(n).find("br").each(function(e,n){n.parentNode.replaceChild(t.getDoc().createTextNode("\n"),n)}),n.contentEditable="false",n.innerHTML=t.dom.encode(n.textContent),w(t).highlightElement(n),n.className=r.trim(n.className)})})}),x(n),(a=n).addCommand("codesample",function(){var e=a.selection.getNode();a.selection.isCollapsed()||p(e)?k(a):a.formatter.toggle("code")}),n.on("dblclick",function(e){p(e.target)&&k(n)})})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";tinymce.util.Tools.resolve("tinymce.PluginManager").add("colorpicker",function(){console.warn("Color picker plugin is now built in to the core editor, please remove it from your editor configuration")})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";tinymce.util.Tools.resolve("tinymce.PluginManager").add("contextmenu",function(){console.warn("Context menu plugin is now built in to the core editor, please remove it from your editor configuration")})}();/**
+ * 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/
+ *
+ * Version: 5.5.1 (2020-10-01)
+ */
+!function(){"use strict";var n,t,e,o,r=tinymce.util.Tools.resolve("tinymce.PluginManager"),u=tinymce.util.Tools.resolve("tinymce.util.Tools"),i=function(n,t){var e,o=n.dom,r=n.selection.getSelectedBlocks();r.length&&(e=o.getAttrib(r[0],"dir"),u.each(r,function(n){o.getParent(n.parentNode,'*[dir="'+t+'"]',o.getRoot())||o.setAttrib(n,"dir",e!==t?t:null)}),n.nodeChanged())},c=function(n){return function(){return n}},f=c(!1),d=c(!0),l=function(){return m},m=(n=function(n){return n.isNone()},{fold:function(n,t){return n()},is:f,isSome:f,isNone:d,getOr:e=function(n){return n},getOrThunk:t=function(n){return n()},getOrDie:function(n){throw new Error(n||"error: getOrDie called on none.")},getOrNull:c(null),getOrUndefined:c(undefined),or:e,orThunk:t,map:l,each:function(){},bind:l,exists:f,forall:d,filter:l,equals:n,equals_:n,toArray:function(){return[]},toString:c("none()")}),a=function(e){var n=c(e),t=function(){return r},o=function(n){return n(e)},r={fold:function(n,t){return t(e)},is:function(n){return e===n},isSome:d,isNone:f,getOr:n,getOrThunk:n,getOrDie:n,getOrNull:n,getOrUndefined:n,or:t,orThunk:t,map:function(n){return a(n(e))},each:function(n){n(e)},bind:o,exists:o,forall:o,filter:function(n){return n(e)?r:m},toArray:function(){return[e]},toString:function(){return"some("+e+")"},equals:function(n){return n.is(e)},equals_:function(n,t){return n.fold(f,function(n){return t(e,n)})}};return r},s={some:a,none:l,from:function(n){return null===n||n===undefined?m:a(n)}},g=(o="function",function(n){return typeof n===o}),h=function(n){if(null===n||n===undefined)throw new Error("Node cannot be null or undefined");return{dom:n}},y={fromHtml:function(n,t){var e=(t||document).createElement("div");if(e.innerHTML=n,!e.hasChildNodes()||1
"+A.translate(["Plugins installed ({0}):",r])+"
'+A.translate("Premium plugins:")+"
The sections of the outer UI of the editor - the menubar, toolbar, sidebar and footer - are all keyboard navigable. As such, there are multiple ways to activate keyboard navigation:
\nFocusing the menubar or toolbar will start keyboard navigation at the first item in the menubar or toolbar, which will be highlighted with a gray background. Focusing the footer will start keyboard navigation at the first item in the element path, which will be highlighted with an underline.
\n\nWhen keyboard navigation is active, pressing tab will move the focus to the next major section of the UI, where applicable. These sections are:
\nPressing shift + tab will move backwards through the same sections, except when moving from the footer to the toolbar. Focusing the element path then pressing shift + tab will move focus to the first toolbar group, not the last.
\n\nKeyboard navigation within UI sections can usually be achieved using the left and right arrow keys. This includes:
\nIn all these UI sections, keyboard navigation will cycle within the section. For example, focusing the last button in a toolbar group then pressing right arrow will move focus to the first item in the same toolbar group.
\n\nTo execute a button, navigate the selection to the desired button and hit space or enter.
\n\nWhen focusing a menubar button or a toolbar button with a menu, pressing space, enter or down arrow will open the menu. When the menu opens the first item will be selected. To move up or down the menu, press the up or down arrow key respectively. This is the same for submenus, which can also be opened and closed using the left and right arrow keys.
\n\nTo close any active menu, hit the escape key. When a menu is closed the selection will be restored to its previous selection. This also works for closing submenus.
\n\nTo focus an open context toolbar such as the table context toolbar, press Ctrl + F9 (Windows) or ⌃F9 (MacOS).
\n\nContext toolbar navigation is the same as toolbar navigation, and context menu navigation is the same as standard menu navigation.
\n\nThere are two types of dialog UIs in TinyMCE: tabbed dialogs and non-tabbed dialogs.
\n\nWhen a non-tabbed dialog is opened, the first interactive component in the dialog will be focused. Users can navigate between interactive components by pressing tab. This includes any footer buttons. Navigation will cycle back to the first dialog component if tab is pressed while focusing the last component in the dialog. Pressing shift + tab will navigate backwards.
\n\nWhen a tabbed dialog is opened, the first button in the tab menu is focused. Pressing tab will navigate to the first interactive component in that tab, and will cycle through the tab\u2019s components, the footer buttons, then back to the tab button. To switch to another tab, focus the tab button for the current tab, then use the arrow keys to cycle through the tab buttons.
"}]},c=T(e),u=(i='TinyMCE '+(a=x.majorVersion,o=x.minorVersion,0===a.indexOf("@")?"X.X.X":a+"."+o)+"",{name:"versions",title:"Version",items:[{type:"htmlpanel",html:""+A.translate(["You are using {0}",i])+"
",presets:"document"}]}),h=m(((n={})[s.name]=s,n[l.name]=l,n[c.name]=c,n[u.name]=u,n),t.get());return r=e,d.from(r.getParam("help_tabs")).fold(function(){return t=f(e=h),-1!==(n=t.indexOf("versions"))&&(t.splice(n,1),t.push("versions")),{tabs:e,names:t};var e,t,n},function(e){return t=h,n={},a=p(e,function(e){return"string"==typeof e?(y(t,e)&&(n[e]=t[e]),e):(n[e.name]=e).name}),{tabs:n,names:a};var t,n,a})},M=function(o,i){return function(){var e=P(o,i),a=e.tabs,t=e.names,n={type:"tabpanel",tabs:function(e){for(var t=[],n=function(e){t.push(e)},a=0;aabcabc123
would produceabc
abc123
. - * - * @method split - * @param {Element} parentElm Parent element to split. - * @param {Element} splitElm Element to split at. - * @param {Element} replacementElm Optional replacement element to replace the split element with. - * @return {Element} Returns the split element or the replacement element if that is specified. - */ - split: function(parentElm, splitElm, replacementElm) { - var self = this, r = self.createRng(), bef, aft, pa; - - // W3C valid browsers tend to leave empty nodes to the left/right side of the contents - this makes sense - // but we don't want that in our code since it serves no purpose for the end user - // For example splitting this html at the bold element: - //text 1CHOPtext 2
- // would produce: - //text 1
CHOPtext 2
- // this function will then trim off empty edges and produce: - //text 1
CHOPtext 2
- function trimNode(node) { - var i, children = node.childNodes, type = node.nodeType; - - function surroundedBySpans(node) { - var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; - var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; - return previousIsSpan && nextIsSpan; - } - - if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') { - return; - } - - for (i = children.length - 1; i >= 0; i--) { - trimNode(children[i]); - } - - if (type != 9) { - // Keep non whitespace text nodes - if (type == 3 && node.nodeValue.length > 0) { - // If parent element isn't a block or there isn't any useful contents for example "" - // Also keep text nodes with only spaces if surrounded by spans. - // eg. "
a b
" should keep space between a and b - var trimmedLength = trim(node.nodeValue).length; - if (!self.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) { - return; - } - } else if (type == 1) { - // If the only child is a bookmark then move it up - children = node.childNodes; - - // TODO fix this complex if - if (children.length == 1 && children[0] && children[0].nodeType == 1 && - children[0].getAttribute('data-mce-type') == 'bookmark') { - node.parentNode.insertBefore(children[0], node); - } - - // Keep non empty elements or img, hr etc - if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) { - return; - } - } - - self.remove(node); - } - - return node; - } - - if (parentElm && splitElm) { - // Get before chunk - r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); - r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); - bef = r.extractContents(); - - // Get after chunk - r = self.createRng(); - r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); - r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); - aft = r.extractContents(); - - // Insert before chunk - pa = parentElm.parentNode; - pa.insertBefore(trimNode(bef), parentElm); - - // Insert middle chunk - if (replacementElm) { - pa.replaceChild(replacementElm, splitElm); - } else { - pa.insertBefore(splitElm, parentElm); - } - - // Insert after chunk - pa.insertBefore(trimNode(aft), parentElm); - self.remove(parentElm); - - return replacementElm || splitElm; - } - }, - - /** - * Adds an event handler to the specified object. - * - * @method bind - * @param {Element/Document/Window/Array} target Target element to bind events to. - * handler to or an array of elements/ids/documents. - * @param {String} name Name of event handler to add, for example: click. - * @param {function} func Function to execute when the event occurs. - * @param {Object} scope Optional scope to execute the function in. - * @return {function} Function callback handler the same as the one passed in. - */ - bind: function(target, name, func, scope) { - var self = this; - - if (Tools.isArray(target)) { - var i = target.length; - - while (i--) { - target[i] = self.bind(target[i], name, func, scope); - } - - return target; - } - - // Collect all window/document events bound by editor instance - if (self.settings.collect && (target === self.doc || target === self.win)) { - self.boundEvents.push([target, name, func, scope]); - } - - return self.events.bind(target, name, func, scope || self); - }, - - /** - * Removes the specified event handler by name and function from an element or collection of elements. - * - * @method unbind - * @param {Element/Document/Window/Array} target Target element to unbind events on. - * @param {String} name Event handler name, for example: "click" - * @param {function} func Function to remove. - * @return {bool/Array} Bool state of true if the handler was removed, or an array of states if multiple input elements - * were passed in. - */ - unbind: function(target, name, func) { - var self = this, i; - - if (Tools.isArray(target)) { - i = target.length; - - while (i--) { - target[i] = self.unbind(target[i], name, func); - } - - return target; - } - - // Remove any bound events matching the input - if (self.boundEvents && (target === self.doc || target === self.win)) { - i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - - if (target == item[0] && (!name || name == item[1]) && (!func || func == item[2])) { - this.events.unbind(item[0], item[1], item[2]); - } - } - } - - return this.events.unbind(target, name, func); - }, - - /** - * Fires the specified event name with object on target. - * - * @method fire - * @param {Node/Document/Window} target Target element or object to fire event on. - * @param {String} name Name of the event to fire. - * @param {Object} evt Event object to send. - * @return {Event} Event object. - */ - fire: function(target, name, evt) { - return this.events.fire(target, name, evt); - }, - - // Returns the content editable state of a node - getContentEditable: function(node) { - var contentEditable; - - // Check type - if (node.nodeType != 1) { - return null; - } - - // Check for fake content editable - contentEditable = node.getAttribute("data-mce-contenteditable"); - if (contentEditable && contentEditable !== "inherit") { - return contentEditable; - } - - // Check for real content editable - return node.contentEditable !== "inherit" ? node.contentEditable : null; - }, - - /** - * Destroys all internal references to the DOM to solve IE leak issues. - * - * @method destroy - */ - destroy: function() { - var self = this; - - // Unbind all events bound to window/document by editor instance - if (self.boundEvents) { - var i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - this.events.unbind(item[0], item[1], item[2]); - } - - self.boundEvents = null; - } - - // Restore sizzle document to window.document - // Since the current document might be removed producing "Permission denied" on IE see #6325 - if (Sizzle.setDocument) { - Sizzle.setDocument(); - } - - self.win = self.doc = self.root = self.events = self.frag = null; - }, - - // #ifdef debug - - dumpRng: function(r) { - return ( - 'startContainer: ' + r.startContainer.nodeName + - ', startOffset: ' + r.startOffset + - ', endContainer: ' + r.endContainer.nodeName + - ', endOffset: ' + r.endOffset - ); - }, - - // #endif - - _findSib: function(node, selector, name) { - var self = this, func = selector; - - if (node) { - // If expression make a function of it using is - if (typeof(func) == 'string') { - func = function(node) { - return self.is(node, selector); - }; - } - - // Loop all siblings - for (node = node[name]; node; node = node[name]) { - if (func(node)) { - return node; - } - } - } - - return null; - } - }; - - /** - * Instance of DOMUtils for the current document. - * - * @static - * @property DOM - * @type tinymce.dom.DOMUtils - * @example - * // Example of how to add a class to some element by id - * tinymce.DOM.addClass('someid', 'someclass'); - */ - DOMUtils.DOM = new DOMUtils(document); - - return DOMUtils; -}); - -// Included from: js/tinymce/classes/dom/ScriptLoader.js - -/** - * ScriptLoader.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*globals console*/ - -/** - * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks - * when various items gets loaded. This class is useful to load external JavaScript files. - * - * @class tinymce.dom.ScriptLoader - * @example - * // Load a script from a specific URL using the global script loader - * tinymce.ScriptLoader.load('somescript.js'); - * - * // Load a script using a unique instance of the script loader - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.load('somescript.js'); - * - * // Load multiple scripts - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.add('somescript1.js'); - * scriptLoader.add('somescript2.js'); - * scriptLoader.add('somescript3.js'); - * - * scriptLoader.loadQueue(function() { - * alert('All scripts are now loaded.'); - * }); - */ -define("tinymce/dom/ScriptLoader", [ - "tinymce/dom/DOMUtils", - "tinymce/util/Tools" -], function(DOMUtils, Tools) { - var DOM = DOMUtils.DOM; - var each = Tools.each, grep = Tools.grep; - - function ScriptLoader() { - var QUEUED = 0, - LOADING = 1, - LOADED = 2, - states = {}, - queue = [], - scriptLoadedCallbacks = {}, - queueLoadedCallbacks = [], - loading = 0, - undef; - - /** - * Loads a specific script directly without adding it to the load queue. - * - * @method load - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - function loadScript(url, callback) { - var dom = DOM, elm, id; - - // Execute callback when script is loaded - function done() { - dom.remove(id); - - if (elm) { - elm.onreadystatechange = elm.onload = elm = null; - } - - callback(); - } - - function error() { - /*eslint no-console:0 */ - - // Report the error so it's easier for people to spot loading errors - if (typeof(console) !== "undefined" && console.log) { - console.log("Failed to load: " + url); - } - - // We can't mark it as done if there is a load error since - // A) We don't want to produce 404 errors on the server and - // B) the onerror event won't fire on all browsers. - // done(); - } - - id = dom.uniqueId(); - - // Create new script element - elm = document.createElement('script'); - elm.id = id; - elm.type = 'text/javascript'; - elm.src = url; - - // Seems that onreadystatechange works better on IE 10 onload seems to fire incorrectly - if ("onreadystatechange" in elm) { - elm.onreadystatechange = function() { - if (/loaded|complete/.test(elm.readyState)) { - done(); - } - }; - } else { - elm.onload = done; - } - - // Add onerror event will get fired on some browsers but not all of them - elm.onerror = error; - - // Add script to document - (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); - } - - /** - * Returns true/false if a script has been loaded or not. - * - * @method isDone - * @param {String} url URL to check for. - * @return {Boolean} true/false if the URL is loaded. - */ - this.isDone = function(url) { - return states[url] == LOADED; - }; - - /** - * Marks a specific script to be loaded. This can be useful if a script got loaded outside - * the script loader or to skip it from loading some script. - * - * @method markDone - * @param {string} u Absolute URL to the script to mark as loaded. - */ - this.markDone = function(url) { - states[url] = LOADED; - }; - - /** - * Adds a specific script to the load queue of the script loader. - * - * @method add - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.add = this.load = function(url, callback, scope) { - var state = states[url]; - - // Add url to load queue - if (state == undef) { - queue.push(url); - states[url] = QUEUED; - } - - if (callback) { - // Store away callback for later execution - if (!scriptLoadedCallbacks[url]) { - scriptLoadedCallbacks[url] = []; - } - - scriptLoadedCallbacks[url].push({ - func: callback, - scope: scope || this - }); - } - }; - - /** - * Starts the loading of the queue. - * - * @method loadQueue - * @param {function} callback Optional callback to execute when all queued items are loaded. - * @param {Object} scope Optional scope to execute the callback in. - */ - this.loadQueue = function(callback, scope) { - this.loadScripts(queue, callback, scope); - }; - - /** - * Loads the specified queue of files and executes the callback ones they are loaded. - * This method is generally not used outside this class but it might be useful in some scenarios. - * - * @method loadScripts - * @param {Array} scripts Array of queue items to load. - * @param {function} callback Optional callback to execute ones all items are loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.loadScripts = function(scripts, callback, scope) { - var loadScripts; - - function execScriptLoadedCallbacks(url) { - // Execute URL callback functions - each(scriptLoadedCallbacks[url], function(callback) { - callback.func.call(callback.scope); - }); - - scriptLoadedCallbacks[url] = undef; - } - - queueLoadedCallbacks.push({ - func: callback, - scope: scope || this - }); - - loadScripts = function() { - var loadingScripts = grep(scripts); - - // Current scripts has been handled - scripts.length = 0; - - // Load scripts that needs to be loaded - each(loadingScripts, function(url) { - // Script is already loaded then execute script callbacks directly - if (states[url] == LOADED) { - execScriptLoadedCallbacks(url); - return; - } - - // Is script not loading then start loading it - if (states[url] != LOADING) { - states[url] = LOADING; - loading++; - - loadScript(url, function() { - states[url] = LOADED; - loading--; - - execScriptLoadedCallbacks(url); - - // Load more scripts if they where added by the recently loaded script - loadScripts(); - }); - } - }); - - // No scripts are currently loading then execute all pending queue loaded callbacks - if (!loading) { - each(queueLoadedCallbacks, function(callback) { - callback.func.call(callback.scope); - }); - - queueLoadedCallbacks.length = 0; - } - }; - - loadScripts(); - }; - } - - ScriptLoader.ScriptLoader = new ScriptLoader(); - - return ScriptLoader; -}); - -// Included from: js/tinymce/classes/AddOnManager.js - -/** - * AddOnManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the loading of themes/plugins or other add-ons and their language packs. - * - * @class tinymce.AddOnManager - */ -define("tinymce/AddOnManager", [ - "tinymce/dom/ScriptLoader", - "tinymce/util/Tools" -], function(ScriptLoader, Tools) { - var each = Tools.each; - - function AddOnManager() { - var self = this; - - self.items = []; - self.urls = {}; - self.lookup = {}; - } - - AddOnManager.prototype = { - /** - * Returns the specified add on by the short name. - * - * @method get - * @param {String} name Add-on to look for. - * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. - */ - get: function(name) { - if (this.lookup[name]) { - return this.lookup[name].instance; - } else { - return undefined; - } - }, - - dependencies: function(name) { - var result; - - if (this.lookup[name]) { - result = this.lookup[name].dependencies; - } - - return result || []; - }, - - /** - * Loads a language pack for the specified add-on. - * - * @method requireLangPack - * @param {String} name Short name of the add-on. - * @param {String} languages Optional comma or space separated list of languages to check if it matches the name. - */ - requireLangPack: function(name, languages) { - if (AddOnManager.language && AddOnManager.languageLoad !== false) { - if (languages && new RegExp('([, ]|\\b)' + AddOnManager.language + '([, ]|\\b)').test(languages) === false) { - return; - } - - ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + AddOnManager.language + '.js'); - } - }, - - /** - * Adds a instance of the add-on by it's short name. - * - * @method add - * @param {String} id Short name/id for the add-on. - * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. - * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. - * @example - * // Create a simple plugin - * tinymce.create('tinymce.plugins.TestPlugin', { - * TestPlugin: function(ed, url) { - * ed.on('click', function(e) { - * ed.windowManager.alert('Hello World!'); - * }); - * } - * }); - * - * // Register plugin using the add method - * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-test' // Init the plugin but don't try to load it - * }); - */ - add: function(id, addOn, dependencies) { - this.items.push(addOn); - this.lookup[id] = {instance: addOn, dependencies: dependencies}; - - return addOn; - }, - - createUrl: function(baseUrl, dep) { - if (typeof dep === "object") { - return dep; - } else { - return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; - } - }, - - /** - * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. - * This should be used in development mode. A new compressor/javascript munger process will ensure that the - * components are put together into the plugin.js file and compressed correctly. - * - * @method addComponents - * @param {String} pluginName name of the plugin to load scripts from (will be used to get the base url for the plugins). - * @param {Array} scripts Array containing the names of the scripts to load. - */ - addComponents: function(pluginName, scripts) { - var pluginUrl = this.urls[pluginName]; - - each(scripts, function(script) { - ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); - }); - }, - - /** - * Loads an add-on from a specific url. - * - * @method load - * @param {String} name Short name of the add-on that gets loaded. - * @param {String} addOnUrl URL to the add-on that will get loaded. - * @param {function} callback Optional callback to execute ones the add-on is loaded. - * @param {Object} scope Optional scope to execute the callback in. - * @example - * // Loads a plugin from an external URL - * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-myplugin' // Don't try to load it again - * }); - */ - load: function(name, addOnUrl, callback, scope) { - var self = this, url = addOnUrl; - - function loadDependencies() { - var dependencies = self.dependencies(name); - - each(dependencies, function(dep) { - var newUrl = self.createUrl(addOnUrl, dep); - - self.load(newUrl.resource, newUrl, undefined, undefined); - }); - - if (callback) { - if (scope) { - callback.call(scope); - } else { - callback.call(ScriptLoader); - } - } - } - - if (self.urls[name]) { - return; - } - - if (typeof addOnUrl === "object") { - url = addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix; - } - - if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) { - url = AddOnManager.baseURL + '/' + url; - } - - self.urls[name] = url.substring(0, url.lastIndexOf('/')); - - if (self.lookup[name]) { - loadDependencies(); - } else { - ScriptLoader.ScriptLoader.add(url, loadDependencies, scope); - } - } - }; - - AddOnManager.PluginManager = new AddOnManager(); - AddOnManager.ThemeManager = new AddOnManager(); - - return AddOnManager; -}); - -/** - * TinyMCE theme class. - * - * @class tinymce.Theme - */ - -/** - * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. - * - * @method renderUI - * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. - * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. - */ - -/** - * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. - * - * @class tinymce.Plugin - * @example - * tinymce.PluginManager.add('example', function(editor, url) { - * // Add a button that opens a window - * editor.addButton('example', { - * text: 'My button', - * icon: false, - * onclick: function() { - * // Open window - * editor.windowManager.open({ - * title: 'Example plugin', - * body: [ - * {type: 'textbox', name: 'title', label: 'Title'} - * ], - * onsubmit: function(e) { - * // Insert content when the window form is submitted - * editor.insertContent('Title: ' + e.data.title); - * } - * }); - * } - * }); - * - * // Adds a menu item to the tools menu - * editor.addMenuItem('example', { - * text: 'Example plugin', - * context: 'tools', - * onclick: function() { - * // Open window with a specific url - * editor.windowManager.open({ - * title: 'TinyMCE site', - * url: 'http://www.tinymce.com', - * width: 800, - * height: 600, - * buttons: [{ - * text: 'Close', - * onclick: 'close' - * }] - * }); - * } - * }); - * }); - */ - -// Included from: js/tinymce/classes/html/Node.js - -/** - * Node.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is a minimalistic implementation of a DOM like node used by the DomParser class. - * - * @example - * var node = new tinymce.html.Node('strong', 1); - * someRoot.append(node); - * - * @class tinymce.html.Node - * @version 3.4 - */ -define("tinymce/html/Node", [], function() { - var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { - '#text': 3, - '#comment': 8, - '#cdata': 4, - '#pi': 7, - '#doctype': 10, - '#document-fragment': 11 - }; - - // Walks the tree left/right - function walk(node, root_node, prev) { - var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; - - // Walk into nodes if it has a start - if (node[startName]) { - return node[startName]; - } - - // Return the sibling if it has one - if (node !== root_node) { - sibling = node[siblingName]; - - if (sibling) { - return sibling; - } - - // Walk up the parents to look for siblings - for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { - sibling = parent[siblingName]; - - if (sibling) { - return sibling; - } - } - } - } - - /** - * Constructs a new Node instance. - * - * @constructor - * @method Node - * @param {String} name Name of the node type. - * @param {Number} type Numeric type representing the node. - */ - function Node(name, type) { - this.name = name; - this.type = type; - - if (type === 1) { - this.attributes = []; - this.attributes.map = {}; - } - } - - Node.prototype = { - /** - * Replaces the current node with the specified one. - * - * @example - * someNode.replace(someNewNode); - * - * @method replace - * @param {tinymce.html.Node} node Node to replace the current node with. - * @return {tinymce.html.Node} The old node that got replaced. - */ - replace: function(node) { - var self = this; - - if (node.parent) { - node.remove(); - } - - self.insert(node, self); - self.remove(); - - return self; - }, - - /** - * Gets/sets or removes an attribute by name. - * - * @example - * someNode.attr("name", "value"); // Sets an attribute - * console.log(someNode.attr("name")); // Gets an attribute - * someNode.attr("name", null); // Removes an attribute - * - * @method attr - * @param {String} name Attribute name to set or get. - * @param {String} value Optional value to set. - * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. - */ - attr: function(name, value) { - var self = this, attrs, i, undef; - - if (typeof name !== "string") { - for (i in name) { - self.attr(i, name[i]); - } - - return self; - } - - if ((attrs = self.attributes)) { - if (value !== undef) { - // Remove attribute - if (value === null) { - if (name in attrs.map) { - delete attrs.map[name]; - - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs = attrs.splice(i, 1); - return self; - } - } - } - - return self; - } - - // Set attribute - if (name in attrs.map) { - // Set attribute - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs[i].value = value; - break; - } - } - } else { - attrs.push({name: name, value: value}); - } - - attrs.map[name] = value; - - return self; - } else { - return attrs.map[name]; - } - } - }, - - /** - * Does a shallow clones the node into a new node. It will also exclude id attributes since - * there should only be one id per document. - * - * @example - * var clonedNode = node.clone(); - * - * @method clone - * @return {tinymce.html.Node} New copy of the original node. - */ - clone: function() { - var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; - - // Clone element attributes - if ((selfAttrs = self.attributes)) { - cloneAttrs = []; - cloneAttrs.map = {}; - - for (i = 0, l = selfAttrs.length; i < l; i++) { - selfAttr = selfAttrs[i]; - - // Clone everything except id - if (selfAttr.name !== 'id') { - cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; - cloneAttrs.map[selfAttr.name] = selfAttr.value; - } - } - - clone.attributes = cloneAttrs; - } - - clone.value = self.value; - clone.shortEnded = self.shortEnded; - - return clone; - }, - - /** - * Wraps the node in in another node. - * - * @example - * node.wrap(wrapperNode); - * - * @method wrap - */ - wrap: function(wrapper) { - var self = this; - - self.parent.insert(wrapper, self); - wrapper.append(self); - - return self; - }, - - /** - * Unwraps the node in other words it removes the node but keeps the children. - * - * @example - * node.unwrap(); - * - * @method unwrap - */ - unwrap: function() { - var self = this, node, next; - - for (node = self.firstChild; node; ) { - next = node.next; - self.insert(node, self, true); - node = next; - } - - self.remove(); - }, - - /** - * Removes the node from it's parent. - * - * @example - * node.remove(); - * - * @method remove - * @return {tinymce.html.Node} Current node that got removed. - */ - remove: function() { - var self = this, parent = self.parent, next = self.next, prev = self.prev; - - if (parent) { - if (parent.firstChild === self) { - parent.firstChild = next; - - if (next) { - next.prev = null; - } - } else { - prev.next = next; - } - - if (parent.lastChild === self) { - parent.lastChild = prev; - - if (prev) { - prev.next = null; - } - } else { - next.prev = prev; - } - - self.parent = self.next = self.prev = null; - } - - return self; - }, - - /** - * Appends a new node as a child of the current node. - * - * @example - * node.append(someNode); - * - * @method append - * @param {tinymce.html.Node} node Node to append as a child of the current one. - * @return {tinymce.html.Node} The node that got appended. - */ - append: function(node) { - var self = this, last; - - if (node.parent) { - node.remove(); - } - - last = self.lastChild; - if (last) { - last.next = node; - node.prev = last; - self.lastChild = node; - } else { - self.lastChild = self.firstChild = node; - } - - node.parent = self; - - return node; - }, - - /** - * Inserts a node at a specific position as a child of the current node. - * - * @example - * parentNode.insert(newChildNode, oldChildNode); - * - * @method insert - * @param {tinymce.html.Node} node Node to insert as a child of the current node. - * @param {tinymce.html.Node} ref_node Reference node to set node before/after. - * @param {Boolean} before Optional state to insert the node before the reference node. - * @return {tinymce.html.Node} The node that got inserted. - */ - insert: function(node, ref_node, before) { - var parent; - - if (node.parent) { - node.remove(); - } - - parent = ref_node.parent || this; - - if (before) { - if (ref_node === parent.firstChild) { - parent.firstChild = node; - } else { - ref_node.prev.next = node; - } - - node.prev = ref_node.prev; - node.next = ref_node; - ref_node.prev = node; - } else { - if (ref_node === parent.lastChild) { - parent.lastChild = node; - } else { - ref_node.next.prev = node; - } - - node.next = ref_node.next; - node.prev = ref_node; - ref_node.next = node; - } - - node.parent = parent; - - return node; - }, - - /** - * Get all children by name. - * - * @method getAll - * @param {String} name Name of the child nodes to collect. - * @return {Array} Array with child nodes matchin the specified name. - */ - getAll: function(name) { - var self = this, node, collection = []; - - for (node = self.firstChild; node; node = walk(node, self)) { - if (node.name === name) { - collection.push(node); - } - } - - return collection; - }, - - /** - * Removes all children of the current node. - * - * @method empty - * @return {tinymce.html.Node} The current node that got cleared. - */ - empty: function() { - var self = this, nodes, i, node; - - // Remove all children - if (self.firstChild) { - nodes = []; - - // Collect the children - for (node = self.firstChild; node; node = walk(node, self)) { - nodes.push(node); - } - - // Remove the children - i = nodes.length; - while (i--) { - node = nodes[i]; - node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; - } - } - - self.firstChild = self.lastChild = null; - - return self; - }, - - /** - * Returns true/false if the node is to be considered empty or not. - * - * @example - * node.isEmpty({img: true}); - * @method isEmpty - * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. - * @return {Boolean} true/false if the node is empty or not. - */ - isEmpty: function(elements) { - var self = this, node = self.firstChild, i, name; - - if (node) { - do { - if (node.type === 1) { - // Ignore bogus elements - if (node.attributes.map['data-mce-bogus']) { - continue; - } - - // Keep empty elements likea
b
c will becomea
b
c
- * - * @example - * var parser = new tinymce.html.DomParser({validate: true}, schema); - * var rootNode = parser.parse('x
->x
- function trim(rootBlockNode) { - if (rootBlockNode) { - node = rootBlockNode.firstChild; - if (node && node.type == 3) { - node.value = node.value.replace(startWhiteSpaceRegExp, ''); - } - - node = rootBlockNode.lastChild; - if (node && node.type == 3) { - node.value = node.value.replace(endWhiteSpaceRegExp, ''); - } - } - } - - // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root - if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { - return; - } - - while (node) { - next = node.next; - - if (node.type == 3 || (node.type == 1 && node.name !== 'p' && - !blockElements[node.name] && !node.attr('data-mce-type'))) { - if (!rootBlockNode) { - // Create a new root block element - rootBlockNode = createNode(rootBlockName, 1); - rootBlockNode.attr(settings.forced_root_block_attrs); - rootNode.insert(rootBlockNode, node); - rootBlockNode.append(node); - } else { - rootBlockNode.append(node); - } - } else { - trim(rootBlockNode); - rootBlockNode = null; - } - - node = next; - } - - trim(rootBlockNode); - } - - function createNode(name, type) { - var node = new Node(name, type), list; - - if (name in nodeFilters) { - list = matchedNodes[name]; - - if (list) { - list.push(node); - } else { - matchedNodes[name] = [node]; - } - } - - return node; - } - - function removeWhitespaceBefore(node) { - var textNode, textVal, sibling; - - for (textNode = node.prev; textNode && textNode.type === 3; ) { - textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); - - if (textVal.length > 0) { - textNode.value = textVal; - textNode = textNode.prev; - } else { - sibling = textNode.prev; - textNode.remove(); - textNode = sibling; - } - } - } - - function cloneAndExcludeBlocks(input) { - var name, output = {}; - - for (name in input) { - if (name !== 'li' && name != 'p') { - output[name] = input[name]; - } - } - - return output; - } - - parser = new SaxParser({ - validate: validate, - allow_script_urls: settings.allow_script_urls, - allow_conditional_comments: settings.allow_conditional_comments, - - // Exclude P and LI from DOM parsing since it's treated better by the DOM parser - self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), - - cdata: function(text) { - node.append(createNode('#cdata', 4)).value = text; - }, - - text: function(text, raw) { - var textNode; - - // Trim all redundant whitespace on non white space elements - if (!isInWhiteSpacePreservedElement) { - text = text.replace(allWhiteSpaceRegExp, ' '); - - if (node.lastChild && blockElements[node.lastChild.name]) { - text = text.replace(startWhiteSpaceRegExp, ''); - } - } - - // Do we need to create the node - if (text.length !== 0) { - textNode = createNode('#text', 3); - textNode.raw = !!raw; - node.append(textNode).value = text; - } - }, - - comment: function(text) { - node.append(createNode('#comment', 8)).value = text; - }, - - pi: function(name, text) { - node.append(createNode(name, 7)).value = text; - removeWhitespaceBefore(node); - }, - - doctype: function(text) { - var newNode; - - newNode = node.append(createNode('#doctype', 10)); - newNode.value = text; - removeWhitespaceBefore(node); - }, - - start: function(name, attrs, empty) { - var newNode, attrFiltersLen, elementRule, attrName, parent; - - elementRule = validate ? schema.getElementRule(name) : {}; - if (elementRule) { - newNode = createNode(elementRule.outputName || name, 1); - newNode.attributes = attrs; - newNode.shortEnded = empty; - - node.append(newNode); - - // Check if node is valid child of the parent node is the child is - // unknown we don't collect it since it's probably a custom element - parent = children[node.name]; - if (parent && children[newNode.name] && !parent[newNode.name]) { - invalidChildren.push(newNode); - } - - attrFiltersLen = attributeFilters.length; - while (attrFiltersLen--) { - attrName = attributeFilters[attrFiltersLen].name; - - if (attrName in attrs.map) { - list = matchedAttributes[attrName]; - - if (list) { - list.push(newNode); - } else { - matchedAttributes[attrName] = [newNode]; - } - } - } - - // Trim whitespace before block - if (blockElements[name]) { - removeWhitespaceBefore(newNode); - } - - // Change current node if the element wasn't empty i.e nota
- lastParent = node; - while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) { - lastParent = parent; - - if (blockElements[parent.name]) { - break; - } - - parent = parent.parent; - } - - if (lastParent === parent) { - textNode = new Node('#text', 3); - textNode.value = '\u00a0'; - node.replace(textNode); - } - } - } - }); - } - - // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. - if (!settings.allow_html_in_named_anchor) { - self.addAttributeFilter('id,name', function(nodes) { - var i = nodes.length, sibling, prevSibling, parent, node; - - while (i--) { - node = nodes[i]; - if (node.name === 'a' && node.firstChild && !node.attr('href')) { - parent = node.parent; - - // Move children after current node - sibling = node.lastChild; - do { - prevSibling = sibling.prev; - parent.insert(sibling, node); - sibling = prevSibling; - } while (sibling); - } - } - }); - } - }; -}); - -// Included from: js/tinymce/classes/html/Writer.js - -/** - * Writer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. - * - * @class tinymce.html.Writer - * @example - * var writer = new tinymce.html.Writer({indent: true}); - * var parser = new tinymce.html.SaxParser(writer).parse('
.
- *
- * @method start
- * @param {String} name Name of the element.
- * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
- * @param {Boolean} empty Optional empty state if the tag should end like
.
- */
- start: function(name, attrs, empty) {
- var i, l, attr, value;
-
- if (indent && indentBefore[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
-
- html.push('<', name);
-
- if (attrs) {
- for (i = 0, l = attrs.length; i < l; i++) {
- attr = attrs[i];
- html.push(' ', attr.name, '="', encode(attr.value, true), '"');
- }
- }
-
- if (!empty || htmlOutput) {
- html[html.length] = '>';
- } else {
- html[html.length] = ' />';
- }
-
- if (empty && indent && indentAfter[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
- },
-
- /**
- * Writes the a end element such as
text
')); - * @class tinymce.html.Serializer - * @version 3.4 - */ -define("tinymce/html/Serializer", [ - "tinymce/html/Writer", - "tinymce/html/Schema" -], function(Writer, Schema) { - /** - * Constructs a new Serializer instance. - * - * @constructor - * @method Serializer - * @param {Object} settings Name/value settings object. - * @param {tinymce.html.Schema} schema Schema instance to use. - */ - return function(settings, schema) { - var self = this, writer = new Writer(settings); - - settings = settings || {}; - settings.validate = "validate" in settings ? settings.validate : true; - - self.schema = schema = schema || new Schema(); - self.writer = writer; - - /** - * Serializes the specified node into a string. - * - * @example - * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('text
')); - * @method serialize - * @param {tinymce.html.Node} node Node instance to serialize. - * @return {String} String with HTML based on DOM tree. - */ - self.serialize = function(node) { - var handlers, validate; - - validate = settings.validate; - - handlers = { - // #text - 3: function(node) { - writer.text(node.value, node.raw); - }, - - // #comment - 8: function(node) { - writer.comment(node.value); - }, - - // Processing instruction - 7: function(node) { - writer.pi(node.name, node.value); - }, - - // Doctype - 10: function(node) { - writer.doctype(node.value); - }, - - // CDATA - 4: function(node) { - writer.cdata(node.value); - }, - - // Document fragment - 11: function(node) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - } - }; - - writer.reset(); - - function walk(node) { - var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; - - if (!handler) { - name = node.name; - isEmpty = node.shortEnded; - attrs = node.attributes; - - // Sort attributes - if (validate && attrs && attrs.length > 1) { - sortedAttrs = []; - sortedAttrs.map = {}; - - elementRule = schema.getElementRule(node.name); - for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { - attrName = elementRule.attributesOrder[i]; - - if (attrName in attrs.map) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - for (i = 0, l = attrs.length; i < l; i++) { - attrName = attrs[i].name; - - if (!(attrName in sortedAttrs.map)) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - attrs = sortedAttrs; - } - - writer.start(node.name, attrs, isEmpty); - - if (!isEmpty) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - - writer.end(name); - } - } else { - handler(node); - } - } - - // Serialize element and treat all non elements as fragments - if (node.type == 1 && !settings.inner) { - walk(node); - } else { - handlers[11](node); - } - - return writer.getContent(); - }; - }; -}); - -// Included from: js/tinymce/classes/dom/Serializer.js - -/** - * Serializer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for - * more details and examples on how to use this class. - * - * @class tinymce.dom.Serializer - */ -define("tinymce/dom/Serializer", [ - "tinymce/dom/DOMUtils", - "tinymce/html/DomParser", - "tinymce/html/Entities", - "tinymce/html/Serializer", - "tinymce/html/Node", - "tinymce/html/Schema", - "tinymce/Env", - "tinymce/util/Tools" -], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { - var each = Tools.each, trim = Tools.trim; - var DOM = DOMUtils.DOM; - - /** - * Constructs a new DOM serializer class. - * - * @constructor - * @method Serializer - * @param {Object} settings Serializer settings object. - * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. - */ - return function(settings, editor) { - var dom, schema, htmlParser; - - if (editor) { - dom = editor.dom; - schema = editor.schema; - } - - // Default DOM and Schema if they are undefined - dom = dom || DOM; - schema = schema || new Schema(settings); - settings.entity_encoding = settings.entity_encoding || 'named'; - settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; - - htmlParser = new DomParser(settings, schema); - - // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed - htmlParser.addAttributeFilter('src,href,style', function(nodes, name) { - var i = nodes.length, node, value, internalName = 'data-mce-' + name; - var urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef; - - while (i--) { - node = nodes[i]; - - value = node.attributes.map[internalName]; - if (value !== undef) { - // Set external name to internal value and remove internal - node.attr(name, value.length > 0 ? value : null); - node.attr(internalName, null); - } else { - // No internal attribute found then convert the value we have in the DOM - value = node.attributes.map[name]; - - if (name === "style") { - value = dom.serializeStyle(dom.parseStyle(value), node.name); - } else if (urlConverter) { - value = urlConverter.call(urlConverterScope, value, name, node.name); - } - - node.attr(name, value.length > 0 ? value : null); - } - } - }); - - // Remove internal classes mceItem<..> or mceSelected - htmlParser.addAttributeFilter('class', function(nodes) { - var i = nodes.length, node, value; - - while (i--) { - node = nodes[i]; - value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, ''); - node.attr('class', value.length > 0 ? value : null); - } - }); - - // Remove bookmark elements - htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) { - node.remove(); - } - } - }); - - // Remove expando attributes - htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - htmlParser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i].firstChild; - - if (node) { - node.value = Entities.decode(node.value); - } - } - }); - - // Force script into CDATA sections and remove the mce- prefix also add comments around styles - htmlParser.addNodeFilter('script,style', function(nodes, name) { - var i = nodes.length, node, value; - - function trim(value) { - /*jshint maxlen:255 */ - /*eslint max-len:0 */ - return value.replace(/()/g, '\n') - .replace(/^[\r\n]*|[\r\n]*$/g, '') - .replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, ''); - } - - while (i--) { - node = nodes[i]; - value = node.firstChild ? node.firstChild.value : ''; - - if (name === "script") { - // Remove mce- prefix from script elements and remove default text/javascript mime type (HTML5) - var type = (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''); - node.attr('type', type === 'text/javascript' ? null : type); - - if (value.length > 0) { - node.firstChild.value = '// '; - } - } else { - if (value.length > 0) { - node.firstChild.value = ''; - } - } - } - }); - - // Convert comments to cdata and handle protected comments - htmlParser.addNodeFilter('#comment', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.value.indexOf('[CDATA[') === 0) { - node.name = '#cdata'; - node.type = 4; - node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, ''); - } else if (node.value.indexOf('mce:protected ') === 0) { - node.name = "#text"; - node.type = 3; - node.raw = true; - node.value = unescape(node.value).substr(14); - } - } - }); - - htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - if (node.type === 7) { - node.remove(); - } else if (node.type === 1) { - if (name === "input" && !("type" in node.attributes.map)) { - node.attr('type', 'text'); - } - } - } - }); - - // Fix list elements, TODO: Replace this later - if (settings.fix_list_elements) { - htmlParser.addNodeFilter('ul,ol', function(nodes) { - var i = nodes.length, node, parentNode; - - while (i--) { - node = nodes[i]; - parentNode = node.parent; - - if (parentNode.name === 'ul' || parentNode.name === 'ol') { - if (node.prev && node.prev.name === 'li') { - node.prev.append(node); - } - } - } - }); - } - - // Remove internal data attributes - htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,data-mce-selected', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - // Return public methods - return { - /** - * Schema instance that was used to when the Serializer was constructed. - * - * @field {tinymce.html.Schema} schema - */ - schema: schema, - - /** - * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addNodeFilter('p,h1', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addNodeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addNodeFilter: htmlParser.addNodeFilter, - - /** - * Adds a attribute filter function to the parser used by the serializer, the parser will - * collect nodes that has the specified attributes - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addAttributeFilter('src,href', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addAttributeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addAttributeFilter: htmlParser.addAttributeFilter, - - /** - * Serializes the specified browser DOM node into a HTML string. - * - * @method serialize - * @param {DOMNode} node DOM node to serialize. - * @param {Object} args Arguments option that gets passed to event handlers. - */ - serialize: function(node, args) { - var self = this, impl, doc, oldDoc, htmlSerializer, content; - - // Explorer won't clone contents of script and style and the - // selected index of select elements are cleared on a clone operation. - if (Env.ie && dom.select('script,style,select,map').length > 0) { - content = node.innerHTML; - node = node.cloneNode(false); - dom.setHTML(node, content); - } else { - node = node.cloneNode(true); - } - - // Nodes needs to be attached to something in WebKit/Opera - // This fix will make DOM ranges and make Sizzle happy! - impl = node.ownerDocument.implementation; - if (impl.createHTMLDocument) { - // Create an empty HTML document - doc = impl.createHTMLDocument(""); - - // Add the element or it's children if it's a body element to the new document - each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) { - doc.body.appendChild(doc.importNode(node, true)); - }); - - // Grab first child or body element for serialization - if (node.nodeName != 'BODY') { - node = doc.body.firstChild; - } else { - node = doc.body; - } - - // set the new document in DOMUtils so createElement etc works - oldDoc = dom.doc; - dom.doc = doc; - } - - args = args || {}; - args.format = args.format || 'html'; - - // Don't wrap content if we want selected html - if (args.selection) { - args.forced_root_block = ''; - } - - // Pre process - if (!args.no_events) { - args.node = node; - self.onPreProcess(args); - } - - // Setup serializer - htmlSerializer = new Serializer(settings, schema); - - // Parse and serialize HTML - args.content = htmlSerializer.serialize( - htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args) - ); - - // Replace all BOM characters for now until we can find a better solution - if (!args.cleanup) { - args.content = args.content.replace(/\uFEFF/g, ''); - } - - // Post process - if (!args.no_events) { - self.onPostProcess(args); - } - - // Restore the old document if it was changed - if (oldDoc) { - dom.doc = oldDoc; - } - - args.node = null; - - return args.content; - }, - - /** - * Adds valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method addRules - * @param {String} rules Valid elements rules string to add to schema. - */ - addRules: function(rules) { - schema.addValidElements(rules); - }, - - /** - * Sets the valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method setRules - * @param {String} rules Valid elements rules string. - */ - setRules: function(rules) { - schema.setValidElements(rules); - }, - - onPreProcess: function(args) { - if (editor) { - editor.fire('PreProcess', args); - } - }, - - onPostProcess: function(args) { - if (editor) { - editor.fire('PostProcess', args); - } - } - }; - }; -}); - -// Included from: js/tinymce/classes/dom/TridentSelection.js - -/** - * TridentSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Selection class for old explorer versions. This one fakes the - * native selection object available on modern browsers. - * - * @class tinymce.dom.TridentSelection - */ -define("tinymce/dom/TridentSelection", [], function() { - function Selection(selection) { - var self = this, dom = selection.dom, FALSE = false; - - function getPosition(rng, start) { - var checkRng, startIndex = 0, endIndex, inside, - children, child, offset, index, position = -1, parent; - - // Setup test range, collapse it and get the parent - checkRng = rng.duplicate(); - checkRng.collapse(start); - parent = checkRng.parentElement(); - - // Check if the selection is within the right document - if (parent.ownerDocument !== selection.dom.doc) { - return; - } - - // IE will report non editable elements as it's parent so look for an editable one - while (parent.contentEditable === "false") { - parent = parent.parentNode; - } - - // If parent doesn't have any children then return that we are inside the element - if (!parent.hasChildNodes()) { - return {node: parent, inside: 1}; - } - - // Setup node list and endIndex - children = parent.children; - endIndex = children.length - 1; - - // Perform a binary search for the position - while (startIndex <= endIndex) { - index = Math.floor((startIndex + endIndex) / 2); - - // Move selection to node and compare the ranges - child = children[index]; - checkRng.moveToElementText(child); - position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng); - - // Before/after or an exact match - if (position > 0) { - endIndex = index - 1; - } else if (position < 0) { - startIndex = index + 1; - } else { - return {node: child}; - } - } - - // Check if child position is before or we didn't find a position - if (position < 0) { - // No element child was found use the parent element and the offset inside that - if (!child) { - checkRng.moveToElementText(parent); - checkRng.collapse(true); - child = parent; - inside = true; - } else { - checkRng.collapse(false); - } - - // Walk character by character in text node until we hit the selected range endpoint, - // hit the end of document or parent isn't the right one - // We need to walk char by char since rng.text or rng.htmlText will trim line endings - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } else { - // Child position is after the selection endpoint - checkRng.collapse(true); - - // Walk character by character in text node until we hit the selected range endpoint, hit - // the end of document or parent isn't the right one - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } - - return {node: child, position: position, offset: offset, inside: inside}; - } - - // Returns a W3C DOM compatible range object by using the IE Range API - function getRange() { - var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark; - - // If selection is outside the current document just return an empty range - element = ieRange.item ? ieRange.item(0) : ieRange.parentElement(); - if (element.ownerDocument != dom.doc) { - return domRange; - } - - collapsed = selection.isCollapsed(); - - // Handle control selection - if (ieRange.item) { - domRange.setStart(element.parentNode, dom.nodeIndex(element)); - domRange.setEnd(domRange.startContainer, domRange.startOffset + 1); - - return domRange; - } - - function findEndPoint(start) { - var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue; - - container = endPoint.node; - offset = endPoint.offset; - - if (endPoint.inside && !container.hasChildNodes()) { - domRange[start ? 'setStart' : 'setEnd'](container, 0); - return; - } - - if (offset === undef) { - domRange[start ? 'setStartBefore' : 'setEndAfter'](container); - return; - } - - if (endPoint.position < 0) { - sibling = endPoint.inside ? container.firstChild : container.nextSibling; - - if (!sibling) { - domRange[start ? 'setStartAfter' : 'setEndAfter'](container); - return; - } - - if (!offset) { - if (sibling.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, 0); - } else { - domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling); - } - - return; - } - - // Find the text node and offset - while (sibling) { - nodeValue = sibling.nodeValue; - textNodeOffset += nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - textNodeOffset = nodeValue.length - textNodeOffset; - break; - } - - sibling = sibling.nextSibling; - } - } else { - // Find the text node and offset - sibling = container.previousSibling; - - if (!sibling) { - return domRange[start ? 'setStartBefore' : 'setEndBefore'](container); - } - - // If there isn't any text to loop then use the first position - if (!offset) { - if (container.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length); - } else { - domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling); - } - - return; - } - - while (sibling) { - textNodeOffset += sibling.nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - break; - } - - sibling = sibling.previousSibling; - } - } - - domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset); - } - - try { - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } catch (ex) { - // IE has a nasty bug where text nodes might throw "invalid argument" when you - // access the nodeValue or other properties of text nodes. This seems to happend when - // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it. - if (ex.number == -2147024809) { - // Get the current selection - bookmark = self.getBookmark(2); - - // Get start element - tmpRange = ieRange.duplicate(); - tmpRange.collapse(true); - element = tmpRange.parentElement(); - - // Get end element - if (!collapsed) { - tmpRange = ieRange.duplicate(); - tmpRange.collapse(false); - element2 = tmpRange.parentElement(); - element2.innerHTML = element2.innerHTML; - } - - // Remove the broken elements - element.innerHTML = element.innerHTML; - - // Restore the selection - self.moveToBookmark(bookmark); - - // Since the range has moved we need to re-get it - ieRange = selection.getRng(); - - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } else { - throw ex; // Throw other errors - } - } - - return domRange; - } - - this.getBookmark = function(type) { - var rng = selection.getRng(), bookmark = {}; - - function getIndexes(node) { - var parent, root, children, i, indexes = []; - - parent = node.parentNode; - root = dom.getRoot().parentNode; - - while (parent != root && parent.nodeType !== 9) { - children = parent.children; - - i = children.length; - while (i--) { - if (node === children[i]) { - indexes.push(i); - break; - } - } - - node = parent; - parent = parent.parentNode; - } - - return indexes; - } - - function getBookmarkEndPoint(start) { - var position; - - position = getPosition(rng, start); - if (position) { - return { - position: position.position, - offset: position.offset, - indexes: getIndexes(position.node), - inside: position.inside - }; - } - } - - // Non ubstructive bookmark - if (type === 2) { - // Handle text selection - if (!rng.item) { - bookmark.start = getBookmarkEndPoint(true); - - if (!selection.isCollapsed()) { - bookmark.end = getBookmarkEndPoint(); - } - } else { - bookmark.start = {ctrl: true, indexes: getIndexes(rng.item(0))}; - } - } - - return bookmark; - }; - - this.moveToBookmark = function(bookmark) { - var rng, body = dom.doc.body; - - function resolveIndexes(indexes) { - var node, i, idx, children; - - node = dom.getRoot(); - for (i = indexes.length - 1; i >= 0; i--) { - children = node.children; - idx = indexes[i]; - - if (idx <= children.length - 1) { - node = children[idx]; - } - } - - return node; - } - - function setBookmarkEndPoint(start) { - var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef, offset; - - if (endPoint) { - moveLeft = endPoint.position > 0; - - moveRng = body.createTextRange(); - moveRng.moveToElementText(resolveIndexes(endPoint.indexes)); - - offset = endPoint.offset; - if (offset !== undef) { - moveRng.collapse(endPoint.inside || moveLeft); - moveRng.moveStart('character', moveLeft ? -offset : offset); - } else { - moveRng.collapse(start); - } - - rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng); - - if (start) { - rng.collapse(true); - } - } - } - - if (bookmark.start) { - if (bookmark.start.ctrl) { - rng = body.createControlRange(); - rng.addElement(resolveIndexes(bookmark.start.indexes)); - rng.select(); - } else { - rng = body.createTextRange(); - setBookmarkEndPoint(true); - setBookmarkEndPoint(); - rng.select(); - } - } - }; - - this.addRange = function(rng) { - var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling, - doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; - - function setEndPoint(start) { - var container, offset, marker, tmpRng, nodes; - - marker = dom.create('a'); - container = start ? startContainer : endContainer; - offset = start ? startOffset : endOffset; - tmpRng = ieRng.duplicate(); - - if (container == doc || container == doc.documentElement) { - container = body; - offset = 0; - } - - if (container.nodeType == 3) { - container.parentNode.insertBefore(marker, container); - tmpRng.moveToElementText(marker); - tmpRng.moveStart('character', offset); - dom.remove(marker); - ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); - } else { - nodes = container.childNodes; - - if (nodes.length) { - if (offset >= nodes.length) { - dom.insertAfter(marker, nodes[nodes.length - 1]); - } else { - container.insertBefore(marker, nodes[offset]); - } - - tmpRng.moveToElementText(marker); - } else if (container.canHaveHTML) { - // Empty node selection for example|
would become this:|
- sibling = startContainer.previousSibling; - if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { - sibling.innerHTML = ''; - } else { - sibling = null; - } - - startContainer.innerHTML = ''; - ieRng.moveToElementText(startContainer.lastChild); - ieRng.select(); - dom.doc.selection.clear(); - startContainer.innerHTML = ''; - - if (sibling) { - sibling.innerHTML = ''; - } - return; - } else { - startOffset = dom.nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - } - - if (startOffset == endOffset - 1) { - try { - ctrlElm = startContainer.childNodes[startOffset]; - ctrlRng = body.createControlRange(); - ctrlRng.addElement(ctrlElm); - ctrlRng.select(); - - // Check if the range produced is on the correct element and is a control range - // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 - nativeRng = selection.getRng(); - if (nativeRng.item && ctrlElm === nativeRng.item(0)) { - return; - } - } catch (ex) { - // Ignore - } - } - } - - // Set start/end point of selection - setEndPoint(true); - setEndPoint(); - - // Select the new range and scroll it into view - ieRng.select(); - }; - - // Expose range method - this.getRangeAt = getRange; - } - - return Selection; -}); - -// Included from: js/tinymce/classes/util/VK.js - -/** - * VK.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This file exposes a set of the common KeyCodes for use. Please grow it as needed. - */ -define("tinymce/util/VK", [ - "tinymce/Env" -], function(Env) { - return { - BACKSPACE: 8, - DELETE: 46, - DOWN: 40, - ENTER: 13, - LEFT: 37, - RIGHT: 39, - SPACEBAR: 32, - TAB: 9, - UP: 38, - - modifierPressed: function(e) { - return e.shiftKey || e.ctrlKey || e.altKey; - }, - - metaKeyPressed: function(e) { - // Check if ctrl or meta key is pressed also check if alt is false for Polish users - return (Env.mac ? e.metaKey : e.ctrlKey) && !e.altKey; - } - }; -}); - -// Included from: js/tinymce/classes/dom/ControlSelection.js - -/** - * ControlSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles control selection of elements. Controls are elements - * that can be resized and needs to be selected as a whole. It adds custom resize handles - * to all browser engines that support properly disabling the built in resize logic. - * - * @class tinymce.dom.ControlSelection - */ -define("tinymce/dom/ControlSelection", [ - "tinymce/util/VK", - "tinymce/util/Tools", - "tinymce/Env" -], function(VK, Tools, Env) { - return function(selection, editor) { - var dom = editor.dom, each = Tools.each; - var selectedElm, selectedElmGhost, resizeHandles, selectedHandle, lastMouseDownEvent; - var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; - var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie && Env.ie < 11; - - // Details about each resize handle how to scale etc - resizeHandles = { - // Name: x multiplier, y multiplier, delta size x, delta size y - n: [0.5, 0, 0, -1], - e: [1, 0.5, 1, 0], - s: [0.5, 1, 0, 1], - w: [0, 0.5, -1, 0], - nw: [0, 0, -1, -1], - ne: [1, 0, 1, -1], - se: [1, 1, 1, 1], - sw: [0, 1, -1, 1] - }; - - // Add CSS for resize handles, cloned element and selected - var rootClass = '.mce-content-body'; - editor.contentStyles.push( - rootClass + ' div.mce-resizehandle {' + - 'position: absolute;' + - 'border: 1px solid black;' + - 'background: #FFF;' + - 'width: 5px;' + - 'height: 5px;' + - 'z-index: 10000' + - '}' + - rootClass + ' .mce-resizehandle:hover {' + - 'background: #000' + - '}' + - rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + - 'outline: 1px solid black;' + - 'resize: none' + // Have been talks about implementing this in browsers - '}' + - rootClass + ' .mce-clonedresizable {' + - 'position: absolute;' + - (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing - 'opacity: .5;' + - 'filter: alpha(opacity=50);' + - 'z-index: 10000' + - '}' - ); - - function isResizable(elm) { - var selector = editor.settings.object_resizing; - - if (selector === false || Env.iOS) { - return false; - } - - if (typeof selector != 'string') { - selector = 'table,img,div'; - } - - if (elm.getAttribute('data-mce-resize') === 'false') { - return false; - } - - return editor.dom.is(elm, selector); - } - - function resizeGhostElement(e) { - var deltaX, deltaY; - - // Calc new width/height - deltaX = e.screenX - startX; - deltaY = e.screenY - startY; - - // Calc new size - width = deltaX * selectedHandle[2] + startW; - height = deltaY * selectedHandle[3] + startH; - - // Never scale down lower than 5 pixels - width = width < 5 ? 5 : width; - height = height < 5 ? 5 : height; - - // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image - if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { - width = Math.round(height / ratio); - height = Math.round(width * ratio); - } - - // Update ghost size - dom.setStyles(selectedElmGhost, { - width: width, - height: height - }); - - // Update ghost X position if needed - if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { - dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); - } - - // Update ghost Y position if needed - if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { - dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); - } - - if (!resizeStarted) { - editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); - resizeStarted = true; - } - } - - function endGhostResize() { - resizeStarted = false; - - function setSizeProp(name, value) { - if (value) { - // Resize by using style or attribute - if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { - dom.setStyle(selectedElm, name, value); - } else { - dom.setAttrib(selectedElm, name, value); - } - } - } - - // Set width/height properties - setSizeProp('width', width); - setSizeProp('height', height); - - dom.unbind(editableDoc, 'mousemove', resizeGhostElement); - dom.unbind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.unbind(rootDocument, 'mousemove', resizeGhostElement); - dom.unbind(rootDocument, 'mouseup', endGhostResize); - } - - // Remove ghost and update resize handle positions - dom.remove(selectedElmGhost); - - if (!isIE || selectedElm.nodeName == "TABLE") { - showResizeRect(selectedElm); - } - - editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); - editor.nodeChanged(); - } - - function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { - var position, targetWidth, targetHeight, e, rect, offsetParent = editor.getBody(); - - unbindResizeHandleEvents(); - - // Get position and size of target - position = dom.getPos(targetElm, offsetParent); - selectedElmX = position.x; - selectedElmY = position.y; - rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption - targetWidth = rect.width || (rect.right - rect.left); - targetHeight = rect.height || (rect.bottom - rect.top); - - // Reset width/height if user selects a new image/table - if (selectedElm != targetElm) { - detachResizeStartListener(); - selectedElm = targetElm; - width = height = 0; - } - - // Makes it possible to disable resizing - e = editor.fire('ObjectSelected', {target: targetElm}); - - if (isResizable(targetElm) && !e.isDefaultPrevented()) { - each(resizeHandles, function(handle, name) { - var handleElm, handlerContainerElm; - - function startDrag(e) { - startX = e.screenX; - startY = e.screenY; - startW = selectedElm.clientWidth; - startH = selectedElm.clientHeight; - ratio = startH / startW; - selectedHandle = handle; - - selectedElmGhost = selectedElm.cloneNode(true); - dom.addClass(selectedElmGhost, 'mce-clonedresizable'); - selectedElmGhost.contentEditable = false; // Hides IE move layer cursor - selectedElmGhost.unSelectabe = true; - dom.setStyles(selectedElmGhost, { - left: selectedElmX, - top: selectedElmY, - margin: 0 - }); - - selectedElmGhost.removeAttribute('data-mce-selected'); - editor.getBody().appendChild(selectedElmGhost); - - dom.bind(editableDoc, 'mousemove', resizeGhostElement); - dom.bind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.bind(rootDocument, 'mousemove', resizeGhostElement); - dom.bind(rootDocument, 'mouseup', endGhostResize); - } - } - - if (mouseDownHandleName) { - // Drag started by IE native resizestart - if (name == mouseDownHandleName) { - startDrag(mouseDownEvent); - } - - return; - } - - // Get existing or render resize handle - handleElm = dom.get('mceResizeHandle' + name); - if (!handleElm) { - handlerContainerElm = editor.getBody(); - - handleElm = dom.add(handlerContainerElm, 'div', { - id: 'mceResizeHandle' + name, - 'data-mce-bogus': true, - 'class': 'mce-resizehandle', - unselectable: true, - style: 'cursor:' + name + '-resize; margin:0; padding:0' - }); - - // Hides IE move layer cursor - // If we set it on Chrome we get this wounderful bug: #6725 - if (Env.ie) { - handleElm.contentEditable = false; - } - } else { - dom.show(handleElm); - } - - if (!handle.elm) { - dom.bind(handleElm, 'mousedown', function(e) { - e.stopImmediatePropagation(); - e.preventDefault(); - startDrag(e); - }); - - handle.elm = handleElm; - } - - /* - var halfHandleW = handleElm.offsetWidth / 2; - var halfHandleH = handleElm.offsetHeight / 2; - - // Position element - dom.setStyles(handleElm, { - left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), - top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) - }); - */ - - // Position element - dom.setStyles(handleElm, { - left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), - top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) - }); - }); - } else { - hideResizeRect(); - } - - selectedElm.setAttribute('data-mce-selected', '1'); - } - - function hideResizeRect() { - var name, handleElm; - - unbindResizeHandleEvents(); - - if (selectedElm) { - selectedElm.removeAttribute('data-mce-selected'); - } - - for (name in resizeHandles) { - handleElm = dom.get('mceResizeHandle' + name); - if (handleElm) { - dom.unbind(handleElm); - dom.remove(handleElm); - } - } - } - - function updateResizeRect(e) { - var controlElm; - - function isChildOrEqual(node, parent) { - if (node) { - do { - if (node === parent) { - return true; - } - } while ((node = node.parentNode)); - } - } - - // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v - each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { - img.removeAttribute('data-mce-selected'); - }); - - controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); - controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); - - if (isChildOrEqual(controlElm, editor.getBody())) { - disableGeckoResize(); - - if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { - if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { - showResizeRect(controlElm); - return; - } - } - } - - hideResizeRect(); - } - - function attachEvent(elm, name, func) { - if (elm && elm.attachEvent) { - elm.attachEvent('on' + name, func); - } - } - - function detachEvent(elm, name, func) { - if (elm && elm.detachEvent) { - elm.detachEvent('on' + name, func); - } - } - - function resizeNativeStart(e) { - var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; - - pos = target.getBoundingClientRect(); - relativeX = lastMouseDownEvent.clientX - pos.left; - relativeY = lastMouseDownEvent.clientY - pos.top; - - // Figure out what corner we are draging on - for (name in resizeHandles) { - corner = resizeHandles[name]; - - cornerX = target.offsetWidth * corner[0]; - cornerY = target.offsetHeight * corner[1]; - - if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { - selectedHandle = corner; - break; - } - } - - // Remove native selection and let the magic begin - resizeStarted = true; - editor.getDoc().selection.empty(); - showResizeRect(target, name, lastMouseDownEvent); - } - - function nativeControlSelect(e) { - var target = e.srcElement; - - if (target != selectedElm) { - detachResizeStartListener(); - - if (target.id.indexOf('mceResizeHandle') === 0) { - e.returnValue = false; - return; - } - - if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { - hideResizeRect(); - selectedElm = target; - attachEvent(target, 'resizestart', resizeNativeStart); - } - } - } - - function detachResizeStartListener() { - detachEvent(selectedElm, 'resizestart', resizeNativeStart); - } - - function unbindResizeHandleEvents() { - for (var name in resizeHandles) { - var handle = resizeHandles[name]; - - if (handle.elm) { - dom.unbind(handle.elm); - delete handle.elm; - } - } - } - - function disableGeckoResize() { - try { - // Disable object resizing on Gecko - editor.getDoc().execCommand('enableObjectResizing', false, false); - } catch (ex) { - // Ignore - } - } - - function controlSelect(elm) { - var ctrlRng; - - if (!isIE) { - return; - } - - ctrlRng = editableDoc.body.createControlRange(); - - try { - ctrlRng.addElement(elm); - ctrlRng.select(); - return true; - } catch (ex) { - // Ignore since the element can't be control selected for example a P tag - } - } - - editor.on('init', function() { - if (isIE) { - // Hide the resize rect on resize and reselect the image - editor.on('ObjectResized', function(e) { - if (e.target.nodeName != 'TABLE') { - hideResizeRect(); - controlSelect(e.target); - } - }); - - attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - - editor.on('mousedown', function(e) { - lastMouseDownEvent = e; - }); - } else { - disableGeckoResize(); - - if (Env.ie >= 11) { - // TODO: Drag/drop doesn't work - editor.on('mouseup', function(e) { - var nodeName = e.target.nodeName; - - if (/^(TABLE|IMG|HR)$/.test(nodeName)) { - editor.selection.select(e.target, nodeName == 'TABLE'); - editor.nodeChanged(); - } - }); - - editor.dom.bind(editor.getBody(), 'mscontrolselect', function(e) { - if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) { - e.preventDefault(); - - // This moves the selection from being a control selection to a text like selection like in WebKit #6753 - // TODO: Fix this the day IE works like other browsers without this nasty native ugly control selections. - if (e.target.tagName == 'IMG') { - window.setTimeout(function() { - editor.selection.select(e.target); - }, 0); - } - } - }); - } - } - - editor.on('nodechange mousedown mouseup ResizeEditor', updateResizeRect); - - // Update resize rect while typing in a table - editor.on('keydown keyup', function(e) { - if (selectedElm && selectedElm.nodeName == "TABLE") { - updateResizeRect(e); - } - }); - - // Hide rect on focusout since it would float on top of windows otherwise - //editor.on('focusout', hideResizeRect); - }); - - editor.on('remove', unbindResizeHandleEvents); - - function destroy() { - selectedElm = selectedElmGhost = null; - - if (isIE) { - detachResizeStartListener(); - detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - } - } - - return { - isResizable: isResizable, - showResizeRect: showResizeRect, - hideResizeRect: hideResizeRect, - updateResizeRect: updateResizeRect, - controlSelect: controlSelect, - destroy: destroy - }; - }; -}); - -// Included from: js/tinymce/classes/dom/RangeUtils.js - -/** - * Range.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * RangeUtils - * - * @class tinymce.dom.RangeUtils - * @private - */ -define("tinymce/dom/RangeUtils", [ - "tinymce/util/Tools", - "tinymce/dom/TreeWalker" -], function(Tools, TreeWalker) { - var each = Tools.each; - - function RangeUtils(dom) { - /** - * Walks the specified range like object and executes the callback for each sibling collection it finds. - * - * @method walk - * @param {Object} rng Range like object. - * @param {function} callback Callback function to execute for each sibling collection. - */ - this.walk = function(rng, callback) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset, - ancestor, startPoint, - endPoint, node, parent, siblings, nodes; - - // Handle table cell selection the table plugin enables - // you to fake select table cells and perform formatting actions on them - nodes = dom.select('td.mce-item-selected,th.mce-item-selected'); - if (nodes.length > 0) { - each(nodes, function(node) { - callback([node]); - }); - - return; - } - - /** - * Excludes start/end text node if they are out side the range - * - * @private - * @param {Array} nodes Nodes to exclude items from. - * @return {Array} Array with nodes excluding the start/end container if needed. - */ - function exclude(nodes) { - var node; - - // First node is excluded - node = nodes[0]; - if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { - nodes.splice(0, 1); - } - - // Last node is excluded - node = nodes[nodes.length - 1]; - if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { - nodes.splice(nodes.length - 1, 1); - } - - return nodes; - } - - /** - * Collects siblings - * - * @private - * @param {Node} node Node to collect siblings from. - * @param {String} name Name of the sibling to check for. - * @return {Array} Array of collected siblings. - */ - function collectSiblings(node, name, end_node) { - var siblings = []; - - for (; node && node != end_node; node = node[name]) { - siblings.push(node); - } - - return siblings; - } - - /** - * Find an end point this is the node just before the common ancestor root. - * - * @private - * @param {Node} node Node to start at. - * @param {Node} root Root/ancestor element to stop just before. - * @return {Node} Node just before the root element. - */ - function findEndPoint(node, root) { - do { - if (node.parentNode == root) { - return node; - } - - node = node.parentNode; - } while(node); - } - - function walkBoundary(start_node, end_node, next) { - var siblingName = next ? 'nextSibling' : 'previousSibling'; - - for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { - parent = node.parentNode; - siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); - - if (siblings.length) { - if (!next) { - siblings.reverse(); - } - - callback(exclude(siblings)); - } - } - } - - // If index based start position then resolve it - if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { - startContainer = startContainer.childNodes[startOffset]; - } - - // If index based end position then resolve it - if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { - endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; - } - - // Same container - if (startContainer == endContainer) { - return callback(exclude([startContainer])); - } - - // Find common ancestor and end points - ancestor = dom.findCommonAncestor(startContainer, endContainer); - - // Process left side - for (node = startContainer; node; node = node.parentNode) { - if (node === endContainer) { - return walkBoundary(startContainer, ancestor, true); - } - - if (node === ancestor) { - break; - } - } - - // Process right side - for (node = endContainer; node; node = node.parentNode) { - if (node === startContainer) { - return walkBoundary(endContainer, ancestor); - } - - if (node === ancestor) { - break; - } - } - - // Find start/end point - startPoint = findEndPoint(startContainer, ancestor) || startContainer; - endPoint = findEndPoint(endContainer, ancestor) || endContainer; - - // Walk left leaf - walkBoundary(startContainer, startPoint, true); - - // Walk the middle from start to end point - siblings = collectSiblings( - startPoint == startContainer ? startPoint : startPoint.nextSibling, - 'nextSibling', - endPoint == endContainer ? endPoint.nextSibling : endPoint - ); - - if (siblings.length) { - callback(exclude(siblings)); - } - - // Walk right leaf - walkBoundary(endContainer, endPoint); - }; - - /** - * Splits the specified range at it's start/end points. - * - * @private - * @param {Range/RangeObject} rng Range to split. - * @return {Object} Range position object. - */ - this.split = function(rng) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset; - - function splitText(node, offset) { - return node.splitText(offset); - } - - // Handle single text node - if (startContainer == endContainer && startContainer.nodeType == 3) { - if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { - endContainer = splitText(startContainer, startOffset); - startContainer = endContainer.previousSibling; - - if (endOffset > startOffset) { - endOffset = endOffset - startOffset; - startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - startOffset = 0; - } else { - endOffset = 0; - } - } - } else { - // Split startContainer text node if needed - if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { - startContainer = splitText(startContainer, startOffset); - startOffset = 0; - } - - // Split endContainer text node if needed - if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { - endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - } - } - - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - }; - - /** - * Normalizes the specified range by finding the closest best suitable caret location. - * - * @private - * @param {Range} rng Range to normalize. - * @return {Boolean} True/false if the specified range was normalized or not. - */ - this.normalize = function(rng) { - var normalized, collapsed; - - function normalizeEndPoint(start) { - var container, offset, walker, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; - var directionLeft, isAfterNode; - - function hasBrBeforeAfter(node, left) { - var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); - - while ((node = walker[left ? 'prev' : 'next']())) { - if (node.nodeName === "BR") { - return true; - } - } - } - - function isPrevNode(node, name) { - return node.previousSibling && node.previousSibling.nodeName == name; - } - - // Walks the dom left/right to find a suitable text node to move the endpoint into - // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG - function findTextNodeRelative(left, startNode) { - var walker, lastInlineElement, parentBlockContainer; - - startNode = startNode || container; - parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body; - - // Lean left before the BR element if it's the only BR within a block element. Gecko bug: #6680 - // This:
|
|
x|
]
- rng.moveToElementText(rng2.parentElement()); - if (rng.compareEndPoints('StartToEnd', rng2) === 0) { - rng2.move('character', -1); - } - - rng2.pasteHTML('' + chr + ''); - } - } catch (ex) { - // IE might throw unspecified error so lets ignore it - return null; - } - } else { - // Control selection - element = rng.item(0); - name = element.nodeName; - - return {name: name, index: findIndex(name, element)}; - } - } else { - element = self.getNode(); - name = element.nodeName; - if (name == 'IMG') { - return {name: name, index: findIndex(name, element)}; - } - - // W3C method - rng2 = normalizeTableCellSelection(rng.cloneRange()); - - // Insert end marker - if (!collapsed) { - rng2.collapse(false); - rng2.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_end', style: styles}, chr)); - } - - rng = normalizeTableCellSelection(rng); - rng.collapse(true); - rng.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_start', style: styles}, chr)); - } - - self.moveToBookmark({id: id, keep: 1}); - - return {id: id}; - }, - - /** - * Restores the selection to the specified bookmark. - * - * @method moveToBookmark - * @param {Object} bookmark Bookmark to restore selection from. - * @return {Boolean} true/false if it was successful or not. - * @example - * // Stores a bookmark of the current selection - * var bm = tinymce.activeEditor.selection.getBookmark(); - * - * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); - * - * // Restore the selection bookmark - * tinymce.activeEditor.selection.moveToBookmark(bm); - */ - moveToBookmark: function(bookmark) { - var self = this, dom = self.dom, rng, root, startContainer, endContainer, startOffset, endOffset; - - function setEndPoint(start) { - var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; - - if (point) { - offset = point[0]; - - // Find container node - for (node = root, i = point.length - 1; i >= 1; i--) { - children = node.childNodes; - - if (point[i] > children.length - 1) { - return; - } - - node = children[point[i]]; - } - - // Move text offset to best suitable location - if (node.nodeType === 3) { - offset = Math.min(point[0], node.nodeValue.length); - } - - // Move element offset to best suitable location - if (node.nodeType === 1) { - offset = Math.min(point[0], node.childNodes.length); - } - - // Set offset within container node - if (start) { - rng.setStart(node, offset); - } else { - rng.setEnd(node, offset); - } - } - - return true; - } - - function restoreEndPoint(suffix) { - var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; - - if (marker) { - node = marker.parentNode; - - if (suffix == 'start') { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - startContainer = endContainer = node; - startOffset = endOffset = idx; - } else { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - endContainer = node; - endOffset = idx; - } - - if (!keep) { - prev = marker.previousSibling; - next = marker.nextSibling; - - // Remove all marker text nodes - each(grep(marker.childNodes), function(node) { - if (node.nodeType == 3) { - node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); - } - }); - - // Remove marker but keep children if for example contents where inserted into the marker - // Also remove duplicated instances of the marker for example by a - // split operation or by WebKit auto split on paste feature - while ((marker = dom.get(bookmark.id + '_' + suffix))) { - dom.remove(marker, 1); - } - - // If siblings are text nodes then merge them unless it's Opera since it some how removes the node - // and we are sniffing since adding a lot of detection code for a browser with 3% of the market - // isn't worth the effort. Sorry, Opera but it's just a fact - if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !isOpera) { - idx = prev.nodeValue.length; - prev.appendData(next.nodeValue); - dom.remove(next); - - if (suffix == 'start') { - startContainer = endContainer = prev; - startOffset = endOffset = idx; - } else { - endContainer = prev; - endOffset = idx; - } - } - } - } - } - - function addBogus(node) { - // Adds a bogus BR element for empty block elements - if (dom.isBlock(node) && !node.innerHTML && !isIE) { - node.innerHTML = '*texttext*
! - // This will reduce the number of wrapper elements that needs to be created - // Move start point up the tree - if (format[0].inline || format[0].block_expand) { - if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { - startContainer = findParentContainer(true); - } - - if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { - endContainer = findParentContainer(); - } - } - - // Expand start/end container to matching selector - if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { - // Find new startContainer/endContainer if there is better one - startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); - endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); - } - - // Expand start/end container to matching block element or text node - if (format[0].block || format[0].selector) { - // Find new startContainer/endContainer if there is better one - startContainer = findBlockEndPoint(startContainer, 'previousSibling'); - endContainer = findBlockEndPoint(endContainer, 'nextSibling'); - - // Non block element then try to expand up the leaf - if (format[0].block) { - if (!isBlock(startContainer)) { - startContainer = findParentContainer(true); - } - - if (!isBlock(endContainer)) { - endContainer = findParentContainer(); - } - } - } - - // Setup index for startContainer - if (startContainer.nodeType == 1) { - startOffset = nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - - // Setup index for endContainer - if (endContainer.nodeType == 1) { - endOffset = nodeIndex(endContainer) + 1; - endContainer = endContainer.parentNode; - } - - // Return new range like object - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - } - - /** - * Removes the specified format for the specified node. It will also remove the node if it doesn't have - * any attributes if the format specifies it to do so. - * - * @private - * @param {Object} format Format object with items to remove from node. - * @param {Object} vars Name/value object with variables to apply to format. - * @param {Node} node Node to remove the format styles on. - * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. - * @return {Boolean} True/false if the node was removed or not. - */ - function removeFormat(format, vars, node, compare_node) { - var i, attrs, stylesModified; - - // Check if node matches format - if (!matchName(node, format)) { - return FALSE; - } - - // Should we compare with format attribs and styles - if (format.remove != 'all') { - // Remove styles - each(format.styles, function(value, name) { - value = normalizeStyleValue(replaceVars(value, vars), name); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(getStyle(compare_node, name), value)) { - dom.setStyle(node, name, ''); - } - - stylesModified = 1; - }); - - // Remove style attribute if it's empty - if (stylesModified && dom.getAttrib(node, 'style') === '') { - node.removeAttribute('style'); - node.removeAttribute('data-mce-style'); - } - - // Remove attributes - each(format.attributes, function(value, name) { - var valueOut; - - value = replaceVars(value, vars); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { - // Keep internal classes - if (name == 'class') { - value = dom.getAttrib(node, name); - if (value) { - // Build new class value where everything is removed except the internal prefixed classes - valueOut = ''; - each(value.split(/\s+/), function(cls) { - if (/mce\w+/.test(cls)) { - valueOut += (valueOut ? ' ' : '') + cls; - } - }); - - // We got some internal classes left - if (valueOut) { - dom.setAttrib(node, name, valueOut); - return; - } - } - } - - // IE6 has a bug where the attribute doesn't get removed correctly - if (name == "class") { - node.removeAttribute('className'); - } - - // Remove mce prefixed attributes - if (MCE_ATTR_RE.test(name)) { - node.removeAttribute('data-mce-' + name); - } - - node.removeAttribute(name); - } - }); - - // Remove classes - each(format.classes, function(value) { - value = replaceVars(value, vars); - - if (!compare_node || dom.hasClass(compare_node, value)) { - dom.removeClass(node, value); - } - }); - - // Check for non internal attributes - attrs = dom.getAttribs(node); - for (i = 0; i < attrs.length; i++) { - if (attrs[i].nodeName.indexOf('_') !== 0) { - return FALSE; - } - } - } - - // Remove the inline child if it's empty for example or - if (format.remove != 'none') { - removeNode(node, format); - return TRUE; - } - } - - /** - * Removes the node and wrap it's children in paragraphs before doing so or - * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. - * - * If the div in the node below gets removed: - * text|
- formatNode.parentNode.replaceChild(caretContainer, formatNode); - } else { - // Insert caret container after the formated node - dom.insertAfter(caretContainer, formatNode); - } - - // Move selection to text node - selection.setCursorLocation(node, 1); - - // If the formatNode is empty, we can remove it safely. - if (dom.isEmpty(formatNode)) { - dom.remove(formatNode); - } - } - } - - // Checks if the parent caret container node isn't empty if that is the case it - // will remove the bogus state on all children that isn't empty - function unmarkBogusCaretParents() { - var caretContainer; - - caretContainer = getParentCaretContainer(selection.getStart()); - if (caretContainer && !dom.isEmpty(caretContainer)) { - walk(caretContainer, function(node) { - if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { - dom.setAttrib(node, 'data-mce-bogus', null); - } - }, 'childNodes'); - } - } - - // Only bind the caret events once - if (!ed._hasCaretEvents) { - // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements - markCaretContainersBogus = function() { - var nodes = [], i; - - if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { - // Mark children - i = nodes.length; - while (i--) { - dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); - } - } - }; - - disableCaretContainer = function(e) { - var keyCode = e.keyCode; - - removeCaretContainer(); - - // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys - if (keyCode == 8 || keyCode == 37 || keyCode == 39) { - removeCaretContainer(getParentCaretContainer(selection.getStart())); - } - - unmarkBogusCaretParents(); - }; - - // Remove bogus state if they got filled by contents using editor.selection.setContent - ed.on('SetContent', function(e) { - if (e.selection) { - unmarkBogusCaretParents(); - } - }); - ed._hasCaretEvents = true; - } - - // Do apply or remove caret format - if (type == "apply") { - applyCaretFormat(); - } else { - removeCaretFormat(); - } - } - - /** - * Moves the start to the first suitable text node. - */ - function moveStart(rng) { - var container = rng.startContainer, - offset = rng.startOffset, isAtEndOfText, - walker, node, nodes, tmpNode; - - // Convert text node into index if possible - if (container.nodeType == 3 && offset >= container.nodeValue.length) { - // Get the parent container location and walk from there - offset = nodeIndex(container); - container = container.parentNode; - isAtEndOfText = true; - } - - // Move startContainer/startOffset in to a suitable node - if (container.nodeType == 1) { - nodes = container.childNodes; - container = nodes[Math.min(offset, nodes.length - 1)]; - walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); - - // If offset is at end of the parent node walk to the next one - if (offset > nodes.length - 1 || isAtEndOfText) { - walker.next(); - } - - for (node = walker.current(); node; node = walker.next()) { - if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { - // IE has a "neat" feature where it moves the start node into the closest element - // we can avoid this by inserting an element before it and then remove it after we set the selection - tmpNode = dom.create('a', null, INVISIBLE_CHAR); - node.parentNode.insertBefore(tmpNode, node); - - // Set selection and remove tmpNode - rng.setStart(node, 0); - selection.setRng(rng); - dom.remove(tmpNode); - - return; - } - } - } - } - }; -}); - -// Included from: js/tinymce/classes/UndoManager.js - -/** - * UndoManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. - * - * @class tinymce.UndoManager - */ -define("tinymce/UndoManager", [ - "tinymce/Env", - "tinymce/util/Tools" -], function(Env, Tools) { - var trim = Tools.trim, trimContentRegExp; - - trimContentRegExp = new RegExp([ - ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers - 'x
becomes this:x
- function trimInlineElementsOnLeftSideOfBlock(block) { - var node = block, firstChilds = [], i; - - // Find inner most first child ex:*
- while ((node = node.firstChild)) { - if (dom.isBlock(node)) { - return; - } - - if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { - firstChilds.push(node); - } - } - - i = firstChilds.length; - while (i--) { - node = firstChilds[i]; - if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { - dom.remove(node); - } else { - // Remove see #5381 - if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { - dom.remove(node); - } - } - } - } - - // Moves the caret to a suitable position within the root for example in the first non - // pure whitespace text node or before an image - function moveToCaretPosition(root) { - var walker, node, rng, lastNode = root, tempElm; - - function firstNonWhiteSpaceNodeSibling(node) { - while (node) { - if (node.nodeType == 1 || (node.nodeType == 3 && node.data && /[\r\n\s]/.test(node.data))) { - return node; - } - - node = node.nextSibling; - } - } - - // Old IE versions doesn't properly render blocks with br elements in them - // For exampletext|
text|text2
|
- rng = selection.getRng(); - var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); - var body = editor.getBody(); - if (caretElement === body && selection.isCollapsed()) { - if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { - rng = dom.createRng(); - rng.setStart(body.firstChild, 0); - rng.setEnd(body.firstChild, 0); - selection.setRng(rng); - } - } - - // Insert node maker where we will insert the new HTML and get it's parent - if (!selection.isCollapsed()) { - editor.getDoc().execCommand('Delete', false, null); - } - - parentNode = selection.getNode(); - - // Parse the fragment within the context of the parent node - var parserArgs = {context: parentNode.nodeName.toLowerCase()}; - fragment = parser.parse(value, parserArgs); - - // Move the caret to a more suitable location - node = fragment.lastChild; - if (node.attr('id') == 'mce_marker') { - marker = node; - - for (node = node.prev; node; node = node.walk(true)) { - if (node.type == 3 || !dom.isBlock(node.name)) { - node.parent.insert(marker, node, node.name === 'br'); - break; - } - } - } - - // If parser says valid we can insert the contents into that parent - if (!parserArgs.invalid) { - value = serializer.serialize(fragment); - - // Check if parent is empty or only has one BR element then set the innerHTML of that parent - node = parentNode.firstChild; - node2 = parentNode.lastChild; - if (!node || (node === node2 && node.nodeName === 'BR')) { - dom.setHTML(parentNode, value); - } else { - selection.setContent(value); - } - } else { - // If the fragment was invalid within that context then we need - // to parse and process the parent it's inserted into - - // Insert bookmark node and get the parent - selection.setContent(bookmarkHtml); - parentNode = selection.getNode(); - rootNode = editor.getBody(); - - // Opera will return the document node when selection is in root - if (parentNode.nodeType == 9) { - parentNode = node = rootNode; - } else { - node = parentNode; - } - - // Find the ancestor just before the root element - while (node !== rootNode) { - parentNode = node; - node = node.parentNode; - } - - // Get the outer/inner HTML depending on if we are in the root and parser and serialize that - value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); - value = serializer.serialize( - parser.parse( - // Need to replace by using a function since $ in the contents would otherwise be a problem - value.replace(//i, function() { - return serializer.serialize(fragment); - }) - ) - ); - - // Set the inner/outer HTML depending on if we are in the root or not - if (parentNode == rootNode) { - dom.setHTML(rootNode, value); - } else { - dom.setOuterHTML(parentNode, value); - } - } - - marker = dom.get('mce_marker'); - selection.scrollIntoView(marker); - - // Move selection before marker and remove it - rng = dom.createRng(); - - // If previous sibling is a text node set the selection to the end of that node - node = marker.previousSibling; - if (node && node.nodeType == 3) { - rng.setStart(node, node.nodeValue.length); - - // TODO: Why can't we normalize on IE - if (!isIE) { - node2 = marker.nextSibling; - if (node2 && node2.nodeType == 3) { - node.appendData(node2.data); - node2.parentNode.removeChild(node2); - } - } - } else { - // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node - rng.setStartBefore(marker); - rng.setEndBefore(marker); - } - - // Remove the marker node and set the new range - dom.remove(marker); - selection.setRng(rng); - - // Dispatch after event and add any visual elements needed - editor.fire('SetContent', args); - editor.addVisual(); - }, - - mceInsertRawHTML: function(command, ui, value) { - selection.setContent('tiny_mce_marker'); - editor.setContent( - editor.getContent().replace(/tiny_mce_marker/g, function() { - return value; - }) - ); - }, - - mceToggleFormat: function(command, ui, value) { - toggleFormat(value); - }, - - mceSetContent: function(command, ui, value) { - editor.setContent(value); - }, - - 'Indent,Outdent': function(command) { - var intentValue, indentUnit, value; - - // Setup indent level - intentValue = settings.indentation; - indentUnit = /[a-z%]+$/i.exec(intentValue); - intentValue = parseInt(intentValue, 10); - - if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { - // If forced_root_blocks is set to false we don't have a block to indent so lets create a div - if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { - formatter.apply('div'); - } - - each(selection.getSelectedBlocks(), function(element) { - if (element.nodeName != "LI") { - var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; - - indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; - - if (command == 'outdent') { - value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); - dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); - } else { - value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; - dom.setStyle(element, indentStyleName, value); - } - } - }); - } else { - execNativeCommand(command); - } - }, - - mceRepaint: function() { - if (isGecko) { - try { - storeSelection(TRUE); - - if (selection.getSel()) { - selection.getSel().selectAllChildren(editor.getBody()); - } - - selection.collapse(TRUE); - restoreSelection(); - } catch (ex) { - // Ignore - } - } - }, - - InsertHorizontalRule: function() { - editor.execCommand('mceInsertContent', false, '|
- rng = selection.getRng(); - if (!rng.item) { - rng.moveToElementText(root); - rng.select(); - } - } - }, - - "delete": function() { - execNativeCommand("Delete"); - - // Check if body is empty after the delete call if so then set the contents - // to an empty string and move the caret to any block produced by that operation - // this fixes the issue with root blocks not being properly produced after a delete call on IE - var body = editor.getBody(); - - if (dom.isEmpty(body)) { - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - } - }, - - mceNewDocument: function() { - editor.setContent(''); - } - }); - - // Add queryCommandState overrides - addCommands({ - // Override justify commands - 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { - var name = 'align' + command.substring(7); - var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); - var matches = map(nodes, function(node) { - return !!formatter.matchNode(node, name); - }); - return inArray(matches, TRUE) !== -1; - }, - - 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { - return isFormatMatch(command); - }, - - mceBlockQuote: function() { - return isFormatMatch('blockquote'); - }, - - Outdent: function() { - var node; - - if (settings.inline_styles) { - if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - - if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - } - - return ( - queryCommandState('InsertUnorderedList') || - queryCommandState('InsertOrderedList') || - (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) - ); - }, - - 'InsertUnorderedList,InsertOrderedList': function(command) { - var list = dom.getParent(selection.getNode(), 'ul,ol'); - - return list && - ( - command === 'insertunorderedlist' && list.tagName === 'UL' || - command === 'insertorderedlist' && list.tagName === 'OL' - ); - } - }, 'state'); - - // Add queryCommandValue overrides - addCommands({ - 'FontSize,FontName': function(command) { - var value = 0, parent; - - if ((parent = dom.getParent(selection.getNode(), 'span'))) { - if (command == 'fontsize') { - value = parent.style.fontSize; - } else { - value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); - } - } - - return value; - } - }, 'value'); - - // Add undo manager logic - addCommands({ - Undo: function() { - editor.undoManager.undo(); - }, - - Redo: function() { - editor.undoManager.redo(); - } - }); - }; -}); - -// Included from: js/tinymce/classes/util/URI.js - -/** - * URI.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles parsing, modification and serialization of URI/URL strings. - * @class tinymce.util.URI - */ -define("tinymce/util/URI", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, trim = Tools.trim; - - /** - * Constructs a new URI instance. - * - * @constructor - * @method URI - * @param {String} url URI string to parse. - * @param {Object} settings Optional settings object. - */ - function URI(url, settings) { - var self = this, baseUri, base_url; - - // Trim whitespace - url = trim(url); - - // Default settings - settings = self.settings = settings || {}; - - // Strange app protocol that isn't http/https or local anchor - // For example: mailto,skype,tel etc. - if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) { - self.source = url; - return; - } - - var isProtocolRelative = url.indexOf('//') === 0; - - // Absolute path with no host, fake host and protocol - if (url.indexOf('/') === 0 && !isProtocolRelative) { - url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url; - } - - // Relative path http:// or protocol relative //path - if (!/^[\w\-]*:?\/\//.test(url)) { - base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory; - if (settings.base_uri.protocol === "") { - url = '//mce_host' + self.toAbsPath(base_url, url); - } else { - url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url); - } - } - - // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) - url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something - - /*jshint maxlen: 255 */ - /*eslint max-len: 0 */ - url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url); - - each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { - var part = url[i]; - - // Zope 3 workaround, they use @@something - if (part) { - part = part.replace(/\(mce_at\)/g, '@@'); - } - - self[v] = part; - }); - - baseUri = settings.base_uri; - if (baseUri) { - if (!self.protocol) { - self.protocol = baseUri.protocol; - } - - if (!self.userInfo) { - self.userInfo = baseUri.userInfo; - } - - if (!self.port && self.host === 'mce_host') { - self.port = baseUri.port; - } - - if (!self.host || self.host === 'mce_host') { - self.host = baseUri.host; - } - - self.source = ''; - } - - if (isProtocolRelative) { - self.protocol = ''; - } - - //t.path = t.path || '/'; - } - - URI.prototype = { - /** - * Sets the internal path part of the URI. - * - * @method setPath - * @param {string} path Path string to set. - */ - setPath: function(path) { - var self = this; - - path = /^(.*?)\/?(\w+)?$/.exec(path); - - // Update path parts - self.path = path[0]; - self.directory = path[1]; - self.file = path[2]; - - // Rebuild source - self.source = ''; - self.getURI(); - }, - - /** - * Converts the specified URI into a relative URI based on the current URI instance location. - * - * @method toRelative - * @param {String} uri URI to convert into a relative path/URI. - * @return {String} Relative URI from the point specified in the current URI instance. - * @example - * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm'); - */ - toRelative: function(uri) { - var self = this, output; - - if (uri === "./") { - return uri; - } - - uri = new URI(uri, {base_uri: self}); - - // Not on same domain/port or protocol - if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port || - (self.protocol != uri.protocol && uri.protocol !== "")) { - return uri.getURI(); - } - - var tu = self.getURI(), uu = uri.getURI(); - - // Allow usage of the base_uri when relative_urls = true - if (tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) { - return tu; - } - - output = self.toRelPath(self.path, uri.path); - - // Add query - if (uri.query) { - output += '?' + uri.query; - } - - // Add anchor - if (uri.anchor) { - output += '#' + uri.anchor; - } - - return output; - }, - - /** - * Converts the specified URI into a absolute URI based on the current URI instance location. - * - * @method toAbsolute - * @param {String} uri URI to convert into a relative path/URI. - * @param {Boolean} noHost No host and protocol prefix. - * @return {String} Absolute URI from the point specified in the current URI instance. - * @example - * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm'); - */ - toAbsolute: function(uri, noHost) { - uri = new URI(uri, {base_uri: this}); - - return uri.getURI(this.host == uri.host && this.protocol == uri.protocol ? noHost : 0); - }, - - /** - * Converts a absolute path into a relative path. - * - * @method toRelPath - * @param {String} base Base point to convert the path from. - * @param {String} path Absolute path to convert into a relative path. - */ - toRelPath: function(base, path) { - var items, breakPoint = 0, out = '', i, l; - - // Split the paths - base = base.substring(0, base.lastIndexOf('/')); - base = base.split('/'); - items = path.split('/'); - - if (base.length >= items.length) { - for (i = 0, l = base.length; i < l; i++) { - if (i >= items.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (base.length < items.length) { - for (i = 0, l = items.length; i < l; i++) { - if (i >= base.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (breakPoint === 1) { - return path; - } - - for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { - out += "../"; - } - - for (i = breakPoint - 1, l = items.length; i < l; i++) { - if (i != breakPoint - 1) { - out += "/" + items[i]; - } else { - out += items[i]; - } - } - - return out; - }, - - /** - * Converts a relative path into a absolute path. - * - * @method toAbsPath - * @param {String} base Base point to convert the path from. - * @param {String} path Relative path to convert into an absolute path. - */ - toAbsPath: function(base, path) { - var i, nb = 0, o = [], tr, outPath; - - // Split paths - tr = /\/$/.test(path) ? '/' : ''; - base = base.split('/'); - path = path.split('/'); - - // Remove empty chunks - each(base, function(k) { - if (k) { - o.push(k); - } - }); - - base = o; - - // Merge relURLParts chunks - for (i = path.length - 1, o = []; i >= 0; i--) { - // Ignore empty or . - if (path[i].length === 0 || path[i] === ".") { - continue; - } - - // Is parent - if (path[i] === '..') { - nb++; - continue; - } - - // Move up - if (nb > 0) { - nb--; - continue; - } - - o.push(path[i]); - } - - i = base.length - nb; - - // If /a/b/c or / - if (i <= 0) { - outPath = o.reverse().join('/'); - } else { - outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/'); - } - - // Add front / if it's needed - if (outPath.indexOf('/') !== 0) { - outPath = '/' + outPath; - } - - // Add traling / if it's needed - if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) { - outPath += tr; - } - - return outPath; - }, - - /** - * Returns the full URI of the internal structure. - * - * @method getURI - * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. - */ - getURI: function(noProtoHost) { - var s, self = this; - - // Rebuild source - if (!self.source || noProtoHost) { - s = ''; - - if (!noProtoHost) { - if (self.protocol) { - s += self.protocol + '://'; - } else { - s += '//'; - } - - if (self.userInfo) { - s += self.userInfo + '@'; - } - - if (self.host) { - s += self.host; - } - - if (self.port) { - s += ':' + self.port; - } - } - - if (self.path) { - s += self.path; - } - - if (self.query) { - s += '?' + self.query; - } - - if (self.anchor) { - s += '#' + self.anchor; - } - - self.source = s; - } - - return self.source; - } - }; - - return URI; -}); - -// Included from: js/tinymce/classes/util/Class.js - -/** - * Class.js - * - * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. - */ - -/** - * This utilitiy class is used for easier inheritage. - * - * Features: - * * Exposed super functions: this._super(); - * * Mixins - * * Dummy functions - * * Property functions: var value = object.value(); and object.value(newValue); - * * Static functions - * * Defaults settings - */ -define("tinymce/util/Class", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, extend = Tools.extend; - - var extendClass, initializing; - - function Class() { - } - - // Provides classical inheritance, based on code made by John Resig - Class.extend = extendClass = function(prop) { - var self = this, _super = self.prototype, prototype, name, member; - - // The dummy class constructor - function Class() { - var i, mixins, mixin, self = this; - - // All construction is actually done in the init method - if (!initializing) { - // Run class constuctor - if (self.init) { - self.init.apply(self, arguments); - } - - // Run mixin constructors - mixins = self.Mixins; - if (mixins) { - i = mixins.length; - while (i--) { - mixin = mixins[i]; - if (mixin.init) { - mixin.init.apply(self, arguments); - } - } - } - } - } - - // Dummy function, needs to be extended in order to provide functionality - function dummy() { - return this; - } - - // Creates a overloaded method for the class - // this enables you to use this._super(); to call the super function - function createMethod(name, fn) { - return function(){ - var self = this, tmp = self._super, ret; - - self._super = _super[name]; - ret = fn.apply(self, arguments); - self._super = tmp; - - return ret; - }; - } - - // Instantiate a base class (but only create the instance, - // don't run the init constructor) - initializing = true; - prototype = new self(); - initializing = false; - - // Add mixins - if (prop.Mixins) { - each(prop.Mixins, function(mixin) { - mixin = mixin; - - for (var name in mixin) { - if (name !== "init") { - prop[name] = mixin[name]; - } - } - }); - - if (_super.Mixins) { - prop.Mixins = _super.Mixins.concat(prop.Mixins); - } - } - - // Generate dummy methods - if (prop.Methods) { - each(prop.Methods.split(','), function(name) { - prop[name] = dummy; - }); - } - - // Generate property methods - if (prop.Properties) { - each(prop.Properties.split(','), function(name) { - var fieldName = '_' + name; - - prop[name] = function(value) { - var self = this, undef; - - // Set value - if (value !== undef) { - self[fieldName] = value; - - return self; - } - - // Get value - return self[fieldName]; - }; - }); - } - - // Static functions - if (prop.Statics) { - each(prop.Statics, function(func, name) { - Class[name] = func; - }); - } - - // Default settings - if (prop.Defaults && _super.Defaults) { - prop.Defaults = extend({}, _super.Defaults, prop.Defaults); - } - - // Copy the properties over onto the new prototype - for (name in prop) { - member = prop[name]; - - if (typeof member == "function" && _super[name]) { - prototype[name] = createMethod(name, member); - } else { - prototype[name] = member; - } - } - - // Populate our constructed prototype object - Class.prototype = prototype; - - // Enforce the constructor to be what we expect - Class.constructor = Class; - - // And make this class extendible - Class.extend = extendClass; - - return Class; - }; - - return Class; -}); - -// Included from: js/tinymce/classes/ui/Selector.js - -/** - * Selector.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*eslint no-nested-ternary:0 */ - -/** - * Selector engine, enables you to select controls by using CSS like expressions. - * We currently only support basic CSS expressions to reduce the size of the core - * and the ones we support should be enough for most cases. - * - * @example - * Supported expressions: - * element - * element#name - * element.class - * element[attr] - * element[attr*=value] - * element[attr~=value] - * element[attr!=value] - * element[attr^=value] - * element[attr$=value] - * element: bug on IE 8 #6178
- DOMUtils.DOM.setHTML(elm, html);
- }
- };
-});
-
-// Included from: js/tinymce/classes/ui/Control.js
-
-/**
- * Control.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*eslint consistent-this:0 */
-
-/**
- * This is the base class for all controls and containers. All UI control instances inherit
- * from this one as it has the base logic needed by all of them.
- *
- * @class tinymce.ui.Control
- */
-define("tinymce/ui/Control", [
- "tinymce/util/Class",
- "tinymce/util/Tools",
- "tinymce/ui/Collection",
- "tinymce/ui/DomUtils"
-], function(Class, Tools, Collection, DomUtils) {
- "use strict";
-
- var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" +
- " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " ");
-
- var elementIdCache = {};
- var hasMouseWheelEventSupport = "onmousewheel" in document;
- var hasWheelEventSupport = false;
-
- var Control = Class.extend({
- Statics: {
- elementIdCache: elementIdCache
- },
-
- isRtl: function() {
- return Control.rtl;
- },
-
- /**
- * Class/id prefix to use for all controls.
- *
- * @final
- * @field {String} classPrefix
- */
- classPrefix: "mce-",
-
- /**
- * Constructs a new control instance with the specified settings.
- *
- * @constructor
- * @param {Object} settings Name/value object with settings.
- * @setting {String} style Style CSS properties to add.
- * @setting {String} border Border box values example: 1 1 1 1
- * @setting {String} padding Padding box values example: 1 1 1 1
- * @setting {String} margin Margin box values example: 1 1 1 1
- * @setting {Number} minWidth Minimal width for the control.
- * @setting {Number} minHeight Minimal height for the control.
- * @setting {String} classes Space separated list of classes to add.
- * @setting {String} role WAI-ARIA role to use for control.
- * @setting {Boolean} hidden Is the control hidden by default.
- * @setting {Boolean} disabled Is the control disabled by default.
- * @setting {String} name Name of the control instance.
- */
- init: function(settings) {
- var self = this, classes, i;
-
- self.settings = settings = Tools.extend({}, self.Defaults, settings);
-
- // Initial states
- self._id = settings.id || DomUtils.id();
- self._text = self._name = '';
- self._width = self._height = 0;
- self._aria = {role: settings.role};
-
- // Setup classes
- classes = settings.classes;
- if (classes) {
- classes = classes.split(' ');
- classes.map = {};
- i = classes.length;
- while (i--) {
- classes.map[classes[i]] = true;
- }
- }
-
- self._classes = classes || [];
- self.visible(true);
-
- // Set some properties
- Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) {
- var value = settings[name], undef;
-
- if (value !== undef) {
- self[name](value);
- } else if (self['_' + name] === undef) {
- self['_' + name] = false;
- }
- });
-
- self.on('click', function() {
- if (self.disabled()) {
- return false;
- }
- });
-
- // TODO: Is this needed duplicate code see above?
- if (settings.classes) {
- Tools.each(settings.classes.split(' '), function(cls) {
- self.addClass(cls);
- });
- }
-
- /**
- * Name/value object with settings for the current control.
- *
- * @field {Object} settings
- */
- self.settings = settings;
-
- self._borderBox = self.parseBox(settings.border);
- self._paddingBox = self.parseBox(settings.padding);
- self._marginBox = self.parseBox(settings.margin);
-
- if (settings.hidden) {
- self.hide();
- }
- },
-
- // Will generate getter/setter methods for these properties
- Properties: 'parent,title,text,width,height,disabled,active,name,value',
-
- // Will generate empty dummy functions for these
- Methods: 'renderHtml',
-
- /**
- * Returns the root element to render controls into.
- *
- * @method getContainerElm
- * @return {Element} HTML DOM element to render into.
- */
- getContainerElm: function() {
- return document.body;
- },
-
- /**
- * Returns a control instance for the current DOM element.
- *
- * @method getParentCtrl
- * @param {Element} elm HTML dom element to get parent control from.
- * @return {tinymce.ui.Control} Control instance or undefined.
- */
- getParentCtrl: function(elm) {
- var ctrl, lookup = this.getRoot().controlIdLookup;
-
- while (elm && lookup) {
- ctrl = lookup[elm.id];
- if (ctrl) {
- break;
- }
-
- elm = elm.parentNode;
- }
-
- return ctrl;
- },
-
- /**
- * Parses the specified box value. A box value contains 1-4 properties in clockwise order.
- *
- * @method parseBox
- * @param {String/Number} value Box value "0 1 2 3" or "0" etc.
- * @return {Object} Object with top/right/bottom/left properties.
- * @private
- */
- parseBox: function(value) {
- var len, radix = 10;
-
- if (!value) {
- return;
- }
-
- if (typeof(value) === "number") {
- value = value || 0;
-
- return {
- top: value,
- left: value,
- bottom: value,
- right: value
- };
- }
-
- value = value.split(' ');
- len = value.length;
-
- if (len === 1) {
- value[1] = value[2] = value[3] = value[0];
- } else if (len === 2) {
- value[2] = value[0];
- value[3] = value[1];
- } else if (len === 3) {
- value[3] = value[1];
- }
-
- return {
- top: parseInt(value[0], radix) || 0,
- right: parseInt(value[1], radix) || 0,
- bottom: parseInt(value[2], radix) || 0,
- left: parseInt(value[3], radix) || 0
- };
- },
-
- borderBox: function() {
- return this._borderBox;
- },
-
- paddingBox: function() {
- return this._paddingBox;
- },
-
- marginBox: function() {
- return this._marginBox;
- },
-
- measureBox: function(elm, prefix) {
- function getStyle(name) {
- var defaultView = document.defaultView;
-
- if (defaultView) {
- // Remove camelcase
- name = name.replace(/[A-Z]/g, function(a) {
- return '-' + a;
- });
-
- return defaultView.getComputedStyle(elm, null).getPropertyValue(name);
- }
-
- return elm.currentStyle[name];
- }
-
- function getSide(name) {
- var val = parseFloat(getStyle(name), 10);
-
- return isNaN(val) ? 0 : val;
- }
-
- return {
- top: getSide(prefix + "TopWidth"),
- right: getSide(prefix + "RightWidth"),
- bottom: getSide(prefix + "BottomWidth"),
- left: getSide(prefix + "LeftWidth")
- };
- },
-
- /**
- * Initializes the current controls layout rect.
- * This will be executed by the layout managers to determine the
- * default minWidth/minHeight etc.
- *
- * @method initLayoutRect
- * @return {Object} Layout rect instance.
- */
- initLayoutRect: function() {
- var self = this, settings = self.settings, borderBox, layoutRect;
- var elm = self.getEl(), width, height, minWidth, minHeight, autoResize;
- var startMinWidth, startMinHeight, initialSize;
-
- // Measure the current element
- borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border');
- self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding');
- self._marginBox = self._marginBox || self.measureBox(elm, 'margin');
- initialSize = DomUtils.getSize(elm);
-
- // Setup minWidth/minHeight and width/height
- startMinWidth = settings.minWidth;
- startMinHeight = settings.minHeight;
- minWidth = startMinWidth || initialSize.width;
- minHeight = startMinHeight || initialSize.height;
- width = settings.width;
- height = settings.height;
- autoResize = settings.autoResize;
- autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height;
-
- width = width || minWidth;
- height = height || minHeight;
-
- var deltaW = borderBox.left + borderBox.right;
- var deltaH = borderBox.top + borderBox.bottom;
-
- var maxW = settings.maxWidth || 0xFFFF;
- var maxH = settings.maxHeight || 0xFFFF;
-
- // Setup initial layout rect
- self._layoutRect = layoutRect = {
- x: settings.x || 0,
- y: settings.y || 0,
- w: width,
- h: height,
- deltaW: deltaW,
- deltaH: deltaH,
- contentW: width - deltaW,
- contentH: height - deltaH,
- innerW: width - deltaW,
- innerH: height - deltaH,
- startMinWidth: startMinWidth || 0,
- startMinHeight: startMinHeight || 0,
- minW: Math.min(minWidth, maxW),
- minH: Math.min(minHeight, maxH),
- maxW: maxW,
- maxH: maxH,
- autoResize: autoResize,
- scrollW: 0
- };
-
- self._lastLayoutRect = {};
-
- return layoutRect;
- },
-
- /**
- * Getter/setter for the current layout rect.
- *
- * @method layoutRect
- * @param {Object} [newRect] Optional new layout rect.
- * @return {tinymce.ui.Control/Object} Current control or rect object.
- */
- layoutRect: function(newRect) {
- var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls;
-
- // Initialize default layout rect
- if (!curRect) {
- curRect = self.initLayoutRect();
- }
-
- // Set new rect values
- if (newRect) {
- // Calc deltas between inner and outer sizes
- deltaWidth = curRect.deltaW;
- deltaHeight = curRect.deltaH;
-
- // Set x position
- if (newRect.x !== undef) {
- curRect.x = newRect.x;
- }
-
- // Set y position
- if (newRect.y !== undef) {
- curRect.y = newRect.y;
- }
-
- // Set minW
- if (newRect.minW !== undef) {
- curRect.minW = newRect.minW;
- }
-
- // Set minH
- if (newRect.minH !== undef) {
- curRect.minH = newRect.minH;
- }
-
- // Set new width and calculate inner width
- size = newRect.w;
- if (size !== undef) {
- size = size < curRect.minW ? curRect.minW : size;
- size = size > curRect.maxW ? curRect.maxW : size;
- curRect.w = size;
- curRect.innerW = size - deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.h;
- if (size !== undef) {
- size = size < curRect.minH ? curRect.minH : size;
- size = size > curRect.maxH ? curRect.maxH : size;
- curRect.h = size;
- curRect.innerH = size - deltaHeight;
- }
-
- // Set new inner width and calculate width
- size = newRect.innerW;
- if (size !== undef) {
- size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size;
- size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size;
- curRect.innerW = size;
- curRect.w = size + deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.innerH;
- if (size !== undef) {
- size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size;
- size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size;
- curRect.innerH = size;
- curRect.h = size + deltaHeight;
- }
-
- // Set new contentW
- if (newRect.contentW !== undef) {
- curRect.contentW = newRect.contentW;
- }
-
- // Set new contentH
- if (newRect.contentH !== undef) {
- curRect.contentH = newRect.contentH;
- }
-
- // Compare last layout rect with the current one to see if we need to repaint or not
- lastLayoutRect = self._lastLayoutRect;
- if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y ||
- lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) {
- repaintControls = Control.repaintControls;
-
- if (repaintControls) {
- if (repaintControls.map && !repaintControls.map[self._id]) {
- repaintControls.push(self);
- repaintControls.map[self._id] = true;
- }
- }
-
- lastLayoutRect.x = curRect.x;
- lastLayoutRect.y = curRect.y;
- lastLayoutRect.w = curRect.w;
- lastLayoutRect.h = curRect.h;
- }
-
- return self;
- }
-
- return curRect;
- },
-
- /**
- * Repaints the control after a layout operation.
- *
- * @method repaint
- */
- repaint: function() {
- var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect, round;
-
- // Use Math.round on all values on IE < 9
- round = !document.createRange ? Math.round : function(value) {
- return value;
- };
-
- style = self.getEl().style;
- rect = self._layoutRect;
- lastRepaintRect = self._lastRepaintRect || {};
-
- borderBox = self._borderBox;
- borderW = borderBox.left + borderBox.right;
- borderH = borderBox.top + borderBox.bottom;
-
- if (rect.x !== lastRepaintRect.x) {
- style.left = round(rect.x) + 'px';
- lastRepaintRect.x = rect.x;
- }
-
- if (rect.y !== lastRepaintRect.y) {
- style.top = round(rect.y) + 'px';
- lastRepaintRect.y = rect.y;
- }
-
- if (rect.w !== lastRepaintRect.w) {
- style.width = round(rect.w - borderW) + 'px';
- lastRepaintRect.w = rect.w;
- }
-
- if (rect.h !== lastRepaintRect.h) {
- style.height = round(rect.h - borderH) + 'px';
- lastRepaintRect.h = rect.h;
- }
-
- // Update body if needed
- if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) {
- bodyStyle = self.getEl('body').style;
- bodyStyle.width = round(rect.innerW) + 'px';
- lastRepaintRect.innerW = rect.innerW;
- }
-
- if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) {
- bodyStyle = bodyStyle || self.getEl('body').style;
- bodyStyle.height = round(rect.innerH) + 'px';
- lastRepaintRect.innerH = rect.innerH;
- }
-
- self._lastRepaintRect = lastRepaintRect;
- self.fire('repaint', {}, false);
- },
-
- /**
- * Binds a callback to the specified event. This event can both be
- * native browser events like "click" or custom ones like PostRender.
- *
- * The callback function will be passed a DOM event like object that enables yout do stop propagation.
- *
- * @method on
- * @param {String} name Name of the event to bind. For example "click".
- * @param {String/function} callback Callback function to execute ones the event occurs.
- * @return {tinymce.ui.Control} Current control object.
- */
- on: function(name, callback) {
- var self = this, bindings, handlers, names, i;
-
- function resolveCallbackName(name) {
- var callback, scope;
-
- return function(e) {
- if (!callback) {
- self.parents().each(function(ctrl) {
- var callbacks = ctrl.settings.callbacks;
-
- if (callbacks && (callback = callbacks[name])) {
- scope = ctrl;
- return false;
- }
- });
- }
-
- return callback.call(scope, e);
- };
- }
-
- if (callback) {
- if (typeof(callback) == 'string') {
- callback = resolveCallbackName(callback);
- }
-
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
-
- bindings = self._bindings;
- if (!bindings) {
- bindings = self._bindings = {};
- }
-
- handlers = bindings[name];
- if (!handlers) {
- handlers = bindings[name] = [];
- }
-
- handlers.push(callback);
-
- if (nativeEvents[name]) {
- if (!self._nativeEvents) {
- self._nativeEvents = {name: true};
- } else {
- self._nativeEvents[name] = true;
- }
-
- if (self._rendered) {
- self.bindPendingEvents();
- }
- }
- }
- }
-
- return self;
- },
-
- /**
- * Unbinds the specified event and optionally a specific callback. If you omit the name
- * parameter all event handlers will be removed. If you omit the callback all event handles
- * by the specified name will be removed.
- *
- * @method off
- * @param {String} [name] Name for the event to unbind.
- * @param {function} [callback] Callback function to unbind.
- * @return {mxex.ui.Control} Current control object.
- */
- off: function(name, callback) {
- var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi;
-
- if (bindings) {
- if (name) {
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
- handlers = bindings[name];
-
- // Unbind all handlers
- if (!name) {
- for (bindingName in bindings) {
- bindings[bindingName].length = 0;
- }
-
- return self;
- }
-
- if (handlers) {
- // Unbind all by name
- if (!callback) {
- handlers.length = 0;
- } else {
- // Unbind specific ones
- hi = handlers.length;
- while (hi--) {
- if (handlers[hi] === callback) {
- handlers.splice(hi, 1);
- }
- }
- }
- }
- }
- } else {
- self._bindings = [];
- }
- }
-
- return self;
- },
-
- /**
- * Fires the specified event by name and arguments on the control. This will execute all
- * bound event handlers.
- *
- * @method fire
- * @param {String} name Name of the event to fire.
- * @param {Object} [args] Arguments to pass to the event.
- * @param {Boolean} [bubble] Value to control bubbeling. Defaults to true.
- * @return {Object} Current arguments object.
- */
- fire: function(name, args, bubble) {
- var self = this, i, l, handlers, parentCtrl;
-
- name = name.toLowerCase();
-
- // Dummy function that gets replaced on the delegation state functions
- function returnFalse() {
- return false;
- }
-
- // Dummy function that gets replaced on the delegation state functions
- function returnTrue() {
- return true;
- }
-
- // Setup empty object if args is omited
- args = args || {};
-
- // Stick type into event object
- if (!args.type) {
- args.type = name;
- }
-
- // Stick control into event
- if (!args.control) {
- args.control = self;
- }
-
- // Add event delegation methods if they are missing
- if (!args.preventDefault) {
- // Add preventDefault method
- args.preventDefault = function() {
- args.isDefaultPrevented = returnTrue;
- };
-
- // Add stopPropagation
- args.stopPropagation = function() {
- args.isPropagationStopped = returnTrue;
- };
-
- // Add stopImmediatePropagation
- args.stopImmediatePropagation = function() {
- args.isImmediatePropagationStopped = returnTrue;
- };
-
- // Add event delegation states
- args.isDefaultPrevented = returnFalse;
- args.isPropagationStopped = returnFalse;
- args.isImmediatePropagationStopped = returnFalse;
- }
-
- if (self._bindings) {
- handlers = self._bindings[name];
-
- if (handlers) {
- for (i = 0, l = handlers.length; i < l; i++) {
- // Execute callback and break if the callback returns a false
- if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) {
- break;
- }
- }
- }
- }
-
- // Bubble event up to parent controls
- if (bubble !== false) {
- parentCtrl = self.parent();
- while (parentCtrl && !args.isPropagationStopped()) {
- parentCtrl.fire(name, args, false);
- parentCtrl = parentCtrl.parent();
- }
- }
-
- return args;
- },
-
- /**
- * Returns true/false if the specified event has any listeners.
- *
- * @method hasEventListeners
- * @param {String} name Name of the event to check for.
- * @return {Boolean} True/false state if the event has listeners.
- */
- hasEventListeners: function(name) {
- return name in this._bindings;
- },
-
- /**
- * Returns a control collection with all parent controls.
- *
- * @method parents
- * @param {String} selector Optional selector expression to find parents.
- * @return {tinymce.ui.Collection} Collection with all parent controls.
- */
- parents: function(selector) {
- var self = this, ctrl, parents = new Collection();
-
- // Add each parent to collection
- for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) {
- parents.add(ctrl);
- }
-
- // Filter away everything that doesn't match the selector
- if (selector) {
- parents = parents.filter(selector);
- }
-
- return parents;
- },
-
- /**
- * Returns the control next to the current control.
- *
- * @method next
- * @return {tinymce.ui.Control} Next control instance.
- */
- next: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) + 1];
- },
-
- /**
- * Returns the control previous to the current control.
- *
- * @method prev
- * @return {tinymce.ui.Control} Previous control instance.
- */
- prev: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) - 1];
- },
-
- /**
- * Find the common ancestor for two control instances.
- *
- * @method findCommonAncestor
- * @param {tinymce.ui.Control} ctrl1 First control.
- * @param {tinymce.ui.Control} ctrl2 Second control.
- * @return {tinymce.ui.Control} Ancestor control instance.
- */
- findCommonAncestor: function(ctrl1, ctrl2) {
- var parentCtrl;
-
- while (ctrl1) {
- parentCtrl = ctrl2;
-
- while (parentCtrl && ctrl1 != parentCtrl) {
- parentCtrl = parentCtrl.parent();
- }
-
- if (ctrl1 == parentCtrl) {
- break;
- }
-
- ctrl1 = ctrl1.parent();
- }
-
- return ctrl1;
- },
-
- /**
- * Returns true/false if the specific control has the specific class.
- *
- * @method hasClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {Boolean} True/false if the control has the specified class.
- */
- hasClass: function(cls, group) {
- var classes = this._classes[group || 'control'];
-
- cls = this.classPrefix + cls;
-
- return classes && !!classes.map[cls];
- },
-
- /**
- * Adds the specified class to the control
- *
- * @method addClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- addClass: function(cls, group) {
- var self = this, classes, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
-
- if (!classes) {
- classes = [];
- classes.map = {};
- self._classes[group || 'control'] = classes;
- }
-
- if (!classes.map[cls]) {
- classes.map[cls] = cls;
- classes.push(cls);
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
- }
-
- return self;
- },
-
- /**
- * Removes the specified class from the control.
- *
- * @method removeClass
- * @param {String} cls Class to remove.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- removeClass: function(cls, group) {
- var self = this, classes, i, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
- if (classes && classes.map[cls]) {
- delete classes.map[cls];
-
- i = classes.length;
- while (i--) {
- if (classes[i] === cls) {
- classes.splice(i, 1);
- }
- }
- }
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
-
- return self;
- },
-
- /**
- * Toggles the specified class on the control.
- *
- * @method toggleClass
- * @param {String} cls Class to remove.
- * @param {Boolean} state True/false state to add/remove class.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- toggleClass: function(cls, state, group) {
- var self = this;
-
- if (state) {
- self.addClass(cls, group);
- } else {
- self.removeClass(cls, group);
- }
-
- return self;
- },
-
- /**
- * Returns the class string for the specified group name.
- *
- * @method classes
- * @param {String} [group] Group to get clases by.
- * @return {String} Classes for the specified group.
- */
- classes: function(group) {
- var classes = this._classes[group || 'control'];
-
- return classes ? classes.join(' ') : '';
- },
-
- /**
- * Sets the inner HTML of the control element.
- *
- * @method innerHtml
- * @param {String} html Html string to set as inner html.
- * @return {tinymce.ui.Control} Current control object.
- */
- innerHtml: function(html) {
- DomUtils.innerHtml(this.getEl(), html);
- return this;
- },
-
- /**
- * Returns the control DOM element or sub element.
- *
- * @method getEl
- * @param {String} [suffix] Suffix to get element by.
- * @param {Boolean} [dropCache] True if the cache for the element should be dropped.
- * @return {Element} HTML DOM element for the current control or it's children.
- */
- getEl: function(suffix, dropCache) {
- var elm, id = suffix ? this._id + '-' + suffix : this._id;
-
- elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id);
-
- return elm;
- },
-
- /**
- * Sets/gets the visible for the control.
- *
- * @method visible
- * @param {Boolean} state Value to set to control.
- * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
- */
- visible: function(state) {
- var self = this, parentCtrl;
-
- if (typeof(state) !== "undefined") {
- if (self._visible !== state) {
- if (self._rendered) {
- self.getEl().style.display = state ? '' : 'none';
- }
-
- self._visible = state;
-
- // Parent container needs to reflow
- parentCtrl = self.parent();
- if (parentCtrl) {
- parentCtrl._lastRect = null;
- }
-
- self.fire(state ? 'show' : 'hide');
- }
-
- return self;
- }
-
- return self._visible;
- },
-
- /**
- * Sets the visible state to true.
- *
- * @method show
- * @return {tinymce.ui.Control} Current control instance.
- */
- show: function() {
- return this.visible(true);
- },
-
- /**
- * Sets the visible state to false.
- *
- * @method hide
- * @return {tinymce.ui.Control} Current control instance.
- */
- hide: function() {
- return this.visible(false);
- },
-
- /**
- * Focuses the current control.
- *
- * @method focus
- * @return {tinymce.ui.Control} Current control instance.
- */
- focus: function() {
- try {
- this.getEl().focus();
- } catch (ex) {
- // Ignore IE error
- }
-
- return this;
- },
-
- /**
- * Blurs the current control.
- *
- * @method blur
- * @return {tinymce.ui.Control} Current control instance.
- */
- blur: function() {
- this.getEl().blur();
-
- return this;
- },
-
- /**
- * Sets the specified aria property.
- *
- * @method aria
- * @param {String} name Name of the aria property to set.
- * @param {String} value Value of the aria property.
- * @return {tinymce.ui.Control} Current control instance.
- */
- aria: function(name, value) {
- var self = this, elm = self.getEl(self.ariaTarget);
-
- if (typeof(value) === "undefined") {
- return self._aria[name];
- } else {
- self._aria[name] = value;
- }
-
- if (self._rendered) {
- elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
- }
-
- return self;
- },
-
- /**
- * Encodes the specified string with HTML entities. It will also
- * translate the string to different languages.
- *
- * @method encode
- * @param {String/Object/Array} text Text to entity encode.
- * @param {Boolean} [translate=true] False if the contents shouldn't be translated.
- * @return {String} Encoded and possible traslated string.
- */
- encode: function(text, translate) {
- if (translate !== false && Control.translate) {
- text = Control.translate(text);
- }
-
- return (text || '').replace(/[&<>"]/g, function(match) {
- return '' + match.charCodeAt(0) + ';';
- });
- },
-
- /**
- * Adds items before the current control.
- *
- * @method before
- * @param {Array/tinymce.ui.Collection} items Array of items to prepend before this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- before: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self), true);
- }
-
- return self;
- },
-
- /**
- * Adds items after the current control.
- *
- * @method after
- * @param {Array/tinymce.ui.Collection} items Array of items to append after this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- after: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self));
- }
-
- return self;
- },
-
- /**
- * Removes the current control from DOM and from UI collections.
- *
- * @method remove
- * @return {tinymce.ui.Control} Current control instance.
- */
- remove: function() {
- var self = this, elm = self.getEl(), parent = self.parent(), newItems, i;
-
- if (self.items) {
- var controls = self.items().toArray();
- i = controls.length;
- while (i--) {
- controls[i].remove();
- }
- }
-
- if (parent && parent.items) {
- newItems = [];
-
- parent.items().each(function(item) {
- if (item !== self) {
- newItems.push(item);
- }
- });
-
- parent.items().set(newItems);
- parent._lastRect = null;
- }
-
- if (self._eventsRoot && self._eventsRoot == self) {
- DomUtils.off(elm);
- }
-
- var lookup = self.getRoot().controlIdLookup;
- if (lookup) {
- delete lookup[self._id];
- }
-
- delete elementIdCache[self._id];
-
- if (elm && elm.parentNode) {
- var nodes = elm.getElementsByTagName('*');
-
- i = nodes.length;
- while (i--) {
- delete elementIdCache[nodes[i].id];
- }
-
- elm.parentNode.removeChild(elm);
- }
-
- self._rendered = false;
-
- return self;
- },
-
- /**
- * Renders the control before the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render before.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderBefore: function(elm) {
- var self = this;
-
- elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm);
- self.postRender();
-
- return self;
- },
-
- /**
- * Renders the control to the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render to.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderTo: function(elm) {
- var self = this;
-
- elm = elm || self.getContainerElm();
- elm.appendChild(DomUtils.createFragment(self.renderHtml()));
- self.postRender();
-
- return self;
- },
-
- /**
- * Post render method. Called after the control has been rendered to the target.
- *
- * @method postRender
- * @return {tinymce.ui.Control} Current control instance.
- */
- postRender: function() {
- var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;
-
- // Bind on |ba
ab
|
- * - * Or: - *|
- if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { - isCollapsed = editor.selection.isCollapsed(); - body = editor.getBody(); - - // Selection is collapsed but the editor isn't empty - if (isCollapsed && !dom.isEmpty(body)) { - return; - } - - // Selection isn't collapsed but not all the contents is selected - if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { - return; - } - - // Manually empty the editor - e.preventDefault(); - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - - editor.nodeChanged(); - } - }); - } - - /** - * WebKit doesn't select all the nodes in the body when you press Ctrl+A. - * IE selects more than the contents [a
] instead of[a]
see bug #6438 - * This selects the whole body so that backspace/delete logic will delete everything - */ - function selectAll() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { - e.preventDefault(); - editor.execCommand('SelectAll'); - } - }); - } - - /** - * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. - * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. - * - * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until - * you enter a character into the editor. - * - * It also happens when the first focus in made to the body. - * - * See: https://bugs.webkit.org/show_bug.cgi?id=83566 - */ - function inputMethodFocus() { - if (!editor.settings.content_editable) { - // Case 1 IME doesn't initialize if you focus the document - dom.bind(editor.getDoc(), 'focusin', function() { - selection.setRng(selection.getRng()); - }); - - // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event - dom.bind(editor.getDoc(), 'mousedown', function(e) { - if (e.target == editor.getDoc().documentElement) { - editor.getBody().focus(); - selection.setRng(selection.getRng()); - } - }); - } - } - - /** - * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the - * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is - * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js - * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other - * browsers. - * - * It also fixes a bug on Firefox where it's impossible to delete HR elements. - */ - function removeHrOnBackspace() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var node = selection.getNode(); - var previousSibling = node.previousSibling; - - if (node.nodeName == 'HR') { - dom.remove(node); - e.preventDefault(); - return; - } - - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { - dom.remove(previousSibling); - e.preventDefault(); - } - } - } - }); - } - - /** - * Firefox 3.x has an issue where the body element won't get proper focus if you click out - * side it's rectangle. - */ - function focusBody() { - // Fix for a focus bug in FF 3.x where the body element - // wouldn't get proper focus if the user clicked on the HTML element - if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 - editor.on('mousedown', function(e) { - if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") { - var body = editor.getBody(); - - // Blur the body it's focused but not correctly focused - body.blur(); - - // Refocus the body after a little while - setTimeout(function() { - body.focus(); - }, 0); - } - }); - } - } - - /** - * WebKit has a bug where it isn't possible to select image, hr or anchor elements - * by clicking on them so we need to fake that. - */ - function selectControlElements() { - editor.on('click', function(e) { - e = e.target; - - // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 - // WebKit can't even do simple things like selecting an image - // Needs tobe the setBaseAndExtend or it will fail to select floated images - if (/^(IMG|HR)$/.test(e.nodeName)) { - selection.getSel().setBaseAndExtent(e, 0, e, 1); - } - - if (e.nodeName == 'A' && dom.hasClass(e, 'mce-item-anchor')) { - selection.select(e); - } - - editor.nodeChanged(); - }); - } - - /** - * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. - * - * Fixes do backspace/delete on this: - *bla[ck
r]ed
- * - * Would become: - *bla|ed
- * - * Instead of: - *bla|ed
- */ - function removeStylesWhenDeletingAcrossBlockElements() { - function getAttributeApplyFunction() { - var template = dom.getAttribs(selection.getStart().cloneNode(false)); - - return function() { - var target = selection.getStart(); - - if (target !== editor.getBody()) { - dom.setAttrib(target, "style", null); - - each(template, function(attr) { - target.setAttributeNode(attr.cloneNode(true)); - }); - } - }; - } - - function isSelectionAcrossElements() { - return !selection.isCollapsed() && - dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); - } - - editor.on('keypress', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - editor.getDoc().execCommand('delete', false, null); - applyAttributes(); - e.preventDefault(); - return false; - } - }); - - dom.bind(editor.getDoc(), 'cut', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - - setTimeout(function() { - applyAttributes(); - }, 0); - } - }); - } - - /** - * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange - * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. - */ - function selectionChangeNodeChanged() { - var lastRng, selectionTimer; - - editor.on('selectionchange', function() { - if (selectionTimer) { - clearTimeout(selectionTimer); - selectionTimer = 0; - } - - selectionTimer = window.setTimeout(function() { - if (editor.removed) { - return; - } - - var rng = selection.getRng(); - - // Compare the ranges to see if it was a real change or not - if (!lastRng || !RangeUtils.compareRanges(rng, lastRng)) { - editor.nodeChanged(); - lastRng = rng; - } - }, 50); - }); - } - - /** - * Screen readers on IE needs to have the role application set on the body. - */ - function ensureBodyHasRoleApplication() { - document.body.setAttribute("role", "application"); - } - - /** - * Backspacing into a table behaves differently depending upon browser type. - * Therefore, disable Backspace when cursor immediately follows a table. - */ - function disableBackspaceIntoATable() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var previousSibling = selection.getNode().previousSibling; - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { - e.preventDefault(); - return false; - } - } - } - }); - } - - /** - * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this - * logic adds a \n before the BR so that it will get rendered. - */ - function addNewLinesBeforeBrInPre() { - // IE8+ rendering mode does the right thing with BR in PRE - if (getDocumentMode() > 7) { - return; - } - - // Enable display: none in area and add a specific class that hides all BR elements in PRE to - // avoid the caret from getting stuck at the BR elements while pressing the right arrow key - setEditorCommandState('RespectVisibilityInDesign', true); - editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); - dom.addClass(editor.getBody(), 'mceHideBrInPre'); - - // Adds a \n before all BR elements in PRE to get them visual - parser.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - - // Add \n before BR in PRE elements on older IE:s so the new lines get rendered - sibling = brElm.prev; - if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { - sibling.value += '\n'; - } else { - brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n'; - } - } - } - }); - - // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible - serializer.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - sibling = brElm.prev; - if (sibling && sibling.type == 3) { - sibling.value = sibling.value.replace(/\r?\n$/, ''); - } - } - } - }); - } - - /** - * Moves style width/height to attribute width/height when the user resizes an image on IE. - */ - function removePreSerializedStylesWhenSelectingControls() { - dom.bind(editor.getBody(), 'mouseup', function() { - var value, node = selection.getNode(); - - // Moved styles to attributes on IMG eements - if (node.nodeName == 'IMG') { - // Convert style width to width attribute - if ((value = dom.getStyle(node, 'width'))) { - dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'width', ''); - } - - // Convert style height to height attribute - if ((value = dom.getStyle(node, 'height'))) { - dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'height', ''); - } - } - }); - } - - /** - * Removes a blockquote when backspace is pressed at the beginning of it. - * - * For example: - *- * - * Becomes: - *|x
|x
- */ - function removeBlockQuoteOnBackSpace() { - // Add block quote deletion handler - editor.on('keydown', function(e) { - var rng, container, offset, root, parent; - - if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) { - return; - } - - rng = selection.getRng(); - container = rng.startContainer; - offset = rng.startOffset; - root = dom.getRoot(); - parent = container; - - if (!rng.collapsed || offset !== 0) { - return; - } - - while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) { - parent = parent.parentNode; - } - - // Is the cursor at the beginning of a blockquote? - if (parent.tagName === 'BLOCKQUOTE') { - // Remove the blockquote - editor.formatter.toggle('blockquote', null, parent); - - // Move the caret to the beginning of container - rng = dom.createRng(); - rng.setStart(container, 0); - rng.setEnd(container, 0); - selection.setRng(rng); - } - }); - } - - /** - * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. - */ - function setGeckoEditingOptions() { - function setOpts() { - editor._refreshContentEditable(); - - setEditorCommandState("StyleWithCSS", false); - setEditorCommandState("enableInlineTableEditing", false); - - if (!settings.object_resizing) { - setEditorCommandState("enableObjectResizing", false); - } - } - - if (!settings.readonly) { - editor.on('BeforeExecCommand MouseDown', setOpts); - } - } - - /** - * Fixes a gecko link bug, when a link is placed at the end of block elements there is - * no way to move the caret behind the link. This fix adds a bogus br element after the link. - * - * For example this: - * - * - * Becomes this: - * - */ - function addBrAfterLastLinks() { - function fixLinks() { - each(dom.select('a'), function(node) { - var parentNode = node.parentNode, root = dom.getRoot(); - - if (parentNode.lastChild === node) { - while (parentNode && !dom.isBlock(parentNode)) { - if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { - return; - } - - parentNode = parentNode.parentNode; - } - - dom.add(parentNode, 'br', {'data-mce-bogus': 1}); - } - }); - } - - editor.on('SetContent ExecCommand', function(e) { - if (e.type == "setcontent" || e.command === 'mceInsertLink') { - fixLinks(); - } - }); - } - - /** - * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by - * default we want to change that behavior. - */ - function setDefaultBlockType() { - if (settings.forced_root_block) { - editor.on('init', function() { - setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); - }); - } - } - - /** - * Removes ghost selections from images/tables on Gecko. - */ - function removeGhostSelection() { - editor.on('Undo Redo SetContent', function(e) { - if (!e.initial) { - editor.execCommand('mceRepaint'); - } - }); - } - - /** - * Deletes the selected image on IE instead of navigating to previous page. - */ - function deleteControlItemOnBackSpace() { - editor.on('keydown', function(e) { - var rng; - - if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { - rng = editor.getDoc().selection.createRange(); - if (rng && rng.item) { - e.preventDefault(); - editor.undoManager.beforeChange(); - dom.remove(rng.item(0)); - editor.undoManager.add(); - } - } - }); - } - - /** - * IE10 doesn't properly render block elements with the right height until you add contents to them. - * This fixes that by adding a padding-right to all empty text block elements. - * See: https://connect.microsoft.com/IE/feedback/details/743881 - */ - function renderEmptyBlocksFix() { - var emptyBlocksCSS; - - // IE10+ - if (getDocumentMode() >= 10) { - emptyBlocksCSS = ''; - each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { - emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; - }); - - editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); - } - } - - /** - * Old IE versions can't retain contents within noscript elements so this logic will store the contents - * as a attribute and the insert that value as it's raw text when the DOM is serialized. - */ - function keepNoScriptContents() { - if (getDocumentMode() < 9) { - parser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode; - - while (i--) { - node = nodes[i]; - textNode = node.firstChild; - - if (textNode) { - node.attr('data-mce-innertext', textNode.value); - } - } - }); - - serializer.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode, value; - - while (i--) { - node = nodes[i]; - textNode = nodes[i].firstChild; - - if (textNode) { - textNode.value = Entities.decode(textNode.value); - } else { - // Old IE can't retain noscript value so an attribute is used to store it - value = node.attributes.map['data-mce-innertext']; - if (value) { - node.attr('data-mce-innertext', null); - textNode = new Node('#text', 3); - textNode.value = value; - textNode.raw = true; - node.append(textNode); - } - } - } - }); - } - } - - /** - * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. - */ - function fixCaretSelectionOfDocumentElementOnIe() { - var doc = dom.doc, body = doc.body, started, startRng, htmlElm; - - // Return range from point or null if it failed - function rngFromPoint(x, y) { - var rng = body.createTextRange(); - - try { - rng.moveToPoint(x, y); - } catch (ex) { - // IE sometimes throws and exception, so lets just ignore it - rng = null; - } - - return rng; - } - - // Fires while the selection is changing - function selectionChange(e) { - var pointRng; - - // Check if the button is down or not - if (e.button) { - // Create range from mouse position - pointRng = rngFromPoint(e.x, e.y); - - if (pointRng) { - // Check if pointRange is before/after selection then change the endPoint - if (pointRng.compareEndPoints('StartToStart', startRng) > 0) { - pointRng.setEndPoint('StartToStart', startRng); - } else { - pointRng.setEndPoint('EndToEnd', startRng); - } - - pointRng.select(); - } - } else { - endSelection(); - } - } - - // Removes listeners - function endSelection() { - var rng = doc.selection.createRange(); - - // If the range is collapsed then use the last start range - if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) { - startRng.select(); - } - - dom.unbind(doc, 'mouseup', endSelection); - dom.unbind(doc, 'mousemove', selectionChange); - startRng = started = 0; - } - - // Make HTML element unselectable since we are going to handle selection by hand - doc.documentElement.unselectable = true; - - // Detect when user selects outside BODY - dom.bind(doc, 'mousedown contextmenu', function(e) { - if (e.target.nodeName === 'HTML') { - if (started) { - endSelection(); - } - - // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML - htmlElm = doc.documentElement; - if (htmlElm.scrollHeight > htmlElm.clientHeight) { - return; - } - - started = 1; - // Setup start position - startRng = rngFromPoint(e.x, e.y); - if (startRng) { - // Listen for selection change events - dom.bind(doc, 'mouseup', endSelection); - dom.bind(doc, 'mousemove', selectionChange); - - dom.getRoot().focus(); - startRng.select(); - } - } - }); - } - - /** - * Fixes selection issues where the caret can be placed between two inline elements like a|b - * this fix will lean the caret right into the closest inline element. - */ - function normalizeSelection() { - // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything - editor.on('keyup focusin mouseup', function(e) { - if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { - selection.normalize(); - } - }, true); - } - - /** - * Forces Gecko to render a broken image icon if it fails to load an image. - */ - function showBrokenImageIcon() { - editor.contentStyles.push( - 'img:-moz-broken {' + - '-moz-force-broken-image-icon:1;' + - 'min-width:24px;' + - 'min-height:24px' + - '}' - ); - } - - /** - * iOS has a bug where it's impossible to type if the document has a touchstart event - * bound and the user touches the document while having the on screen keyboard visible. - * - * The touch event moves the focus to the parent document while having the caret inside the iframe - * this fix moves the focus back into the iframe document. - */ - function restoreFocusOnKeyDown() { - if (!editor.inline) { - editor.on('keydown', function() { - if (document.activeElement == document.body) { - editor.getWin().focus(); - } - }); - } - } - - /** - * IE 11 has an annoying issue where you can't move focus into the editor - * by clicking on the white area HTML element. We used to be able to to fix this with - * the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection - * object it's not possible anymore. So we need to hack in a ungly CSS to force the - * body to be at least 150px. If the user clicks the HTML element out side this 150px region - * we simply move the focus into the first paragraph. Not ideal since you loose the - * positioning of the caret but goot enough for most cases. - */ - function bodyHeight() { - if (!editor.inline) { - editor.contentStyles.push('body {min-height: 150px}'); - editor.on('click', function(e) { - if (e.target.nodeName == 'HTML') { - editor.getBody().focus(); - editor.selection.normalize(); - editor.nodeChanged(); - } - }); - } - } - - /** - * Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow. - * You might then loose all your work so we need to block that behavior and replace it with our own. - */ - function blockCmdArrowNavigation() { - if (Env.mac) { - editor.on('keydown', function(e) { - if (VK.metaKeyPressed(e) && (e.keyCode == 37 || e.keyCode == 39)) { - e.preventDefault(); - editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'word'); - } - }); - } - } - - /** - * Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin. - */ - function disableAutoUrlDetect() { - setEditorCommandState("AutoUrlDetect", false); - } - - /** - * IE 11 has a fantastic bug where it will produce two trailing BR elements to iframe bodies when - * the iframe is hidden by display: none on a parent container. The DOM is actually out of sync - * with innerHTML in this case. It's like IE adds shadow DOM BR elements that appears on innerHTML - * but not as the lastChild of the body. However is we add a BR element to the body then remove it - * it doesn't seem to add these BR elements makes sence right?! - * - * Example of what happens: text becomes text]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/, '');
- });
- }
-
- self.load({initial: true, format: 'html'});
- self.startContent = self.getContent({format: 'raw'});
-
- /**
- * Is set to true after the editor instance has been initialized
- *
- * @property initialized
- * @type Boolean
- * @example
- * function isEditorInitialized(editor) {
- * return editor && editor.initialized;
- * }
- */
- self.initialized = true;
-
- each(self._pendingNativeEvents, function(name) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(e.type, e);
- });
- });
-
- self.fire('init');
- self.focus(true);
- self.nodeChanged({initial: true});
- self.execCallback('init_instance_callback', self);
-
- // Add editor specific CSS styles
- if (self.contentStyles.length > 0) {
- contentCssText = '';
-
- each(self.contentStyles, function(style) {
- contentCssText += style + "\r\n";
- });
-
- self.dom.addStyle(contentCssText);
- }
-
- // Load specified content CSS last
- each(self.contentCSS, function(cssUrl) {
- if (!self.loadedCSS[cssUrl]) {
- self.dom.loadCSS(cssUrl);
- self.loadedCSS[cssUrl] = true;
- }
- });
-
- // Handle auto focus
- if (settings.auto_focus) {
- setTimeout(function () {
- var ed = self.editorManager.get(settings.auto_focus);
-
- ed.selection.select(ed.getBody(), 1);
- ed.selection.collapse(1);
- ed.getBody().focus();
- ed.getWin().focus();
- }, 100);
- }
-
- // Clean up references for IE
- targetElm = doc = body = null;
- },
-
- /**
- * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
- * it will also place DOM focus inside the editor.
- *
- * @method focus
- * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
- */
- focus: function(skip_focus) {
- var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
- var controlElm, doc = self.getDoc(), body;
-
- if (!skip_focus) {
- // Get selected control element
- rng = selection.getRng();
- if (rng.item) {
- controlElm = rng.item(0);
- }
-
- self._refreshContentEditable();
-
- // Focus the window iframe
- if (!contentEditable) {
- // WebKit needs this call to fire focusin event properly see #5948
- // But Opera pre Blink engine will produce an empty selection so skip Opera
- if (!Env.opera) {
- self.getBody().focus();
- }
-
- self.getWin().focus();
- }
-
- // Focus the body as well since it's contentEditable
- if (isGecko || contentEditable) {
- body = self.getBody();
-
- // Check for setActive since it doesn't scroll to the element
- if (body.setActive && Env.ie < 11) {
- body.setActive();
- } else {
- body.focus();
- }
-
- if (contentEditable) {
- selection.normalize();
- }
- }
-
- // Restore selected control element
- // This is needed when for example an image is selected within a
- // layer a call to focus will then remove the control selection
- if (controlElm && controlElm.ownerDocument == doc) {
- rng = doc.body.createControlRange();
- rng.addElement(controlElm);
- rng.select();
- }
- }
-
- if (self.editorManager.activeEditor != self) {
- if ((oed = self.editorManager.activeEditor)) {
- oed.fire('deactivate', {relatedTarget: self});
- }
-
- self.fire('activate', {relatedTarget: oed});
- }
-
- self.editorManager.activeEditor = self;
- },
-
- /**
- * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
- * There new event model is a better way to add callback so this method might be removed in the future.
- *
- * @method execCallback
- * @param {String} name Name of the callback to execute.
- * @return {Object} Return value passed from callback function.
- */
- execCallback: function(name) {
- var self = this, callback = self.settings[name], scope;
-
- if (!callback) {
- return;
- }
-
- // Look through lookup
- if (self.callbackLookup && (scope = self.callbackLookup[name])) {
- callback = scope.func;
- scope = scope.scope;
- }
-
- if (typeof(callback) === 'string') {
- scope = callback.replace(/\.\w+$/, '');
- scope = scope ? resolve(scope) : 0;
- callback = resolve(callback);
- self.callbackLookup = self.callbackLookup || {};
- self.callbackLookup[name] = {func: callback, scope: scope};
- }
-
- return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
- },
-
- /**
- * Translates the specified string by replacing variables with language pack items it will also check if there is
- * a key mathcin the input.
- *
- * @method translate
- * @param {String} text String to translate by the language pack data.
- * @return {String} Translated string.
- */
- translate: function(text) {
- var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
-
- if (!text) {
- return '';
- }
-
- return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
- return i18n.data[lang + '.' + b] || '{#' + b + '}';
- });
- },
-
- /**
- * Returns a language pack item by name/key.
- *
- * @method getLang
- * @param {String} name Name/key to get from the language pack.
- * @param {String} defaultVal Optional default value to retrive.
- */
- getLang: function(name, defaultVal) {
- return (
- this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
- (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
- );
- },
-
- /**
- * Returns a configuration parameter by name.
- *
- * @method getParam
- * @param {String} name Configruation parameter to retrive.
- * @param {String} defaultVal Optional default value to return.
- * @param {String} type Optional type parameter.
- * @return {String} Configuration parameter value or default value.
- * @example
- * // Returns a specific config value from the currently active editor
- * var someval = tinymce.activeEditor.getParam('myvalue');
- *
- * // Returns a specific config value from a specific editor instance by id
- * var someval2 = tinymce.get('my_editor').getParam('myvalue');
- */
- getParam: function(name, defaultVal, type) {
- var value = name in this.settings ? this.settings[name] : defaultVal, output;
-
- if (type === 'hash') {
- output = {};
-
- if (typeof(value) === 'string') {
- each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
- value = value.split('=');
-
- if (value.length > 1) {
- output[trim(value[0])] = trim(value[1]);
- } else {
- output[trim(value[0])] = trim(value);
- }
- });
- } else {
- output = value;
- }
-
- return output;
- }
-
- return value;
- },
-
- /**
- * Distpaches out a onNodeChange event to all observers. This method should be called when you
- * need to update the UI states or element path etc.
- *
- * @method nodeChanged
- */
- nodeChanged: function() {
- var self = this, selection = self.selection, node, parents, root;
-
- // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
- if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
- // Get start node
- root = self.getBody();
- node = selection.getStart() || root;
- node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
-
- // Edge case for
|
]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/,"")}),n.load({initial:!0,format:"html"}),n.startContent=n.getContent({format:"raw"}),n.initialized=!0,R(n._pendingNativeEvents,function(e){n.dom.bind(_(n,e),e,function(e){n.fire(e.type,e)})}),n.fire("init"),n.focus(!0),n.nodeChanged({initial:!0}),n.execCallback("init_instance_callback",n),n.contentStyles.length>0&&(h="",R(n.contentStyles,function(e){h+=e+"\r\n"}),n.dom.addStyle(h)),R(n.contentCSS,function(e){n.loadedCSS[e]||(n.dom.loadCSS(e),n.loadedCSS[e]=!0)}),o.auto_focus&&setTimeout(function(){var e=n.editorManager.get(o.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),f=p=m=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||(o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||(b.opera||n.getBody().focus(),n.getWin().focus()),(H||i)&&(l=n.getBody(),l.setActive&&b.ie<11?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?D(r):0,n=D(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n.data[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n.data[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n.data[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.split(r.indexOf("=")>0?/[;,](?![^=;,]*(?:[;,]|$))/:","),function(e){e=e.split("="),i[L(e[0])]=L(e.length>1?e[1]:e)}):i=r,i):r},nodeChanged:function(){var e=this,t=e.selection,n,r,i;!e.initialized||e.settings.disable_nodechange||e.settings.readonly||(i=e.getBody(),n=t.getStart()||i,n=P&&n.ownerDocument!=e.getDoc()?e.getBody():n,"IMG"==n.nodeName&&t.isCollapsed()&&(n=n.parentNode),r=[],e.dom.getParent(n,function(e){return e===i?!0:void r.push(e)}),e.fire("NodeChange",{element:n,parents:r}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),t.text||t.icon||(t.icon=e),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,t,n,r){var i=this,o=0,a;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||r&&r.skip_focus||i.focus(),r=T({},r),r=i.fire("BeforeExecCommand",{command:e,ui:t,value:n}),r.isDefaultPrevented()?!1:(a=i.execCommands[e])&&a.func.call(a.scope,t,n)!==!0?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(R(i.plugins,function(r){return r.execCommand&&r.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),o=!0,!1):void 0}),o?o:i.theme&&i.theme.execCommand&&i.theme.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):i.editorCommands.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(i.getDoc().execCommand(e,t,n),void i.fire("ExecCommand",{command:e,ui:t,value:n})))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;E.show(e.getContainer()),E.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),E.hide(e.getContainer()),E.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!E.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):void 0},save:function(e){var t=this,n=t.getElement(),r,i;if(n&&t.initialized)return e=e||{},e.save=!0,e.element=n,r=e.content=t.getContent(e),e.no_events||t.fire("SaveContent",e),r=e.content,/TEXTAREA|INPUT/i.test(n.nodeName)?n.value=r:(t.inline||(n.innerHTML=r),(i=E.getParent(t.id,"form"))&&R(i.elements,function(e){return e.name==t.id?(e.value=r,!1):void 0})),e.element=n=null,e.set_dirty!==!1&&(t.isNotDirty=!0),r},setContent:function(e,t){var n=this,r=n.getBody(),i;return t=t||{},t.format=t.format||"html",t.set=!0,t.content=e,t.no_events||n.fire("BeforeSetContent",t),e=t.content,0===e.length||/^\s+$/.test(e)?(i=n.settings.forced_root_block,i&&n.schema.isValidChild(r.nodeName.toLowerCase(),i.toLowerCase())?(e=P&&11>P?"":'
',e=n.dom.createHTML(i,n.settings.forced_root_block_attrs,e)):P||(e='
'),r.innerHTML=e,n.fire("SetContent",t)):("raw"!==t.format&&(e=new o({},n.schema).serialize(n.parser.parse(e,{isRootContent:!0}))),t.content=L(e),n.dom.setHTML(r,t.content),t.no_events||n.fire("SetContent",t)),t.content},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty},getContainer:function(){var e=this;return e.container||(e.container=E.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return E.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=E.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",t=i.getAttrib(e,"border"),void(t&&"0"!=t||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)));case"A":return void(i.getAttrib(e,"href",!1)||(t=i.getAttrib(e,"name")||e.id,o=r.visual_anchor_class||"mce-item-anchor",t&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))))}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this;if(!e.removed){e.save(),e.fire("remove"),e.off(),e.removed=1,e.hasHiddenInput&&E.remove(e.getElement().nextSibling),E.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc()));var t=e.getContainer();M.unbind(e.getBody()),M.unbind(t),e.editorManager.remove(e),E.remove(t),e.destroy()}},bindNative:function(e){var t=this;t.settings.readonly||(t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e])},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;if(!t.destroyed){if(!e&&!t.removed)return void t.remove();e&&H&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off("beforeunload",t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n._mceOldSubmit&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null),E.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=t.editorContainer=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1}},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return H?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(ot,[],function(){var e={};return{rtl:!1,add:function(t,n){for(var r in n)e[r]=n[r];this.rtl=this.rtl||"rtl"===e._dir},translate:function(t){if("undefined"==typeof t)return t;if("string"!=typeof t&&t.raw)return t.raw;if(t.push){var n=t.slice(1);t=(e[t[0]]||t[0]).replace(/\{([^\}]+)\}/g,function(e,t){return n[t]})}return e[t]||t},data:e}}),r(at,[v,h],function(e,t){function n(e){function a(){try{return document.activeElement}catch(e){return document.body}}function s(e){return e&&e.startContainer?{startContainer:e.startContainer,startOffset:e.startOffset,endContainer:e.endContainer,endOffset:e.endOffset}:e}function l(e,t){var n;return t.startContainer?(n=e.getDoc().createRange(),n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset)):n=t,n}function c(e){return!!o.getParent(e,n.isEditorUIElement)}function d(e,t){for(var n=t.getBody();e;){if(e==n)return!0;e=e.parentNode}}function u(n){var u=n.editor;u.on("init",function(){(u.inline||t.ie)&&(u.on("nodechange keyup",function(){var e=document.activeElement;e&&e.id==u.id+"_ifr"&&(e=u.getBody()),d(e,u)&&(u.lastRng=u.selection.getRng())}),t.webkit&&!r&&(r=function(){var t=e.activeEditor;if(t&&t.selection){var n=t.selection.getRng();n&&!n.collapsed&&(u.lastRng=n)}},o.bind(document,"selectionchange",r)))}),u.on("setcontent",function(){u.lastRng=null}),u.on("mousedown",function(){u.selection.lastFocusBookmark=null}),u.on("focusin",function(){var t=e.focusedEditor;u.selection.lastFocusBookmark&&(u.selection.setRng(l(u,u.selection.lastFocusBookmark)),u.selection.lastFocusBookmark=null),t!=u&&(t&&t.fire("blur",{focusedEditor:u}),e.activeEditor=u,e.focusedEditor=u,u.fire("focus",{blurredEditor:t}),u.focus(!0)),u.lastRng=null}),u.on("focusout",function(){window.setTimeout(function(){var t=e.focusedEditor;c(a())||t!=u||(u.fire("blur",{focusedEditor:null}),e.focusedEditor=null,u.selection&&(u.selection.lastFocusBookmark=null))},0)}),i||(i=function(t){var n=e.activeEditor;n&&t.target.ownerDocument==document&&(n.selection&&(n.selection.lastFocusBookmark=s(n.lastRng)),c(t.target)||e.focusedEditor!=n||(n.fire("blur",{focusedEditor:null}),e.focusedEditor=null))},o.bind(document,"focusin",i))}function f(t){e.focusedEditor==t.editor&&(e.focusedEditor=null),e.activeEditor||(o.unbind(document,"selectionchange",r),o.unbind(document,"focusin",i),r=i=null)}e.on("AddEditor",u),e.on("RemoveEditor",f)}var r,i,o=e.DOM;return n.isEditorUIElement=function(e){return-1!==e.className.toString().indexOf("mce-")},n}),r(st,[it,v,O,h,f,nt,ot,at],function(e,n,r,i,o,a,s,l){var c=n.DOM,d=o.explode,u=o.each,f=o.extend,p=0,m,h={majorVersion:"4",minorVersion:"0.20",releaseDate:"2014-03-18",editors:[],i18n:s,activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;s
abcabc123
would produceabc
abc123
. - * - * @method split - * @param {Element} parentElm Parent element to split. - * @param {Element} splitElm Element to split at. - * @param {Element} replacementElm Optional replacement element to replace the split element with. - * @return {Element} Returns the split element or the replacement element if that is specified. - */ - split: function(parentElm, splitElm, replacementElm) { - var self = this, r = self.createRng(), bef, aft, pa; - - // W3C valid browsers tend to leave empty nodes to the left/right side of the contents - this makes sense - // but we don't want that in our code since it serves no purpose for the end user - // For example splitting this html at the bold element: - //text 1CHOPtext 2
- // would produce: - //text 1
CHOPtext 2
- // this function will then trim off empty edges and produce: - //text 1
CHOPtext 2
- function trimNode(node) { - var i, children = node.childNodes, type = node.nodeType; - - function surroundedBySpans(node) { - var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN'; - var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN'; - return previousIsSpan && nextIsSpan; - } - - if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') { - return; - } - - for (i = children.length - 1; i >= 0; i--) { - trimNode(children[i]); - } - - if (type != 9) { - // Keep non whitespace text nodes - if (type == 3 && node.nodeValue.length > 0) { - // If parent element isn't a block or there isn't any useful contents for example "" - // Also keep text nodes with only spaces if surrounded by spans. - // eg. "
a b
" should keep space between a and b - var trimmedLength = trim(node.nodeValue).length; - if (!self.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) { - return; - } - } else if (type == 1) { - // If the only child is a bookmark then move it up - children = node.childNodes; - - // TODO fix this complex if - if (children.length == 1 && children[0] && children[0].nodeType == 1 && - children[0].getAttribute('data-mce-type') == 'bookmark') { - node.parentNode.insertBefore(children[0], node); - } - - // Keep non empty elements or img, hr etc - if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) { - return; - } - } - - self.remove(node); - } - - return node; - } - - if (parentElm && splitElm) { - // Get before chunk - r.setStart(parentElm.parentNode, self.nodeIndex(parentElm)); - r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm)); - bef = r.extractContents(); - - // Get after chunk - r = self.createRng(); - r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1); - r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1); - aft = r.extractContents(); - - // Insert before chunk - pa = parentElm.parentNode; - pa.insertBefore(trimNode(bef), parentElm); - - // Insert middle chunk - if (replacementElm) { - pa.replaceChild(replacementElm, splitElm); - } else { - pa.insertBefore(splitElm, parentElm); - } - - // Insert after chunk - pa.insertBefore(trimNode(aft), parentElm); - self.remove(parentElm); - - return replacementElm || splitElm; - } - }, - - /** - * Adds an event handler to the specified object. - * - * @method bind - * @param {Element/Document/Window/Array} target Target element to bind events to. - * handler to or an array of elements/ids/documents. - * @param {String} name Name of event handler to add, for example: click. - * @param {function} func Function to execute when the event occurs. - * @param {Object} scope Optional scope to execute the function in. - * @return {function} Function callback handler the same as the one passed in. - */ - bind: function(target, name, func, scope) { - var self = this; - - if (Tools.isArray(target)) { - var i = target.length; - - while (i--) { - target[i] = self.bind(target[i], name, func, scope); - } - - return target; - } - - // Collect all window/document events bound by editor instance - if (self.settings.collect && (target === self.doc || target === self.win)) { - self.boundEvents.push([target, name, func, scope]); - } - - return self.events.bind(target, name, func, scope || self); - }, - - /** - * Removes the specified event handler by name and function from an element or collection of elements. - * - * @method unbind - * @param {Element/Document/Window/Array} target Target element to unbind events on. - * @param {String} name Event handler name, for example: "click" - * @param {function} func Function to remove. - * @return {bool/Array} Bool state of true if the handler was removed, or an array of states if multiple input elements - * were passed in. - */ - unbind: function(target, name, func) { - var self = this, i; - - if (Tools.isArray(target)) { - i = target.length; - - while (i--) { - target[i] = self.unbind(target[i], name, func); - } - - return target; - } - - // Remove any bound events matching the input - if (self.boundEvents && (target === self.doc || target === self.win)) { - i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - - if (target == item[0] && (!name || name == item[1]) && (!func || func == item[2])) { - this.events.unbind(item[0], item[1], item[2]); - } - } - } - - return this.events.unbind(target, name, func); - }, - - /** - * Fires the specified event name with object on target. - * - * @method fire - * @param {Node/Document/Window} target Target element or object to fire event on. - * @param {String} name Name of the event to fire. - * @param {Object} evt Event object to send. - * @return {Event} Event object. - */ - fire: function(target, name, evt) { - return this.events.fire(target, name, evt); - }, - - // Returns the content editable state of a node - getContentEditable: function(node) { - var contentEditable; - - // Check type - if (node.nodeType != 1) { - return null; - } - - // Check for fake content editable - contentEditable = node.getAttribute("data-mce-contenteditable"); - if (contentEditable && contentEditable !== "inherit") { - return contentEditable; - } - - // Check for real content editable - return node.contentEditable !== "inherit" ? node.contentEditable : null; - }, - - /** - * Destroys all internal references to the DOM to solve IE leak issues. - * - * @method destroy - */ - destroy: function() { - var self = this; - - // Unbind all events bound to window/document by editor instance - if (self.boundEvents) { - var i = self.boundEvents.length; - - while (i--) { - var item = self.boundEvents[i]; - this.events.unbind(item[0], item[1], item[2]); - } - - self.boundEvents = null; - } - - // Restore sizzle document to window.document - // Since the current document might be removed producing "Permission denied" on IE see #6325 - if (Sizzle.setDocument) { - Sizzle.setDocument(); - } - - self.win = self.doc = self.root = self.events = self.frag = null; - }, - - // #ifdef debug - - dumpRng: function(r) { - return ( - 'startContainer: ' + r.startContainer.nodeName + - ', startOffset: ' + r.startOffset + - ', endContainer: ' + r.endContainer.nodeName + - ', endOffset: ' + r.endOffset - ); - }, - - // #endif - - _findSib: function(node, selector, name) { - var self = this, func = selector; - - if (node) { - // If expression make a function of it using is - if (typeof(func) == 'string') { - func = function(node) { - return self.is(node, selector); - }; - } - - // Loop all siblings - for (node = node[name]; node; node = node[name]) { - if (func(node)) { - return node; - } - } - } - - return null; - } - }; - - /** - * Instance of DOMUtils for the current document. - * - * @static - * @property DOM - * @type tinymce.dom.DOMUtils - * @example - * // Example of how to add a class to some element by id - * tinymce.DOM.addClass('someid', 'someclass'); - */ - DOMUtils.DOM = new DOMUtils(document); - - return DOMUtils; -}); - -// Included from: js/tinymce/classes/dom/ScriptLoader.js - -/** - * ScriptLoader.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*globals console*/ - -/** - * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks - * when various items gets loaded. This class is useful to load external JavaScript files. - * - * @class tinymce.dom.ScriptLoader - * @example - * // Load a script from a specific URL using the global script loader - * tinymce.ScriptLoader.load('somescript.js'); - * - * // Load a script using a unique instance of the script loader - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.load('somescript.js'); - * - * // Load multiple scripts - * var scriptLoader = new tinymce.dom.ScriptLoader(); - * - * scriptLoader.add('somescript1.js'); - * scriptLoader.add('somescript2.js'); - * scriptLoader.add('somescript3.js'); - * - * scriptLoader.loadQueue(function() { - * alert('All scripts are now loaded.'); - * }); - */ -define("tinymce/dom/ScriptLoader", [ - "tinymce/dom/DOMUtils", - "tinymce/util/Tools" -], function(DOMUtils, Tools) { - var DOM = DOMUtils.DOM; - var each = Tools.each, grep = Tools.grep; - - function ScriptLoader() { - var QUEUED = 0, - LOADING = 1, - LOADED = 2, - states = {}, - queue = [], - scriptLoadedCallbacks = {}, - queueLoadedCallbacks = [], - loading = 0, - undef; - - /** - * Loads a specific script directly without adding it to the load queue. - * - * @method load - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - function loadScript(url, callback) { - var dom = DOM, elm, id; - - // Execute callback when script is loaded - function done() { - dom.remove(id); - - if (elm) { - elm.onreadystatechange = elm.onload = elm = null; - } - - callback(); - } - - function error() { - /*eslint no-console:0 */ - - // Report the error so it's easier for people to spot loading errors - if (typeof(console) !== "undefined" && console.log) { - console.log("Failed to load: " + url); - } - - // We can't mark it as done if there is a load error since - // A) We don't want to produce 404 errors on the server and - // B) the onerror event won't fire on all browsers. - // done(); - } - - id = dom.uniqueId(); - - // Create new script element - elm = document.createElement('script'); - elm.id = id; - elm.type = 'text/javascript'; - elm.src = url; - - // Seems that onreadystatechange works better on IE 10 onload seems to fire incorrectly - if ("onreadystatechange" in elm) { - elm.onreadystatechange = function() { - if (/loaded|complete/.test(elm.readyState)) { - done(); - } - }; - } else { - elm.onload = done; - } - - // Add onerror event will get fired on some browsers but not all of them - elm.onerror = error; - - // Add script to document - (document.getElementsByTagName('head')[0] || document.body).appendChild(elm); - } - - /** - * Returns true/false if a script has been loaded or not. - * - * @method isDone - * @param {String} url URL to check for. - * @return {Boolean} true/false if the URL is loaded. - */ - this.isDone = function(url) { - return states[url] == LOADED; - }; - - /** - * Marks a specific script to be loaded. This can be useful if a script got loaded outside - * the script loader or to skip it from loading some script. - * - * @method markDone - * @param {string} u Absolute URL to the script to mark as loaded. - */ - this.markDone = function(url) { - states[url] = LOADED; - }; - - /** - * Adds a specific script to the load queue of the script loader. - * - * @method add - * @param {String} url Absolute URL to script to add. - * @param {function} callback Optional callback function to execute ones this script gets loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.add = this.load = function(url, callback, scope) { - var state = states[url]; - - // Add url to load queue - if (state == undef) { - queue.push(url); - states[url] = QUEUED; - } - - if (callback) { - // Store away callback for later execution - if (!scriptLoadedCallbacks[url]) { - scriptLoadedCallbacks[url] = []; - } - - scriptLoadedCallbacks[url].push({ - func: callback, - scope: scope || this - }); - } - }; - - /** - * Starts the loading of the queue. - * - * @method loadQueue - * @param {function} callback Optional callback to execute when all queued items are loaded. - * @param {Object} scope Optional scope to execute the callback in. - */ - this.loadQueue = function(callback, scope) { - this.loadScripts(queue, callback, scope); - }; - - /** - * Loads the specified queue of files and executes the callback ones they are loaded. - * This method is generally not used outside this class but it might be useful in some scenarios. - * - * @method loadScripts - * @param {Array} scripts Array of queue items to load. - * @param {function} callback Optional callback to execute ones all items are loaded. - * @param {Object} scope Optional scope to execute callback in. - */ - this.loadScripts = function(scripts, callback, scope) { - var loadScripts; - - function execScriptLoadedCallbacks(url) { - // Execute URL callback functions - each(scriptLoadedCallbacks[url], function(callback) { - callback.func.call(callback.scope); - }); - - scriptLoadedCallbacks[url] = undef; - } - - queueLoadedCallbacks.push({ - func: callback, - scope: scope || this - }); - - loadScripts = function() { - var loadingScripts = grep(scripts); - - // Current scripts has been handled - scripts.length = 0; - - // Load scripts that needs to be loaded - each(loadingScripts, function(url) { - // Script is already loaded then execute script callbacks directly - if (states[url] == LOADED) { - execScriptLoadedCallbacks(url); - return; - } - - // Is script not loading then start loading it - if (states[url] != LOADING) { - states[url] = LOADING; - loading++; - - loadScript(url, function() { - states[url] = LOADED; - loading--; - - execScriptLoadedCallbacks(url); - - // Load more scripts if they where added by the recently loaded script - loadScripts(); - }); - } - }); - - // No scripts are currently loading then execute all pending queue loaded callbacks - if (!loading) { - each(queueLoadedCallbacks, function(callback) { - callback.func.call(callback.scope); - }); - - queueLoadedCallbacks.length = 0; - } - }; - - loadScripts(); - }; - } - - ScriptLoader.ScriptLoader = new ScriptLoader(); - - return ScriptLoader; -}); - -// Included from: js/tinymce/classes/AddOnManager.js - -/** - * AddOnManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the loading of themes/plugins or other add-ons and their language packs. - * - * @class tinymce.AddOnManager - */ -define("tinymce/AddOnManager", [ - "tinymce/dom/ScriptLoader", - "tinymce/util/Tools" -], function(ScriptLoader, Tools) { - var each = Tools.each; - - function AddOnManager() { - var self = this; - - self.items = []; - self.urls = {}; - self.lookup = {}; - } - - AddOnManager.prototype = { - /** - * Returns the specified add on by the short name. - * - * @method get - * @param {String} name Add-on to look for. - * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined. - */ - get: function(name) { - if (this.lookup[name]) { - return this.lookup[name].instance; - } else { - return undefined; - } - }, - - dependencies: function(name) { - var result; - - if (this.lookup[name]) { - result = this.lookup[name].dependencies; - } - - return result || []; - }, - - /** - * Loads a language pack for the specified add-on. - * - * @method requireLangPack - * @param {String} name Short name of the add-on. - * @param {String} languages Optional comma or space separated list of languages to check if it matches the name. - */ - requireLangPack: function(name, languages) { - if (AddOnManager.language && AddOnManager.languageLoad !== false) { - if (languages && new RegExp('([, ]|\\b)' + AddOnManager.language + '([, ]|\\b)').test(languages) === false) { - return; - } - - ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + AddOnManager.language + '.js'); - } - }, - - /** - * Adds a instance of the add-on by it's short name. - * - * @method add - * @param {String} id Short name/id for the add-on. - * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add. - * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in. - * @example - * // Create a simple plugin - * tinymce.create('tinymce.plugins.TestPlugin', { - * TestPlugin: function(ed, url) { - * ed.on('click', function(e) { - * ed.windowManager.alert('Hello World!'); - * }); - * } - * }); - * - * // Register plugin using the add method - * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-test' // Init the plugin but don't try to load it - * }); - */ - add: function(id, addOn, dependencies) { - this.items.push(addOn); - this.lookup[id] = {instance: addOn, dependencies: dependencies}; - - return addOn; - }, - - createUrl: function(baseUrl, dep) { - if (typeof dep === "object") { - return dep; - } else { - return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix}; - } - }, - - /** - * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url. - * This should be used in development mode. A new compressor/javascript munger process will ensure that the - * components are put together into the plugin.js file and compressed correctly. - * - * @method addComponents - * @param {String} pluginName name of the plugin to load scripts from (will be used to get the base url for the plugins). - * @param {Array} scripts Array containing the names of the scripts to load. - */ - addComponents: function(pluginName, scripts) { - var pluginUrl = this.urls[pluginName]; - - each(scripts, function(script) { - ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script); - }); - }, - - /** - * Loads an add-on from a specific url. - * - * @method load - * @param {String} name Short name of the add-on that gets loaded. - * @param {String} addOnUrl URL to the add-on that will get loaded. - * @param {function} callback Optional callback to execute ones the add-on is loaded. - * @param {Object} scope Optional scope to execute the callback in. - * @example - * // Loads a plugin from an external URL - * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js'); - * - * // Initialize TinyMCE - * tinymce.init({ - * ... - * plugins: '-myplugin' // Don't try to load it again - * }); - */ - load: function(name, addOnUrl, callback, scope) { - var self = this, url = addOnUrl; - - function loadDependencies() { - var dependencies = self.dependencies(name); - - each(dependencies, function(dep) { - var newUrl = self.createUrl(addOnUrl, dep); - - self.load(newUrl.resource, newUrl, undefined, undefined); - }); - - if (callback) { - if (scope) { - callback.call(scope); - } else { - callback.call(ScriptLoader); - } - } - } - - if (self.urls[name]) { - return; - } - - if (typeof addOnUrl === "object") { - url = addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix; - } - - if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) { - url = AddOnManager.baseURL + '/' + url; - } - - self.urls[name] = url.substring(0, url.lastIndexOf('/')); - - if (self.lookup[name]) { - loadDependencies(); - } else { - ScriptLoader.ScriptLoader.add(url, loadDependencies, scope); - } - } - }; - - AddOnManager.PluginManager = new AddOnManager(); - AddOnManager.ThemeManager = new AddOnManager(); - - return AddOnManager; -}); - -/** - * TinyMCE theme class. - * - * @class tinymce.Theme - */ - -/** - * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc. - * - * @method renderUI - * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance. - * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight. - */ - -/** - * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional. - * - * @class tinymce.Plugin - * @example - * tinymce.PluginManager.add('example', function(editor, url) { - * // Add a button that opens a window - * editor.addButton('example', { - * text: 'My button', - * icon: false, - * onclick: function() { - * // Open window - * editor.windowManager.open({ - * title: 'Example plugin', - * body: [ - * {type: 'textbox', name: 'title', label: 'Title'} - * ], - * onsubmit: function(e) { - * // Insert content when the window form is submitted - * editor.insertContent('Title: ' + e.data.title); - * } - * }); - * } - * }); - * - * // Adds a menu item to the tools menu - * editor.addMenuItem('example', { - * text: 'Example plugin', - * context: 'tools', - * onclick: function() { - * // Open window with a specific url - * editor.windowManager.open({ - * title: 'TinyMCE site', - * url: 'http://www.tinymce.com', - * width: 800, - * height: 600, - * buttons: [{ - * text: 'Close', - * onclick: 'close' - * }] - * }); - * } - * }); - * }); - */ - -// Included from: js/tinymce/classes/html/Node.js - -/** - * Node.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is a minimalistic implementation of a DOM like node used by the DomParser class. - * - * @example - * var node = new tinymce.html.Node('strong', 1); - * someRoot.append(node); - * - * @class tinymce.html.Node - * @version 3.4 - */ -define("tinymce/html/Node", [], function() { - var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = { - '#text': 3, - '#comment': 8, - '#cdata': 4, - '#pi': 7, - '#doctype': 10, - '#document-fragment': 11 - }; - - // Walks the tree left/right - function walk(node, root_node, prev) { - var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next'; - - // Walk into nodes if it has a start - if (node[startName]) { - return node[startName]; - } - - // Return the sibling if it has one - if (node !== root_node) { - sibling = node[siblingName]; - - if (sibling) { - return sibling; - } - - // Walk up the parents to look for siblings - for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) { - sibling = parent[siblingName]; - - if (sibling) { - return sibling; - } - } - } - } - - /** - * Constructs a new Node instance. - * - * @constructor - * @method Node - * @param {String} name Name of the node type. - * @param {Number} type Numeric type representing the node. - */ - function Node(name, type) { - this.name = name; - this.type = type; - - if (type === 1) { - this.attributes = []; - this.attributes.map = {}; - } - } - - Node.prototype = { - /** - * Replaces the current node with the specified one. - * - * @example - * someNode.replace(someNewNode); - * - * @method replace - * @param {tinymce.html.Node} node Node to replace the current node with. - * @return {tinymce.html.Node} The old node that got replaced. - */ - replace: function(node) { - var self = this; - - if (node.parent) { - node.remove(); - } - - self.insert(node, self); - self.remove(); - - return self; - }, - - /** - * Gets/sets or removes an attribute by name. - * - * @example - * someNode.attr("name", "value"); // Sets an attribute - * console.log(someNode.attr("name")); // Gets an attribute - * someNode.attr("name", null); // Removes an attribute - * - * @method attr - * @param {String} name Attribute name to set or get. - * @param {String} value Optional value to set. - * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation. - */ - attr: function(name, value) { - var self = this, attrs, i, undef; - - if (typeof name !== "string") { - for (i in name) { - self.attr(i, name[i]); - } - - return self; - } - - if ((attrs = self.attributes)) { - if (value !== undef) { - // Remove attribute - if (value === null) { - if (name in attrs.map) { - delete attrs.map[name]; - - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs = attrs.splice(i, 1); - return self; - } - } - } - - return self; - } - - // Set attribute - if (name in attrs.map) { - // Set attribute - i = attrs.length; - while (i--) { - if (attrs[i].name === name) { - attrs[i].value = value; - break; - } - } - } else { - attrs.push({name: name, value: value}); - } - - attrs.map[name] = value; - - return self; - } else { - return attrs.map[name]; - } - } - }, - - /** - * Does a shallow clones the node into a new node. It will also exclude id attributes since - * there should only be one id per document. - * - * @example - * var clonedNode = node.clone(); - * - * @method clone - * @return {tinymce.html.Node} New copy of the original node. - */ - clone: function() { - var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs; - - // Clone element attributes - if ((selfAttrs = self.attributes)) { - cloneAttrs = []; - cloneAttrs.map = {}; - - for (i = 0, l = selfAttrs.length; i < l; i++) { - selfAttr = selfAttrs[i]; - - // Clone everything except id - if (selfAttr.name !== 'id') { - cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value}; - cloneAttrs.map[selfAttr.name] = selfAttr.value; - } - } - - clone.attributes = cloneAttrs; - } - - clone.value = self.value; - clone.shortEnded = self.shortEnded; - - return clone; - }, - - /** - * Wraps the node in in another node. - * - * @example - * node.wrap(wrapperNode); - * - * @method wrap - */ - wrap: function(wrapper) { - var self = this; - - self.parent.insert(wrapper, self); - wrapper.append(self); - - return self; - }, - - /** - * Unwraps the node in other words it removes the node but keeps the children. - * - * @example - * node.unwrap(); - * - * @method unwrap - */ - unwrap: function() { - var self = this, node, next; - - for (node = self.firstChild; node; ) { - next = node.next; - self.insert(node, self, true); - node = next; - } - - self.remove(); - }, - - /** - * Removes the node from it's parent. - * - * @example - * node.remove(); - * - * @method remove - * @return {tinymce.html.Node} Current node that got removed. - */ - remove: function() { - var self = this, parent = self.parent, next = self.next, prev = self.prev; - - if (parent) { - if (parent.firstChild === self) { - parent.firstChild = next; - - if (next) { - next.prev = null; - } - } else { - prev.next = next; - } - - if (parent.lastChild === self) { - parent.lastChild = prev; - - if (prev) { - prev.next = null; - } - } else { - next.prev = prev; - } - - self.parent = self.next = self.prev = null; - } - - return self; - }, - - /** - * Appends a new node as a child of the current node. - * - * @example - * node.append(someNode); - * - * @method append - * @param {tinymce.html.Node} node Node to append as a child of the current one. - * @return {tinymce.html.Node} The node that got appended. - */ - append: function(node) { - var self = this, last; - - if (node.parent) { - node.remove(); - } - - last = self.lastChild; - if (last) { - last.next = node; - node.prev = last; - self.lastChild = node; - } else { - self.lastChild = self.firstChild = node; - } - - node.parent = self; - - return node; - }, - - /** - * Inserts a node at a specific position as a child of the current node. - * - * @example - * parentNode.insert(newChildNode, oldChildNode); - * - * @method insert - * @param {tinymce.html.Node} node Node to insert as a child of the current node. - * @param {tinymce.html.Node} ref_node Reference node to set node before/after. - * @param {Boolean} before Optional state to insert the node before the reference node. - * @return {tinymce.html.Node} The node that got inserted. - */ - insert: function(node, ref_node, before) { - var parent; - - if (node.parent) { - node.remove(); - } - - parent = ref_node.parent || this; - - if (before) { - if (ref_node === parent.firstChild) { - parent.firstChild = node; - } else { - ref_node.prev.next = node; - } - - node.prev = ref_node.prev; - node.next = ref_node; - ref_node.prev = node; - } else { - if (ref_node === parent.lastChild) { - parent.lastChild = node; - } else { - ref_node.next.prev = node; - } - - node.next = ref_node.next; - node.prev = ref_node; - ref_node.next = node; - } - - node.parent = parent; - - return node; - }, - - /** - * Get all children by name. - * - * @method getAll - * @param {String} name Name of the child nodes to collect. - * @return {Array} Array with child nodes matchin the specified name. - */ - getAll: function(name) { - var self = this, node, collection = []; - - for (node = self.firstChild; node; node = walk(node, self)) { - if (node.name === name) { - collection.push(node); - } - } - - return collection; - }, - - /** - * Removes all children of the current node. - * - * @method empty - * @return {tinymce.html.Node} The current node that got cleared. - */ - empty: function() { - var self = this, nodes, i, node; - - // Remove all children - if (self.firstChild) { - nodes = []; - - // Collect the children - for (node = self.firstChild; node; node = walk(node, self)) { - nodes.push(node); - } - - // Remove the children - i = nodes.length; - while (i--) { - node = nodes[i]; - node.parent = node.firstChild = node.lastChild = node.next = node.prev = null; - } - } - - self.firstChild = self.lastChild = null; - - return self; - }, - - /** - * Returns true/false if the node is to be considered empty or not. - * - * @example - * node.isEmpty({img: true}); - * @method isEmpty - * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements. - * @return {Boolean} true/false if the node is empty or not. - */ - isEmpty: function(elements) { - var self = this, node = self.firstChild, i, name; - - if (node) { - do { - if (node.type === 1) { - // Ignore bogus elements - if (node.attributes.map['data-mce-bogus']) { - continue; - } - - // Keep empty elements likea
b
c will becomea
b
c
- * - * @example - * var parser = new tinymce.html.DomParser({validate: true}, schema); - * var rootNode = parser.parse('x
->x
- function trim(rootBlockNode) { - if (rootBlockNode) { - node = rootBlockNode.firstChild; - if (node && node.type == 3) { - node.value = node.value.replace(startWhiteSpaceRegExp, ''); - } - - node = rootBlockNode.lastChild; - if (node && node.type == 3) { - node.value = node.value.replace(endWhiteSpaceRegExp, ''); - } - } - } - - // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root - if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) { - return; - } - - while (node) { - next = node.next; - - if (node.type == 3 || (node.type == 1 && node.name !== 'p' && - !blockElements[node.name] && !node.attr('data-mce-type'))) { - if (!rootBlockNode) { - // Create a new root block element - rootBlockNode = createNode(rootBlockName, 1); - rootBlockNode.attr(settings.forced_root_block_attrs); - rootNode.insert(rootBlockNode, node); - rootBlockNode.append(node); - } else { - rootBlockNode.append(node); - } - } else { - trim(rootBlockNode); - rootBlockNode = null; - } - - node = next; - } - - trim(rootBlockNode); - } - - function createNode(name, type) { - var node = new Node(name, type), list; - - if (name in nodeFilters) { - list = matchedNodes[name]; - - if (list) { - list.push(node); - } else { - matchedNodes[name] = [node]; - } - } - - return node; - } - - function removeWhitespaceBefore(node) { - var textNode, textVal, sibling; - - for (textNode = node.prev; textNode && textNode.type === 3; ) { - textVal = textNode.value.replace(endWhiteSpaceRegExp, ''); - - if (textVal.length > 0) { - textNode.value = textVal; - textNode = textNode.prev; - } else { - sibling = textNode.prev; - textNode.remove(); - textNode = sibling; - } - } - } - - function cloneAndExcludeBlocks(input) { - var name, output = {}; - - for (name in input) { - if (name !== 'li' && name != 'p') { - output[name] = input[name]; - } - } - - return output; - } - - parser = new SaxParser({ - validate: validate, - allow_script_urls: settings.allow_script_urls, - allow_conditional_comments: settings.allow_conditional_comments, - - // Exclude P and LI from DOM parsing since it's treated better by the DOM parser - self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()), - - cdata: function(text) { - node.append(createNode('#cdata', 4)).value = text; - }, - - text: function(text, raw) { - var textNode; - - // Trim all redundant whitespace on non white space elements - if (!isInWhiteSpacePreservedElement) { - text = text.replace(allWhiteSpaceRegExp, ' '); - - if (node.lastChild && blockElements[node.lastChild.name]) { - text = text.replace(startWhiteSpaceRegExp, ''); - } - } - - // Do we need to create the node - if (text.length !== 0) { - textNode = createNode('#text', 3); - textNode.raw = !!raw; - node.append(textNode).value = text; - } - }, - - comment: function(text) { - node.append(createNode('#comment', 8)).value = text; - }, - - pi: function(name, text) { - node.append(createNode(name, 7)).value = text; - removeWhitespaceBefore(node); - }, - - doctype: function(text) { - var newNode; - - newNode = node.append(createNode('#doctype', 10)); - newNode.value = text; - removeWhitespaceBefore(node); - }, - - start: function(name, attrs, empty) { - var newNode, attrFiltersLen, elementRule, attrName, parent; - - elementRule = validate ? schema.getElementRule(name) : {}; - if (elementRule) { - newNode = createNode(elementRule.outputName || name, 1); - newNode.attributes = attrs; - newNode.shortEnded = empty; - - node.append(newNode); - - // Check if node is valid child of the parent node is the child is - // unknown we don't collect it since it's probably a custom element - parent = children[node.name]; - if (parent && children[newNode.name] && !parent[newNode.name]) { - invalidChildren.push(newNode); - } - - attrFiltersLen = attributeFilters.length; - while (attrFiltersLen--) { - attrName = attributeFilters[attrFiltersLen].name; - - if (attrName in attrs.map) { - list = matchedAttributes[attrName]; - - if (list) { - list.push(newNode); - } else { - matchedAttributes[attrName] = [newNode]; - } - } - } - - // Trim whitespace before block - if (blockElements[name]) { - removeWhitespaceBefore(newNode); - } - - // Change current node if the element wasn't empty i.e nota
- lastParent = node; - while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) { - lastParent = parent; - - if (blockElements[parent.name]) { - break; - } - - parent = parent.parent; - } - - if (lastParent === parent) { - textNode = new Node('#text', 3); - textNode.value = '\u00a0'; - node.replace(textNode); - } - } - } - }); - } - - // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included. - if (!settings.allow_html_in_named_anchor) { - self.addAttributeFilter('id,name', function(nodes) { - var i = nodes.length, sibling, prevSibling, parent, node; - - while (i--) { - node = nodes[i]; - if (node.name === 'a' && node.firstChild && !node.attr('href')) { - parent = node.parent; - - // Move children after current node - sibling = node.lastChild; - do { - prevSibling = sibling.prev; - parent.insert(sibling, node); - sibling = prevSibling; - } while (sibling); - } - } - }); - } - }; -}); - -// Included from: js/tinymce/classes/html/Writer.js - -/** - * Writer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser. - * - * @class tinymce.html.Writer - * @example - * var writer = new tinymce.html.Writer({indent: true}); - * var parser = new tinymce.html.SaxParser(writer).parse('
.
- *
- * @method start
- * @param {String} name Name of the element.
- * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
- * @param {Boolean} empty Optional empty state if the tag should end like
.
- */
- start: function(name, attrs, empty) {
- var i, l, attr, value;
-
- if (indent && indentBefore[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
-
- html.push('<', name);
-
- if (attrs) {
- for (i = 0, l = attrs.length; i < l; i++) {
- attr = attrs[i];
- html.push(' ', attr.name, '="', encode(attr.value, true), '"');
- }
- }
-
- if (!empty || htmlOutput) {
- html[html.length] = '>';
- } else {
- html[html.length] = ' />';
- }
-
- if (empty && indent && indentAfter[name] && html.length > 0) {
- value = html[html.length - 1];
-
- if (value.length > 0 && value !== '\n') {
- html.push('\n');
- }
- }
- },
-
- /**
- * Writes the a end element such as
text
')); - * @class tinymce.html.Serializer - * @version 3.4 - */ -define("tinymce/html/Serializer", [ - "tinymce/html/Writer", - "tinymce/html/Schema" -], function(Writer, Schema) { - /** - * Constructs a new Serializer instance. - * - * @constructor - * @method Serializer - * @param {Object} settings Name/value settings object. - * @param {tinymce.html.Schema} schema Schema instance to use. - */ - return function(settings, schema) { - var self = this, writer = new Writer(settings); - - settings = settings || {}; - settings.validate = "validate" in settings ? settings.validate : true; - - self.schema = schema = schema || new Schema(); - self.writer = writer; - - /** - * Serializes the specified node into a string. - * - * @example - * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('text
')); - * @method serialize - * @param {tinymce.html.Node} node Node instance to serialize. - * @return {String} String with HTML based on DOM tree. - */ - self.serialize = function(node) { - var handlers, validate; - - validate = settings.validate; - - handlers = { - // #text - 3: function(node) { - writer.text(node.value, node.raw); - }, - - // #comment - 8: function(node) { - writer.comment(node.value); - }, - - // Processing instruction - 7: function(node) { - writer.pi(node.name, node.value); - }, - - // Doctype - 10: function(node) { - writer.doctype(node.value); - }, - - // CDATA - 4: function(node) { - writer.cdata(node.value); - }, - - // Document fragment - 11: function(node) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - } - }; - - writer.reset(); - - function walk(node) { - var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule; - - if (!handler) { - name = node.name; - isEmpty = node.shortEnded; - attrs = node.attributes; - - // Sort attributes - if (validate && attrs && attrs.length > 1) { - sortedAttrs = []; - sortedAttrs.map = {}; - - elementRule = schema.getElementRule(node.name); - for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) { - attrName = elementRule.attributesOrder[i]; - - if (attrName in attrs.map) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - for (i = 0, l = attrs.length; i < l; i++) { - attrName = attrs[i].name; - - if (!(attrName in sortedAttrs.map)) { - attrValue = attrs.map[attrName]; - sortedAttrs.map[attrName] = attrValue; - sortedAttrs.push({name: attrName, value: attrValue}); - } - } - - attrs = sortedAttrs; - } - - writer.start(node.name, attrs, isEmpty); - - if (!isEmpty) { - if ((node = node.firstChild)) { - do { - walk(node); - } while ((node = node.next)); - } - - writer.end(name); - } - } else { - handler(node); - } - } - - // Serialize element and treat all non elements as fragments - if (node.type == 1 && !settings.inner) { - walk(node); - } else { - handlers[11](node); - } - - return writer.getContent(); - }; - }; -}); - -// Included from: js/tinymce/classes/dom/Serializer.js - -/** - * Serializer.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for - * more details and examples on how to use this class. - * - * @class tinymce.dom.Serializer - */ -define("tinymce/dom/Serializer", [ - "tinymce/dom/DOMUtils", - "tinymce/html/DomParser", - "tinymce/html/Entities", - "tinymce/html/Serializer", - "tinymce/html/Node", - "tinymce/html/Schema", - "tinymce/Env", - "tinymce/util/Tools" -], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) { - var each = Tools.each, trim = Tools.trim; - var DOM = DOMUtils.DOM; - - /** - * Constructs a new DOM serializer class. - * - * @constructor - * @method Serializer - * @param {Object} settings Serializer settings object. - * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from. - */ - return function(settings, editor) { - var dom, schema, htmlParser; - - if (editor) { - dom = editor.dom; - schema = editor.schema; - } - - // Default DOM and Schema if they are undefined - dom = dom || DOM; - schema = schema || new Schema(settings); - settings.entity_encoding = settings.entity_encoding || 'named'; - settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true; - - htmlParser = new DomParser(settings, schema); - - // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed - htmlParser.addAttributeFilter('src,href,style', function(nodes, name) { - var i = nodes.length, node, value, internalName = 'data-mce-' + name; - var urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef; - - while (i--) { - node = nodes[i]; - - value = node.attributes.map[internalName]; - if (value !== undef) { - // Set external name to internal value and remove internal - node.attr(name, value.length > 0 ? value : null); - node.attr(internalName, null); - } else { - // No internal attribute found then convert the value we have in the DOM - value = node.attributes.map[name]; - - if (name === "style") { - value = dom.serializeStyle(dom.parseStyle(value), node.name); - } else if (urlConverter) { - value = urlConverter.call(urlConverterScope, value, name, node.name); - } - - node.attr(name, value.length > 0 ? value : null); - } - } - }); - - // Remove internal classes mceItem<..> or mceSelected - htmlParser.addAttributeFilter('class', function(nodes) { - var i = nodes.length, node, value; - - while (i--) { - node = nodes[i]; - value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, ''); - node.attr('class', value.length > 0 ? value : null); - } - }); - - // Remove bookmark elements - htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) { - node.remove(); - } - } - }); - - // Remove expando attributes - htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - htmlParser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i].firstChild; - - if (node) { - node.value = Entities.decode(node.value); - } - } - }); - - // Force script into CDATA sections and remove the mce- prefix also add comments around styles - htmlParser.addNodeFilter('script,style', function(nodes, name) { - var i = nodes.length, node, value; - - function trim(value) { - /*jshint maxlen:255 */ - /*eslint max-len:0 */ - return value.replace(/()/g, '\n') - .replace(/^[\r\n]*|[\r\n]*$/g, '') - .replace(/^\s*(()?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, ''); - } - - while (i--) { - node = nodes[i]; - value = node.firstChild ? node.firstChild.value : ''; - - if (name === "script") { - // Remove mce- prefix from script elements and remove default text/javascript mime type (HTML5) - var type = (node.attr('type') || 'text/javascript').replace(/^mce\-/, ''); - node.attr('type', type === 'text/javascript' ? null : type); - - if (value.length > 0) { - node.firstChild.value = '// '; - } - } else { - if (value.length > 0) { - node.firstChild.value = ''; - } - } - } - }); - - // Convert comments to cdata and handle protected comments - htmlParser.addNodeFilter('#comment', function(nodes) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - - if (node.value.indexOf('[CDATA[') === 0) { - node.name = '#cdata'; - node.type = 4; - node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, ''); - } else if (node.value.indexOf('mce:protected ') === 0) { - node.name = "#text"; - node.type = 3; - node.raw = true; - node.value = unescape(node.value).substr(14); - } - } - }); - - htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) { - var i = nodes.length, node; - - while (i--) { - node = nodes[i]; - if (node.type === 7) { - node.remove(); - } else if (node.type === 1) { - if (name === "input" && !("type" in node.attributes.map)) { - node.attr('type', 'text'); - } - } - } - }); - - // Fix list elements, TODO: Replace this later - if (settings.fix_list_elements) { - htmlParser.addNodeFilter('ul,ol', function(nodes) { - var i = nodes.length, node, parentNode; - - while (i--) { - node = nodes[i]; - parentNode = node.parent; - - if (parentNode.name === 'ul' || parentNode.name === 'ol') { - if (node.prev && node.prev.name === 'li') { - node.prev.append(node); - } - } - } - }); - } - - // Remove internal data attributes - htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,data-mce-selected', function(nodes, name) { - var i = nodes.length; - - while (i--) { - nodes[i].attr(name, null); - } - }); - - // Return public methods - return { - /** - * Schema instance that was used to when the Serializer was constructed. - * - * @field {tinymce.html.Schema} schema - */ - schema: schema, - - /** - * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addNodeFilter('p,h1', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addNodeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addNodeFilter: htmlParser.addNodeFilter, - - /** - * Adds a attribute filter function to the parser used by the serializer, the parser will - * collect nodes that has the specified attributes - * and then execute the callback ones it has finished parsing the document. - * - * @example - * parser.addAttributeFilter('src,href', function(nodes, name) { - * for (var i = 0; i < nodes.length; i++) { - * console.log(nodes[i].name); - * } - * }); - * @method addAttributeFilter - * @method {String} name Comma separated list of nodes to collect. - * @param {function} callback Callback function to execute once it has collected nodes. - */ - addAttributeFilter: htmlParser.addAttributeFilter, - - /** - * Serializes the specified browser DOM node into a HTML string. - * - * @method serialize - * @param {DOMNode} node DOM node to serialize. - * @param {Object} args Arguments option that gets passed to event handlers. - */ - serialize: function(node, args) { - var self = this, impl, doc, oldDoc, htmlSerializer, content; - - // Explorer won't clone contents of script and style and the - // selected index of select elements are cleared on a clone operation. - if (Env.ie && dom.select('script,style,select,map').length > 0) { - content = node.innerHTML; - node = node.cloneNode(false); - dom.setHTML(node, content); - } else { - node = node.cloneNode(true); - } - - // Nodes needs to be attached to something in WebKit/Opera - // This fix will make DOM ranges and make Sizzle happy! - impl = node.ownerDocument.implementation; - if (impl.createHTMLDocument) { - // Create an empty HTML document - doc = impl.createHTMLDocument(""); - - // Add the element or it's children if it's a body element to the new document - each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) { - doc.body.appendChild(doc.importNode(node, true)); - }); - - // Grab first child or body element for serialization - if (node.nodeName != 'BODY') { - node = doc.body.firstChild; - } else { - node = doc.body; - } - - // set the new document in DOMUtils so createElement etc works - oldDoc = dom.doc; - dom.doc = doc; - } - - args = args || {}; - args.format = args.format || 'html'; - - // Don't wrap content if we want selected html - if (args.selection) { - args.forced_root_block = ''; - } - - // Pre process - if (!args.no_events) { - args.node = node; - self.onPreProcess(args); - } - - // Setup serializer - htmlSerializer = new Serializer(settings, schema); - - // Parse and serialize HTML - args.content = htmlSerializer.serialize( - htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args) - ); - - // Replace all BOM characters for now until we can find a better solution - if (!args.cleanup) { - args.content = args.content.replace(/\uFEFF/g, ''); - } - - // Post process - if (!args.no_events) { - self.onPostProcess(args); - } - - // Restore the old document if it was changed - if (oldDoc) { - dom.doc = oldDoc; - } - - args.node = null; - - return args.content; - }, - - /** - * Adds valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method addRules - * @param {String} rules Valid elements rules string to add to schema. - */ - addRules: function(rules) { - schema.addValidElements(rules); - }, - - /** - * Sets the valid elements rules to the serializers schema instance this enables you to specify things - * like what elements should be outputted and what attributes specific elements might have. - * Consult the Wiki for more details on this format. - * - * @method setRules - * @param {String} rules Valid elements rules string. - */ - setRules: function(rules) { - schema.setValidElements(rules); - }, - - onPreProcess: function(args) { - if (editor) { - editor.fire('PreProcess', args); - } - }, - - onPostProcess: function(args) { - if (editor) { - editor.fire('PostProcess', args); - } - } - }; - }; -}); - -// Included from: js/tinymce/classes/dom/TridentSelection.js - -/** - * TridentSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * Selection class for old explorer versions. This one fakes the - * native selection object available on modern browsers. - * - * @class tinymce.dom.TridentSelection - */ -define("tinymce/dom/TridentSelection", [], function() { - function Selection(selection) { - var self = this, dom = selection.dom, FALSE = false; - - function getPosition(rng, start) { - var checkRng, startIndex = 0, endIndex, inside, - children, child, offset, index, position = -1, parent; - - // Setup test range, collapse it and get the parent - checkRng = rng.duplicate(); - checkRng.collapse(start); - parent = checkRng.parentElement(); - - // Check if the selection is within the right document - if (parent.ownerDocument !== selection.dom.doc) { - return; - } - - // IE will report non editable elements as it's parent so look for an editable one - while (parent.contentEditable === "false") { - parent = parent.parentNode; - } - - // If parent doesn't have any children then return that we are inside the element - if (!parent.hasChildNodes()) { - return {node: parent, inside: 1}; - } - - // Setup node list and endIndex - children = parent.children; - endIndex = children.length - 1; - - // Perform a binary search for the position - while (startIndex <= endIndex) { - index = Math.floor((startIndex + endIndex) / 2); - - // Move selection to node and compare the ranges - child = children[index]; - checkRng.moveToElementText(child); - position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng); - - // Before/after or an exact match - if (position > 0) { - endIndex = index - 1; - } else if (position < 0) { - startIndex = index + 1; - } else { - return {node: child}; - } - } - - // Check if child position is before or we didn't find a position - if (position < 0) { - // No element child was found use the parent element and the offset inside that - if (!child) { - checkRng.moveToElementText(parent); - checkRng.collapse(true); - child = parent; - inside = true; - } else { - checkRng.collapse(false); - } - - // Walk character by character in text node until we hit the selected range endpoint, - // hit the end of document or parent isn't the right one - // We need to walk char by char since rng.text or rng.htmlText will trim line endings - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } else { - // Child position is after the selection endpoint - checkRng.collapse(true); - - // Walk character by character in text node until we hit the selected range endpoint, hit - // the end of document or parent isn't the right one - offset = 0; - while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) { - if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) { - break; - } - - offset++; - } - } - - return {node: child, position: position, offset: offset, inside: inside}; - } - - // Returns a W3C DOM compatible range object by using the IE Range API - function getRange() { - var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark; - - // If selection is outside the current document just return an empty range - element = ieRange.item ? ieRange.item(0) : ieRange.parentElement(); - if (element.ownerDocument != dom.doc) { - return domRange; - } - - collapsed = selection.isCollapsed(); - - // Handle control selection - if (ieRange.item) { - domRange.setStart(element.parentNode, dom.nodeIndex(element)); - domRange.setEnd(domRange.startContainer, domRange.startOffset + 1); - - return domRange; - } - - function findEndPoint(start) { - var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue; - - container = endPoint.node; - offset = endPoint.offset; - - if (endPoint.inside && !container.hasChildNodes()) { - domRange[start ? 'setStart' : 'setEnd'](container, 0); - return; - } - - if (offset === undef) { - domRange[start ? 'setStartBefore' : 'setEndAfter'](container); - return; - } - - if (endPoint.position < 0) { - sibling = endPoint.inside ? container.firstChild : container.nextSibling; - - if (!sibling) { - domRange[start ? 'setStartAfter' : 'setEndAfter'](container); - return; - } - - if (!offset) { - if (sibling.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, 0); - } else { - domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling); - } - - return; - } - - // Find the text node and offset - while (sibling) { - nodeValue = sibling.nodeValue; - textNodeOffset += nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - textNodeOffset = nodeValue.length - textNodeOffset; - break; - } - - sibling = sibling.nextSibling; - } - } else { - // Find the text node and offset - sibling = container.previousSibling; - - if (!sibling) { - return domRange[start ? 'setStartBefore' : 'setEndBefore'](container); - } - - // If there isn't any text to loop then use the first position - if (!offset) { - if (container.nodeType == 3) { - domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length); - } else { - domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling); - } - - return; - } - - while (sibling) { - textNodeOffset += sibling.nodeValue.length; - - // We are at or passed the position we where looking for - if (textNodeOffset >= offset) { - container = sibling; - textNodeOffset -= offset; - break; - } - - sibling = sibling.previousSibling; - } - } - - domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset); - } - - try { - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } catch (ex) { - // IE has a nasty bug where text nodes might throw "invalid argument" when you - // access the nodeValue or other properties of text nodes. This seems to happend when - // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it. - if (ex.number == -2147024809) { - // Get the current selection - bookmark = self.getBookmark(2); - - // Get start element - tmpRange = ieRange.duplicate(); - tmpRange.collapse(true); - element = tmpRange.parentElement(); - - // Get end element - if (!collapsed) { - tmpRange = ieRange.duplicate(); - tmpRange.collapse(false); - element2 = tmpRange.parentElement(); - element2.innerHTML = element2.innerHTML; - } - - // Remove the broken elements - element.innerHTML = element.innerHTML; - - // Restore the selection - self.moveToBookmark(bookmark); - - // Since the range has moved we need to re-get it - ieRange = selection.getRng(); - - // Find start point - findEndPoint(true); - - // Find end point if needed - if (!collapsed) { - findEndPoint(); - } - } else { - throw ex; // Throw other errors - } - } - - return domRange; - } - - this.getBookmark = function(type) { - var rng = selection.getRng(), bookmark = {}; - - function getIndexes(node) { - var parent, root, children, i, indexes = []; - - parent = node.parentNode; - root = dom.getRoot().parentNode; - - while (parent != root && parent.nodeType !== 9) { - children = parent.children; - - i = children.length; - while (i--) { - if (node === children[i]) { - indexes.push(i); - break; - } - } - - node = parent; - parent = parent.parentNode; - } - - return indexes; - } - - function getBookmarkEndPoint(start) { - var position; - - position = getPosition(rng, start); - if (position) { - return { - position: position.position, - offset: position.offset, - indexes: getIndexes(position.node), - inside: position.inside - }; - } - } - - // Non ubstructive bookmark - if (type === 2) { - // Handle text selection - if (!rng.item) { - bookmark.start = getBookmarkEndPoint(true); - - if (!selection.isCollapsed()) { - bookmark.end = getBookmarkEndPoint(); - } - } else { - bookmark.start = {ctrl: true, indexes: getIndexes(rng.item(0))}; - } - } - - return bookmark; - }; - - this.moveToBookmark = function(bookmark) { - var rng, body = dom.doc.body; - - function resolveIndexes(indexes) { - var node, i, idx, children; - - node = dom.getRoot(); - for (i = indexes.length - 1; i >= 0; i--) { - children = node.children; - idx = indexes[i]; - - if (idx <= children.length - 1) { - node = children[idx]; - } - } - - return node; - } - - function setBookmarkEndPoint(start) { - var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef, offset; - - if (endPoint) { - moveLeft = endPoint.position > 0; - - moveRng = body.createTextRange(); - moveRng.moveToElementText(resolveIndexes(endPoint.indexes)); - - offset = endPoint.offset; - if (offset !== undef) { - moveRng.collapse(endPoint.inside || moveLeft); - moveRng.moveStart('character', moveLeft ? -offset : offset); - } else { - moveRng.collapse(start); - } - - rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng); - - if (start) { - rng.collapse(true); - } - } - } - - if (bookmark.start) { - if (bookmark.start.ctrl) { - rng = body.createControlRange(); - rng.addElement(resolveIndexes(bookmark.start.indexes)); - rng.select(); - } else { - rng = body.createTextRange(); - setBookmarkEndPoint(true); - setBookmarkEndPoint(); - rng.select(); - } - } - }; - - this.addRange = function(rng) { - var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling, - doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm; - - function setEndPoint(start) { - var container, offset, marker, tmpRng, nodes; - - marker = dom.create('a'); - container = start ? startContainer : endContainer; - offset = start ? startOffset : endOffset; - tmpRng = ieRng.duplicate(); - - if (container == doc || container == doc.documentElement) { - container = body; - offset = 0; - } - - if (container.nodeType == 3) { - container.parentNode.insertBefore(marker, container); - tmpRng.moveToElementText(marker); - tmpRng.moveStart('character', offset); - dom.remove(marker); - ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng); - } else { - nodes = container.childNodes; - - if (nodes.length) { - if (offset >= nodes.length) { - dom.insertAfter(marker, nodes[nodes.length - 1]); - } else { - container.insertBefore(marker, nodes[offset]); - } - - tmpRng.moveToElementText(marker); - } else if (container.canHaveHTML) { - // Empty node selection for example|
would become this:|
- sibling = startContainer.previousSibling; - if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) { - sibling.innerHTML = ''; - } else { - sibling = null; - } - - startContainer.innerHTML = ''; - ieRng.moveToElementText(startContainer.lastChild); - ieRng.select(); - dom.doc.selection.clear(); - startContainer.innerHTML = ''; - - if (sibling) { - sibling.innerHTML = ''; - } - return; - } else { - startOffset = dom.nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - } - - if (startOffset == endOffset - 1) { - try { - ctrlElm = startContainer.childNodes[startOffset]; - ctrlRng = body.createControlRange(); - ctrlRng.addElement(ctrlElm); - ctrlRng.select(); - - // Check if the range produced is on the correct element and is a control range - // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398 - nativeRng = selection.getRng(); - if (nativeRng.item && ctrlElm === nativeRng.item(0)) { - return; - } - } catch (ex) { - // Ignore - } - } - } - - // Set start/end point of selection - setEndPoint(true); - setEndPoint(); - - // Select the new range and scroll it into view - ieRng.select(); - }; - - // Expose range method - this.getRangeAt = getRange; - } - - return Selection; -}); - -// Included from: js/tinymce/classes/util/VK.js - -/** - * VK.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This file exposes a set of the common KeyCodes for use. Please grow it as needed. - */ -define("tinymce/util/VK", [ - "tinymce/Env" -], function(Env) { - return { - BACKSPACE: 8, - DELETE: 46, - DOWN: 40, - ENTER: 13, - LEFT: 37, - RIGHT: 39, - SPACEBAR: 32, - TAB: 9, - UP: 38, - - modifierPressed: function(e) { - return e.shiftKey || e.ctrlKey || e.altKey; - }, - - metaKeyPressed: function(e) { - // Check if ctrl or meta key is pressed also check if alt is false for Polish users - return (Env.mac ? e.metaKey : e.ctrlKey) && !e.altKey; - } - }; -}); - -// Included from: js/tinymce/classes/dom/ControlSelection.js - -/** - * ControlSelection.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles control selection of elements. Controls are elements - * that can be resized and needs to be selected as a whole. It adds custom resize handles - * to all browser engines that support properly disabling the built in resize logic. - * - * @class tinymce.dom.ControlSelection - */ -define("tinymce/dom/ControlSelection", [ - "tinymce/util/VK", - "tinymce/util/Tools", - "tinymce/Env" -], function(VK, Tools, Env) { - return function(selection, editor) { - var dom = editor.dom, each = Tools.each; - var selectedElm, selectedElmGhost, resizeHandles, selectedHandle, lastMouseDownEvent; - var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted; - var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie && Env.ie < 11; - - // Details about each resize handle how to scale etc - resizeHandles = { - // Name: x multiplier, y multiplier, delta size x, delta size y - n: [0.5, 0, 0, -1], - e: [1, 0.5, 1, 0], - s: [0.5, 1, 0, 1], - w: [0, 0.5, -1, 0], - nw: [0, 0, -1, -1], - ne: [1, 0, 1, -1], - se: [1, 1, 1, 1], - sw: [0, 1, -1, 1] - }; - - // Add CSS for resize handles, cloned element and selected - var rootClass = '.mce-content-body'; - editor.contentStyles.push( - rootClass + ' div.mce-resizehandle {' + - 'position: absolute;' + - 'border: 1px solid black;' + - 'background: #FFF;' + - 'width: 5px;' + - 'height: 5px;' + - 'z-index: 10000' + - '}' + - rootClass + ' .mce-resizehandle:hover {' + - 'background: #000' + - '}' + - rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' + - 'outline: 1px solid black;' + - 'resize: none' + // Have been talks about implementing this in browsers - '}' + - rootClass + ' .mce-clonedresizable {' + - 'position: absolute;' + - (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing - 'opacity: .5;' + - 'filter: alpha(opacity=50);' + - 'z-index: 10000' + - '}' - ); - - function isResizable(elm) { - var selector = editor.settings.object_resizing; - - if (selector === false || Env.iOS) { - return false; - } - - if (typeof selector != 'string') { - selector = 'table,img,div'; - } - - if (elm.getAttribute('data-mce-resize') === 'false') { - return false; - } - - return editor.dom.is(elm, selector); - } - - function resizeGhostElement(e) { - var deltaX, deltaY; - - // Calc new width/height - deltaX = e.screenX - startX; - deltaY = e.screenY - startY; - - // Calc new size - width = deltaX * selectedHandle[2] + startW; - height = deltaY * selectedHandle[3] + startH; - - // Never scale down lower than 5 pixels - width = width < 5 ? 5 : width; - height = height < 5 ? 5 : height; - - // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image - if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) { - width = Math.round(height / ratio); - height = Math.round(width * ratio); - } - - // Update ghost size - dom.setStyles(selectedElmGhost, { - width: width, - height: height - }); - - // Update ghost X position if needed - if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) { - dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width)); - } - - // Update ghost Y position if needed - if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) { - dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height)); - } - - if (!resizeStarted) { - editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH}); - resizeStarted = true; - } - } - - function endGhostResize() { - resizeStarted = false; - - function setSizeProp(name, value) { - if (value) { - // Resize by using style or attribute - if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) { - dom.setStyle(selectedElm, name, value); - } else { - dom.setAttrib(selectedElm, name, value); - } - } - } - - // Set width/height properties - setSizeProp('width', width); - setSizeProp('height', height); - - dom.unbind(editableDoc, 'mousemove', resizeGhostElement); - dom.unbind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.unbind(rootDocument, 'mousemove', resizeGhostElement); - dom.unbind(rootDocument, 'mouseup', endGhostResize); - } - - // Remove ghost and update resize handle positions - dom.remove(selectedElmGhost); - - if (!isIE || selectedElm.nodeName == "TABLE") { - showResizeRect(selectedElm); - } - - editor.fire('ObjectResized', {target: selectedElm, width: width, height: height}); - editor.nodeChanged(); - } - - function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) { - var position, targetWidth, targetHeight, e, rect, offsetParent = editor.getBody(); - - unbindResizeHandleEvents(); - - // Get position and size of target - position = dom.getPos(targetElm, offsetParent); - selectedElmX = position.x; - selectedElmY = position.y; - rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption - targetWidth = rect.width || (rect.right - rect.left); - targetHeight = rect.height || (rect.bottom - rect.top); - - // Reset width/height if user selects a new image/table - if (selectedElm != targetElm) { - detachResizeStartListener(); - selectedElm = targetElm; - width = height = 0; - } - - // Makes it possible to disable resizing - e = editor.fire('ObjectSelected', {target: targetElm}); - - if (isResizable(targetElm) && !e.isDefaultPrevented()) { - each(resizeHandles, function(handle, name) { - var handleElm, handlerContainerElm; - - function startDrag(e) { - startX = e.screenX; - startY = e.screenY; - startW = selectedElm.clientWidth; - startH = selectedElm.clientHeight; - ratio = startH / startW; - selectedHandle = handle; - - selectedElmGhost = selectedElm.cloneNode(true); - dom.addClass(selectedElmGhost, 'mce-clonedresizable'); - selectedElmGhost.contentEditable = false; // Hides IE move layer cursor - selectedElmGhost.unSelectabe = true; - dom.setStyles(selectedElmGhost, { - left: selectedElmX, - top: selectedElmY, - margin: 0 - }); - - selectedElmGhost.removeAttribute('data-mce-selected'); - editor.getBody().appendChild(selectedElmGhost); - - dom.bind(editableDoc, 'mousemove', resizeGhostElement); - dom.bind(editableDoc, 'mouseup', endGhostResize); - - if (rootDocument != editableDoc) { - dom.bind(rootDocument, 'mousemove', resizeGhostElement); - dom.bind(rootDocument, 'mouseup', endGhostResize); - } - } - - if (mouseDownHandleName) { - // Drag started by IE native resizestart - if (name == mouseDownHandleName) { - startDrag(mouseDownEvent); - } - - return; - } - - // Get existing or render resize handle - handleElm = dom.get('mceResizeHandle' + name); - if (!handleElm) { - handlerContainerElm = editor.getBody(); - - handleElm = dom.add(handlerContainerElm, 'div', { - id: 'mceResizeHandle' + name, - 'data-mce-bogus': true, - 'class': 'mce-resizehandle', - unselectable: true, - style: 'cursor:' + name + '-resize; margin:0; padding:0' - }); - - // Hides IE move layer cursor - // If we set it on Chrome we get this wounderful bug: #6725 - if (Env.ie) { - handleElm.contentEditable = false; - } - } else { - dom.show(handleElm); - } - - if (!handle.elm) { - dom.bind(handleElm, 'mousedown', function(e) { - e.stopImmediatePropagation(); - e.preventDefault(); - startDrag(e); - }); - - handle.elm = handleElm; - } - - /* - var halfHandleW = handleElm.offsetWidth / 2; - var halfHandleH = handleElm.offsetHeight / 2; - - // Position element - dom.setStyles(handleElm, { - left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)), - top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH)) - }); - */ - - // Position element - dom.setStyles(handleElm, { - left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2), - top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2) - }); - }); - } else { - hideResizeRect(); - } - - selectedElm.setAttribute('data-mce-selected', '1'); - } - - function hideResizeRect() { - var name, handleElm; - - unbindResizeHandleEvents(); - - if (selectedElm) { - selectedElm.removeAttribute('data-mce-selected'); - } - - for (name in resizeHandles) { - handleElm = dom.get('mceResizeHandle' + name); - if (handleElm) { - dom.unbind(handleElm); - dom.remove(handleElm); - } - } - } - - function updateResizeRect(e) { - var controlElm; - - function isChildOrEqual(node, parent) { - if (node) { - do { - if (node === parent) { - return true; - } - } while ((node = node.parentNode)); - } - } - - // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v - each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) { - img.removeAttribute('data-mce-selected'); - }); - - controlElm = e.type == 'mousedown' ? e.target : selection.getNode(); - controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr'); - - if (isChildOrEqual(controlElm, editor.getBody())) { - disableGeckoResize(); - - if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) { - if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) { - showResizeRect(controlElm); - return; - } - } - } - - hideResizeRect(); - } - - function attachEvent(elm, name, func) { - if (elm && elm.attachEvent) { - elm.attachEvent('on' + name, func); - } - } - - function detachEvent(elm, name, func) { - if (elm && elm.detachEvent) { - elm.detachEvent('on' + name, func); - } - } - - function resizeNativeStart(e) { - var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY; - - pos = target.getBoundingClientRect(); - relativeX = lastMouseDownEvent.clientX - pos.left; - relativeY = lastMouseDownEvent.clientY - pos.top; - - // Figure out what corner we are draging on - for (name in resizeHandles) { - corner = resizeHandles[name]; - - cornerX = target.offsetWidth * corner[0]; - cornerY = target.offsetHeight * corner[1]; - - if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) { - selectedHandle = corner; - break; - } - } - - // Remove native selection and let the magic begin - resizeStarted = true; - editor.getDoc().selection.empty(); - showResizeRect(target, name, lastMouseDownEvent); - } - - function nativeControlSelect(e) { - var target = e.srcElement; - - if (target != selectedElm) { - detachResizeStartListener(); - - if (target.id.indexOf('mceResizeHandle') === 0) { - e.returnValue = false; - return; - } - - if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') { - hideResizeRect(); - selectedElm = target; - attachEvent(target, 'resizestart', resizeNativeStart); - } - } - } - - function detachResizeStartListener() { - detachEvent(selectedElm, 'resizestart', resizeNativeStart); - } - - function unbindResizeHandleEvents() { - for (var name in resizeHandles) { - var handle = resizeHandles[name]; - - if (handle.elm) { - dom.unbind(handle.elm); - delete handle.elm; - } - } - } - - function disableGeckoResize() { - try { - // Disable object resizing on Gecko - editor.getDoc().execCommand('enableObjectResizing', false, false); - } catch (ex) { - // Ignore - } - } - - function controlSelect(elm) { - var ctrlRng; - - if (!isIE) { - return; - } - - ctrlRng = editableDoc.body.createControlRange(); - - try { - ctrlRng.addElement(elm); - ctrlRng.select(); - return true; - } catch (ex) { - // Ignore since the element can't be control selected for example a P tag - } - } - - editor.on('init', function() { - if (isIE) { - // Hide the resize rect on resize and reselect the image - editor.on('ObjectResized', function(e) { - if (e.target.nodeName != 'TABLE') { - hideResizeRect(); - controlSelect(e.target); - } - }); - - attachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - - editor.on('mousedown', function(e) { - lastMouseDownEvent = e; - }); - } else { - disableGeckoResize(); - - if (Env.ie >= 11) { - // TODO: Drag/drop doesn't work - editor.on('mouseup', function(e) { - var nodeName = e.target.nodeName; - - if (/^(TABLE|IMG|HR)$/.test(nodeName)) { - editor.selection.select(e.target, nodeName == 'TABLE'); - editor.nodeChanged(); - } - }); - - editor.dom.bind(editor.getBody(), 'mscontrolselect', function(e) { - if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) { - e.preventDefault(); - - // This moves the selection from being a control selection to a text like selection like in WebKit #6753 - // TODO: Fix this the day IE works like other browsers without this nasty native ugly control selections. - if (e.target.tagName == 'IMG') { - window.setTimeout(function() { - editor.selection.select(e.target); - }, 0); - } - } - }); - } - } - - editor.on('nodechange mousedown mouseup ResizeEditor', updateResizeRect); - - // Update resize rect while typing in a table - editor.on('keydown keyup', function(e) { - if (selectedElm && selectedElm.nodeName == "TABLE") { - updateResizeRect(e); - } - }); - - // Hide rect on focusout since it would float on top of windows otherwise - //editor.on('focusout', hideResizeRect); - }); - - editor.on('remove', unbindResizeHandleEvents); - - function destroy() { - selectedElm = selectedElmGhost = null; - - if (isIE) { - detachResizeStartListener(); - detachEvent(editor.getBody(), 'controlselect', nativeControlSelect); - } - } - - return { - isResizable: isResizable, - showResizeRect: showResizeRect, - hideResizeRect: hideResizeRect, - updateResizeRect: updateResizeRect, - controlSelect: controlSelect, - destroy: destroy - }; - }; -}); - -// Included from: js/tinymce/classes/dom/RangeUtils.js - -/** - * Range.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * RangeUtils - * - * @class tinymce.dom.RangeUtils - * @private - */ -define("tinymce/dom/RangeUtils", [ - "tinymce/util/Tools", - "tinymce/dom/TreeWalker" -], function(Tools, TreeWalker) { - var each = Tools.each; - - function RangeUtils(dom) { - /** - * Walks the specified range like object and executes the callback for each sibling collection it finds. - * - * @method walk - * @param {Object} rng Range like object. - * @param {function} callback Callback function to execute for each sibling collection. - */ - this.walk = function(rng, callback) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset, - ancestor, startPoint, - endPoint, node, parent, siblings, nodes; - - // Handle table cell selection the table plugin enables - // you to fake select table cells and perform formatting actions on them - nodes = dom.select('td.mce-item-selected,th.mce-item-selected'); - if (nodes.length > 0) { - each(nodes, function(node) { - callback([node]); - }); - - return; - } - - /** - * Excludes start/end text node if they are out side the range - * - * @private - * @param {Array} nodes Nodes to exclude items from. - * @return {Array} Array with nodes excluding the start/end container if needed. - */ - function exclude(nodes) { - var node; - - // First node is excluded - node = nodes[0]; - if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) { - nodes.splice(0, 1); - } - - // Last node is excluded - node = nodes[nodes.length - 1]; - if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) { - nodes.splice(nodes.length - 1, 1); - } - - return nodes; - } - - /** - * Collects siblings - * - * @private - * @param {Node} node Node to collect siblings from. - * @param {String} name Name of the sibling to check for. - * @return {Array} Array of collected siblings. - */ - function collectSiblings(node, name, end_node) { - var siblings = []; - - for (; node && node != end_node; node = node[name]) { - siblings.push(node); - } - - return siblings; - } - - /** - * Find an end point this is the node just before the common ancestor root. - * - * @private - * @param {Node} node Node to start at. - * @param {Node} root Root/ancestor element to stop just before. - * @return {Node} Node just before the root element. - */ - function findEndPoint(node, root) { - do { - if (node.parentNode == root) { - return node; - } - - node = node.parentNode; - } while(node); - } - - function walkBoundary(start_node, end_node, next) { - var siblingName = next ? 'nextSibling' : 'previousSibling'; - - for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) { - parent = node.parentNode; - siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName); - - if (siblings.length) { - if (!next) { - siblings.reverse(); - } - - callback(exclude(siblings)); - } - } - } - - // If index based start position then resolve it - if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) { - startContainer = startContainer.childNodes[startOffset]; - } - - // If index based end position then resolve it - if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) { - endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)]; - } - - // Same container - if (startContainer == endContainer) { - return callback(exclude([startContainer])); - } - - // Find common ancestor and end points - ancestor = dom.findCommonAncestor(startContainer, endContainer); - - // Process left side - for (node = startContainer; node; node = node.parentNode) { - if (node === endContainer) { - return walkBoundary(startContainer, ancestor, true); - } - - if (node === ancestor) { - break; - } - } - - // Process right side - for (node = endContainer; node; node = node.parentNode) { - if (node === startContainer) { - return walkBoundary(endContainer, ancestor); - } - - if (node === ancestor) { - break; - } - } - - // Find start/end point - startPoint = findEndPoint(startContainer, ancestor) || startContainer; - endPoint = findEndPoint(endContainer, ancestor) || endContainer; - - // Walk left leaf - walkBoundary(startContainer, startPoint, true); - - // Walk the middle from start to end point - siblings = collectSiblings( - startPoint == startContainer ? startPoint : startPoint.nextSibling, - 'nextSibling', - endPoint == endContainer ? endPoint.nextSibling : endPoint - ); - - if (siblings.length) { - callback(exclude(siblings)); - } - - // Walk right leaf - walkBoundary(endContainer, endPoint); - }; - - /** - * Splits the specified range at it's start/end points. - * - * @private - * @param {Range/RangeObject} rng Range to split. - * @return {Object} Range position object. - */ - this.split = function(rng) { - var startContainer = rng.startContainer, - startOffset = rng.startOffset, - endContainer = rng.endContainer, - endOffset = rng.endOffset; - - function splitText(node, offset) { - return node.splitText(offset); - } - - // Handle single text node - if (startContainer == endContainer && startContainer.nodeType == 3) { - if (startOffset > 0 && startOffset < startContainer.nodeValue.length) { - endContainer = splitText(startContainer, startOffset); - startContainer = endContainer.previousSibling; - - if (endOffset > startOffset) { - endOffset = endOffset - startOffset; - startContainer = endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - startOffset = 0; - } else { - endOffset = 0; - } - } - } else { - // Split startContainer text node if needed - if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) { - startContainer = splitText(startContainer, startOffset); - startOffset = 0; - } - - // Split endContainer text node if needed - if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) { - endContainer = splitText(endContainer, endOffset).previousSibling; - endOffset = endContainer.nodeValue.length; - } - } - - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - }; - - /** - * Normalizes the specified range by finding the closest best suitable caret location. - * - * @private - * @param {Range} rng Range to normalize. - * @return {Boolean} True/false if the specified range was normalized or not. - */ - this.normalize = function(rng) { - var normalized, collapsed; - - function normalizeEndPoint(start) { - var container, offset, walker, body = dom.getRoot(), node, nonEmptyElementsMap, nodeName; - var directionLeft, isAfterNode; - - function hasBrBeforeAfter(node, left) { - var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body); - - while ((node = walker[left ? 'prev' : 'next']())) { - if (node.nodeName === "BR") { - return true; - } - } - } - - function isPrevNode(node, name) { - return node.previousSibling && node.previousSibling.nodeName == name; - } - - // Walks the dom left/right to find a suitable text node to move the endpoint into - // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG - function findTextNodeRelative(left, startNode) { - var walker, lastInlineElement, parentBlockContainer; - - startNode = startNode || container; - parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body; - - // Lean left before the BR element if it's the only BR within a block element. Gecko bug: #6680 - // This:
|
|
x|
]
- rng.moveToElementText(rng2.parentElement()); - if (rng.compareEndPoints('StartToEnd', rng2) === 0) { - rng2.move('character', -1); - } - - rng2.pasteHTML('' + chr + ''); - } - } catch (ex) { - // IE might throw unspecified error so lets ignore it - return null; - } - } else { - // Control selection - element = rng.item(0); - name = element.nodeName; - - return {name: name, index: findIndex(name, element)}; - } - } else { - element = self.getNode(); - name = element.nodeName; - if (name == 'IMG') { - return {name: name, index: findIndex(name, element)}; - } - - // W3C method - rng2 = normalizeTableCellSelection(rng.cloneRange()); - - // Insert end marker - if (!collapsed) { - rng2.collapse(false); - rng2.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_end', style: styles}, chr)); - } - - rng = normalizeTableCellSelection(rng); - rng.collapse(true); - rng.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_start', style: styles}, chr)); - } - - self.moveToBookmark({id: id, keep: 1}); - - return {id: id}; - }, - - /** - * Restores the selection to the specified bookmark. - * - * @method moveToBookmark - * @param {Object} bookmark Bookmark to restore selection from. - * @return {Boolean} true/false if it was successful or not. - * @example - * // Stores a bookmark of the current selection - * var bm = tinymce.activeEditor.selection.getBookmark(); - * - * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content'); - * - * // Restore the selection bookmark - * tinymce.activeEditor.selection.moveToBookmark(bm); - */ - moveToBookmark: function(bookmark) { - var self = this, dom = self.dom, rng, root, startContainer, endContainer, startOffset, endOffset; - - function setEndPoint(start) { - var point = bookmark[start ? 'start' : 'end'], i, node, offset, children; - - if (point) { - offset = point[0]; - - // Find container node - for (node = root, i = point.length - 1; i >= 1; i--) { - children = node.childNodes; - - if (point[i] > children.length - 1) { - return; - } - - node = children[point[i]]; - } - - // Move text offset to best suitable location - if (node.nodeType === 3) { - offset = Math.min(point[0], node.nodeValue.length); - } - - // Move element offset to best suitable location - if (node.nodeType === 1) { - offset = Math.min(point[0], node.childNodes.length); - } - - // Set offset within container node - if (start) { - rng.setStart(node, offset); - } else { - rng.setEnd(node, offset); - } - } - - return true; - } - - function restoreEndPoint(suffix) { - var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep; - - if (marker) { - node = marker.parentNode; - - if (suffix == 'start') { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - startContainer = endContainer = node; - startOffset = endOffset = idx; - } else { - if (!keep) { - idx = dom.nodeIndex(marker); - } else { - node = marker.firstChild; - idx = 1; - } - - endContainer = node; - endOffset = idx; - } - - if (!keep) { - prev = marker.previousSibling; - next = marker.nextSibling; - - // Remove all marker text nodes - each(grep(marker.childNodes), function(node) { - if (node.nodeType == 3) { - node.nodeValue = node.nodeValue.replace(/\uFEFF/g, ''); - } - }); - - // Remove marker but keep children if for example contents where inserted into the marker - // Also remove duplicated instances of the marker for example by a - // split operation or by WebKit auto split on paste feature - while ((marker = dom.get(bookmark.id + '_' + suffix))) { - dom.remove(marker, 1); - } - - // If siblings are text nodes then merge them unless it's Opera since it some how removes the node - // and we are sniffing since adding a lot of detection code for a browser with 3% of the market - // isn't worth the effort. Sorry, Opera but it's just a fact - if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !isOpera) { - idx = prev.nodeValue.length; - prev.appendData(next.nodeValue); - dom.remove(next); - - if (suffix == 'start') { - startContainer = endContainer = prev; - startOffset = endOffset = idx; - } else { - endContainer = prev; - endOffset = idx; - } - } - } - } - } - - function addBogus(node) { - // Adds a bogus BR element for empty block elements - if (dom.isBlock(node) && !node.innerHTML && !isIE) { - node.innerHTML = '*texttext*
! - // This will reduce the number of wrapper elements that needs to be created - // Move start point up the tree - if (format[0].inline || format[0].block_expand) { - if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) { - startContainer = findParentContainer(true); - } - - if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) { - endContainer = findParentContainer(); - } - } - - // Expand start/end container to matching selector - if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) { - // Find new startContainer/endContainer if there is better one - startContainer = findSelectorEndPoint(startContainer, 'previousSibling'); - endContainer = findSelectorEndPoint(endContainer, 'nextSibling'); - } - - // Expand start/end container to matching block element or text node - if (format[0].block || format[0].selector) { - // Find new startContainer/endContainer if there is better one - startContainer = findBlockEndPoint(startContainer, 'previousSibling'); - endContainer = findBlockEndPoint(endContainer, 'nextSibling'); - - // Non block element then try to expand up the leaf - if (format[0].block) { - if (!isBlock(startContainer)) { - startContainer = findParentContainer(true); - } - - if (!isBlock(endContainer)) { - endContainer = findParentContainer(); - } - } - } - - // Setup index for startContainer - if (startContainer.nodeType == 1) { - startOffset = nodeIndex(startContainer); - startContainer = startContainer.parentNode; - } - - // Setup index for endContainer - if (endContainer.nodeType == 1) { - endOffset = nodeIndex(endContainer) + 1; - endContainer = endContainer.parentNode; - } - - // Return new range like object - return { - startContainer: startContainer, - startOffset: startOffset, - endContainer: endContainer, - endOffset: endOffset - }; - } - - /** - * Removes the specified format for the specified node. It will also remove the node if it doesn't have - * any attributes if the format specifies it to do so. - * - * @private - * @param {Object} format Format object with items to remove from node. - * @param {Object} vars Name/value object with variables to apply to format. - * @param {Node} node Node to remove the format styles on. - * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node. - * @return {Boolean} True/false if the node was removed or not. - */ - function removeFormat(format, vars, node, compare_node) { - var i, attrs, stylesModified; - - // Check if node matches format - if (!matchName(node, format)) { - return FALSE; - } - - // Should we compare with format attribs and styles - if (format.remove != 'all') { - // Remove styles - each(format.styles, function(value, name) { - value = normalizeStyleValue(replaceVars(value, vars), name); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(getStyle(compare_node, name), value)) { - dom.setStyle(node, name, ''); - } - - stylesModified = 1; - }); - - // Remove style attribute if it's empty - if (stylesModified && dom.getAttrib(node, 'style') === '') { - node.removeAttribute('style'); - node.removeAttribute('data-mce-style'); - } - - // Remove attributes - each(format.attributes, function(value, name) { - var valueOut; - - value = replaceVars(value, vars); - - // Indexed array - if (typeof(name) === 'number') { - name = value; - compare_node = 0; - } - - if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) { - // Keep internal classes - if (name == 'class') { - value = dom.getAttrib(node, name); - if (value) { - // Build new class value where everything is removed except the internal prefixed classes - valueOut = ''; - each(value.split(/\s+/), function(cls) { - if (/mce\w+/.test(cls)) { - valueOut += (valueOut ? ' ' : '') + cls; - } - }); - - // We got some internal classes left - if (valueOut) { - dom.setAttrib(node, name, valueOut); - return; - } - } - } - - // IE6 has a bug where the attribute doesn't get removed correctly - if (name == "class") { - node.removeAttribute('className'); - } - - // Remove mce prefixed attributes - if (MCE_ATTR_RE.test(name)) { - node.removeAttribute('data-mce-' + name); - } - - node.removeAttribute(name); - } - }); - - // Remove classes - each(format.classes, function(value) { - value = replaceVars(value, vars); - - if (!compare_node || dom.hasClass(compare_node, value)) { - dom.removeClass(node, value); - } - }); - - // Check for non internal attributes - attrs = dom.getAttribs(node); - for (i = 0; i < attrs.length; i++) { - if (attrs[i].nodeName.indexOf('_') !== 0) { - return FALSE; - } - } - } - - // Remove the inline child if it's empty for example or - if (format.remove != 'none') { - removeNode(node, format); - return TRUE; - } - } - - /** - * Removes the node and wrap it's children in paragraphs before doing so or - * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled. - * - * If the div in the node below gets removed: - * text|
- formatNode.parentNode.replaceChild(caretContainer, formatNode); - } else { - // Insert caret container after the formated node - dom.insertAfter(caretContainer, formatNode); - } - - // Move selection to text node - selection.setCursorLocation(node, 1); - - // If the formatNode is empty, we can remove it safely. - if (dom.isEmpty(formatNode)) { - dom.remove(formatNode); - } - } - } - - // Checks if the parent caret container node isn't empty if that is the case it - // will remove the bogus state on all children that isn't empty - function unmarkBogusCaretParents() { - var caretContainer; - - caretContainer = getParentCaretContainer(selection.getStart()); - if (caretContainer && !dom.isEmpty(caretContainer)) { - walk(caretContainer, function(node) { - if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) { - dom.setAttrib(node, 'data-mce-bogus', null); - } - }, 'childNodes'); - } - } - - // Only bind the caret events once - if (!ed._hasCaretEvents) { - // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements - markCaretContainersBogus = function() { - var nodes = [], i; - - if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) { - // Mark children - i = nodes.length; - while (i--) { - dom.setAttrib(nodes[i], 'data-mce-bogus', '1'); - } - } - }; - - disableCaretContainer = function(e) { - var keyCode = e.keyCode; - - removeCaretContainer(); - - // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys - if (keyCode == 8 || keyCode == 37 || keyCode == 39) { - removeCaretContainer(getParentCaretContainer(selection.getStart())); - } - - unmarkBogusCaretParents(); - }; - - // Remove bogus state if they got filled by contents using editor.selection.setContent - ed.on('SetContent', function(e) { - if (e.selection) { - unmarkBogusCaretParents(); - } - }); - ed._hasCaretEvents = true; - } - - // Do apply or remove caret format - if (type == "apply") { - applyCaretFormat(); - } else { - removeCaretFormat(); - } - } - - /** - * Moves the start to the first suitable text node. - */ - function moveStart(rng) { - var container = rng.startContainer, - offset = rng.startOffset, isAtEndOfText, - walker, node, nodes, tmpNode; - - // Convert text node into index if possible - if (container.nodeType == 3 && offset >= container.nodeValue.length) { - // Get the parent container location and walk from there - offset = nodeIndex(container); - container = container.parentNode; - isAtEndOfText = true; - } - - // Move startContainer/startOffset in to a suitable node - if (container.nodeType == 1) { - nodes = container.childNodes; - container = nodes[Math.min(offset, nodes.length - 1)]; - walker = new TreeWalker(container, dom.getParent(container, dom.isBlock)); - - // If offset is at end of the parent node walk to the next one - if (offset > nodes.length - 1 || isAtEndOfText) { - walker.next(); - } - - for (node = walker.current(); node; node = walker.next()) { - if (node.nodeType == 3 && !isWhiteSpaceNode(node)) { - // IE has a "neat" feature where it moves the start node into the closest element - // we can avoid this by inserting an element before it and then remove it after we set the selection - tmpNode = dom.create('a', null, INVISIBLE_CHAR); - node.parentNode.insertBefore(tmpNode, node); - - // Set selection and remove tmpNode - rng.setStart(node, 0); - selection.setRng(rng); - dom.remove(tmpNode); - - return; - } - } - } - } - }; -}); - -// Included from: js/tinymce/classes/UndoManager.js - -/** - * UndoManager.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. - * - * @class tinymce.UndoManager - */ -define("tinymce/UndoManager", [ - "tinymce/Env", - "tinymce/util/Tools" -], function(Env, Tools) { - var trim = Tools.trim, trimContentRegExp; - - trimContentRegExp = new RegExp([ - ']+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers - 'x
becomes this:x
- function trimInlineElementsOnLeftSideOfBlock(block) { - var node = block, firstChilds = [], i; - - // Find inner most first child ex:*
- while ((node = node.firstChild)) { - if (dom.isBlock(node)) { - return; - } - - if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) { - firstChilds.push(node); - } - } - - i = firstChilds.length; - while (i--) { - node = firstChilds[i]; - if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) { - dom.remove(node); - } else { - // Remove see #5381 - if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') { - dom.remove(node); - } - } - } - } - - // Moves the caret to a suitable position within the root for example in the first non - // pure whitespace text node or before an image - function moveToCaretPosition(root) { - var walker, node, rng, lastNode = root, tempElm; - - function firstNonWhiteSpaceNodeSibling(node) { - while (node) { - if (node.nodeType == 1 || (node.nodeType == 3 && node.data && /[\r\n\s]/.test(node.data))) { - return node; - } - - node = node.nextSibling; - } - } - - // Old IE versions doesn't properly render blocks with br elements in them - // For exampletext|
text|text2
|
- rng = selection.getRng(); - var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); - var body = editor.getBody(); - if (caretElement === body && selection.isCollapsed()) { - if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { - rng = dom.createRng(); - rng.setStart(body.firstChild, 0); - rng.setEnd(body.firstChild, 0); - selection.setRng(rng); - } - } - - // Insert node maker where we will insert the new HTML and get it's parent - if (!selection.isCollapsed()) { - editor.getDoc().execCommand('Delete', false, null); - } - - parentNode = selection.getNode(); - - // Parse the fragment within the context of the parent node - var parserArgs = {context: parentNode.nodeName.toLowerCase()}; - fragment = parser.parse(value, parserArgs); - - // Move the caret to a more suitable location - node = fragment.lastChild; - if (node.attr('id') == 'mce_marker') { - marker = node; - - for (node = node.prev; node; node = node.walk(true)) { - if (node.type == 3 || !dom.isBlock(node.name)) { - node.parent.insert(marker, node, node.name === 'br'); - break; - } - } - } - - // If parser says valid we can insert the contents into that parent - if (!parserArgs.invalid) { - value = serializer.serialize(fragment); - - // Check if parent is empty or only has one BR element then set the innerHTML of that parent - node = parentNode.firstChild; - node2 = parentNode.lastChild; - if (!node || (node === node2 && node.nodeName === 'BR')) { - dom.setHTML(parentNode, value); - } else { - selection.setContent(value); - } - } else { - // If the fragment was invalid within that context then we need - // to parse and process the parent it's inserted into - - // Insert bookmark node and get the parent - selection.setContent(bookmarkHtml); - parentNode = selection.getNode(); - rootNode = editor.getBody(); - - // Opera will return the document node when selection is in root - if (parentNode.nodeType == 9) { - parentNode = node = rootNode; - } else { - node = parentNode; - } - - // Find the ancestor just before the root element - while (node !== rootNode) { - parentNode = node; - node = node.parentNode; - } - - // Get the outer/inner HTML depending on if we are in the root and parser and serialize that - value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); - value = serializer.serialize( - parser.parse( - // Need to replace by using a function since $ in the contents would otherwise be a problem - value.replace(//i, function() { - return serializer.serialize(fragment); - }) - ) - ); - - // Set the inner/outer HTML depending on if we are in the root or not - if (parentNode == rootNode) { - dom.setHTML(rootNode, value); - } else { - dom.setOuterHTML(parentNode, value); - } - } - - marker = dom.get('mce_marker'); - selection.scrollIntoView(marker); - - // Move selection before marker and remove it - rng = dom.createRng(); - - // If previous sibling is a text node set the selection to the end of that node - node = marker.previousSibling; - if (node && node.nodeType == 3) { - rng.setStart(node, node.nodeValue.length); - - // TODO: Why can't we normalize on IE - if (!isIE) { - node2 = marker.nextSibling; - if (node2 && node2.nodeType == 3) { - node.appendData(node2.data); - node2.parentNode.removeChild(node2); - } - } - } else { - // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node - rng.setStartBefore(marker); - rng.setEndBefore(marker); - } - - // Remove the marker node and set the new range - dom.remove(marker); - selection.setRng(rng); - - // Dispatch after event and add any visual elements needed - editor.fire('SetContent', args); - editor.addVisual(); - }, - - mceInsertRawHTML: function(command, ui, value) { - selection.setContent('tiny_mce_marker'); - editor.setContent( - editor.getContent().replace(/tiny_mce_marker/g, function() { - return value; - }) - ); - }, - - mceToggleFormat: function(command, ui, value) { - toggleFormat(value); - }, - - mceSetContent: function(command, ui, value) { - editor.setContent(value); - }, - - 'Indent,Outdent': function(command) { - var intentValue, indentUnit, value; - - // Setup indent level - intentValue = settings.indentation; - indentUnit = /[a-z%]+$/i.exec(intentValue); - intentValue = parseInt(intentValue, 10); - - if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { - // If forced_root_blocks is set to false we don't have a block to indent so lets create a div - if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { - formatter.apply('div'); - } - - each(selection.getSelectedBlocks(), function(element) { - if (element.nodeName != "LI") { - var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; - - indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; - - if (command == 'outdent') { - value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); - dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); - } else { - value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; - dom.setStyle(element, indentStyleName, value); - } - } - }); - } else { - execNativeCommand(command); - } - }, - - mceRepaint: function() { - if (isGecko) { - try { - storeSelection(TRUE); - - if (selection.getSel()) { - selection.getSel().selectAllChildren(editor.getBody()); - } - - selection.collapse(TRUE); - restoreSelection(); - } catch (ex) { - // Ignore - } - } - }, - - InsertHorizontalRule: function() { - editor.execCommand('mceInsertContent', false, '|
- rng = selection.getRng(); - if (!rng.item) { - rng.moveToElementText(root); - rng.select(); - } - } - }, - - "delete": function() { - execNativeCommand("Delete"); - - // Check if body is empty after the delete call if so then set the contents - // to an empty string and move the caret to any block produced by that operation - // this fixes the issue with root blocks not being properly produced after a delete call on IE - var body = editor.getBody(); - - if (dom.isEmpty(body)) { - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - } - }, - - mceNewDocument: function() { - editor.setContent(''); - } - }); - - // Add queryCommandState overrides - addCommands({ - // Override justify commands - 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { - var name = 'align' + command.substring(7); - var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); - var matches = map(nodes, function(node) { - return !!formatter.matchNode(node, name); - }); - return inArray(matches, TRUE) !== -1; - }, - - 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { - return isFormatMatch(command); - }, - - mceBlockQuote: function() { - return isFormatMatch('blockquote'); - }, - - Outdent: function() { - var node; - - if (settings.inline_styles) { - if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - - if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { - return TRUE; - } - } - - return ( - queryCommandState('InsertUnorderedList') || - queryCommandState('InsertOrderedList') || - (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) - ); - }, - - 'InsertUnorderedList,InsertOrderedList': function(command) { - var list = dom.getParent(selection.getNode(), 'ul,ol'); - - return list && - ( - command === 'insertunorderedlist' && list.tagName === 'UL' || - command === 'insertorderedlist' && list.tagName === 'OL' - ); - } - }, 'state'); - - // Add queryCommandValue overrides - addCommands({ - 'FontSize,FontName': function(command) { - var value = 0, parent; - - if ((parent = dom.getParent(selection.getNode(), 'span'))) { - if (command == 'fontsize') { - value = parent.style.fontSize; - } else { - value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); - } - } - - return value; - } - }, 'value'); - - // Add undo manager logic - addCommands({ - Undo: function() { - editor.undoManager.undo(); - }, - - Redo: function() { - editor.undoManager.redo(); - } - }); - }; -}); - -// Included from: js/tinymce/classes/util/URI.js - -/** - * URI.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/** - * This class handles parsing, modification and serialization of URI/URL strings. - * @class tinymce.util.URI - */ -define("tinymce/util/URI", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, trim = Tools.trim; - - /** - * Constructs a new URI instance. - * - * @constructor - * @method URI - * @param {String} url URI string to parse. - * @param {Object} settings Optional settings object. - */ - function URI(url, settings) { - var self = this, baseUri, base_url; - - // Trim whitespace - url = trim(url); - - // Default settings - settings = self.settings = settings || {}; - - // Strange app protocol that isn't http/https or local anchor - // For example: mailto,skype,tel etc. - if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) { - self.source = url; - return; - } - - var isProtocolRelative = url.indexOf('//') === 0; - - // Absolute path with no host, fake host and protocol - if (url.indexOf('/') === 0 && !isProtocolRelative) { - url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url; - } - - // Relative path http:// or protocol relative //path - if (!/^[\w\-]*:?\/\//.test(url)) { - base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory; - if (settings.base_uri.protocol === "") { - url = '//mce_host' + self.toAbsPath(base_url, url); - } else { - url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url); - } - } - - // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri) - url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something - - /*jshint maxlen: 255 */ - /*eslint max-len: 0 */ - url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url); - - each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) { - var part = url[i]; - - // Zope 3 workaround, they use @@something - if (part) { - part = part.replace(/\(mce_at\)/g, '@@'); - } - - self[v] = part; - }); - - baseUri = settings.base_uri; - if (baseUri) { - if (!self.protocol) { - self.protocol = baseUri.protocol; - } - - if (!self.userInfo) { - self.userInfo = baseUri.userInfo; - } - - if (!self.port && self.host === 'mce_host') { - self.port = baseUri.port; - } - - if (!self.host || self.host === 'mce_host') { - self.host = baseUri.host; - } - - self.source = ''; - } - - if (isProtocolRelative) { - self.protocol = ''; - } - - //t.path = t.path || '/'; - } - - URI.prototype = { - /** - * Sets the internal path part of the URI. - * - * @method setPath - * @param {string} path Path string to set. - */ - setPath: function(path) { - var self = this; - - path = /^(.*?)\/?(\w+)?$/.exec(path); - - // Update path parts - self.path = path[0]; - self.directory = path[1]; - self.file = path[2]; - - // Rebuild source - self.source = ''; - self.getURI(); - }, - - /** - * Converts the specified URI into a relative URI based on the current URI instance location. - * - * @method toRelative - * @param {String} uri URI to convert into a relative path/URI. - * @return {String} Relative URI from the point specified in the current URI instance. - * @example - * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm'); - */ - toRelative: function(uri) { - var self = this, output; - - if (uri === "./") { - return uri; - } - - uri = new URI(uri, {base_uri: self}); - - // Not on same domain/port or protocol - if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port || - (self.protocol != uri.protocol && uri.protocol !== "")) { - return uri.getURI(); - } - - var tu = self.getURI(), uu = uri.getURI(); - - // Allow usage of the base_uri when relative_urls = true - if (tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) { - return tu; - } - - output = self.toRelPath(self.path, uri.path); - - // Add query - if (uri.query) { - output += '?' + uri.query; - } - - // Add anchor - if (uri.anchor) { - output += '#' + uri.anchor; - } - - return output; - }, - - /** - * Converts the specified URI into a absolute URI based on the current URI instance location. - * - * @method toAbsolute - * @param {String} uri URI to convert into a relative path/URI. - * @param {Boolean} noHost No host and protocol prefix. - * @return {String} Absolute URI from the point specified in the current URI instance. - * @example - * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm - * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm'); - */ - toAbsolute: function(uri, noHost) { - uri = new URI(uri, {base_uri: this}); - - return uri.getURI(this.host == uri.host && this.protocol == uri.protocol ? noHost : 0); - }, - - /** - * Converts a absolute path into a relative path. - * - * @method toRelPath - * @param {String} base Base point to convert the path from. - * @param {String} path Absolute path to convert into a relative path. - */ - toRelPath: function(base, path) { - var items, breakPoint = 0, out = '', i, l; - - // Split the paths - base = base.substring(0, base.lastIndexOf('/')); - base = base.split('/'); - items = path.split('/'); - - if (base.length >= items.length) { - for (i = 0, l = base.length; i < l; i++) { - if (i >= items.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (base.length < items.length) { - for (i = 0, l = items.length; i < l; i++) { - if (i >= base.length || base[i] != items[i]) { - breakPoint = i + 1; - break; - } - } - } - - if (breakPoint === 1) { - return path; - } - - for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) { - out += "../"; - } - - for (i = breakPoint - 1, l = items.length; i < l; i++) { - if (i != breakPoint - 1) { - out += "/" + items[i]; - } else { - out += items[i]; - } - } - - return out; - }, - - /** - * Converts a relative path into a absolute path. - * - * @method toAbsPath - * @param {String} base Base point to convert the path from. - * @param {String} path Relative path to convert into an absolute path. - */ - toAbsPath: function(base, path) { - var i, nb = 0, o = [], tr, outPath; - - // Split paths - tr = /\/$/.test(path) ? '/' : ''; - base = base.split('/'); - path = path.split('/'); - - // Remove empty chunks - each(base, function(k) { - if (k) { - o.push(k); - } - }); - - base = o; - - // Merge relURLParts chunks - for (i = path.length - 1, o = []; i >= 0; i--) { - // Ignore empty or . - if (path[i].length === 0 || path[i] === ".") { - continue; - } - - // Is parent - if (path[i] === '..') { - nb++; - continue; - } - - // Move up - if (nb > 0) { - nb--; - continue; - } - - o.push(path[i]); - } - - i = base.length - nb; - - // If /a/b/c or / - if (i <= 0) { - outPath = o.reverse().join('/'); - } else { - outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/'); - } - - // Add front / if it's needed - if (outPath.indexOf('/') !== 0) { - outPath = '/' + outPath; - } - - // Add traling / if it's needed - if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) { - outPath += tr; - } - - return outPath; - }, - - /** - * Returns the full URI of the internal structure. - * - * @method getURI - * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false. - */ - getURI: function(noProtoHost) { - var s, self = this; - - // Rebuild source - if (!self.source || noProtoHost) { - s = ''; - - if (!noProtoHost) { - if (self.protocol) { - s += self.protocol + '://'; - } else { - s += '//'; - } - - if (self.userInfo) { - s += self.userInfo + '@'; - } - - if (self.host) { - s += self.host; - } - - if (self.port) { - s += ':' + self.port; - } - } - - if (self.path) { - s += self.path; - } - - if (self.query) { - s += '?' + self.query; - } - - if (self.anchor) { - s += '#' + self.anchor; - } - - self.source = s; - } - - return self.source; - } - }; - - return URI; -}); - -// Included from: js/tinymce/classes/util/Class.js - -/** - * Class.js - * - * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved. - */ - -/** - * This utilitiy class is used for easier inheritage. - * - * Features: - * * Exposed super functions: this._super(); - * * Mixins - * * Dummy functions - * * Property functions: var value = object.value(); and object.value(newValue); - * * Static functions - * * Defaults settings - */ -define("tinymce/util/Class", [ - "tinymce/util/Tools" -], function(Tools) { - var each = Tools.each, extend = Tools.extend; - - var extendClass, initializing; - - function Class() { - } - - // Provides classical inheritance, based on code made by John Resig - Class.extend = extendClass = function(prop) { - var self = this, _super = self.prototype, prototype, name, member; - - // The dummy class constructor - function Class() { - var i, mixins, mixin, self = this; - - // All construction is actually done in the init method - if (!initializing) { - // Run class constuctor - if (self.init) { - self.init.apply(self, arguments); - } - - // Run mixin constructors - mixins = self.Mixins; - if (mixins) { - i = mixins.length; - while (i--) { - mixin = mixins[i]; - if (mixin.init) { - mixin.init.apply(self, arguments); - } - } - } - } - } - - // Dummy function, needs to be extended in order to provide functionality - function dummy() { - return this; - } - - // Creates a overloaded method for the class - // this enables you to use this._super(); to call the super function - function createMethod(name, fn) { - return function(){ - var self = this, tmp = self._super, ret; - - self._super = _super[name]; - ret = fn.apply(self, arguments); - self._super = tmp; - - return ret; - }; - } - - // Instantiate a base class (but only create the instance, - // don't run the init constructor) - initializing = true; - prototype = new self(); - initializing = false; - - // Add mixins - if (prop.Mixins) { - each(prop.Mixins, function(mixin) { - mixin = mixin; - - for (var name in mixin) { - if (name !== "init") { - prop[name] = mixin[name]; - } - } - }); - - if (_super.Mixins) { - prop.Mixins = _super.Mixins.concat(prop.Mixins); - } - } - - // Generate dummy methods - if (prop.Methods) { - each(prop.Methods.split(','), function(name) { - prop[name] = dummy; - }); - } - - // Generate property methods - if (prop.Properties) { - each(prop.Properties.split(','), function(name) { - var fieldName = '_' + name; - - prop[name] = function(value) { - var self = this, undef; - - // Set value - if (value !== undef) { - self[fieldName] = value; - - return self; - } - - // Get value - return self[fieldName]; - }; - }); - } - - // Static functions - if (prop.Statics) { - each(prop.Statics, function(func, name) { - Class[name] = func; - }); - } - - // Default settings - if (prop.Defaults && _super.Defaults) { - prop.Defaults = extend({}, _super.Defaults, prop.Defaults); - } - - // Copy the properties over onto the new prototype - for (name in prop) { - member = prop[name]; - - if (typeof member == "function" && _super[name]) { - prototype[name] = createMethod(name, member); - } else { - prototype[name] = member; - } - } - - // Populate our constructed prototype object - Class.prototype = prototype; - - // Enforce the constructor to be what we expect - Class.constructor = Class; - - // And make this class extendible - Class.extend = extendClass; - - return Class; - }; - - return Class; -}); - -// Included from: js/tinymce/classes/ui/Selector.js - -/** - * Selector.js - * - * Copyright, Moxiecode Systems AB - * Released under LGPL License. - * - * License: http://www.tinymce.com/license - * Contributing: http://www.tinymce.com/contributing - */ - -/*eslint no-nested-ternary:0 */ - -/** - * Selector engine, enables you to select controls by using CSS like expressions. - * We currently only support basic CSS expressions to reduce the size of the core - * and the ones we support should be enough for most cases. - * - * @example - * Supported expressions: - * element - * element#name - * element.class - * element[attr] - * element[attr*=value] - * element[attr~=value] - * element[attr!=value] - * element[attr^=value] - * element[attr$=value] - * element: bug on IE 8 #6178
- DOMUtils.DOM.setHTML(elm, html);
- }
- };
-});
-
-// Included from: js/tinymce/classes/ui/Control.js
-
-/**
- * Control.js
- *
- * Copyright, Moxiecode Systems AB
- * Released under LGPL License.
- *
- * License: http://www.tinymce.com/license
- * Contributing: http://www.tinymce.com/contributing
- */
-
-/*eslint consistent-this:0 */
-
-/**
- * This is the base class for all controls and containers. All UI control instances inherit
- * from this one as it has the base logic needed by all of them.
- *
- * @class tinymce.ui.Control
- */
-define("tinymce/ui/Control", [
- "tinymce/util/Class",
- "tinymce/util/Tools",
- "tinymce/ui/Collection",
- "tinymce/ui/DomUtils"
-], function(Class, Tools, Collection, DomUtils) {
- "use strict";
-
- var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" +
- " mouseout mouseenter mouseleave wheel keydown keypress keyup contextmenu", " ");
-
- var elementIdCache = {};
- var hasMouseWheelEventSupport = "onmousewheel" in document;
- var hasWheelEventSupport = false;
-
- var Control = Class.extend({
- Statics: {
- elementIdCache: elementIdCache
- },
-
- isRtl: function() {
- return Control.rtl;
- },
-
- /**
- * Class/id prefix to use for all controls.
- *
- * @final
- * @field {String} classPrefix
- */
- classPrefix: "mce-",
-
- /**
- * Constructs a new control instance with the specified settings.
- *
- * @constructor
- * @param {Object} settings Name/value object with settings.
- * @setting {String} style Style CSS properties to add.
- * @setting {String} border Border box values example: 1 1 1 1
- * @setting {String} padding Padding box values example: 1 1 1 1
- * @setting {String} margin Margin box values example: 1 1 1 1
- * @setting {Number} minWidth Minimal width for the control.
- * @setting {Number} minHeight Minimal height for the control.
- * @setting {String} classes Space separated list of classes to add.
- * @setting {String} role WAI-ARIA role to use for control.
- * @setting {Boolean} hidden Is the control hidden by default.
- * @setting {Boolean} disabled Is the control disabled by default.
- * @setting {String} name Name of the control instance.
- */
- init: function(settings) {
- var self = this, classes, i;
-
- self.settings = settings = Tools.extend({}, self.Defaults, settings);
-
- // Initial states
- self._id = settings.id || DomUtils.id();
- self._text = self._name = '';
- self._width = self._height = 0;
- self._aria = {role: settings.role};
-
- // Setup classes
- classes = settings.classes;
- if (classes) {
- classes = classes.split(' ');
- classes.map = {};
- i = classes.length;
- while (i--) {
- classes.map[classes[i]] = true;
- }
- }
-
- self._classes = classes || [];
- self.visible(true);
-
- // Set some properties
- Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) {
- var value = settings[name], undef;
-
- if (value !== undef) {
- self[name](value);
- } else if (self['_' + name] === undef) {
- self['_' + name] = false;
- }
- });
-
- self.on('click', function() {
- if (self.disabled()) {
- return false;
- }
- });
-
- // TODO: Is this needed duplicate code see above?
- if (settings.classes) {
- Tools.each(settings.classes.split(' '), function(cls) {
- self.addClass(cls);
- });
- }
-
- /**
- * Name/value object with settings for the current control.
- *
- * @field {Object} settings
- */
- self.settings = settings;
-
- self._borderBox = self.parseBox(settings.border);
- self._paddingBox = self.parseBox(settings.padding);
- self._marginBox = self.parseBox(settings.margin);
-
- if (settings.hidden) {
- self.hide();
- }
- },
-
- // Will generate getter/setter methods for these properties
- Properties: 'parent,title,text,width,height,disabled,active,name,value',
-
- // Will generate empty dummy functions for these
- Methods: 'renderHtml',
-
- /**
- * Returns the root element to render controls into.
- *
- * @method getContainerElm
- * @return {Element} HTML DOM element to render into.
- */
- getContainerElm: function() {
- return document.body;
- },
-
- /**
- * Returns a control instance for the current DOM element.
- *
- * @method getParentCtrl
- * @param {Element} elm HTML dom element to get parent control from.
- * @return {tinymce.ui.Control} Control instance or undefined.
- */
- getParentCtrl: function(elm) {
- var ctrl, lookup = this.getRoot().controlIdLookup;
-
- while (elm && lookup) {
- ctrl = lookup[elm.id];
- if (ctrl) {
- break;
- }
-
- elm = elm.parentNode;
- }
-
- return ctrl;
- },
-
- /**
- * Parses the specified box value. A box value contains 1-4 properties in clockwise order.
- *
- * @method parseBox
- * @param {String/Number} value Box value "0 1 2 3" or "0" etc.
- * @return {Object} Object with top/right/bottom/left properties.
- * @private
- */
- parseBox: function(value) {
- var len, radix = 10;
-
- if (!value) {
- return;
- }
-
- if (typeof(value) === "number") {
- value = value || 0;
-
- return {
- top: value,
- left: value,
- bottom: value,
- right: value
- };
- }
-
- value = value.split(' ');
- len = value.length;
-
- if (len === 1) {
- value[1] = value[2] = value[3] = value[0];
- } else if (len === 2) {
- value[2] = value[0];
- value[3] = value[1];
- } else if (len === 3) {
- value[3] = value[1];
- }
-
- return {
- top: parseInt(value[0], radix) || 0,
- right: parseInt(value[1], radix) || 0,
- bottom: parseInt(value[2], radix) || 0,
- left: parseInt(value[3], radix) || 0
- };
- },
-
- borderBox: function() {
- return this._borderBox;
- },
-
- paddingBox: function() {
- return this._paddingBox;
- },
-
- marginBox: function() {
- return this._marginBox;
- },
-
- measureBox: function(elm, prefix) {
- function getStyle(name) {
- var defaultView = document.defaultView;
-
- if (defaultView) {
- // Remove camelcase
- name = name.replace(/[A-Z]/g, function(a) {
- return '-' + a;
- });
-
- return defaultView.getComputedStyle(elm, null).getPropertyValue(name);
- }
-
- return elm.currentStyle[name];
- }
-
- function getSide(name) {
- var val = parseFloat(getStyle(name), 10);
-
- return isNaN(val) ? 0 : val;
- }
-
- return {
- top: getSide(prefix + "TopWidth"),
- right: getSide(prefix + "RightWidth"),
- bottom: getSide(prefix + "BottomWidth"),
- left: getSide(prefix + "LeftWidth")
- };
- },
-
- /**
- * Initializes the current controls layout rect.
- * This will be executed by the layout managers to determine the
- * default minWidth/minHeight etc.
- *
- * @method initLayoutRect
- * @return {Object} Layout rect instance.
- */
- initLayoutRect: function() {
- var self = this, settings = self.settings, borderBox, layoutRect;
- var elm = self.getEl(), width, height, minWidth, minHeight, autoResize;
- var startMinWidth, startMinHeight, initialSize;
-
- // Measure the current element
- borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border');
- self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding');
- self._marginBox = self._marginBox || self.measureBox(elm, 'margin');
- initialSize = DomUtils.getSize(elm);
-
- // Setup minWidth/minHeight and width/height
- startMinWidth = settings.minWidth;
- startMinHeight = settings.minHeight;
- minWidth = startMinWidth || initialSize.width;
- minHeight = startMinHeight || initialSize.height;
- width = settings.width;
- height = settings.height;
- autoResize = settings.autoResize;
- autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height;
-
- width = width || minWidth;
- height = height || minHeight;
-
- var deltaW = borderBox.left + borderBox.right;
- var deltaH = borderBox.top + borderBox.bottom;
-
- var maxW = settings.maxWidth || 0xFFFF;
- var maxH = settings.maxHeight || 0xFFFF;
-
- // Setup initial layout rect
- self._layoutRect = layoutRect = {
- x: settings.x || 0,
- y: settings.y || 0,
- w: width,
- h: height,
- deltaW: deltaW,
- deltaH: deltaH,
- contentW: width - deltaW,
- contentH: height - deltaH,
- innerW: width - deltaW,
- innerH: height - deltaH,
- startMinWidth: startMinWidth || 0,
- startMinHeight: startMinHeight || 0,
- minW: Math.min(minWidth, maxW),
- minH: Math.min(minHeight, maxH),
- maxW: maxW,
- maxH: maxH,
- autoResize: autoResize,
- scrollW: 0
- };
-
- self._lastLayoutRect = {};
-
- return layoutRect;
- },
-
- /**
- * Getter/setter for the current layout rect.
- *
- * @method layoutRect
- * @param {Object} [newRect] Optional new layout rect.
- * @return {tinymce.ui.Control/Object} Current control or rect object.
- */
- layoutRect: function(newRect) {
- var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls;
-
- // Initialize default layout rect
- if (!curRect) {
- curRect = self.initLayoutRect();
- }
-
- // Set new rect values
- if (newRect) {
- // Calc deltas between inner and outer sizes
- deltaWidth = curRect.deltaW;
- deltaHeight = curRect.deltaH;
-
- // Set x position
- if (newRect.x !== undef) {
- curRect.x = newRect.x;
- }
-
- // Set y position
- if (newRect.y !== undef) {
- curRect.y = newRect.y;
- }
-
- // Set minW
- if (newRect.minW !== undef) {
- curRect.minW = newRect.minW;
- }
-
- // Set minH
- if (newRect.minH !== undef) {
- curRect.minH = newRect.minH;
- }
-
- // Set new width and calculate inner width
- size = newRect.w;
- if (size !== undef) {
- size = size < curRect.minW ? curRect.minW : size;
- size = size > curRect.maxW ? curRect.maxW : size;
- curRect.w = size;
- curRect.innerW = size - deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.h;
- if (size !== undef) {
- size = size < curRect.minH ? curRect.minH : size;
- size = size > curRect.maxH ? curRect.maxH : size;
- curRect.h = size;
- curRect.innerH = size - deltaHeight;
- }
-
- // Set new inner width and calculate width
- size = newRect.innerW;
- if (size !== undef) {
- size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size;
- size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size;
- curRect.innerW = size;
- curRect.w = size + deltaWidth;
- }
-
- // Set new height and calculate inner height
- size = newRect.innerH;
- if (size !== undef) {
- size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size;
- size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size;
- curRect.innerH = size;
- curRect.h = size + deltaHeight;
- }
-
- // Set new contentW
- if (newRect.contentW !== undef) {
- curRect.contentW = newRect.contentW;
- }
-
- // Set new contentH
- if (newRect.contentH !== undef) {
- curRect.contentH = newRect.contentH;
- }
-
- // Compare last layout rect with the current one to see if we need to repaint or not
- lastLayoutRect = self._lastLayoutRect;
- if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y ||
- lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) {
- repaintControls = Control.repaintControls;
-
- if (repaintControls) {
- if (repaintControls.map && !repaintControls.map[self._id]) {
- repaintControls.push(self);
- repaintControls.map[self._id] = true;
- }
- }
-
- lastLayoutRect.x = curRect.x;
- lastLayoutRect.y = curRect.y;
- lastLayoutRect.w = curRect.w;
- lastLayoutRect.h = curRect.h;
- }
-
- return self;
- }
-
- return curRect;
- },
-
- /**
- * Repaints the control after a layout operation.
- *
- * @method repaint
- */
- repaint: function() {
- var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect, round;
-
- // Use Math.round on all values on IE < 9
- round = !document.createRange ? Math.round : function(value) {
- return value;
- };
-
- style = self.getEl().style;
- rect = self._layoutRect;
- lastRepaintRect = self._lastRepaintRect || {};
-
- borderBox = self._borderBox;
- borderW = borderBox.left + borderBox.right;
- borderH = borderBox.top + borderBox.bottom;
-
- if (rect.x !== lastRepaintRect.x) {
- style.left = round(rect.x) + 'px';
- lastRepaintRect.x = rect.x;
- }
-
- if (rect.y !== lastRepaintRect.y) {
- style.top = round(rect.y) + 'px';
- lastRepaintRect.y = rect.y;
- }
-
- if (rect.w !== lastRepaintRect.w) {
- style.width = round(rect.w - borderW) + 'px';
- lastRepaintRect.w = rect.w;
- }
-
- if (rect.h !== lastRepaintRect.h) {
- style.height = round(rect.h - borderH) + 'px';
- lastRepaintRect.h = rect.h;
- }
-
- // Update body if needed
- if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) {
- bodyStyle = self.getEl('body').style;
- bodyStyle.width = round(rect.innerW) + 'px';
- lastRepaintRect.innerW = rect.innerW;
- }
-
- if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) {
- bodyStyle = bodyStyle || self.getEl('body').style;
- bodyStyle.height = round(rect.innerH) + 'px';
- lastRepaintRect.innerH = rect.innerH;
- }
-
- self._lastRepaintRect = lastRepaintRect;
- self.fire('repaint', {}, false);
- },
-
- /**
- * Binds a callback to the specified event. This event can both be
- * native browser events like "click" or custom ones like PostRender.
- *
- * The callback function will be passed a DOM event like object that enables yout do stop propagation.
- *
- * @method on
- * @param {String} name Name of the event to bind. For example "click".
- * @param {String/function} callback Callback function to execute ones the event occurs.
- * @return {tinymce.ui.Control} Current control object.
- */
- on: function(name, callback) {
- var self = this, bindings, handlers, names, i;
-
- function resolveCallbackName(name) {
- var callback, scope;
-
- return function(e) {
- if (!callback) {
- self.parents().each(function(ctrl) {
- var callbacks = ctrl.settings.callbacks;
-
- if (callbacks && (callback = callbacks[name])) {
- scope = ctrl;
- return false;
- }
- });
- }
-
- return callback.call(scope, e);
- };
- }
-
- if (callback) {
- if (typeof(callback) == 'string') {
- callback = resolveCallbackName(callback);
- }
-
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
-
- bindings = self._bindings;
- if (!bindings) {
- bindings = self._bindings = {};
- }
-
- handlers = bindings[name];
- if (!handlers) {
- handlers = bindings[name] = [];
- }
-
- handlers.push(callback);
-
- if (nativeEvents[name]) {
- if (!self._nativeEvents) {
- self._nativeEvents = {name: true};
- } else {
- self._nativeEvents[name] = true;
- }
-
- if (self._rendered) {
- self.bindPendingEvents();
- }
- }
- }
- }
-
- return self;
- },
-
- /**
- * Unbinds the specified event and optionally a specific callback. If you omit the name
- * parameter all event handlers will be removed. If you omit the callback all event handles
- * by the specified name will be removed.
- *
- * @method off
- * @param {String} [name] Name for the event to unbind.
- * @param {function} [callback] Callback function to unbind.
- * @return {mxex.ui.Control} Current control object.
- */
- off: function(name, callback) {
- var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi;
-
- if (bindings) {
- if (name) {
- names = name.toLowerCase().split(' ');
- i = names.length;
- while (i--) {
- name = names[i];
- handlers = bindings[name];
-
- // Unbind all handlers
- if (!name) {
- for (bindingName in bindings) {
- bindings[bindingName].length = 0;
- }
-
- return self;
- }
-
- if (handlers) {
- // Unbind all by name
- if (!callback) {
- handlers.length = 0;
- } else {
- // Unbind specific ones
- hi = handlers.length;
- while (hi--) {
- if (handlers[hi] === callback) {
- handlers.splice(hi, 1);
- }
- }
- }
- }
- }
- } else {
- self._bindings = [];
- }
- }
-
- return self;
- },
-
- /**
- * Fires the specified event by name and arguments on the control. This will execute all
- * bound event handlers.
- *
- * @method fire
- * @param {String} name Name of the event to fire.
- * @param {Object} [args] Arguments to pass to the event.
- * @param {Boolean} [bubble] Value to control bubbeling. Defaults to true.
- * @return {Object} Current arguments object.
- */
- fire: function(name, args, bubble) {
- var self = this, i, l, handlers, parentCtrl;
-
- name = name.toLowerCase();
-
- // Dummy function that gets replaced on the delegation state functions
- function returnFalse() {
- return false;
- }
-
- // Dummy function that gets replaced on the delegation state functions
- function returnTrue() {
- return true;
- }
-
- // Setup empty object if args is omited
- args = args || {};
-
- // Stick type into event object
- if (!args.type) {
- args.type = name;
- }
-
- // Stick control into event
- if (!args.control) {
- args.control = self;
- }
-
- // Add event delegation methods if they are missing
- if (!args.preventDefault) {
- // Add preventDefault method
- args.preventDefault = function() {
- args.isDefaultPrevented = returnTrue;
- };
-
- // Add stopPropagation
- args.stopPropagation = function() {
- args.isPropagationStopped = returnTrue;
- };
-
- // Add stopImmediatePropagation
- args.stopImmediatePropagation = function() {
- args.isImmediatePropagationStopped = returnTrue;
- };
-
- // Add event delegation states
- args.isDefaultPrevented = returnFalse;
- args.isPropagationStopped = returnFalse;
- args.isImmediatePropagationStopped = returnFalse;
- }
-
- if (self._bindings) {
- handlers = self._bindings[name];
-
- if (handlers) {
- for (i = 0, l = handlers.length; i < l; i++) {
- // Execute callback and break if the callback returns a false
- if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) {
- break;
- }
- }
- }
- }
-
- // Bubble event up to parent controls
- if (bubble !== false) {
- parentCtrl = self.parent();
- while (parentCtrl && !args.isPropagationStopped()) {
- parentCtrl.fire(name, args, false);
- parentCtrl = parentCtrl.parent();
- }
- }
-
- return args;
- },
-
- /**
- * Returns true/false if the specified event has any listeners.
- *
- * @method hasEventListeners
- * @param {String} name Name of the event to check for.
- * @return {Boolean} True/false state if the event has listeners.
- */
- hasEventListeners: function(name) {
- return name in this._bindings;
- },
-
- /**
- * Returns a control collection with all parent controls.
- *
- * @method parents
- * @param {String} selector Optional selector expression to find parents.
- * @return {tinymce.ui.Collection} Collection with all parent controls.
- */
- parents: function(selector) {
- var self = this, ctrl, parents = new Collection();
-
- // Add each parent to collection
- for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) {
- parents.add(ctrl);
- }
-
- // Filter away everything that doesn't match the selector
- if (selector) {
- parents = parents.filter(selector);
- }
-
- return parents;
- },
-
- /**
- * Returns the control next to the current control.
- *
- * @method next
- * @return {tinymce.ui.Control} Next control instance.
- */
- next: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) + 1];
- },
-
- /**
- * Returns the control previous to the current control.
- *
- * @method prev
- * @return {tinymce.ui.Control} Previous control instance.
- */
- prev: function() {
- var parentControls = this.parent().items();
-
- return parentControls[parentControls.indexOf(this) - 1];
- },
-
- /**
- * Find the common ancestor for two control instances.
- *
- * @method findCommonAncestor
- * @param {tinymce.ui.Control} ctrl1 First control.
- * @param {tinymce.ui.Control} ctrl2 Second control.
- * @return {tinymce.ui.Control} Ancestor control instance.
- */
- findCommonAncestor: function(ctrl1, ctrl2) {
- var parentCtrl;
-
- while (ctrl1) {
- parentCtrl = ctrl2;
-
- while (parentCtrl && ctrl1 != parentCtrl) {
- parentCtrl = parentCtrl.parent();
- }
-
- if (ctrl1 == parentCtrl) {
- break;
- }
-
- ctrl1 = ctrl1.parent();
- }
-
- return ctrl1;
- },
-
- /**
- * Returns true/false if the specific control has the specific class.
- *
- * @method hasClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {Boolean} True/false if the control has the specified class.
- */
- hasClass: function(cls, group) {
- var classes = this._classes[group || 'control'];
-
- cls = this.classPrefix + cls;
-
- return classes && !!classes.map[cls];
- },
-
- /**
- * Adds the specified class to the control
- *
- * @method addClass
- * @param {String} cls Class to check for.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- addClass: function(cls, group) {
- var self = this, classes, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
-
- if (!classes) {
- classes = [];
- classes.map = {};
- self._classes[group || 'control'] = classes;
- }
-
- if (!classes.map[cls]) {
- classes.map[cls] = cls;
- classes.push(cls);
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
- }
-
- return self;
- },
-
- /**
- * Removes the specified class from the control.
- *
- * @method removeClass
- * @param {String} cls Class to remove.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- removeClass: function(cls, group) {
- var self = this, classes, i, elm;
-
- cls = this.classPrefix + cls;
- classes = self._classes[group || 'control'];
- if (classes && classes.map[cls]) {
- delete classes.map[cls];
-
- i = classes.length;
- while (i--) {
- if (classes[i] === cls) {
- classes.splice(i, 1);
- }
- }
- }
-
- if (self._rendered) {
- elm = self.getEl(group);
-
- if (elm) {
- elm.className = classes.join(' ');
- }
- }
-
- return self;
- },
-
- /**
- * Toggles the specified class on the control.
- *
- * @method toggleClass
- * @param {String} cls Class to remove.
- * @param {Boolean} state True/false state to add/remove class.
- * @param {String} [group] Sub element group name.
- * @return {tinymce.ui.Control} Current control object.
- */
- toggleClass: function(cls, state, group) {
- var self = this;
-
- if (state) {
- self.addClass(cls, group);
- } else {
- self.removeClass(cls, group);
- }
-
- return self;
- },
-
- /**
- * Returns the class string for the specified group name.
- *
- * @method classes
- * @param {String} [group] Group to get clases by.
- * @return {String} Classes for the specified group.
- */
- classes: function(group) {
- var classes = this._classes[group || 'control'];
-
- return classes ? classes.join(' ') : '';
- },
-
- /**
- * Sets the inner HTML of the control element.
- *
- * @method innerHtml
- * @param {String} html Html string to set as inner html.
- * @return {tinymce.ui.Control} Current control object.
- */
- innerHtml: function(html) {
- DomUtils.innerHtml(this.getEl(), html);
- return this;
- },
-
- /**
- * Returns the control DOM element or sub element.
- *
- * @method getEl
- * @param {String} [suffix] Suffix to get element by.
- * @param {Boolean} [dropCache] True if the cache for the element should be dropped.
- * @return {Element} HTML DOM element for the current control or it's children.
- */
- getEl: function(suffix, dropCache) {
- var elm, id = suffix ? this._id + '-' + suffix : this._id;
-
- elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id);
-
- return elm;
- },
-
- /**
- * Sets/gets the visible for the control.
- *
- * @method visible
- * @param {Boolean} state Value to set to control.
- * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
- */
- visible: function(state) {
- var self = this, parentCtrl;
-
- if (typeof(state) !== "undefined") {
- if (self._visible !== state) {
- if (self._rendered) {
- self.getEl().style.display = state ? '' : 'none';
- }
-
- self._visible = state;
-
- // Parent container needs to reflow
- parentCtrl = self.parent();
- if (parentCtrl) {
- parentCtrl._lastRect = null;
- }
-
- self.fire(state ? 'show' : 'hide');
- }
-
- return self;
- }
-
- return self._visible;
- },
-
- /**
- * Sets the visible state to true.
- *
- * @method show
- * @return {tinymce.ui.Control} Current control instance.
- */
- show: function() {
- return this.visible(true);
- },
-
- /**
- * Sets the visible state to false.
- *
- * @method hide
- * @return {tinymce.ui.Control} Current control instance.
- */
- hide: function() {
- return this.visible(false);
- },
-
- /**
- * Focuses the current control.
- *
- * @method focus
- * @return {tinymce.ui.Control} Current control instance.
- */
- focus: function() {
- try {
- this.getEl().focus();
- } catch (ex) {
- // Ignore IE error
- }
-
- return this;
- },
-
- /**
- * Blurs the current control.
- *
- * @method blur
- * @return {tinymce.ui.Control} Current control instance.
- */
- blur: function() {
- this.getEl().blur();
-
- return this;
- },
-
- /**
- * Sets the specified aria property.
- *
- * @method aria
- * @param {String} name Name of the aria property to set.
- * @param {String} value Value of the aria property.
- * @return {tinymce.ui.Control} Current control instance.
- */
- aria: function(name, value) {
- var self = this, elm = self.getEl(self.ariaTarget);
-
- if (typeof(value) === "undefined") {
- return self._aria[name];
- } else {
- self._aria[name] = value;
- }
-
- if (self._rendered) {
- elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
- }
-
- return self;
- },
-
- /**
- * Encodes the specified string with HTML entities. It will also
- * translate the string to different languages.
- *
- * @method encode
- * @param {String/Object/Array} text Text to entity encode.
- * @param {Boolean} [translate=true] False if the contents shouldn't be translated.
- * @return {String} Encoded and possible traslated string.
- */
- encode: function(text, translate) {
- if (translate !== false && Control.translate) {
- text = Control.translate(text);
- }
-
- return (text || '').replace(/[&<>"]/g, function(match) {
- return '' + match.charCodeAt(0) + ';';
- });
- },
-
- /**
- * Adds items before the current control.
- *
- * @method before
- * @param {Array/tinymce.ui.Collection} items Array of items to prepend before this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- before: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self), true);
- }
-
- return self;
- },
-
- /**
- * Adds items after the current control.
- *
- * @method after
- * @param {Array/tinymce.ui.Collection} items Array of items to append after this control.
- * @return {tinymce.ui.Control} Current control instance.
- */
- after: function(items) {
- var self = this, parent = self.parent();
-
- if (parent) {
- parent.insert(items, parent.items().indexOf(self));
- }
-
- return self;
- },
-
- /**
- * Removes the current control from DOM and from UI collections.
- *
- * @method remove
- * @return {tinymce.ui.Control} Current control instance.
- */
- remove: function() {
- var self = this, elm = self.getEl(), parent = self.parent(), newItems, i;
-
- if (self.items) {
- var controls = self.items().toArray();
- i = controls.length;
- while (i--) {
- controls[i].remove();
- }
- }
-
- if (parent && parent.items) {
- newItems = [];
-
- parent.items().each(function(item) {
- if (item !== self) {
- newItems.push(item);
- }
- });
-
- parent.items().set(newItems);
- parent._lastRect = null;
- }
-
- if (self._eventsRoot && self._eventsRoot == self) {
- DomUtils.off(elm);
- }
-
- var lookup = self.getRoot().controlIdLookup;
- if (lookup) {
- delete lookup[self._id];
- }
-
- delete elementIdCache[self._id];
-
- if (elm && elm.parentNode) {
- var nodes = elm.getElementsByTagName('*');
-
- i = nodes.length;
- while (i--) {
- delete elementIdCache[nodes[i].id];
- }
-
- elm.parentNode.removeChild(elm);
- }
-
- self._rendered = false;
-
- return self;
- },
-
- /**
- * Renders the control before the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render before.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderBefore: function(elm) {
- var self = this;
-
- elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm);
- self.postRender();
-
- return self;
- },
-
- /**
- * Renders the control to the specified element.
- *
- * @method renderBefore
- * @param {Element} elm Element to render to.
- * @return {tinymce.ui.Control} Current control instance.
- */
- renderTo: function(elm) {
- var self = this;
-
- elm = elm || self.getContainerElm();
- elm.appendChild(DomUtils.createFragment(self.renderHtml()));
- self.postRender();
-
- return self;
- },
-
- /**
- * Post render method. Called after the control has been rendered to the target.
- *
- * @method postRender
- * @return {tinymce.ui.Control} Current control instance.
- */
- postRender: function() {
- var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;
-
- // Bind on |ba
ab
|
- * - * Or: - *|
- if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) { - isCollapsed = editor.selection.isCollapsed(); - body = editor.getBody(); - - // Selection is collapsed but the editor isn't empty - if (isCollapsed && !dom.isEmpty(body)) { - return; - } - - // Selection isn't collapsed but not all the contents is selected - if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { - return; - } - - // Manually empty the editor - e.preventDefault(); - editor.setContent(''); - - if (body.firstChild && dom.isBlock(body.firstChild)) { - editor.selection.setCursorLocation(body.firstChild, 0); - } else { - editor.selection.setCursorLocation(body, 0); - } - - editor.nodeChanged(); - } - }); - } - - /** - * WebKit doesn't select all the nodes in the body when you press Ctrl+A. - * IE selects more than the contents [a
] instead of[a]
see bug #6438 - * This selects the whole body so that backspace/delete logic will delete everything - */ - function selectAll() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) { - e.preventDefault(); - editor.execCommand('SelectAll'); - } - }); - } - - /** - * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes. - * The IME on Mac doesn't initialize when it doesn't fire a proper focus event. - * - * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until - * you enter a character into the editor. - * - * It also happens when the first focus in made to the body. - * - * See: https://bugs.webkit.org/show_bug.cgi?id=83566 - */ - function inputMethodFocus() { - if (!editor.settings.content_editable) { - // Case 1 IME doesn't initialize if you focus the document - dom.bind(editor.getDoc(), 'focusin', function() { - selection.setRng(selection.getRng()); - }); - - // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event - dom.bind(editor.getDoc(), 'mousedown', function(e) { - if (e.target == editor.getDoc().documentElement) { - editor.getBody().focus(); - selection.setRng(selection.getRng()); - } - }); - } - } - - /** - * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the - * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is - * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js - * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other - * browsers. - * - * It also fixes a bug on Firefox where it's impossible to delete HR elements. - */ - function removeHrOnBackspace() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var node = selection.getNode(); - var previousSibling = node.previousSibling; - - if (node.nodeName == 'HR') { - dom.remove(node); - e.preventDefault(); - return; - } - - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") { - dom.remove(previousSibling); - e.preventDefault(); - } - } - } - }); - } - - /** - * Firefox 3.x has an issue where the body element won't get proper focus if you click out - * side it's rectangle. - */ - function focusBody() { - // Fix for a focus bug in FF 3.x where the body element - // wouldn't get proper focus if the user clicked on the HTML element - if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4 - editor.on('mousedown', function(e) { - if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") { - var body = editor.getBody(); - - // Blur the body it's focused but not correctly focused - body.blur(); - - // Refocus the body after a little while - setTimeout(function() { - body.focus(); - }, 0); - } - }); - } - } - - /** - * WebKit has a bug where it isn't possible to select image, hr or anchor elements - * by clicking on them so we need to fake that. - */ - function selectControlElements() { - editor.on('click', function(e) { - e = e.target; - - // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250 - // WebKit can't even do simple things like selecting an image - // Needs tobe the setBaseAndExtend or it will fail to select floated images - if (/^(IMG|HR)$/.test(e.nodeName)) { - selection.getSel().setBaseAndExtent(e, 0, e, 1); - } - - if (e.nodeName == 'A' && dom.hasClass(e, 'mce-item-anchor')) { - selection.select(e); - } - - editor.nodeChanged(); - }); - } - - /** - * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements. - * - * Fixes do backspace/delete on this: - *bla[ck
r]ed
- * - * Would become: - *bla|ed
- * - * Instead of: - *bla|ed
- */ - function removeStylesWhenDeletingAcrossBlockElements() { - function getAttributeApplyFunction() { - var template = dom.getAttribs(selection.getStart().cloneNode(false)); - - return function() { - var target = selection.getStart(); - - if (target !== editor.getBody()) { - dom.setAttrib(target, "style", null); - - each(template, function(attr) { - target.setAttributeNode(attr.cloneNode(true)); - }); - } - }; - } - - function isSelectionAcrossElements() { - return !selection.isCollapsed() && - dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock); - } - - editor.on('keypress', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - editor.getDoc().execCommand('delete', false, null); - applyAttributes(); - e.preventDefault(); - return false; - } - }); - - dom.bind(editor.getDoc(), 'cut', function(e) { - var applyAttributes; - - if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { - applyAttributes = getAttributeApplyFunction(); - - setTimeout(function() { - applyAttributes(); - }, 0); - } - }); - } - - /** - * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange - * event every 50ms since it would other wise update the UI when you type and it hogs the CPU. - */ - function selectionChangeNodeChanged() { - var lastRng, selectionTimer; - - editor.on('selectionchange', function() { - if (selectionTimer) { - clearTimeout(selectionTimer); - selectionTimer = 0; - } - - selectionTimer = window.setTimeout(function() { - if (editor.removed) { - return; - } - - var rng = selection.getRng(); - - // Compare the ranges to see if it was a real change or not - if (!lastRng || !RangeUtils.compareRanges(rng, lastRng)) { - editor.nodeChanged(); - lastRng = rng; - } - }, 50); - }); - } - - /** - * Screen readers on IE needs to have the role application set on the body. - */ - function ensureBodyHasRoleApplication() { - document.body.setAttribute("role", "application"); - } - - /** - * Backspacing into a table behaves differently depending upon browser type. - * Therefore, disable Backspace when cursor immediately follows a table. - */ - function disableBackspaceIntoATable() { - editor.on('keydown', function(e) { - if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { - if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) { - var previousSibling = selection.getNode().previousSibling; - if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") { - e.preventDefault(); - return false; - } - } - } - }); - } - - /** - * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this - * logic adds a \n before the BR so that it will get rendered. - */ - function addNewLinesBeforeBrInPre() { - // IE8+ rendering mode does the right thing with BR in PRE - if (getDocumentMode() > 7) { - return; - } - - // Enable display: none in area and add a specific class that hides all BR elements in PRE to - // avoid the caret from getting stuck at the BR elements while pressing the right arrow key - setEditorCommandState('RespectVisibilityInDesign', true); - editor.contentStyles.push('.mceHideBrInPre pre br {display: none}'); - dom.addClass(editor.getBody(), 'mceHideBrInPre'); - - // Adds a \n before all BR elements in PRE to get them visual - parser.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - - // Add \n before BR in PRE elements on older IE:s so the new lines get rendered - sibling = brElm.prev; - if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') { - sibling.value += '\n'; - } else { - brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n'; - } - } - } - }); - - // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible - serializer.addNodeFilter('pre', function(nodes) { - var i = nodes.length, brNodes, j, brElm, sibling; - - while (i--) { - brNodes = nodes[i].getAll('br'); - j = brNodes.length; - while (j--) { - brElm = brNodes[j]; - sibling = brElm.prev; - if (sibling && sibling.type == 3) { - sibling.value = sibling.value.replace(/\r?\n$/, ''); - } - } - } - }); - } - - /** - * Moves style width/height to attribute width/height when the user resizes an image on IE. - */ - function removePreSerializedStylesWhenSelectingControls() { - dom.bind(editor.getBody(), 'mouseup', function() { - var value, node = selection.getNode(); - - // Moved styles to attributes on IMG eements - if (node.nodeName == 'IMG') { - // Convert style width to width attribute - if ((value = dom.getStyle(node, 'width'))) { - dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'width', ''); - } - - // Convert style height to height attribute - if ((value = dom.getStyle(node, 'height'))) { - dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, '')); - dom.setStyle(node, 'height', ''); - } - } - }); - } - - /** - * Removes a blockquote when backspace is pressed at the beginning of it. - * - * For example: - *- * - * Becomes: - *|x
|x
- */ - function removeBlockQuoteOnBackSpace() { - // Add block quote deletion handler - editor.on('keydown', function(e) { - var rng, container, offset, root, parent; - - if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) { - return; - } - - rng = selection.getRng(); - container = rng.startContainer; - offset = rng.startOffset; - root = dom.getRoot(); - parent = container; - - if (!rng.collapsed || offset !== 0) { - return; - } - - while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) { - parent = parent.parentNode; - } - - // Is the cursor at the beginning of a blockquote? - if (parent.tagName === 'BLOCKQUOTE') { - // Remove the blockquote - editor.formatter.toggle('blockquote', null, parent); - - // Move the caret to the beginning of container - rng = dom.createRng(); - rng.setStart(container, 0); - rng.setEnd(container, 0); - selection.setRng(rng); - } - }); - } - - /** - * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc. - */ - function setGeckoEditingOptions() { - function setOpts() { - editor._refreshContentEditable(); - - setEditorCommandState("StyleWithCSS", false); - setEditorCommandState("enableInlineTableEditing", false); - - if (!settings.object_resizing) { - setEditorCommandState("enableObjectResizing", false); - } - } - - if (!settings.readonly) { - editor.on('BeforeExecCommand MouseDown', setOpts); - } - } - - /** - * Fixes a gecko link bug, when a link is placed at the end of block elements there is - * no way to move the caret behind the link. This fix adds a bogus br element after the link. - * - * For example this: - * - * - * Becomes this: - * - */ - function addBrAfterLastLinks() { - function fixLinks() { - each(dom.select('a'), function(node) { - var parentNode = node.parentNode, root = dom.getRoot(); - - if (parentNode.lastChild === node) { - while (parentNode && !dom.isBlock(parentNode)) { - if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { - return; - } - - parentNode = parentNode.parentNode; - } - - dom.add(parentNode, 'br', {'data-mce-bogus': 1}); - } - }); - } - - editor.on('SetContent ExecCommand', function(e) { - if (e.type == "setcontent" || e.command === 'mceInsertLink') { - fixLinks(); - } - }); - } - - /** - * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by - * default we want to change that behavior. - */ - function setDefaultBlockType() { - if (settings.forced_root_block) { - editor.on('init', function() { - setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block); - }); - } - } - - /** - * Removes ghost selections from images/tables on Gecko. - */ - function removeGhostSelection() { - editor.on('Undo Redo SetContent', function(e) { - if (!e.initial) { - editor.execCommand('mceRepaint'); - } - }); - } - - /** - * Deletes the selected image on IE instead of navigating to previous page. - */ - function deleteControlItemOnBackSpace() { - editor.on('keydown', function(e) { - var rng; - - if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) { - rng = editor.getDoc().selection.createRange(); - if (rng && rng.item) { - e.preventDefault(); - editor.undoManager.beforeChange(); - dom.remove(rng.item(0)); - editor.undoManager.add(); - } - } - }); - } - - /** - * IE10 doesn't properly render block elements with the right height until you add contents to them. - * This fixes that by adding a padding-right to all empty text block elements. - * See: https://connect.microsoft.com/IE/feedback/details/743881 - */ - function renderEmptyBlocksFix() { - var emptyBlocksCSS; - - // IE10+ - if (getDocumentMode() >= 10) { - emptyBlocksCSS = ''; - each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) { - emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty'; - }); - - editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}'); - } - } - - /** - * Old IE versions can't retain contents within noscript elements so this logic will store the contents - * as a attribute and the insert that value as it's raw text when the DOM is serialized. - */ - function keepNoScriptContents() { - if (getDocumentMode() < 9) { - parser.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode; - - while (i--) { - node = nodes[i]; - textNode = node.firstChild; - - if (textNode) { - node.attr('data-mce-innertext', textNode.value); - } - } - }); - - serializer.addNodeFilter('noscript', function(nodes) { - var i = nodes.length, node, textNode, value; - - while (i--) { - node = nodes[i]; - textNode = nodes[i].firstChild; - - if (textNode) { - textNode.value = Entities.decode(textNode.value); - } else { - // Old IE can't retain noscript value so an attribute is used to store it - value = node.attributes.map['data-mce-innertext']; - if (value) { - node.attr('data-mce-innertext', null); - textNode = new Node('#text', 3); - textNode.value = value; - textNode.raw = true; - node.append(textNode); - } - } - } - }); - } - } - - /** - * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode. - */ - function fixCaretSelectionOfDocumentElementOnIe() { - var doc = dom.doc, body = doc.body, started, startRng, htmlElm; - - // Return range from point or null if it failed - function rngFromPoint(x, y) { - var rng = body.createTextRange(); - - try { - rng.moveToPoint(x, y); - } catch (ex) { - // IE sometimes throws and exception, so lets just ignore it - rng = null; - } - - return rng; - } - - // Fires while the selection is changing - function selectionChange(e) { - var pointRng; - - // Check if the button is down or not - if (e.button) { - // Create range from mouse position - pointRng = rngFromPoint(e.x, e.y); - - if (pointRng) { - // Check if pointRange is before/after selection then change the endPoint - if (pointRng.compareEndPoints('StartToStart', startRng) > 0) { - pointRng.setEndPoint('StartToStart', startRng); - } else { - pointRng.setEndPoint('EndToEnd', startRng); - } - - pointRng.select(); - } - } else { - endSelection(); - } - } - - // Removes listeners - function endSelection() { - var rng = doc.selection.createRange(); - - // If the range is collapsed then use the last start range - if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) { - startRng.select(); - } - - dom.unbind(doc, 'mouseup', endSelection); - dom.unbind(doc, 'mousemove', selectionChange); - startRng = started = 0; - } - - // Make HTML element unselectable since we are going to handle selection by hand - doc.documentElement.unselectable = true; - - // Detect when user selects outside BODY - dom.bind(doc, 'mousedown contextmenu', function(e) { - if (e.target.nodeName === 'HTML') { - if (started) { - endSelection(); - } - - // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML - htmlElm = doc.documentElement; - if (htmlElm.scrollHeight > htmlElm.clientHeight) { - return; - } - - started = 1; - // Setup start position - startRng = rngFromPoint(e.x, e.y); - if (startRng) { - // Listen for selection change events - dom.bind(doc, 'mouseup', endSelection); - dom.bind(doc, 'mousemove', selectionChange); - - dom.getRoot().focus(); - startRng.select(); - } - } - }); - } - - /** - * Fixes selection issues where the caret can be placed between two inline elements like a|b - * this fix will lean the caret right into the closest inline element. - */ - function normalizeSelection() { - // Normalize selection for example a|a becomes a|a except for Ctrl+A since it selects everything - editor.on('keyup focusin mouseup', function(e) { - if (e.keyCode != 65 || !VK.metaKeyPressed(e)) { - selection.normalize(); - } - }, true); - } - - /** - * Forces Gecko to render a broken image icon if it fails to load an image. - */ - function showBrokenImageIcon() { - editor.contentStyles.push( - 'img:-moz-broken {' + - '-moz-force-broken-image-icon:1;' + - 'min-width:24px;' + - 'min-height:24px' + - '}' - ); - } - - /** - * iOS has a bug where it's impossible to type if the document has a touchstart event - * bound and the user touches the document while having the on screen keyboard visible. - * - * The touch event moves the focus to the parent document while having the caret inside the iframe - * this fix moves the focus back into the iframe document. - */ - function restoreFocusOnKeyDown() { - if (!editor.inline) { - editor.on('keydown', function() { - if (document.activeElement == document.body) { - editor.getWin().focus(); - } - }); - } - } - - /** - * IE 11 has an annoying issue where you can't move focus into the editor - * by clicking on the white area HTML element. We used to be able to to fix this with - * the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection - * object it's not possible anymore. So we need to hack in a ungly CSS to force the - * body to be at least 150px. If the user clicks the HTML element out side this 150px region - * we simply move the focus into the first paragraph. Not ideal since you loose the - * positioning of the caret but goot enough for most cases. - */ - function bodyHeight() { - if (!editor.inline) { - editor.contentStyles.push('body {min-height: 150px}'); - editor.on('click', function(e) { - if (e.target.nodeName == 'HTML') { - editor.getBody().focus(); - editor.selection.normalize(); - editor.nodeChanged(); - } - }); - } - } - - /** - * Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow. - * You might then loose all your work so we need to block that behavior and replace it with our own. - */ - function blockCmdArrowNavigation() { - if (Env.mac) { - editor.on('keydown', function(e) { - if (VK.metaKeyPressed(e) && (e.keyCode == 37 || e.keyCode == 39)) { - e.preventDefault(); - editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'word'); - } - }); - } - } - - /** - * Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin. - */ - function disableAutoUrlDetect() { - setEditorCommandState("AutoUrlDetect", false); - } - - /** - * IE 11 has a fantastic bug where it will produce two trailing BR elements to iframe bodies when - * the iframe is hidden by display: none on a parent container. The DOM is actually out of sync - * with innerHTML in this case. It's like IE adds shadow DOM BR elements that appears on innerHTML - * but not as the lastChild of the body. However is we add a BR element to the body then remove it - * it doesn't seem to add these BR elements makes sence right?! - * - * Example of what happens: text becomes text]*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/, '');
- });
- }
-
- self.load({initial: true, format: 'html'});
- self.startContent = self.getContent({format: 'raw'});
-
- /**
- * Is set to true after the editor instance has been initialized
- *
- * @property initialized
- * @type Boolean
- * @example
- * function isEditorInitialized(editor) {
- * return editor && editor.initialized;
- * }
- */
- self.initialized = true;
-
- each(self._pendingNativeEvents, function(name) {
- self.dom.bind(getEventTarget(self, name), name, function(e) {
- self.fire(e.type, e);
- });
- });
-
- self.fire('init');
- self.focus(true);
- self.nodeChanged({initial: true});
- self.execCallback('init_instance_callback', self);
-
- // Add editor specific CSS styles
- if (self.contentStyles.length > 0) {
- contentCssText = '';
-
- each(self.contentStyles, function(style) {
- contentCssText += style + "\r\n";
- });
-
- self.dom.addStyle(contentCssText);
- }
-
- // Load specified content CSS last
- each(self.contentCSS, function(cssUrl) {
- if (!self.loadedCSS[cssUrl]) {
- self.dom.loadCSS(cssUrl);
- self.loadedCSS[cssUrl] = true;
- }
- });
-
- // Handle auto focus
- if (settings.auto_focus) {
- setTimeout(function () {
- var ed = self.editorManager.get(settings.auto_focus);
-
- ed.selection.select(ed.getBody(), 1);
- ed.selection.collapse(1);
- ed.getBody().focus();
- ed.getWin().focus();
- }, 100);
- }
-
- // Clean up references for IE
- targetElm = doc = body = null;
- },
-
- /**
- * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
- * it will also place DOM focus inside the editor.
- *
- * @method focus
- * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
- */
- focus: function(skip_focus) {
- var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
- var controlElm, doc = self.getDoc(), body;
-
- if (!skip_focus) {
- // Get selected control element
- rng = selection.getRng();
- if (rng.item) {
- controlElm = rng.item(0);
- }
-
- self._refreshContentEditable();
-
- // Focus the window iframe
- if (!contentEditable) {
- // WebKit needs this call to fire focusin event properly see #5948
- // But Opera pre Blink engine will produce an empty selection so skip Opera
- if (!Env.opera) {
- self.getBody().focus();
- }
-
- self.getWin().focus();
- }
-
- // Focus the body as well since it's contentEditable
- if (isGecko || contentEditable) {
- body = self.getBody();
-
- // Check for setActive since it doesn't scroll to the element
- if (body.setActive && Env.ie < 11) {
- body.setActive();
- } else {
- body.focus();
- }
-
- if (contentEditable) {
- selection.normalize();
- }
- }
-
- // Restore selected control element
- // This is needed when for example an image is selected within a
- // layer a call to focus will then remove the control selection
- if (controlElm && controlElm.ownerDocument == doc) {
- rng = doc.body.createControlRange();
- rng.addElement(controlElm);
- rng.select();
- }
- }
-
- if (self.editorManager.activeEditor != self) {
- if ((oed = self.editorManager.activeEditor)) {
- oed.fire('deactivate', {relatedTarget: self});
- }
-
- self.fire('activate', {relatedTarget: oed});
- }
-
- self.editorManager.activeEditor = self;
- },
-
- /**
- * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
- * There new event model is a better way to add callback so this method might be removed in the future.
- *
- * @method execCallback
- * @param {String} name Name of the callback to execute.
- * @return {Object} Return value passed from callback function.
- */
- execCallback: function(name) {
- var self = this, callback = self.settings[name], scope;
-
- if (!callback) {
- return;
- }
-
- // Look through lookup
- if (self.callbackLookup && (scope = self.callbackLookup[name])) {
- callback = scope.func;
- scope = scope.scope;
- }
-
- if (typeof(callback) === 'string') {
- scope = callback.replace(/\.\w+$/, '');
- scope = scope ? resolve(scope) : 0;
- callback = resolve(callback);
- self.callbackLookup = self.callbackLookup || {};
- self.callbackLookup[name] = {func: callback, scope: scope};
- }
-
- return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
- },
-
- /**
- * Translates the specified string by replacing variables with language pack items it will also check if there is
- * a key mathcin the input.
- *
- * @method translate
- * @param {String} text String to translate by the language pack data.
- * @return {String} Translated string.
- */
- translate: function(text) {
- var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
-
- if (!text) {
- return '';
- }
-
- return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
- return i18n.data[lang + '.' + b] || '{#' + b + '}';
- });
- },
-
- /**
- * Returns a language pack item by name/key.
- *
- * @method getLang
- * @param {String} name Name/key to get from the language pack.
- * @param {String} defaultVal Optional default value to retrive.
- */
- getLang: function(name, defaultVal) {
- return (
- this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
- (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
- );
- },
-
- /**
- * Returns a configuration parameter by name.
- *
- * @method getParam
- * @param {String} name Configruation parameter to retrive.
- * @param {String} defaultVal Optional default value to return.
- * @param {String} type Optional type parameter.
- * @return {String} Configuration parameter value or default value.
- * @example
- * // Returns a specific config value from the currently active editor
- * var someval = tinymce.activeEditor.getParam('myvalue');
- *
- * // Returns a specific config value from a specific editor instance by id
- * var someval2 = tinymce.get('my_editor').getParam('myvalue');
- */
- getParam: function(name, defaultVal, type) {
- var value = name in this.settings ? this.settings[name] : defaultVal, output;
-
- if (type === 'hash') {
- output = {};
-
- if (typeof(value) === 'string') {
- each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
- value = value.split('=');
-
- if (value.length > 1) {
- output[trim(value[0])] = trim(value[1]);
- } else {
- output[trim(value[0])] = trim(value);
- }
- });
- } else {
- output = value;
- }
-
- return output;
- }
-
- return value;
- },
-
- /**
- * Distpaches out a onNodeChange event to all observers. This method should be called when you
- * need to update the UI states or element path etc.
- *
- * @method nodeChanged
- */
- nodeChanged: function() {
- var self = this, selection = self.selection, node, parents, root;
-
- // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
- if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
- // Get start node
- root = self.getBody();
- node = selection.getStart() || root;
- node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
-
- // Edge case for
|
\xA0
').append(targetClone); + newRange.setStartAfter($realSelectionContainer[0].firstChild.firstChild); + newRange.setEndAfter(targetClone); + } else { + $realSelectionContainer.empty().append(nbsp).append(targetClone).append(nbsp); + newRange.setStart($realSelectionContainer[0].firstChild, 1); + newRange.setEnd($realSelectionContainer[0].lastChild, 0); + } + $realSelectionContainer.css({ top: dom.getPos(node, editor.getBody()).y }); + $realSelectionContainer[0].focus(); + var sel = selection.getSel(); + sel.removeAllRanges(); + sel.addRange(newRange); + return newRange; + }; + var selectElement = function (elm) { + var targetClone = elm.cloneNode(true); + var e = editor.fire('ObjectSelected', { + target: elm, + targetClone: targetClone + }); + if (e.isDefaultPrevented()) { + return null; + } + var range = setupOffscreenSelection(elm, e.targetClone, targetClone); + var nodeElm = SugarElement.fromDom(elm); + each(descendants$1(SugarElement.fromDom(editor.getBody()), '*[data-mce-selected]'), function (elm) { + if (!eq$2(nodeElm, elm)) { + remove$1(elm, elementSelectionAttr); + } + }); + if (!dom.getAttrib(elm, elementSelectionAttr)) { + elm.setAttribute(elementSelectionAttr, '1'); + } + selectedElement = elm; + hideFakeCaret(); + return range; + }; + var setElementSelection = function (range, forward) { + if (!range) { + return null; + } + if (range.collapsed) { + if (!isRangeInCaretContainer(range)) { + var dir = forward ? 1 : -1; + var caretPosition = getNormalizedRangeEndPoint(dir, rootNode, range); + var beforeNode = caretPosition.getNode(!forward); + if (isFakeCaretTarget(beforeNode)) { + return showCaret(dir, beforeNode, forward ? !caretPosition.isAtEnd() : false, false); + } + var afterNode = caretPosition.getNode(forward); + if (isFakeCaretTarget(afterNode)) { + return showCaret(dir, afterNode, forward ? false : !caretPosition.isAtEnd(), false); + } + } + return null; + } + var startContainer = range.startContainer; + var startOffset = range.startOffset; + var endOffset = range.endOffset; + if (startContainer.nodeType === 3 && startOffset === 0 && isContentEditableFalse$b(startContainer.parentNode)) { + startContainer = startContainer.parentNode; + startOffset = dom.nodeIndex(startContainer); + startContainer = startContainer.parentNode; + } + if (startContainer.nodeType !== 1) { + return null; + } + if (endOffset === startOffset + 1 && startContainer === range.endContainer) { + var node = startContainer.childNodes[startOffset]; + if (isFakeSelectionTargetElement(node)) { + return selectElement(node); + } + } + return null; + }; + var removeElementSelection = function () { + if (selectedElement) { + selectedElement.removeAttribute(elementSelectionAttr); + } + descendant(SugarElement.fromDom(editor.getBody()), '#' + realSelectionId).each(remove); + selectedElement = null; + }; + var destroy = function () { + fakeCaret.destroy(); + selectedElement = null; + }; + var hideFakeCaret = function () { + fakeCaret.hide(); + }; + if (Env.ceFalse) { + registerEvents(); + } + return { + showCaret: showCaret, + showBlockCaretContainer: showBlockCaretContainer, + hideFakeCaret: hideFakeCaret, + destroy: destroy + }; + }; + + var Quirks = function (editor) { + var each = Tools.each; + var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection, parser = editor.parser; + var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit; + var mceInternalUrlPrefix = 'data:text/mce-internal,'; + var mceInternalDataType = isIE ? 'Text' : 'URL'; + var setEditorCommandState = function (cmd, state) { + try { + editor.getDoc().execCommand(cmd, false, state); + } catch (ex) { + } + }; + var isDefaultPrevented = function (e) { + return e.isDefaultPrevented(); + }; + var setMceInternalContent = function (e) { + var selectionHtml, internalContent; + if (e.dataTransfer) { + if (editor.selection.isCollapsed() && e.target.tagName === 'IMG') { + selection.select(e.target); + } + selectionHtml = editor.selection.getContent(); + if (selectionHtml.length > 0) { + internalContent = mceInternalUrlPrefix + escape(editor.id) + ',' + escape(selectionHtml); + e.dataTransfer.setData(mceInternalDataType, internalContent); + } + } + }; + var getMceInternalContent = function (e) { + var internalContent; + if (e.dataTransfer) { + internalContent = e.dataTransfer.getData(mceInternalDataType); + if (internalContent && internalContent.indexOf(mceInternalUrlPrefix) >= 0) { + internalContent = internalContent.substr(mceInternalUrlPrefix.length).split(','); + return { + id: unescape(internalContent[0]), + html: unescape(internalContent[1]) + }; + } + } + return null; + }; + var insertClipboardContents = function (content, internal) { + if (editor.queryCommandSupported('mceInsertClipboardContent')) { + editor.execCommand('mceInsertClipboardContent', false, { + content: content, + internal: internal + }); + } else { + editor.execCommand('mceInsertContent', false, content); + } + }; + var emptyEditorWhenDeleting = function () { + var serializeRng = function (rng) { + var body = dom.create('body'); + var contents = rng.cloneContents(); + body.appendChild(contents); + return selection.serializer.serialize(body, { format: 'html' }); + }; + var allContentsSelected = function (rng) { + var selection = serializeRng(rng); + var allRng = dom.createRng(); + allRng.selectNode(editor.getBody()); + var allSelection = serializeRng(allRng); + return selection === allSelection; + }; + editor.on('keydown', function (e) { + var keyCode = e.keyCode; + var isCollapsed, body; + if (!isDefaultPrevented(e) && (keyCode === DELETE || keyCode === BACKSPACE)) { + isCollapsed = editor.selection.isCollapsed(); + body = editor.getBody(); + if (isCollapsed && !dom.isEmpty(body)) { + return; + } + if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) { + return; + } + e.preventDefault(); + editor.setContent(''); + if (body.firstChild && dom.isBlock(body.firstChild)) { + editor.selection.setCursorLocation(body.firstChild, 0); + } else { + editor.selection.setCursorLocation(body, 0); + } + editor.nodeChanged(); + } + }); + }; + var selectAll = function () { + editor.shortcuts.add('meta+a', null, 'SelectAll'); + }; + var inputMethodFocus = function () { + if (!editor.inline) { + dom.bind(editor.getDoc(), 'mousedown mouseup', function (e) { + var rng; + if (e.target === editor.getDoc().documentElement) { + rng = selection.getRng(); + editor.getBody().focus(); + if (e.type === 'mousedown') { + if (isCaretContainer(rng.startContainer)) { + return; + } + selection.placeCaretAt(e.clientX, e.clientY); + } else { + selection.setRng(rng); + } + } + }); + } + }; + var removeHrOnBackspace = function () { + editor.on('keydown', function (e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (!editor.getBody().getElementsByTagName('hr').length) { + return; + } + if (selection.isCollapsed() && selection.getRng().startOffset === 0) { + var node = selection.getNode(); + var previousSibling = node.previousSibling; + if (node.nodeName === 'HR') { + dom.remove(node); + e.preventDefault(); + return; + } + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'hr') { + dom.remove(previousSibling); + e.preventDefault(); + } + } + } + }); + }; + var focusBody = function () { + if (!Range.prototype.getClientRects) { + editor.on('mousedown', function (e) { + if (!isDefaultPrevented(e) && e.target.nodeName === 'HTML') { + var body_1 = editor.getBody(); + body_1.blur(); + Delay.setEditorTimeout(editor, function () { + body_1.focus(); + }); + } + }); + } + }; + var selectControlElements = function () { + editor.on('click', function (e) { + var target = e.target; + if (/^(IMG|HR)$/.test(target.nodeName) && dom.getContentEditableParent(target) !== 'false') { + e.preventDefault(); + editor.selection.select(target); + editor.nodeChanged(); + } + if (target.nodeName === 'A' && dom.hasClass(target, 'mce-item-anchor')) { + e.preventDefault(); + selection.select(target); + } + }); + }; + var removeStylesWhenDeletingAcrossBlockElements = function () { + var getAttributeApplyFunction = function () { + var template = dom.getAttribs(selection.getStart().cloneNode(false)); + return function () { + var target = selection.getStart(); + if (target !== editor.getBody()) { + dom.setAttrib(target, 'style', null); + each(template, function (attr) { + target.setAttributeNode(attr.cloneNode(true)); + }); + } + }; + }; + var isSelectionAcrossElements = function () { + return !selection.isCollapsed() && dom.getParent(selection.getStart(), dom.isBlock) !== dom.getParent(selection.getEnd(), dom.isBlock); + }; + editor.on('keypress', function (e) { + var applyAttributes; + if (!isDefaultPrevented(e) && (e.keyCode === 8 || e.keyCode === 46) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + editor.getDoc().execCommand('delete', false, null); + applyAttributes(); + e.preventDefault(); + return false; + } + }); + dom.bind(editor.getDoc(), 'cut', function (e) { + var applyAttributes; + if (!isDefaultPrevented(e) && isSelectionAcrossElements()) { + applyAttributes = getAttributeApplyFunction(); + Delay.setEditorTimeout(editor, function () { + applyAttributes(); + }); + } + }); + }; + var disableBackspaceIntoATable = function () { + editor.on('keydown', function (e) { + if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) { + if (selection.isCollapsed() && selection.getRng().startOffset === 0) { + var previousSibling = selection.getNode().previousSibling; + if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === 'table') { + e.preventDefault(); + return false; + } + } + } + }); + }; + var removeBlockQuoteOnBackSpace = function () { + editor.on('keydown', function (e) { + var rng, parent; + if (isDefaultPrevented(e) || e.keyCode !== VK.BACKSPACE) { + return; + } + rng = selection.getRng(); + var container = rng.startContainer; + var offset = rng.startOffset; + var root = dom.getRoot(); + parent = container; + if (!rng.collapsed || offset !== 0) { + return; + } + while (parent && parent.parentNode && parent.parentNode.firstChild === parent && parent.parentNode !== root) { + parent = parent.parentNode; + } + if (parent.tagName === 'BLOCKQUOTE') { + editor.formatter.toggle('blockquote', null, parent); + rng = dom.createRng(); + rng.setStart(container, 0); + rng.setEnd(container, 0); + selection.setRng(rng); + } + }); + }; + var setGeckoEditingOptions = function () { + var setOpts = function () { + setEditorCommandState('StyleWithCSS', false); + setEditorCommandState('enableInlineTableEditing', false); + if (!getObjectResizing(editor)) { + setEditorCommandState('enableObjectResizing', false); + } + }; + if (!isReadOnly(editor)) { + editor.on('BeforeExecCommand mousedown', setOpts); + } + }; + var addBrAfterLastLinks = function () { + var fixLinks = function () { + each(dom.select('a'), function (node) { + var parentNode = node.parentNode; + var root = dom.getRoot(); + if (parentNode.lastChild === node) { + while (parentNode && !dom.isBlock(parentNode)) { + if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) { + return; + } + parentNode = parentNode.parentNode; + } + dom.add(parentNode, 'br', { 'data-mce-bogus': 1 }); + } + }); + }; + editor.on('SetContent ExecCommand', function (e) { + if (e.type === 'setcontent' || e.command === 'mceInsertLink') { + fixLinks(); + } + }); + }; + var setDefaultBlockType = function () { + if (getForcedRootBlock(editor)) { + editor.on('init', function () { + setEditorCommandState('DefaultParagraphSeparator', getForcedRootBlock(editor)); + }); + } + }; + var normalizeSelection = function () { + editor.on('keyup focusin mouseup', function (e) { + if (!VK.modifierPressed(e)) { + selection.normalize(); + } + }, true); + }; + var showBrokenImageIcon = function () { + editor.contentStyles.push('img:-moz-broken {' + '-moz-force-broken-image-icon:1;' + 'min-width:24px;' + 'min-height:24px' + '}'); + }; + var restoreFocusOnKeyDown = function () { + if (!editor.inline) { + editor.on('keydown', function () { + if (document.activeElement === document.body) { + editor.getWin().focus(); + } + }); + } + }; + var bodyHeight = function () { + if (!editor.inline) { + editor.contentStyles.push('body {min-height: 150px}'); + editor.on('click', function (e) { + var rng; + if (e.target.nodeName === 'HTML') { + if (Env.ie > 11) { + editor.getBody().focus(); + return; + } + rng = editor.selection.getRng(); + editor.getBody().focus(); + editor.selection.setRng(rng); + editor.selection.normalize(); + editor.nodeChanged(); + } + }); + } + }; + var blockCmdArrowNavigation = function () { + if (Env.mac) { + editor.on('keydown', function (e) { + if (VK.metaKeyPressed(e) && !e.shiftKey && (e.keyCode === 37 || e.keyCode === 39)) { + e.preventDefault(); + var selection_1 = editor.selection.getSel(); + selection_1.modify('move', e.keyCode === 37 ? 'backward' : 'forward', 'lineboundary'); + } + }); + } + }; + var disableAutoUrlDetect = function () { + setEditorCommandState('AutoUrlDetect', false); + }; + var tapLinksAndImages = function () { + editor.on('click', function (e) { + var elm = e.target; + do { + if (elm.tagName === 'A') { + e.preventDefault(); + return; + } + } while (elm = elm.parentNode); + }); + editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}'); + }; + var blockFormSubmitInsideEditor = function () { + editor.on('init', function () { + editor.dom.bind(editor.getBody(), 'submit', function (e) { + e.preventDefault(); + }); + }); + }; + var removeAppleInterchangeBrs = function () { + parser.addNodeFilter('br', function (nodes) { + var i = nodes.length; + while (i--) { + if (nodes[i].attr('class') === 'Apple-interchange-newline') { + nodes[i].remove(); + } + } + }); + }; + var ieInternalDragAndDrop = function () { + editor.on('dragstart', function (e) { + setMceInternalContent(e); + }); + editor.on('drop', function (e) { + if (!isDefaultPrevented(e)) { + var internalContent = getMceInternalContent(e); + if (internalContent && internalContent.id !== editor.id) { + e.preventDefault(); + var rng = fromPoint$1(e.x, e.y, editor.getDoc()); + selection.setRng(rng); + insertClipboardContents(internalContent.html, true); + } + } + }); + }; + var refreshContentEditable = function () { + }; + var isHidden = function () { + if (!isGecko || editor.removed) { + return false; + } + var sel = editor.selection.getSel(); + return !sel || !sel.rangeCount || sel.rangeCount === 0; + }; + removeBlockQuoteOnBackSpace(); + emptyEditorWhenDeleting(); + if (!Env.windowsPhone) { + normalizeSelection(); + } + if (isWebKit) { + inputMethodFocus(); + selectControlElements(); + setDefaultBlockType(); + blockFormSubmitInsideEditor(); + disableBackspaceIntoATable(); + removeAppleInterchangeBrs(); + if (Env.iOS) { + restoreFocusOnKeyDown(); + bodyHeight(); + tapLinksAndImages(); + } else { + selectAll(); + } + } + if (Env.ie >= 11) { + bodyHeight(); + disableBackspaceIntoATable(); + } + if (Env.ie) { + selectAll(); + disableAutoUrlDetect(); + ieInternalDragAndDrop(); + } + if (isGecko) { + removeHrOnBackspace(); + focusBody(); + removeStylesWhenDeletingAcrossBlockElements(); + setGeckoEditingOptions(); + addBrAfterLastLinks(); + showBrokenImageIcon(); + blockCmdArrowNavigation(); + disableBackspaceIntoATable(); + } + return { + refreshContentEditable: refreshContentEditable, + isHidden: isHidden + }; + }; + + var DOM$4 = DOMUtils$1.DOM; + var appendStyle = function (editor, text) { + var body = SugarElement.fromDom(editor.getBody()); + var container = getStyleContainer(getRootNode(body)); + var style = SugarElement.fromTag('style'); + set(style, 'type', 'text/css'); + append(style, SugarElement.fromText(text)); + append(container, style); + editor.on('remove', function () { + remove(style); + }); + }; + var getRootName = function (editor) { + return editor.inline ? editor.getElement().nodeName.toLowerCase() : undefined; + }; + var removeUndefined = function (obj) { + return filter$1(obj, function (v) { + return isUndefined(v) === false; + }); + }; + var mkParserSettings = function (editor) { + var settings = editor.settings; + var blobCache = editor.editorUpload.blobCache; + return removeUndefined({ + allow_conditional_comments: settings.allow_conditional_comments, + allow_html_data_urls: settings.allow_html_data_urls, + allow_html_in_named_anchor: settings.allow_html_in_named_anchor, + allow_script_urls: settings.allow_script_urls, + allow_unsafe_link_target: settings.allow_unsafe_link_target, + convert_fonts_to_spans: settings.convert_fonts_to_spans, + fix_list_elements: settings.fix_list_elements, + font_size_legacy_values: settings.font_size_legacy_values, + forced_root_block: settings.forced_root_block, + forced_root_block_attrs: settings.forced_root_block_attrs, + padd_empty_with_br: settings.padd_empty_with_br, + preserve_cdata: settings.preserve_cdata, + remove_trailing_brs: settings.remove_trailing_brs, + inline_styles: settings.inline_styles, + root_name: getRootName(editor), + validate: true, + blob_cache: blobCache, + images_dataimg_filter: settings.images_dataimg_filter + }); + }; + var mkSerializerSettings = function (editor) { + var settings = editor.settings; + return __assign(__assign({}, mkParserSettings(editor)), removeUndefined({ + url_converter: settings.url_converter, + url_converter_scope: settings.url_converter_scope, + element_format: settings.element_format, + entities: settings.entities, + entity_encoding: settings.entity_encoding, + indent: settings.indent, + indent_after: settings.indent_after, + indent_before: settings.indent_before, + block_elements: settings.block_elements, + boolean_attributes: settings.boolean_attributes, + custom_elements: settings.custom_elements, + extended_valid_elements: settings.extended_valid_elements, + invalid_elements: settings.invalid_elements, + invalid_styles: settings.invalid_styles, + move_caret_before_on_enter_elements: settings.move_caret_before_on_enter_elements, + non_empty_elements: settings.non_empty_elements, + schema: settings.schema, + self_closing_elements: settings.self_closing_elements, + short_ended_elements: settings.short_ended_elements, + special: settings.special, + text_block_elements: settings.text_block_elements, + text_inline_elements: settings.text_inline_elements, + valid_children: settings.valid_children, + valid_classes: settings.valid_classes, + valid_elements: settings.valid_elements, + valid_styles: settings.valid_styles, + verify_html: settings.verify_html, + whitespace_elements: settings.whitespace_elements + })); + }; + var createParser = function (editor) { + var parser = DomParser(mkParserSettings(editor), editor.schema); + parser.addAttributeFilter('src,href,style,tabindex', function (nodes, name) { + var i = nodes.length, node, value; + var dom = editor.dom; + var internalName = 'data-mce-' + name; + while (i--) { + node = nodes[i]; + value = node.attr(name); + if (value && !node.attr(internalName)) { + if (value.indexOf('data:') === 0 || value.indexOf('blob:') === 0) { + continue; + } + if (name === 'style') { + value = dom.serializeStyle(dom.parseStyle(value), node.name); + if (!value.length) { + value = null; + } + node.attr(internalName, value); + node.attr(name, value); + } else if (name === 'tabindex') { + node.attr(internalName, value); + node.attr(name, null); + } else { + node.attr(internalName, editor.convertURL(value, name, node.name)); + } + } + } + }); + parser.addNodeFilter('script', function (nodes) { + var i = nodes.length; + while (i--) { + var node = nodes[i]; + var type = node.attr('type') || 'no/type'; + if (type.indexOf('mce-') !== 0) { + node.attr('type', 'mce-' + type); + } + } + }); + if (editor.settings.preserve_cdata) { + parser.addNodeFilter('#cdata', function (nodes) { + var i = nodes.length; + while (i--) { + var node = nodes[i]; + node.type = 8; + node.name = '#comment'; + node.value = '[CDATA[' + editor.dom.encode(node.value) + ']]'; + } + }); + } + parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function (nodes) { + var i = nodes.length; + var nonEmptyElements = editor.schema.getNonEmptyElements(); + while (i--) { + var node = nodes[i]; + if (node.isEmpty(nonEmptyElements) && node.getAll('br').length === 0) { + node.append(new AstNode('br', 1)).shortEnded = true; + } + } + }); + return parser; + }; + var autoFocus = function (editor) { + if (editor.settings.auto_focus) { + Delay.setEditorTimeout(editor, function () { + var focusEditor; + if (editor.settings.auto_focus === true) { + focusEditor = editor; + } else { + focusEditor = editor.editorManager.get(editor.settings.auto_focus); + } + if (!focusEditor.destroyed) { + focusEditor.focus(); + } + }, 100); + } + }; + var moveSelectionToFirstCaretPosition = function (editor) { + var root = editor.dom.getRoot(); + if (!editor.inline && (!hasAnyRanges(editor) || editor.selection.getStart(true) === root)) { + firstPositionIn(root).each(function (pos) { + var node = pos.getNode(); + var caretPos = isTable(node) ? firstPositionIn(node).getOr(pos) : pos; + if (Env.browser.isIE()) { + storeNative(editor, caretPos.toRange()); + } else { + editor.selection.setRng(caretPos.toRange()); + } + }); + } + }; + var initEditor = function (editor) { + editor.bindPendingEventDelegates(); + editor.initialized = true; + fireInit(editor); + editor.focus(true); + moveSelectionToFirstCaretPosition(editor); + editor.nodeChanged({ initial: true }); + editor.execCallback('init_instance_callback', editor); + autoFocus(editor); + }; + var getStyleSheetLoader = function (editor) { + return editor.inline ? editor.ui.styleSheetLoader : editor.dom.styleSheetLoader; + }; + var loadContentCss = function (editor, css) { + var styleSheetLoader = getStyleSheetLoader(editor); + var loaded = function () { + editor.on('remove', function () { + return styleSheetLoader.unloadAll(css); + }); + initEditor(editor); + }; + styleSheetLoader.loadAll(css, loaded, loaded); + }; + var preInit = function (editor, rtcMode) { + var settings = editor.settings, doc = editor.getDoc(), body = editor.getBody(); + if (!settings.browser_spellcheck && !settings.gecko_spellcheck) { + doc.body.spellcheck = false; + DOM$4.setAttrib(body, 'spellcheck', 'false'); + } + editor.quirks = Quirks(editor); + firePostRender(editor); + var directionality = getDirectionality(editor); + if (directionality !== undefined) { + body.dir = directionality; + } + if (settings.protect) { + editor.on('BeforeSetContent', function (e) { + Tools.each(settings.protect, function (pattern) { + e.content = e.content.replace(pattern, function (str) { + return ''; + }); + }); + }); + } + editor.on('SetContent', function () { + editor.addVisual(editor.getBody()); + }); + if (rtcMode === false) { + editor.load({ + initial: true, + format: 'html' + }); + } + editor.startContent = editor.getContent({ format: 'raw' }); + editor.on('compositionstart compositionend', function (e) { + editor.composing = e.type === 'compositionstart'; + }); + if (editor.contentStyles.length > 0) { + var contentCssText_1 = ''; + Tools.each(editor.contentStyles, function (style) { + contentCssText_1 += style + '\r\n'; + }); + editor.dom.addStyle(contentCssText_1); + } + loadContentCss(editor, editor.contentCSS); + if (settings.content_style) { + appendStyle(editor, settings.content_style); + } + }; + var initContentBody = function (editor, skipWrite) { + var settings = editor.settings; + var targetElm = editor.getElement(); + var doc = editor.getDoc(); + if (!settings.inline) { + editor.getElement().style.visibility = editor.orgVisibility; + } + if (!skipWrite && !editor.inline) { + doc.open(); + doc.write(editor.iframeHTML); + doc.close(); + } + if (editor.inline) { + DOM$4.addClass(targetElm, 'mce-content-body'); + editor.contentDocument = doc = document; + editor.contentWindow = window; + editor.bodyElement = targetElm; + editor.contentAreaContainer = targetElm; + } + var body = editor.getBody(); + body.disabled = true; + editor.readonly = !!settings.readonly; + if (!editor.readonly) { + if (editor.inline && DOM$4.getStyle(body, 'position', true) === 'static') { + body.style.position = 'relative'; + } + body.contentEditable = editor.getParam('content_editable_state', true); + } + body.disabled = false; + editor.editorUpload = EditorUpload(editor); + editor.schema = Schema(settings); + editor.dom = DOMUtils$1(doc, { + keep_values: true, + url_converter: editor.convertURL, + url_converter_scope: editor, + hex_colors: settings.force_hex_style_colors, + update_styles: true, + root_element: editor.inline ? editor.getBody() : null, + collect: function () { + return editor.inline; + }, + schema: editor.schema, + contentCssCors: shouldUseContentCssCors(editor), + referrerPolicy: getReferrerPolicy(editor), + onSetAttrib: function (e) { + editor.fire('SetAttrib', e); + } + }); + editor.parser = createParser(editor); + editor.serializer = DomSerializer(mkSerializerSettings(editor), editor); + editor.selection = EditorSelection(editor.dom, editor.getWin(), editor.serializer, editor); + editor.annotator = Annotator(editor); + editor.formatter = Formatter(editor); + editor.undoManager = UndoManager(editor); + editor._nodeChangeDispatcher = new NodeChange(editor); + editor._selectionOverrides = SelectionOverrides(editor); + setup$9(editor); + setup$j(editor); + if (!isRtc(editor)) { + setup$k(editor); + } + var caret = setup$i(editor); + setup$8(editor, caret); + setup$a(editor); + setup$7(editor); + firePreInit(editor); + setup$4(editor).fold(function () { + preInit(editor, false); + }, function (loadingRtc) { + editor.setProgressState(true); + loadingRtc.then(function (rtcMode) { + editor.setProgressState(false); + preInit(editor, rtcMode); + }); + }); + }; + + var DOM$5 = DOMUtils$1.DOM; + var relaxDomain = function (editor, ifr) { + if (document.domain !== window.location.hostname && Env.browser.isIE()) { + var bodyUuid = uuid('mce'); + editor[bodyUuid] = function () { + initContentBody(editor); + }; + var domainRelaxUrl = 'javascript:(function(){' + 'document.open();document.domain="' + document.domain + '";' + 'var ed = window.parent.tinymce.get("' + editor.id + '");document.write(ed.iframeHTML);' + 'document.close();ed.' + bodyUuid + '(true);})()'; + DOM$5.setAttrib(ifr, 'src', domainRelaxUrl); + return true; + } + return false; + }; + var createIframeElement = function (id, title, height, customAttrs) { + var iframe = SugarElement.fromTag('iframe'); + setAll(iframe, customAttrs); + setAll(iframe, { + id: id + '_ifr', + frameBorder: '0', + allowTransparency: 'true', + title: title + }); + add$3(iframe, 'tox-edit-area__iframe'); + return iframe; + }; + var getIframeHtml = function (editor) { + var iframeHTML = getDocType(editor) + ''; + if (getDocumentBaseUrl(editor) !== editor.documentBaseUrl) { + iframeHTML += ']*>( | |\s|\u00a0|)<\/p>[\r\n]*|
[\r\n]*)$/,"")}),n.load({initial:!0,format:"html"}),n.startContent=n.getContent({format:"raw"}),n.initialized=!0,R(n._pendingNativeEvents,function(e){n.dom.bind(_(n,e),e,function(e){n.fire(e.type,e)})}),n.fire("init"),n.focus(!0),n.nodeChanged({initial:!0}),n.execCallback("init_instance_callback",n),n.contentStyles.length>0&&(h="",R(n.contentStyles,function(e){h+=e+"\r\n"}),n.dom.addStyle(h)),R(n.contentCSS,function(e){n.loadedCSS[e]||(n.dom.loadCSS(e),n.loadedCSS[e]=!0)}),o.auto_focus&&setTimeout(function(){var e=n.editorManager.get(o.auto_focus);e.selection.select(e.getBody(),1),e.selection.collapse(1),e.getBody().focus(),e.getWin().focus()},100),f=p=m=null},focus:function(e){var t,n=this,r=n.selection,i=n.settings.content_editable,o,a,s=n.getDoc(),l;e||(o=r.getRng(),o.item&&(a=o.item(0)),n._refreshContentEditable(),i||(b.opera||n.getBody().focus(),n.getWin().focus()),(H||i)&&(l=n.getBody(),l.setActive&&b.ie<11?l.setActive():l.focus(),i&&r.normalize()),a&&a.ownerDocument==s&&(o=s.body.createControlRange(),o.addElement(a),o.select())),n.editorManager.activeEditor!=n&&((t=n.editorManager.activeEditor)&&t.fire("deactivate",{relatedTarget:n}),n.fire("activate",{relatedTarget:t})),n.editorManager.activeEditor=n},execCallback:function(e){var t=this,n=t.settings[e],r;if(n)return t.callbackLookup&&(r=t.callbackLookup[e])&&(n=r.func,r=r.scope),"string"==typeof n&&(r=n.replace(/\.\w+$/,""),r=r?D(r):0,n=D(n),t.callbackLookup=t.callbackLookup||{},t.callbackLookup[e]={func:n,scope:r}),n.apply(r||t,Array.prototype.slice.call(arguments,1))},translate:function(e){var t=this.settings.language||"en",n=this.editorManager.i18n;return e?n.data[t+"."+e]||e.replace(/\{\#([^\}]+)\}/g,function(e,r){return n.data[t+"."+r]||"{#"+r+"}"}):""},getLang:function(e,n){return this.editorManager.i18n.data[(this.settings.language||"en")+"."+e]||(n!==t?n:"{#"+e+"}")},getParam:function(e,t,n){var r=e in this.settings?this.settings[e]:t,i;return"hash"===n?(i={},"string"==typeof r?R(r.split(r.indexOf("=")>0?/[;,](?![^=;,]*(?:[;,]|$))/:","),function(e){e=e.split("="),i[L(e[0])]=L(e.length>1?e[1]:e)}):i=r,i):r},nodeChanged:function(){var e=this,t=e.selection,n,r,i;!e.initialized||e.settings.disable_nodechange||e.settings.readonly||(i=e.getBody(),n=t.getStart()||i,n=P&&n.ownerDocument!=e.getDoc()?e.getBody():n,"IMG"==n.nodeName&&t.isCollapsed()&&(n=n.parentNode),r=[],e.dom.getParent(n,function(e){return e===i?!0:void r.push(e)
-}),e.fire("NodeChange",{element:n,parents:r}))},addButton:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),t.text||t.icon||(t.icon=e),n.buttons=n.buttons||{},t.tooltip=t.tooltip||t.title,n.buttons[e]=t},addMenuItem:function(e,t){var n=this;t.cmd&&(t.onclick=function(){n.execCommand(t.cmd)}),n.menuItems=n.menuItems||{},n.menuItems[e]=t},addCommand:function(e,t,n){this.execCommands[e]={func:t,scope:n||this}},addQueryStateHandler:function(e,t,n){this.queryStateCommands[e]={func:t,scope:n||this}},addQueryValueHandler:function(e,t,n){this.queryValueCommands[e]={func:t,scope:n||this}},addShortcut:function(e,t,n,r){this.shortcuts.add(e,t,n,r)},execCommand:function(e,t,n,r){var i=this,o=0,a;return/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(e)||r&&r.skip_focus||i.focus(),r=T({},r),r=i.fire("BeforeExecCommand",{command:e,ui:t,value:n}),r.isDefaultPrevented()?!1:(a=i.execCommands[e])&&a.func.call(a.scope,t,n)!==!0?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(R(i.plugins,function(r){return r.execCommand&&r.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),o=!0,!1):void 0}),o?o:i.theme&&i.theme.execCommand&&i.theme.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):i.editorCommands.execCommand(e,t,n)?(i.fire("ExecCommand",{command:e,ui:t,value:n}),!0):(i.getDoc().execCommand(e,t,n),void i.fire("ExecCommand",{command:e,ui:t,value:n})))},queryCommandState:function(e){var t=this,n,r;if(!t._isHidden()){if((n=t.queryStateCommands[e])&&(r=n.func.call(n.scope),r!==!0))return r;if(r=t.editorCommands.queryCommandState(e),-1!==r)return r;try{return t.getDoc().queryCommandState(e)}catch(i){}}},queryCommandValue:function(e){var n=this,r,i;if(!n._isHidden()){if((r=n.queryValueCommands[e])&&(i=r.func.call(r.scope),i!==!0))return i;if(i=n.editorCommands.queryCommandValue(e),i!==t)return i;try{return n.getDoc().queryCommandValue(e)}catch(o){}}},show:function(){var e=this;E.show(e.getContainer()),E.hide(e.id),e.load(),e.fire("show")},hide:function(){var e=this,t=e.getDoc();P&&t&&!e.inline&&t.execCommand("SelectAll"),e.save(),E.hide(e.getContainer()),E.setStyle(e.id,"display",e.orgDisplay),e.fire("hide")},isHidden:function(){return!E.isHidden(this.id)},setProgressState:function(e,t){this.fire("ProgressState",{state:e,time:t})},load:function(e){var n=this,r=n.getElement(),i;return r?(e=e||{},e.load=!0,i=n.setContent(r.value!==t?r.value:r.innerHTML,e),e.element=r,e.no_events||n.fire("LoadContent",e),e.element=r=null,i):void 0},save:function(e){var t=this,n=t.getElement(),r,i;if(n&&t.initialized)return e=e||{},e.save=!0,e.element=n,r=e.content=t.getContent(e),e.no_events||t.fire("SaveContent",e),r=e.content,/TEXTAREA|INPUT/i.test(n.nodeName)?n.value=r:(t.inline||(n.innerHTML=r),(i=E.getParent(t.id,"form"))&&R(i.elements,function(e){return e.name==t.id?(e.value=r,!1):void 0})),e.element=n=null,e.set_dirty!==!1&&(t.isNotDirty=!0),r},setContent:function(e,t){var n=this,r=n.getBody(),i;return t=t||{},t.format=t.format||"html",t.set=!0,t.content=e,t.no_events||n.fire("BeforeSetContent",t),e=t.content,0===e.length||/^\s+$/.test(e)?(i=n.settings.forced_root_block,i&&n.schema.isValidChild(r.nodeName.toLowerCase(),i.toLowerCase())?(e=P&&11>P?"":'
',e=n.dom.createHTML(i,n.settings.forced_root_block_attrs,e)):P||(e='
'),r.innerHTML=e,n.fire("SetContent",t)):("raw"!==t.format&&(e=new o({},n.schema).serialize(n.parser.parse(e,{isRootContent:!0}))),t.content=L(e),n.dom.setHTML(r,t.content),t.no_events||n.fire("SetContent",t)),t.content},getContent:function(e){var t=this,n,r=t.getBody();return e=e||{},e.format=e.format||"html",e.get=!0,e.getInner=!0,e.no_events||t.fire("BeforeGetContent",e),n="raw"==e.format?r.innerHTML:"text"==e.format?r.innerText||r.textContent:t.serializer.serialize(r,e),e.content="text"!=e.format?L(n):n,e.no_events||t.fire("GetContent",e),e.content},insertContent:function(e){this.execCommand("mceInsertContent",!1,e)},isDirty:function(){return!this.isNotDirty},getContainer:function(){var e=this;return e.container||(e.container=E.get(e.editorContainer||e.id+"_parent")),e.container},getContentAreaContainer:function(){return this.contentAreaContainer},getElement:function(){return E.get(this.settings.content_element||this.id)},getWin:function(){var e=this,t;return e.contentWindow||(t=E.get(e.id+"_ifr"),t&&(e.contentWindow=t.contentWindow)),e.contentWindow},getDoc:function(){var e=this,t;return e.contentDocument||(t=e.getWin(),t&&(e.contentDocument=t.document)),e.contentDocument},getBody:function(){return this.bodyElement||this.getDoc().body},convertURL:function(e,t,n){var r=this,i=r.settings;return i.urlconverter_callback?r.execCallback("urlconverter_callback",e,n,!0,t):!i.convert_urls||n&&"LINK"==n.nodeName||0===e.indexOf("file:")||0===e.length?e:i.relative_urls?r.documentBaseURI.toRelative(e):e=r.documentBaseURI.toAbsolute(e,i.remove_script_host)},addVisual:function(e){var n=this,r=n.settings,i=n.dom,o;e=e||n.getBody(),n.hasVisual===t&&(n.hasVisual=r.visual),R(i.select("table,a",e),function(e){var t;switch(e.nodeName){case"TABLE":return o=r.visual_table_class||"mce-item-table",t=i.getAttrib(e,"border"),void(t&&"0"!=t||(n.hasVisual?i.addClass(e,o):i.removeClass(e,o)));case"A":return void(i.getAttrib(e,"href",!1)||(t=i.getAttrib(e,"name")||e.id,o=r.visual_anchor_class||"mce-item-anchor",t&&(n.hasVisual?i.addClass(e,o):i.removeClass(e,o))))}}),n.fire("VisualAid",{element:e,hasVisual:n.hasVisual})},remove:function(){var e=this;if(!e.removed){e.save(),e.fire("remove"),e.off(),e.removed=1,e.hasHiddenInput&&E.remove(e.getElement().nextSibling),E.setStyle(e.id,"display",e.orgDisplay),e.settings.content_editable||(M.unbind(e.getWin()),M.unbind(e.getDoc()));var t=e.getContainer();M.unbind(e.getBody()),M.unbind(t),e.editorManager.remove(e),E.remove(t),e.destroy()}},bindNative:function(e){var t=this;t.settings.readonly||(t.initialized?t.dom.bind(_(t,e),e,function(n){t.fire(e,n)}):t._pendingNativeEvents?t._pendingNativeEvents.push(e):t._pendingNativeEvents=[e])},unbindNative:function(e){var t=this;t.initialized&&t.dom.unbind(e)},destroy:function(e){var t=this,n;if(!t.destroyed){if(!e&&!t.removed)return void t.remove();e&&H&&(M.unbind(t.getDoc()),M.unbind(t.getWin()),M.unbind(t.getBody())),e||(t.editorManager.off("beforeunload",t._beforeUnload),t.theme&&t.theme.destroy&&t.theme.destroy(),t.selection.destroy(),t.dom.destroy()),n=t.formElement,n&&(n._mceOldSubmit&&(n.submit=n._mceOldSubmit,n._mceOldSubmit=null),E.unbind(n,"submit reset",t.formEventDelegate)),t.contentAreaContainer=t.formElement=t.container=t.editorContainer=null,t.settings.content_element=t.bodyElement=t.contentDocument=t.contentWindow=null,t.selection&&(t.selection=t.selection.win=t.selection.dom=t.selection.dom.doc=null),t.destroyed=1}},_refreshContentEditable:function(){var e=this,t,n;e._isHidden()&&(t=e.getBody(),n=t.parentNode,n.removeChild(t),n.appendChild(t),t.focus())},_isHidden:function(){var e;return H?(e=this.selection.getSel(),!e||!e.rangeCount||0===e.rangeCount):0}},T(N.prototype,x),N}),r(at,[],function(){var e={};return{rtl:!1,add:function(t,n){for(var r in n)e[r]=n[r];this.rtl=this.rtl||"rtl"===e._dir},translate:function(t){if("undefined"==typeof t)return t;if("string"!=typeof t&&t.raw)return t.raw;if(t.push){var n=t.slice(1);t=(e[t[0]]||t[0]).replace(/\{([^\}]+)\}/g,function(e,t){return n[t]})}return e[t]||t},data:e}}),r(st,[y,g],function(e,t){function n(e){function a(){try{return document.activeElement}catch(e){return document.body}}function s(e){return e&&e.startContainer?{startContainer:e.startContainer,startOffset:e.startOffset,endContainer:e.endContainer,endOffset:e.endOffset}:e}function l(e,t){var n;return t.startContainer?(n=e.getDoc().createRange(),n.setStart(t.startContainer,t.startOffset),n.setEnd(t.endContainer,t.endOffset)):n=t,n}function c(e){return!!o.getParent(e,n.isEditorUIElement)}function u(e,t){for(var n=t.getBody();e;){if(e==n)return!0;e=e.parentNode}}function d(n){var d=n.editor;d.on("init",function(){(d.inline||t.ie)&&(d.on("nodechange keyup",function(){var e=document.activeElement;e&&e.id==d.id+"_ifr"&&(e=d.getBody()),u(e,d)&&(d.lastRng=d.selection.getRng())}),t.webkit&&!r&&(r=function(){var t=e.activeEditor;if(t&&t.selection){var n=t.selection.getRng();n&&!n.collapsed&&(d.lastRng=n)}},o.bind(document,"selectionchange",r)))}),d.on("setcontent",function(){d.lastRng=null}),d.on("mousedown",function(){d.selection.lastFocusBookmark=null}),d.on("focusin",function(){var t=e.focusedEditor;d.selection.lastFocusBookmark&&(d.selection.setRng(l(d,d.selection.lastFocusBookmark)),d.selection.lastFocusBookmark=null),t!=d&&(t&&t.fire("blur",{focusedEditor:d}),e.activeEditor=d,e.focusedEditor=d,d.fire("focus",{blurredEditor:t}),d.focus(!0)),d.lastRng=null}),d.on("focusout",function(){window.setTimeout(function(){var t=e.focusedEditor;c(a())||t!=d||(d.fire("blur",{focusedEditor:null}),e.focusedEditor=null,d.selection&&(d.selection.lastFocusBookmark=null))},0)}),i||(i=function(t){var n=e.activeEditor;n&&t.target.ownerDocument==document&&(n.selection&&(n.selection.lastFocusBookmark=s(n.lastRng)),c(t.target)||e.focusedEditor!=n||(n.fire("blur",{focusedEditor:null}),e.focusedEditor=null))},o.bind(document,"focusin",i))}function f(t){e.focusedEditor==t.editor&&(e.focusedEditor=null),e.activeEditor||(o.unbind(document,"selectionchange",r),o.unbind(document,"focusin",i),r=i=null)}e.on("AddEditor",d),e.on("RemoveEditor",f)}var r,i,o=e.DOM;return n.isEditorUIElement=function(e){return-1!==e.className.toString().indexOf("mce-")},n}),r(lt,[ot,y,I,g,p,rt,at,st],function(e,n,r,i,o,a,s,l){var c=n.DOM,u=o.explode,d=o.each,f=o.extend,p=0,m,h={majorVersion:"4",minorVersion:"0.20",releaseDate:"2014-03-18",editors:[],i18n:s,activeEditor:null,setup:function(){var e=this,t,n,i="",o;if(n=document.location.href.replace(/[\?#].*$/,"").replace(/[\/\\][^\/]+$/,""),/[\/\\]$/.test(n)||(n+="/"),o=window.tinymce||window.tinyMCEPreInit)t=o.base||o.baseURL,i=o.suffix;else for(var a=document.getElementsByTagName("script"),s=0;s
\xa0
').append(t),i.setStartAfter(o[0].firstChild.firstChild),i.setEndAfter(t)):(o.empty().append(oo).append(t).append(oo),i.setStart(o[0].firstChild,1),i.setEnd(o[0].lastChild,0)),o.css({top:l.getPos(e,u.getBody()).y}),o[0].focus();var a=c.getSel();return a.removeAllRanges(),a.addRange(i),i}(e,n.targetClone,t),o=Nt.fromDom(e);return $(qu(Nt.fromDom(u.getBody()),"*[data-mce-selected]"),function(e){Rt(o,e)||Kn(e,i)}),l.getAttrib(e,i)||e.setAttribute(i,"1"),s=e,S(),r},w=function(e,t){if(!e)return null;if(e.collapsed){if(!y(e)){var n=t?1:-1,r=al(n,d,e),o=r.getNode(!t);if(jc(o))return v(n,o,!!t&&!r.isAtEnd(),!1);var i=r.getNode(t);if(jc(i))return v(n,i,!t&&!r.isAtEnd(),!1)}return null}var a=e.startContainer,u=e.startOffset,s=e.endOffset;if(3===a.nodeType&&0===u&&XS(a.parentNode)&&(a=a.parentNode,u=l.nodeIndex(a),a=a.parentNode),1!==a.nodeType)return null;if(s===u+1&&a===e.endContainer){var c=a.childNodes[u];if(g(c))return C(c)}return null},x=function(){s&&s.removeAttribute(i),Er(Nt.fromDom(u.getBody()),"#"+p).each(ln),s=null},S=function(){m.hide()};return vt.ceFalse&&function(){u.on("mouseup",function(e){var t=r();t.collapsed&&Ly(u,e.clientX,e.clientY)&&Wb(u,t,!1).each(h)}),u.on("click",function(e){var t=YS(u,e.target);t&&(XS(t)&&(e.preventDefault(),u.focus()),KS(t)&&l.isChildOf(t,c.getNode())&&x())}),u.on("blur NewBlock",x),u.on("ResizeWindow FullscreenStateChanged",m.reposition);var a=function(e){var t=wl(e);if(!e.firstChild)return!1;var n,r=Us.before(e.firstChild),o=t.next(r);return o&&!(ep(n=o)||tp(n)||Gm(n)||Jm(n))},i=function(e,t){var n,r,o=l.getParent(e,f),i=l.getParent(t,f);return!(!o||e===i||!l.isChildOf(o,i)||!1!==XS(YS(u,o)))||o&&(n=o,r=i,!(l.getParent(n,f)===l.getParent(r,f)))&&a(o)};u.on("tap",function(e){var t=e.target,n=YS(u,t);XS(n)?(e.preventDefault(),$b(u,n).each(w)):g(t)&&$b(u,t).each(w)},!0),u.on("mousedown",function(e){var t,n,r,o=e.target;o!==d&&"HTML"!==o.nodeName&&!l.isChildOf(o,d)||!1===Ly(u,e.clientX,e.clientY)||((t=YS(u,o))?XS(t)?(e.preventDefault(),$b(u,t).each(w)):(x(),KS(t)&&e.shiftKey||Yf(e.clientX,e.clientY,c.getRng())||(S(),c.placeCaretAt(e.clientX,e.clientY))):g(o)?$b(u,o).each(w):!1===jc(o)&&(x(),S(),(n=$w(d,e.clientX,e.clientY))&&(i(o,n.node)||(e.preventDefault(),r=v(1,n.node,n.before,!1),u.getBody().focus(),h(r)))))}),u.on("keypress",function(e){Gf.modifierPressed(e)||XS(c.getNode())&&e.preventDefault()}),u.on("GetSelectionRange",function(e){var t=e.range;if(s){if(!s.parentNode)return void(s=null);(t=t.cloneRange()).selectNode(s),e.range=t}}),u.on("SetSelectionRange",function(e){e.range=b(e.range);var t=w(e.range,e.forward);t&&(e.range=t)});var n,e,o;u.on("AfterSetSelectionRange",function(e){var t,n=e.range,r=n.startContainer.parentNode;y(n)||"mcepastebin"===r.id||S(),t=r,l.hasClass(t,"mce-offscreen-selection")||x()}),u.on("copy",function(e){var t,n,r=e.clipboardData;e.isDefaultPrevented()||!e.clipboardData||vt.ie||(t=(n=l.get(p))?n.getElementsByTagName("*")[0]:n)&&(e.preventDefault(),r.clearData(),r.setData("text/html",t.outerHTML),r.setData("text/plain",t.outerText||t.innerText))}),WS(u),e=Pu(function(){var e,t;n.removed||!n.getBody().contains(document.activeElement)||(e=n.selection.getRng()).collapsed&&(t=Kb(n,e,!1),n.selection.setRng(t))},0),(n=u).on("focus",function(){e.throttle()}),n.on("blur",function(){e.cancel()}),(o=u).on("init",function(){o.on("focusin",function(e){var t,n,r=e.target;jn(r)&&(t=Xf(o.getBody(),r),n=Un(t)?t:r,o.selection.getNode()!==n&&$b(o,n).each(function(e){return o.selection.setRng(e)}))})})}(),{showCaret:v,showBlockCaretContainer:function(e){e.hasAttribute("data-mce-caret")&&(Co(e),h(r()),c.scrollIntoView(e))},hideFakeCaret:S,destroy:function(){m.destroy(),s=null}}},JS=function(u){var s,n,r,o=xt.each,c=Gf.BACKSPACE,l=Gf.DELETE,f=u.dom,d=u.selection,e=u.parser,t=vt.gecko,i=vt.ie,a=vt.webkit,m="data:text/mce-internal,",p=i?"Text":"URL",g=function(e,t){try{u.getDoc().execCommand(e,!1,t)}catch(n){}},h=function(e){return e.isDefaultPrevented()},v=function(){u.shortcuts.add("meta+a",null,"SelectAll")},y=function(){u.on("keydown",function(e){if(!h(e)&&e.keyCode===c&&d.isCollapsed()&&0===d.getRng().startOffset){var t=d.getNode().previousSibling;if(t&&t.nodeName&&"table"===t.nodeName.toLowerCase())return e.preventDefault(),!1}})},b=function(){u.inline||(u.contentStyles.push("body {min-height: 150px}"),u.on("click",function(e){var t;if("HTML"===e.target.nodeName){if(11original visual text
'; }}; + {getContent() { return 'original visual text' }}; spyOn(this.descriptor, 'getVisualEditor').and.callFake(() => visualEditorStub); - const { data } = this.descriptor.save(); - expect(data).toEqual('raw text'); + + var self = this; + jasmine.waitUntil(function() { + return !!self.descriptor.starting_content; + }, 10000).then(function() { + const { data } = self.descriptor.save(); + expect(data).toEqual('raw text'); + }).always(done); }); - it('Performs link rewriting for static assets when saving', function() { + it('Performs link rewriting for static assets when saving', function(done) { const visualEditorStub = {getContent() { return 'from visual editor with /c4x/foo/bar/asset/image.jpg'; }}; spyOn(this.descriptor, 'getVisualEditor').and.callFake(() => visualEditorStub); - const { data } = this.descriptor.save(); - expect(data).toEqual('from visual editor with /static/image.jpg'); + + var self = this; + jasmine.waitUntil(function() { + return !!self.descriptor.starting_content; + }, 10000).then(function() { + const { data } = self.descriptor.save(); + expect(data).toEqual('from visual editor with /static/image.jpg'); + }).always(done); + }); it('When showing visual editor links are rewritten to c4x format', function() { const visualEditorStub = { diff --git a/xmodule/js/src/html/edit.js b/xmodule/js/src/html/edit.js index 33accebc07..267297e216 100644 --- a/xmodule/js/src/html/edit.js +++ b/xmodule/js/src/html/edit.js @@ -99,8 +99,8 @@ var tinyMceConfig = { script_url: baseUrl + "js/vendor/tinymce/js/tinymce/tinymce.full.min.js", font_formats: _getFonts(), - theme: "modern", - skin: 'studio-tmce4', + theme: "silver", + skin: "studio-tmce5", schema: "html5", entity_encoding: "raw", @@ -125,19 +125,23 @@ Disable visual aid on borderless table. */ visual: false, - plugins: "textcolor, link, image, codemirror", + plugins: "lists, link, image, codemirror", codemirror: { - path: baseUrl + "js/vendor" + path: baseUrl + "js/vendor", + disableFilesMerge: true, + jsFiles: ["codemirror-compressed.js"], + cssFiles: ["CodeMirror/codemirror.css"] }, + image_advtab: true, /* We may want to add "styleselect" when we collect all styles used throughout the LMS */ - toolbar: "formatselect | fontselect | bold italic underline forecolor wrapAsCode | " + - "alignleft aligncenter alignright alignjustify | " + - "bullist numlist outdent indent blockquote | link unlink " + - ((this.new_image_modal ? 'insertImage' : 'image') + " | code"), + toolbar: "formatselect fontselect bold italic underline forecolor wrapAsCode " + + "alignleft aligncenter alignright alignjustify " + + "bullist numlist outdent indent blockquote link unlink " + + ((this.new_image_modal ? 'insertImage' : 'image') + " code"), block_formats: edx.StringUtils.interpolate( gettext("{paragraph}=p;{preformatted}=pre;{heading3}=h3;{heading4}=h4;{heading5}=h5;{heading6}=h6"), { @@ -149,7 +153,7 @@ heading6: gettext("Heading 6") }), width: '100%', - height: '400px', + height: '435px', menubar: false, statusbar: false, @@ -1233,25 +1237,25 @@ } HTMLEditingDescriptor.prototype.setupTinyMCE = function(ed) { - ed.addButton('wrapAsCode', { + ed.ui.registry.addButton('wrapAsCode', { /* Translators: this is a toolbar button tooltip from the raw HTML editor displayed in the browser when a user needs to edit HTML */ - title: gettext('Code block'), - image: baseUrl + "images/ico-tinymce-code.png", - onclick: function() { + tooltip: gettext('Code block'), + icon: 'code-sample', + onAction: function() { return ed.formatter.toggle('code'); } }); - ed.addButton('insertImage', { + ed.ui.registry.addButton('insertImage', { /* Translators: this is a toolbar button tooltip from the raw HTML editor displayed in the browser when a user needs to edit HTML */ - title: gettext('Insert/Edit Image'), + tooltip: gettext('Insert/Edit Image'), icon: 'image', - onclick: this.openImageModal + onAction: this.openImageModal }); this.visualEditor = ed; this.imageModal = $('#edit-image-modal #modalWrapper'); @@ -1266,7 +1270,7 @@ ed.on('EditLink', this.editLink); ed.on('ShowCodeEditor', this.showCodeEditor); ed.on('SaveCodeEditor', this.saveCodeEditor); - $(".action-cancel").on('click', this.cancelButton) + $(".action-cancel").on('click', this.cancelButton); this.imageModal.on('closeModal', this.closeImageModal); return this.imageModal.on('submitForm', this.editImageSubmit); @@ -1386,7 +1390,7 @@ haven't dirtied the Editor. Store the raw content so we can compare it later. */ this.starting_content = visualEditor.getContent({ - format: "raw", + format: "text", no_events: 1 }); return visualEditor.focus(); @@ -1406,7 +1410,7 @@ if (this.editor_choice === 'visual') { visualEditor = this.getVisualEditor(); raw_content = visualEditor.getContent({ - format: "raw", + format: "text", no_events: 1 }); if (this.starting_content !== raw_content) { diff --git a/xmodule/modulestore/mixed.py b/xmodule/modulestore/mixed.py index 88bb8215fe..17b5e8a086 100644 --- a/xmodule/modulestore/mixed.py +++ b/xmodule/modulestore/mixed.py @@ -15,10 +15,9 @@ from opaque_keys.edx.locator import LibraryLocator from xmodule.assetstore import AssetMetadata -from . import XMODULE_FIELDS_WITH_USAGE_KEYS, ModuleStoreEnum, ModuleStoreWriteBase +from . import XMODULE_FIELDS_WITH_USAGE_KEYS, ModuleStoreWriteBase from .draft_and_published import ModuleStoreDraftAndPublished from .exceptions import DuplicateCourseError, ItemNotFoundError -from .split_migrator import SplitMigrator log = logging.getLogger(__name__) @@ -717,17 +716,9 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase): if source_modulestore == dest_modulestore: return source_modulestore.clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) - if dest_modulestore.get_modulestore_type() == ModuleStoreEnum.Type.split: - split_migrator = SplitMigrator(dest_modulestore, source_modulestore) - split_migrator.migrate_mongo_course(source_course_id, user_id, dest_course_id.org, - dest_course_id.course, dest_course_id.run, fields, **kwargs) - - # the super handles assets and any other necessities - super().clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) - else: - raise NotImplementedError("No code for cloning from {} to {}".format( - source_modulestore, dest_modulestore - )) + raise NotImplementedError("No code for cloning from {} to {}".format( + source_modulestore, dest_modulestore + )) @strip_key @prepare_asides diff --git a/xmodule/modulestore/mongo/base.py b/xmodule/modulestore/mongo/base.py index 869d45cd15..863d009555 100644 --- a/xmodule/modulestore/mongo/base.py +++ b/xmodule/modulestore/mongo/base.py @@ -204,7 +204,6 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li kwargs.setdefault('id_reader', id_manager) kwargs.setdefault('id_generator', id_manager) super().__init__( - field_data=None, load_item=self.load_item, **kwargs ) diff --git a/xmodule/modulestore/split_migrator.py b/xmodule/modulestore/split_migrator.py deleted file mode 100644 index c773648bbb..0000000000 --- a/xmodule/modulestore/split_migrator.py +++ /dev/null @@ -1,231 +0,0 @@ -''' -Code for migrating from other modulestores to the split_mongo modulestore. - -Exists at the top level of modulestore b/c it needs to know about and access each modulestore. - -In general, it's strategy is to treat the other modulestores as read-only and to never directly -manipulate storage but use existing api's. -''' - - -import logging - -from opaque_keys.edx.locator import CourseLocator -from xblock.fields import Reference, ReferenceList, ReferenceValueDict - -from xmodule.modulestore import ModuleStoreEnum -from xmodule.modulestore.exceptions import ItemNotFoundError - -log = logging.getLogger(__name__) - - -class SplitMigrator: - """ - Copies courses from old mongo to split mongo and sets up location mapping so any references to the old - name will be able to find the new elements. - """ - def __init__(self, split_modulestore, source_modulestore): - super().__init__() - self.split_modulestore = split_modulestore - self.source_modulestore = source_modulestore - - def migrate_mongo_course( - self, source_course_key, user_id, new_org=None, new_course=None, new_run=None, fields=None, **kwargs - ): - """ - Create a new course in split_mongo representing the published and draft versions of the course from the - original mongo store. And return the new CourseLocator - - If the new course already exists, this raises DuplicateItemError - - :param source_course_key: which course to migrate - :param user_id: the user whose action is causing this migration - :param new_org, new_course, new_run: (optional) identifiers for the new course. Defaults to - the source_course_key's values. - """ - # the only difference in data between the old and split_mongo xblocks are the locations; - # so, any field which holds a location must change to a Locator; otherwise, the persistence - # layer and kvs's know how to store it. - # locations are in location, children, conditionals, course.tab - - # create the course: set fields to explicitly_set for each scope, id_root = new_course_locator, master_branch = 'production' # lint-amnesty, pylint: disable=line-too-long - original_course = self.source_modulestore.get_course(source_course_key, **kwargs) - if original_course is None: - raise ItemNotFoundError(str(source_course_key)) - - if new_org is None: - new_org = source_course_key.org - if new_course is None: - new_course = source_course_key.course - if new_run is None: - new_run = source_course_key.run - - new_course_key = CourseLocator(new_org, new_course, new_run, branch=ModuleStoreEnum.BranchName.published) - with self.split_modulestore.bulk_operations(new_course_key): - new_fields = self._get_fields_translate_references(original_course, new_course_key, None) - if fields: - new_fields.update(fields) - new_course = self.split_modulestore.create_course( - new_org, new_course, new_run, user_id, - fields=new_fields, - master_branch=ModuleStoreEnum.BranchName.published, - skip_auto_publish=True, - **kwargs - ) - - self._copy_published_modules_to_course( - new_course, original_course.location, source_course_key, user_id, **kwargs - ) - - # TODO: This should be merged back into the above transaction, but can't be until split.py - # is refactored to have more coherent access patterns - with self.split_modulestore.bulk_operations(new_course_key): - - # create a new version for the drafts - self._add_draft_modules_to_course(new_course.location, source_course_key, user_id, **kwargs) - - return new_course.id - - def _copy_published_modules_to_course(self, new_course, old_course_loc, source_course_key, user_id, **kwargs): - """ - Copy all of the modules from the 'direct' version of the course to the new split course. - """ - course_version_locator = new_course.id.version_agnostic() - - # iterate over published course elements. Wildcarding rather than descending b/c some elements are orphaned (e.g., # lint-amnesty, pylint: disable=line-too-long - # course about pages, conditionals) - for module in self.source_modulestore.get_items( - source_course_key, revision=ModuleStoreEnum.RevisionOption.published_only, **kwargs - ): - # don't copy the course again. - if module.location != old_course_loc: - # create split_xblock using split.create_item - # NOTE: the below auto populates the children when it migrates the parent; so, - # it doesn't need the parent as the first arg. That is, it translates and populates - # the 'children' field as it goes. - _new_module = self.split_modulestore.create_item( - user_id, - course_version_locator, - module.location.block_type, - block_id=module.location.block_id, - fields=self._get_fields_translate_references( - module, course_version_locator, new_course.location.block_id - ), - skip_auto_publish=True, - **kwargs - ) - # after done w/ published items, add version for DRAFT pointing to the published structure - index_info = self.split_modulestore.get_course_index_info(course_version_locator) - versions = index_info['versions'] - versions[ModuleStoreEnum.BranchName.draft] = versions[ModuleStoreEnum.BranchName.published] - self.split_modulestore.update_course_index(course_version_locator, index_info) - - # clean up orphans in published version: in old mongo, parents pointed to the union of their published and draft - # children which meant some pointers were to non-existent locations in 'direct' - self.split_modulestore.fix_not_found(course_version_locator, user_id) - - def _add_draft_modules_to_course(self, published_course_usage_key, source_course_key, user_id, **kwargs): - """ - update each draft. Create any which don't exist in published and attach to their parents. - """ - # each true update below will trigger a new version of the structure. We may want to just have one new version - # but that's for a later date. - new_draft_course_loc = published_course_usage_key.course_key.for_branch(ModuleStoreEnum.BranchName.draft) - # to prevent race conditions of grandchilden being added before their parents and thus having no parent to - # add to - awaiting_adoption = {} - for module in self.source_modulestore.get_items( - source_course_key, revision=ModuleStoreEnum.RevisionOption.draft_only, **kwargs - ): - new_locator = new_draft_course_loc.make_usage_key(module.category, module.location.block_id) - if self.split_modulestore.has_item(new_locator): - # was in 'direct' so draft is a new version - split_module = self.split_modulestore.get_item(new_locator, **kwargs) - # need to remove any no-longer-explicitly-set values and add/update any now set values. - for name, field in split_module.fields.items(): - if field.is_set_on(split_module) and not module.fields[name].is_set_on(module): - field.delete_from(split_module) - for field, value in self._get_fields_translate_references( - module, new_draft_course_loc, published_course_usage_key.block_id, field_names=False - ).items(): - field.write_to(split_module, value) - - _new_module = self.split_modulestore.update_item(split_module, user_id, **kwargs) - else: - # only a draft version (aka, 'private'). - _new_module = self.split_modulestore.create_item( - user_id, new_draft_course_loc, - new_locator.block_type, - block_id=new_locator.block_id, - fields=self._get_fields_translate_references( - module, new_draft_course_loc, published_course_usage_key.block_id - ), - **kwargs - ) - awaiting_adoption[module.location] = new_locator - for draft_location, new_locator in awaiting_adoption.items(): - parent_loc = self.source_modulestore.get_parent_location( - draft_location, revision=ModuleStoreEnum.RevisionOption.draft_preferred, **kwargs - ) - if parent_loc is None: - log.warning('No parent found in source course for %s', draft_location) - continue - old_parent = self.source_modulestore.get_item(parent_loc, **kwargs) - split_parent_loc = new_draft_course_loc.make_usage_key( - parent_loc.block_type, - parent_loc.block_id if parent_loc.block_type != 'course' else published_course_usage_key.block_id - ) - new_parent = self.split_modulestore.get_item(split_parent_loc, **kwargs) - # this only occurs if the parent was also awaiting adoption: skip this one, go to next - if any(new_locator.block_id == child.block_id for child in new_parent.children): - continue - # find index for module: new_parent may be missing quite a few of old_parent's children - new_parent_cursor = 0 - for old_child_loc in old_parent.children: - if old_child_loc.block_id == draft_location.block_id: - break # moved cursor enough, insert it here - # sibling may move cursor - for idx in range(new_parent_cursor, len(new_parent.children)): - if new_parent.children[idx].block_id == old_child_loc.block_id: - new_parent_cursor = idx + 1 - break # skipped sibs enough, pick back up scan - new_parent.children.insert(new_parent_cursor, new_locator) - new_parent = self.split_modulestore.update_item(new_parent, user_id) - - def _get_fields_translate_references(self, xblock, new_course_key, course_block_id, field_names=True): - """ - Return a dictionary of field: value pairs for explicitly set fields - but convert all references to their BlockUsageLocators - Args: - field_names: if Truthy, the dictionary keys are the field names. If falsey, the keys are the - field objects. - """ - def get_translation(location): - """ - Convert the location - """ - return new_course_key.make_usage_key( - location.block_type, - location.block_id if location.block_type != 'course' else course_block_id - ) - - result = {} - for field_name, field in xblock.fields.items(): - if field.is_set_on(xblock): - field_value = field.read_from(xblock) - field_key = field_name if field_names else field - if isinstance(field, Reference) and field_value is not None: - result[field_key] = get_translation(field_value) - elif isinstance(field, ReferenceList): - result[field_key] = [ - get_translation(ele) for ele in field_value - ] - elif isinstance(field, ReferenceValueDict): - result[field_key] = { - key: get_translation(subvalue) - for key, subvalue in field_value.items() - } - else: - result[field_key] = field_value - - return result diff --git a/xmodule/modulestore/split_mongo/caching_descriptor_system.py b/xmodule/modulestore/split_mongo/caching_descriptor_system.py index 6849cc2c68..f951e5b000 100644 --- a/xmodule/modulestore/split_mongo/caching_descriptor_system.py +++ b/xmodule/modulestore/split_mongo/caching_descriptor_system.py @@ -60,7 +60,6 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li kwargs.setdefault('id_generator', id_manager) super().__init__( - field_data=None, load_item=self._load_item, resources_fs=OSFS(root), **kwargs diff --git a/xmodule/modulestore/tests/test_mixed_modulestore.py b/xmodule/modulestore/tests/test_mixed_modulestore.py index 5d50dfb5ad..318f6dc57d 100644 --- a/xmodule/modulestore/tests/test_mixed_modulestore.py +++ b/xmodule/modulestore/tests/test_mixed_modulestore.py @@ -2510,7 +2510,6 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup): @ddt.data( [ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.mongo], - [ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split], [ModuleStoreEnum.Type.split, ModuleStoreEnum.Type.split] ) @ddt.unpack diff --git a/xmodule/modulestore/tests/test_split_migrator.py b/xmodule/modulestore/tests/test_split_migrator.py deleted file mode 100644 index a322e2b396..0000000000 --- a/xmodule/modulestore/tests/test_split_migrator.py +++ /dev/null @@ -1,190 +0,0 @@ -""" -Tests for split_migrator - -""" - - -import random -import uuid -from unittest import mock - -from xblock.fields import UNIQUE_ID, Reference, ReferenceList, ReferenceValueDict - -from openedx.core.lib.tests import attr -from xmodule.modulestore.split_migrator import SplitMigrator -from xmodule.modulestore.tests.test_split_w_old_mongo import SplitWMongoCourseBootstrapper - - -@attr('mongo') -class TestMigration(SplitWMongoCourseBootstrapper): - """ - Test the split migrator - """ - - def setUp(self): - super().setUp() - self.migrator = SplitMigrator(self.split_mongo, self.draft_mongo) - - def _create_course(self): # lint-amnesty, pylint: disable=arguments-differ - """ - A course testing all of the conversion mechanisms: - * some inheritable settings - * sequences w/ draft and live intermixed children to ensure all get to the draft but - only the live ones get to published. Some are only draft, some are both, some are only live. - * about, static_tab, and conditional documents - """ - super()._create_course(split=False) - - # chapters - chapter1_name = uuid.uuid4().hex - self._create_item('chapter', chapter1_name, {}, {'display_name': 'Chapter 1'}, 'course', 'runid', split=False) - chap2_loc = self.old_course_key.make_usage_key('chapter', uuid.uuid4().hex) - self._create_item( - chap2_loc.block_type, chap2_loc.block_id, {}, {'display_name': 'Chapter 2'}, 'course', 'runid', split=False - ) - # vertical in live only - live_vert_name = uuid.uuid4().hex - self._create_item( - 'vertical', live_vert_name, {}, {'display_name': 'Live vertical'}, 'chapter', chapter1_name, - draft=False, split=False - ) - self.create_random_units(False, self.old_course_key.make_usage_key('vertical', live_vert_name)) - # vertical in both live and draft - both_vert_loc = self.old_course_key.make_usage_key('vertical', uuid.uuid4().hex) - self._create_item( - both_vert_loc.block_type, both_vert_loc.block_id, {}, {'display_name': 'Both vertical'}, 'chapter', chapter1_name, # lint-amnesty, pylint: disable=line-too-long - draft=False, split=False - ) - self.create_random_units(False, both_vert_loc) - draft_both = self.draft_mongo.get_item(both_vert_loc) - draft_both.display_name = 'Both vertical renamed' - self.draft_mongo.update_item(draft_both, self.user_id) - self.create_random_units(True, both_vert_loc) - # vertical in draft only (x2) - draft_vert_loc = self.old_course_key.make_usage_key('vertical', uuid.uuid4().hex) - self._create_item( - draft_vert_loc.block_type, draft_vert_loc.block_id, {}, {'display_name': 'Draft vertical'}, 'chapter', chapter1_name, # lint-amnesty, pylint: disable=line-too-long - draft=True, split=False - ) - self.create_random_units(True, draft_vert_loc) - draft_vert_loc = self.old_course_key.make_usage_key('vertical', uuid.uuid4().hex) - self._create_item( - draft_vert_loc.block_type, draft_vert_loc.block_id, {}, {'display_name': 'Draft vertical2'}, 'chapter', chapter1_name, # lint-amnesty, pylint: disable=line-too-long - draft=True, split=False - ) - self.create_random_units(True, draft_vert_loc) - - # and finally one in live only (so published has to skip 2 preceding sibs) - live_vert_loc = self.old_course_key.make_usage_key('vertical', uuid.uuid4().hex) - self._create_item( - live_vert_loc.block_type, live_vert_loc.block_id, {}, {'display_name': 'Live vertical end'}, 'chapter', chapter1_name, # lint-amnesty, pylint: disable=line-too-long - draft=False, split=False - ) - self.create_random_units(False, live_vert_loc) - - # now the other chapter w/ the conditional - # create pointers to children (before the children exist) - indirect1_loc = self.old_course_key.make_usage_key('discussion', uuid.uuid4().hex) - indirect2_loc = self.old_course_key.make_usage_key('html', uuid.uuid4().hex) - conditional_loc = self.old_course_key.make_usage_key('conditional', uuid.uuid4().hex) - self._create_item( - conditional_loc.block_type, conditional_loc.block_id, - { - 'show_tag_list': [indirect1_loc, indirect2_loc], - 'sources_list': [live_vert_loc, ], - }, - { - 'xml_attributes': { - 'completed': True, - }, - }, - chap2_loc.block_type, chap2_loc.block_id, - draft=False, split=False - ) - # create the children - self._create_item( - indirect1_loc.block_type, indirect1_loc.block_id, {'data': ""}, {'display_name': 'conditional show 1'}, - conditional_loc.block_type, conditional_loc.block_id, - draft=False, split=False - ) - self._create_item( - indirect2_loc.block_type, indirect2_loc.block_id, {'data': ""}, {'display_name': 'conditional show 2'}, - conditional_loc.block_type, conditional_loc.block_id, - draft=False, split=False - ) - - # add direct children - self.create_random_units(False, conditional_loc) - - # and the ancillary docs (not children) - self._create_item( - 'static_tab', uuid.uuid4().hex, {'data': ""}, {'display_name': 'Tab uno'}, - None, None, draft=False, split=False - ) - self._create_item( - 'about', 'overview', {'data': "test
"}, {}, - None, None, draft=False, split=False - ) - self._create_item( - 'course_info', 'updates', {'data': "test