plugin.js 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  1. /**
  2. * TinyMCE version 8.0.2 (2025-08-14)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global$6 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  7. /* eslint-disable @typescript-eslint/no-wrapper-object-types */
  8. const hasProto = (v, constructor, predicate) => {
  9. var _a;
  10. if (predicate(v, constructor.prototype)) {
  11. return true;
  12. }
  13. else {
  14. // String-based fallback time
  15. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  16. }
  17. };
  18. const typeOf = (x) => {
  19. const t = typeof x;
  20. if (x === null) {
  21. return 'null';
  22. }
  23. else if (t === 'object' && Array.isArray(x)) {
  24. return 'array';
  25. }
  26. else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  27. return 'string';
  28. }
  29. else {
  30. return t;
  31. }
  32. };
  33. const isType = (type) => (value) => typeOf(value) === type;
  34. const isSimpleType = (type) => (value) => typeof value === type;
  35. const isString = isType('string');
  36. const isObject = isType('object');
  37. const isArray = isType('array');
  38. const isNullable = (a) => a === null || a === undefined;
  39. const isNonNullable = (a) => !isNullable(a);
  40. const isFunction = isSimpleType('function');
  41. /**
  42. * The `Optional` type represents a value (of any type) that potentially does
  43. * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the
  44. * value does exist) or a `None` (in which case the value does not exist). This
  45. * module defines a whole lot of FP-inspired utility functions for dealing with
  46. * `Optional` objects.
  47. *
  48. * Comparison with null or undefined:
  49. * - We don't get fancy null coalescing operators with `Optional`
  50. * - We do get fancy helper functions with `Optional`
  51. * - `Optional` support nesting, and allow for the type to still be nullable (or
  52. * another `Optional`)
  53. * - There is no option to turn off strict-optional-checks like there is for
  54. * strict-null-checks
  55. */
  56. class Optional {
  57. // The internal representation has a `tag` and a `value`, but both are
  58. // private: able to be console.logged, but not able to be accessed by code
  59. constructor(tag, value) {
  60. this.tag = tag;
  61. this.value = value;
  62. }
  63. // --- Identities ---
  64. /**
  65. * Creates a new `Optional<T>` that **does** contain a value.
  66. */
  67. static some(value) {
  68. return new Optional(true, value);
  69. }
  70. /**
  71. * Create a new `Optional<T>` that **does not** contain a value. `T` can be
  72. * any type because we don't actually have a `T`.
  73. */
  74. static none() {
  75. return Optional.singletonNone;
  76. }
  77. /**
  78. * Perform a transform on an `Optional` type. Regardless of whether this
  79. * `Optional` contains a value or not, `fold` will return a value of type `U`.
  80. * If this `Optional` does not contain a value, the `U` will be created by
  81. * calling `onNone`. If this `Optional` does contain a value, the `U` will be
  82. * created by calling `onSome`.
  83. *
  84. * For the FP enthusiasts in the room, this function:
  85. * 1. Could be used to implement all of the functions below
  86. * 2. Forms a catamorphism
  87. */
  88. fold(onNone, onSome) {
  89. if (this.tag) {
  90. return onSome(this.value);
  91. }
  92. else {
  93. return onNone();
  94. }
  95. }
  96. /**
  97. * Determine if this `Optional` object contains a value.
  98. */
  99. isSome() {
  100. return this.tag;
  101. }
  102. /**
  103. * Determine if this `Optional` object **does not** contain a value.
  104. */
  105. isNone() {
  106. return !this.tag;
  107. }
  108. // --- Functor (name stolen from Haskell / maths) ---
  109. /**
  110. * Perform a transform on an `Optional` object, **if** there is a value. If
  111. * you provide a function to turn a T into a U, this is the function you use
  112. * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain
  113. * a value then the output will also contain a value (that value being the
  114. * output of `mapper(this.value)`), and if this **does not** contain a value
  115. * then neither will the output.
  116. */
  117. map(mapper) {
  118. if (this.tag) {
  119. return Optional.some(mapper(this.value));
  120. }
  121. else {
  122. return Optional.none();
  123. }
  124. }
  125. // --- Monad (name stolen from Haskell / maths) ---
  126. /**
  127. * Perform a transform on an `Optional` object, **if** there is a value.
  128. * Unlike `map`, here the transform itself also returns an `Optional`.
  129. */
  130. bind(binder) {
  131. if (this.tag) {
  132. return binder(this.value);
  133. }
  134. else {
  135. return Optional.none();
  136. }
  137. }
  138. // --- Traversable (name stolen from Haskell / maths) ---
  139. /**
  140. * For a given predicate, this function finds out if there **exists** a value
  141. * inside this `Optional` object that meets the predicate. In practice, this
  142. * means that for `Optional`s that do not contain a value it returns false (as
  143. * no predicate-meeting value exists).
  144. */
  145. exists(predicate) {
  146. return this.tag && predicate(this.value);
  147. }
  148. /**
  149. * For a given predicate, this function finds out if **all** the values inside
  150. * this `Optional` object meet the predicate. In practice, this means that
  151. * for `Optional`s that do not contain a value it returns true (as all 0
  152. * objects do meet the predicate).
  153. */
  154. forall(predicate) {
  155. return !this.tag || predicate(this.value);
  156. }
  157. filter(predicate) {
  158. if (!this.tag || predicate(this.value)) {
  159. return this;
  160. }
  161. else {
  162. return Optional.none();
  163. }
  164. }
  165. // --- Getters ---
  166. /**
  167. * Get the value out of the inside of the `Optional` object, using a default
  168. * `replacement` value if the provided `Optional` object does not contain a
  169. * value.
  170. */
  171. getOr(replacement) {
  172. return this.tag ? this.value : replacement;
  173. }
  174. /**
  175. * Get the value out of the inside of the `Optional` object, using a default
  176. * `replacement` value if the provided `Optional` object does not contain a
  177. * value. Unlike `getOr`, in this method the `replacement` object is also
  178. * `Optional` - meaning that this method will always return an `Optional`.
  179. */
  180. or(replacement) {
  181. return this.tag ? this : replacement;
  182. }
  183. /**
  184. * Get the value out of the inside of the `Optional` object, using a default
  185. * `replacement` value if the provided `Optional` object does not contain a
  186. * value. Unlike `getOr`, in this method the `replacement` value is
  187. * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you
  188. * pass a function which (if called) will **return** the `value` you want to
  189. * use.
  190. */
  191. getOrThunk(thunk) {
  192. return this.tag ? this.value : thunk();
  193. }
  194. /**
  195. * Get the value out of the inside of the `Optional` object, using a default
  196. * `replacement` value if the provided Optional object does not contain a
  197. * value.
  198. *
  199. * Unlike `or`, in this method the `replacement` value is "thunked" - that is
  200. * to say that you don't pass a value to `orThunk`, you pass a function which
  201. * (if called) will **return** the `value` you want to use.
  202. *
  203. * Unlike `getOrThunk`, in this method the `replacement` value is also
  204. * `Optional`, meaning that this method will always return an `Optional`.
  205. */
  206. orThunk(thunk) {
  207. return this.tag ? this : thunk();
  208. }
  209. /**
  210. * Get the value out of the inside of the `Optional` object, throwing an
  211. * exception if the provided `Optional` object does not contain a value.
  212. *
  213. * WARNING:
  214. * You should only be using this function if you know that the `Optional`
  215. * object **is not** empty (otherwise you're throwing exceptions in production
  216. * code, which is bad).
  217. *
  218. * In tests this is more acceptable.
  219. *
  220. * Prefer other methods to this, such as `.each`.
  221. */
  222. getOrDie(message) {
  223. if (!this.tag) {
  224. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  225. }
  226. else {
  227. return this.value;
  228. }
  229. }
  230. // --- Interop with null and undefined ---
  231. /**
  232. * Creates an `Optional` value from a nullable (or undefined-able) input.
  233. * Null, or undefined, is converted to `None`, and anything else is converted
  234. * to `Some`.
  235. */
  236. static from(value) {
  237. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  238. }
  239. /**
  240. * Converts an `Optional` to a nullable type, by getting the value if it
  241. * exists, or returning `null` if it does not.
  242. */
  243. getOrNull() {
  244. return this.tag ? this.value : null;
  245. }
  246. /**
  247. * Converts an `Optional` to an undefined-able type, by getting the value if
  248. * it exists, or returning `undefined` if it does not.
  249. */
  250. getOrUndefined() {
  251. return this.value;
  252. }
  253. // --- Utilities ---
  254. /**
  255. * If the `Optional` contains a value, perform an action on that value.
  256. * Unlike the rest of the methods on this type, `.each` has side-effects. If
  257. * you want to transform an `Optional<T>` **into** something, then this is not
  258. * the method for you. If you want to use an `Optional<T>` to **do**
  259. * something, then this is the method for you - provided you're okay with not
  260. * doing anything in the case where the `Optional` doesn't have a value inside
  261. * it. If you're not sure whether your use-case fits into transforming
  262. * **into** something or **doing** something, check whether it has a return
  263. * value. If it does, you should be performing a transform.
  264. */
  265. each(worker) {
  266. if (this.tag) {
  267. worker(this.value);
  268. }
  269. }
  270. /**
  271. * Turn the `Optional` object into an array that contains all of the values
  272. * stored inside the `Optional`. In practice, this means the output will have
  273. * either 0 or 1 elements.
  274. */
  275. toArray() {
  276. return this.tag ? [this.value] : [];
  277. }
  278. /**
  279. * Turn the `Optional` object into a string for debugging or printing. Not
  280. * recommended for production code, but good for debugging. Also note that
  281. * these days an `Optional` object can be logged to the console directly, and
  282. * its inner value (if it exists) will be visible.
  283. */
  284. toString() {
  285. return this.tag ? `some(${this.value})` : 'none()';
  286. }
  287. }
  288. // Sneaky optimisation: every instance of Optional.none is identical, so just
  289. // reuse the same object
  290. Optional.singletonNone = new Optional(false);
  291. const nativeSlice = Array.prototype.slice;
  292. const nativePush = Array.prototype.push;
  293. // Unwound implementing other functions in terms of each.
  294. // The code size is roughly the same, and it should allow for better optimisation.
  295. // const each = function<T, U>(xs: T[], f: (x: T, i?: number, xs?: T[]) => void): void {
  296. const each$1 = (xs, f) => {
  297. for (let i = 0, len = xs.length; i < len; i++) {
  298. const x = xs[i];
  299. f(x, i);
  300. }
  301. };
  302. const flatten = (xs) => {
  303. // Note, this is possible because push supports multiple arguments:
  304. // http://jsperf.com/concat-push/6
  305. // Note that in the past, concat() would silently work (very slowly) for array-like objects.
  306. // With this change it will throw an error.
  307. const r = [];
  308. for (let i = 0, len = xs.length; i < len; ++i) {
  309. // Ensure that each value is an array itself
  310. if (!isArray(xs[i])) {
  311. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  312. }
  313. nativePush.apply(r, xs[i]);
  314. }
  315. return r;
  316. };
  317. isFunction(Array.from) ? Array.from : (x) => nativeSlice.call(x);
  318. // There are many variations of Object iteration that are faster than the 'for-in' style:
  319. // http://jsperf.com/object-keys-iteration/107
  320. //
  321. // Use the native keys if it is available (IE9+), otherwise fall back to manually filtering
  322. const keys = Object.keys;
  323. const hasOwnProperty = Object.hasOwnProperty;
  324. const each = (obj, f) => {
  325. const props = keys(obj);
  326. for (let k = 0, len = props.length; k < len; k++) {
  327. const i = props[k];
  328. const x = obj[i];
  329. f(x, i);
  330. }
  331. };
  332. const get$1 = (obj, key) => {
  333. return has(obj, key) ? Optional.from(obj[key]) : Optional.none();
  334. };
  335. const has = (obj, key) => hasOwnProperty.call(obj, key);
  336. const Cell = (initial) => {
  337. let value = initial;
  338. const get = () => {
  339. return value;
  340. };
  341. const set = (v) => {
  342. value = v;
  343. };
  344. return {
  345. get,
  346. set
  347. };
  348. };
  349. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  350. /** Does 'str' start with 'prefix'?
  351. * Note: all strings start with the empty string.
  352. * More formally, for all strings x, startsWith(x, "").
  353. * This is so that for all strings x and y, startsWith(y + x, y)
  354. */
  355. const startsWith = (str, prefix) => {
  356. return checkRange(str, prefix, 0);
  357. };
  358. const option = (name) => (editor) => editor.options.get(name);
  359. const register$2 = (editor) => {
  360. const registerOption = editor.options.register;
  361. registerOption('audio_template_callback', {
  362. processor: 'function'
  363. });
  364. registerOption('video_template_callback', {
  365. processor: 'function'
  366. });
  367. registerOption('iframe_template_callback', {
  368. processor: 'function'
  369. });
  370. registerOption('media_live_embeds', {
  371. processor: 'boolean',
  372. default: true
  373. });
  374. registerOption('media_filter_html', {
  375. processor: 'boolean',
  376. default: true
  377. });
  378. registerOption('media_url_resolver', {
  379. processor: 'function'
  380. });
  381. registerOption('media_alt_source', {
  382. processor: 'boolean',
  383. default: true
  384. });
  385. registerOption('media_poster', {
  386. processor: 'boolean',
  387. default: true
  388. });
  389. registerOption('media_dimensions', {
  390. processor: 'boolean',
  391. default: true
  392. });
  393. };
  394. const getAudioTemplateCallback = option('audio_template_callback');
  395. const getVideoTemplateCallback = option('video_template_callback');
  396. const getIframeTemplateCallback = option('iframe_template_callback');
  397. const hasLiveEmbeds = option('media_live_embeds');
  398. const shouldFilterHtml = option('media_filter_html');
  399. const getUrlResolver = option('media_url_resolver');
  400. const hasAltSource = option('media_alt_source');
  401. const hasPoster = option('media_poster');
  402. const hasDimensions = option('media_dimensions');
  403. var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  404. var global$4 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  405. var global$3 = tinymce.util.Tools.resolve('tinymce.html.DomParser');
  406. const DOM$1 = global$4.DOM;
  407. const trimPx = (value) => value.replace(/px$/, '');
  408. const getEphoxEmbedData = (node) => {
  409. const style = node.attr('style');
  410. const styles = style ? DOM$1.parseStyle(style) : {};
  411. return {
  412. type: 'ephox-embed-iri',
  413. source: node.attr('data-ephox-embed-iri'),
  414. altsource: '',
  415. poster: '',
  416. width: get$1(styles, 'max-width').map(trimPx).getOr(''),
  417. height: get$1(styles, 'max-height').map(trimPx).getOr('')
  418. };
  419. };
  420. const htmlToData = (html, schema) => {
  421. let data = {};
  422. const parser = global$3({ validate: false, forced_root_block: false }, schema);
  423. const rootNode = parser.parse(html);
  424. for (let node = rootNode; node; node = node.walk()) {
  425. if (node.type === 1) {
  426. const name = node.name;
  427. if (node.attr('data-ephox-embed-iri')) {
  428. data = getEphoxEmbedData(node);
  429. // Don't continue to collect if we find an EME embed
  430. break;
  431. }
  432. else {
  433. if (!data.source && name === 'param') {
  434. data.source = node.attr('movie');
  435. }
  436. if (name === 'iframe' || name === 'object' || name === 'embed' || name === 'video' || name === 'audio') {
  437. if (!data.type) {
  438. data.type = name;
  439. }
  440. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  441. data = global$5.extend(node.attributes.map, data);
  442. }
  443. if (name === 'source') {
  444. if (!data.source) {
  445. data.source = node.attr('src');
  446. }
  447. else if (!data.altsource) {
  448. data.altsource = node.attr('src');
  449. }
  450. }
  451. if (name === 'img' && !data.poster) {
  452. data.poster = node.attr('src');
  453. }
  454. }
  455. }
  456. }
  457. data.source = data.source || data.src || '';
  458. data.altsource = data.altsource || '';
  459. data.poster = data.poster || '';
  460. return data;
  461. };
  462. const guess = (url) => {
  463. var _a;
  464. const mimes = {
  465. mp3: 'audio/mpeg',
  466. m4a: 'audio/x-m4a',
  467. wav: 'audio/wav',
  468. mp4: 'video/mp4',
  469. webm: 'video/webm',
  470. ogg: 'video/ogg',
  471. swf: 'application/x-shockwave-flash'
  472. };
  473. const fileEnd = (_a = url.toLowerCase().split('.').pop()) !== null && _a !== void 0 ? _a : '';
  474. return get$1(mimes, fileEnd).getOr('');
  475. };
  476. var global$2 = tinymce.util.Tools.resolve('tinymce.html.Node');
  477. var global$1 = tinymce.util.Tools.resolve('tinymce.html.Serializer');
  478. const Parser = (schema, settings = {}) => global$3({
  479. forced_root_block: false,
  480. validate: false,
  481. allow_conditional_comments: true,
  482. ...settings
  483. }, schema);
  484. const DOM = global$4.DOM;
  485. const addPx = (value) => /^[0-9.]+$/.test(value) ? (value + 'px') : value;
  486. const updateEphoxEmbed = (data, node) => {
  487. const style = node.attr('style');
  488. const styleMap = style ? DOM.parseStyle(style) : {};
  489. if (isNonNullable(data.width)) {
  490. styleMap['max-width'] = addPx(data.width);
  491. }
  492. if (isNonNullable(data.height)) {
  493. styleMap['max-height'] = addPx(data.height);
  494. }
  495. node.attr('style', DOM.serializeStyle(styleMap));
  496. };
  497. const sources = ['source', 'altsource'];
  498. const updateHtml = (html, data, updateAll, schema) => {
  499. let numSources = 0;
  500. let sourceCount = 0;
  501. const parser = Parser(schema);
  502. parser.addNodeFilter('source', (nodes) => numSources = nodes.length);
  503. const rootNode = parser.parse(html);
  504. for (let node = rootNode; node; node = node.walk()) {
  505. if (node.type === 1) {
  506. const name = node.name;
  507. if (node.attr('data-ephox-embed-iri')) {
  508. updateEphoxEmbed(data, node);
  509. // Don't continue to update if we find an EME embed
  510. break;
  511. }
  512. else {
  513. switch (name) {
  514. case 'video':
  515. case 'object':
  516. case 'embed':
  517. case 'img':
  518. case 'iframe':
  519. if (data.height !== undefined && data.width !== undefined) {
  520. node.attr('width', data.width);
  521. node.attr('height', data.height);
  522. }
  523. break;
  524. }
  525. if (updateAll) {
  526. switch (name) {
  527. case 'video':
  528. node.attr('poster', data.poster);
  529. node.attr('src', null);
  530. // Add <source> child elements
  531. for (let index = numSources; index < 2; index++) {
  532. if (data[sources[index]]) {
  533. const source = new global$2('source', 1);
  534. source.attr('src', data[sources[index]]);
  535. source.attr('type', data[sources[index] + 'mime'] || null);
  536. node.append(source);
  537. }
  538. }
  539. break;
  540. case 'iframe':
  541. node.attr('src', data.source);
  542. break;
  543. case 'object':
  544. const hasImage = node.getAll('img').length > 0;
  545. if (data.poster && !hasImage) {
  546. node.attr('src', data.poster);
  547. const img = new global$2('img', 1);
  548. img.attr('src', data.poster);
  549. img.attr('width', data.width);
  550. img.attr('height', data.height);
  551. node.append(img);
  552. }
  553. break;
  554. case 'source':
  555. if (sourceCount < 2) {
  556. node.attr('src', data[sources[sourceCount]]);
  557. node.attr('type', data[sources[sourceCount] + 'mime'] || null);
  558. if (!data[sources[sourceCount]]) {
  559. node.remove();
  560. continue;
  561. }
  562. }
  563. sourceCount++;
  564. break;
  565. case 'img':
  566. if (!data.poster) {
  567. node.remove();
  568. }
  569. break;
  570. }
  571. }
  572. }
  573. }
  574. }
  575. return global$1({}, schema).serialize(rootNode);
  576. };
  577. const urlPatterns = [
  578. {
  579. regex: /youtu\.be\/([\w\-_\?&=.]+)/i,
  580. type: 'iframe', w: 560, h: 314,
  581. url: 'www.youtube.com/embed/$1',
  582. allowFullscreen: true
  583. },
  584. {
  585. regex: /youtube\.com(.+)v=([^&]+)(&([a-z0-9&=\-_]+))?/i,
  586. type: 'iframe', w: 560, h: 314,
  587. url: 'www.youtube.com/embed/$2?$4',
  588. allowFullscreen: true
  589. },
  590. {
  591. regex: /youtube.com\/embed\/([a-z0-9\?&=\-_]+)/i,
  592. type: 'iframe', w: 560, h: 314,
  593. url: 'www.youtube.com/embed/$1',
  594. allowFullscreen: true
  595. },
  596. {
  597. regex: /vimeo\.com\/([0-9]+)\?h=(\w+)/,
  598. type: 'iframe', w: 425, h: 350,
  599. url: 'player.vimeo.com/video/$1?h=$2&title=0&byline=0&portrait=0&color=8dc7dc',
  600. allowFullscreen: true
  601. },
  602. {
  603. regex: /vimeo\.com\/(.*)\/([0-9]+)\?h=(\w+)/,
  604. type: 'iframe', w: 425, h: 350,
  605. url: 'player.vimeo.com/video/$2?h=$3&title=0&amp;byline=0',
  606. allowFullscreen: true
  607. },
  608. {
  609. regex: /vimeo\.com\/([0-9]+)/,
  610. type: 'iframe', w: 425, h: 350,
  611. url: 'player.vimeo.com/video/$1?title=0&byline=0&portrait=0&color=8dc7dc',
  612. allowFullscreen: true
  613. },
  614. {
  615. regex: /vimeo\.com\/(.*)\/([0-9]+)/,
  616. type: 'iframe', w: 425, h: 350,
  617. url: 'player.vimeo.com/video/$2?title=0&amp;byline=0',
  618. allowFullscreen: true
  619. },
  620. {
  621. regex: /maps\.google\.([a-z]{2,3})\/maps\/(.+)msid=(.+)/,
  622. type: 'iframe', w: 425, h: 350,
  623. url: 'maps.google.com/maps/ms?msid=$2&output=embed"',
  624. allowFullscreen: false
  625. },
  626. {
  627. regex: /dailymotion\.com\/video\/([^_]+)/,
  628. type: 'iframe', w: 480, h: 270,
  629. url: 'www.dailymotion.com/embed/video/$1',
  630. allowFullscreen: true
  631. },
  632. {
  633. regex: /dai\.ly\/([^_]+)/,
  634. type: 'iframe', w: 480, h: 270,
  635. url: 'www.dailymotion.com/embed/video/$1',
  636. allowFullscreen: true
  637. }
  638. ];
  639. const getProtocol = (url) => {
  640. const protocolMatches = url.match(/^(https?:\/\/|www\.)(.+)$/i);
  641. if (protocolMatches && protocolMatches.length > 1) {
  642. return protocolMatches[1] === 'www.' ? 'https://' : protocolMatches[1];
  643. }
  644. else {
  645. return 'https://';
  646. }
  647. };
  648. const getUrl = (pattern, url) => {
  649. const protocol = getProtocol(url);
  650. const match = pattern.regex.exec(url);
  651. let newUrl = protocol + pattern.url;
  652. if (isNonNullable(match)) {
  653. for (let i = 0; i < match.length; i++) {
  654. newUrl = newUrl.replace('$' + i, () => match[i] ? match[i] : '');
  655. }
  656. }
  657. return newUrl.replace(/\?$/, '');
  658. };
  659. const matchPattern = (url) => {
  660. const patterns = urlPatterns.filter((pattern) => pattern.regex.test(url));
  661. if (patterns.length > 0) {
  662. return global$5.extend({}, patterns[0], { url: getUrl(patterns[0], url) });
  663. }
  664. else {
  665. return null;
  666. }
  667. };
  668. const getIframeHtml = (data, iframeTemplateCallback) => {
  669. if (iframeTemplateCallback) {
  670. return iframeTemplateCallback(data);
  671. }
  672. else {
  673. const allowFullscreen = data.allowfullscreen ? ' allowFullscreen="1"' : '';
  674. return '<iframe src="' + data.source + '" width="' + data.width + '" height="' + data.height + '"' + allowFullscreen + '></iframe>';
  675. }
  676. };
  677. const getFlashHtml = (data) => {
  678. let html = '<object data="' + data.source + '" width="' + data.width + '" height="' + data.height + '" type="application/x-shockwave-flash">';
  679. if (data.poster) {
  680. html += '<img src="' + data.poster + '" width="' + data.width + '" height="' + data.height + '" />';
  681. }
  682. html += '</object>';
  683. return html;
  684. };
  685. const getAudioHtml = (data, audioTemplateCallback) => {
  686. if (audioTemplateCallback) {
  687. return audioTemplateCallback(data);
  688. }
  689. else {
  690. return ('<audio controls="controls" src="' + data.source + '">' +
  691. (data.altsource ?
  692. '\n<source src="' + data.altsource + '"' +
  693. (data.altsourcemime ? ' type="' + data.altsourcemime + '"' : '') +
  694. ' />\n' : '') +
  695. '</audio>');
  696. }
  697. };
  698. const getVideoHtml = (data, videoTemplateCallback) => {
  699. if (videoTemplateCallback) {
  700. return videoTemplateCallback(data);
  701. }
  702. else {
  703. return ('<video width="' + data.width +
  704. '" height="' + data.height + '"' +
  705. (data.poster ? ' poster="' + data.poster + '"' : '') + ' controls="controls">\n' +
  706. '<source src="' + data.source + '"' +
  707. (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + ' />\n' +
  708. (data.altsource ? '<source src="' + data.altsource + '"' +
  709. (data.altsourcemime ? ' type="' + data.altsourcemime + '"' : '') + ' />\n' : '') +
  710. '</video>');
  711. }
  712. };
  713. const dataToHtml = (editor, dataIn) => {
  714. var _a;
  715. const data = global$5.extend({}, dataIn);
  716. if (!data.source) {
  717. global$5.extend(data, htmlToData((_a = data.embed) !== null && _a !== void 0 ? _a : '', editor.schema));
  718. if (!data.source) {
  719. return '';
  720. }
  721. }
  722. if (!data.altsource) {
  723. data.altsource = '';
  724. }
  725. if (!data.poster) {
  726. data.poster = '';
  727. }
  728. data.source = editor.convertURL(data.source, 'source');
  729. data.altsource = editor.convertURL(data.altsource, 'source');
  730. data.sourcemime = guess(data.source);
  731. data.altsourcemime = guess(data.altsource);
  732. data.poster = editor.convertURL(data.poster, 'poster');
  733. const pattern = matchPattern(data.source);
  734. if (pattern) {
  735. data.source = pattern.url;
  736. data.type = pattern.type;
  737. data.allowfullscreen = pattern.allowFullscreen;
  738. data.width = data.width || String(pattern.w);
  739. data.height = data.height || String(pattern.h);
  740. }
  741. if (data.embed) {
  742. return updateHtml(data.embed, data, true, editor.schema);
  743. }
  744. else {
  745. const audioTemplateCallback = getAudioTemplateCallback(editor);
  746. const videoTemplateCallback = getVideoTemplateCallback(editor);
  747. const iframeTemplateCallback = getIframeTemplateCallback(editor);
  748. data.width = data.width || '300';
  749. data.height = data.height || '150';
  750. global$5.each(data, (value, key) => {
  751. data[key] = editor.dom.encode('' + value);
  752. });
  753. if (data.type === 'iframe') {
  754. return getIframeHtml(data, iframeTemplateCallback);
  755. }
  756. else if (data.sourcemime === 'application/x-shockwave-flash') {
  757. return getFlashHtml(data);
  758. }
  759. else if (data.sourcemime.indexOf('audio') !== -1) {
  760. return getAudioHtml(data, audioTemplateCallback);
  761. }
  762. else {
  763. return getVideoHtml(data, videoTemplateCallback);
  764. }
  765. }
  766. };
  767. const isMediaElement = (element) => element.hasAttribute('data-mce-object') || element.hasAttribute('data-ephox-embed-iri');
  768. const setup$2 = (editor) => {
  769. // TINY-10774: On Safari all events bubble out even if you click on the video play button on other browsers the video element doesn't bubble the event
  770. editor.on('mousedown', (e) => {
  771. const previewObj = editor.dom.getParent(e.target, '.mce-preview-object');
  772. if (previewObj && editor.dom.getAttrib(previewObj, 'data-mce-selected') === '2') {
  773. e.stopImmediatePropagation();
  774. }
  775. });
  776. editor.on('click keyup touchend', () => {
  777. const selectedNode = editor.selection.getNode();
  778. if (selectedNode && editor.dom.hasClass(selectedNode, 'mce-preview-object')) {
  779. if (editor.dom.getAttrib(selectedNode, 'data-mce-selected')) {
  780. selectedNode.setAttribute('data-mce-selected', '2');
  781. }
  782. }
  783. });
  784. editor.on('ObjectResized', (e) => {
  785. const target = e.target;
  786. if (target.getAttribute('data-mce-object')) {
  787. let html = target.getAttribute('data-mce-html');
  788. if (html) {
  789. html = unescape(html);
  790. target.setAttribute('data-mce-html', escape(updateHtml(html, {
  791. width: String(e.width),
  792. height: String(e.height)
  793. }, false, editor.schema)));
  794. }
  795. }
  796. });
  797. };
  798. const cache = {};
  799. const embedPromise = (data, dataToHtml, handler) => {
  800. return new Promise((res, rej) => {
  801. const wrappedResolve = (response) => {
  802. if (response.html) {
  803. cache[data.source] = response;
  804. }
  805. return res({
  806. url: data.source,
  807. html: response.html ? response.html : dataToHtml(data)
  808. });
  809. };
  810. if (cache[data.source]) {
  811. wrappedResolve(cache[data.source]);
  812. }
  813. else {
  814. handler({ url: data.source }).then(wrappedResolve).catch(rej);
  815. }
  816. });
  817. };
  818. const defaultPromise = (data, dataToHtml) => Promise.resolve({ html: dataToHtml(data), url: data.source });
  819. const loadedData = (editor) => (data) => dataToHtml(editor, data);
  820. const getEmbedHtml = (editor, data) => {
  821. const embedHandler = getUrlResolver(editor);
  822. return embedHandler ? embedPromise(data, loadedData(editor), embedHandler) : defaultPromise(data, loadedData(editor));
  823. };
  824. const isCached = (url) => has(cache, url);
  825. const extractMeta = (sourceInput, data) => get$1(data, sourceInput).bind((mainData) => get$1(mainData, 'meta'));
  826. const getValue = (data, metaData, sourceInput) => (prop) => {
  827. // Cases:
  828. // 1. Get the nested value prop (component is the executed urlinput)
  829. // 2. Get from metadata (a urlinput was executed but urlinput != this component)
  830. // 3. Not a urlinput so just get string
  831. // If prop === sourceInput do 1, 2 then 3, else do 2 then 1 or 3
  832. // ASSUMPTION: we only want to get values for props that already exist in data
  833. const getFromData = () => get$1(data, prop);
  834. const getFromMetaData = () => get$1(metaData, prop);
  835. const getNonEmptyValue = (c) => get$1(c, 'value').bind((v) => v.length > 0 ? Optional.some(v) : Optional.none());
  836. const getFromValueFirst = () => getFromData().bind((child) => isObject(child)
  837. ? getNonEmptyValue(child).orThunk(getFromMetaData)
  838. : getFromMetaData().orThunk(() => Optional.from(child)));
  839. const getFromMetaFirst = () => getFromMetaData().orThunk(() => getFromData().bind((child) => isObject(child)
  840. ? getNonEmptyValue(child)
  841. : Optional.from(child)));
  842. return { [prop]: (prop === sourceInput ? getFromValueFirst() : getFromMetaFirst()).getOr('') };
  843. };
  844. const getDimensions = (data, metaData) => {
  845. const dimensions = {};
  846. get$1(data, 'dimensions').each((dims) => {
  847. each$1(['width', 'height'], (prop) => {
  848. get$1(metaData, prop).orThunk(() => get$1(dims, prop)).each((value) => dimensions[prop] = value);
  849. });
  850. });
  851. return dimensions;
  852. };
  853. const unwrap = (data, sourceInput) => {
  854. const metaData = sourceInput && sourceInput !== 'dimensions' ? extractMeta(sourceInput, data).getOr({}) : {};
  855. const get = getValue(data, metaData, sourceInput);
  856. return {
  857. ...get('source'),
  858. ...get('altsource'),
  859. ...get('poster'),
  860. ...get('embed'),
  861. ...getDimensions(data, metaData)
  862. };
  863. };
  864. const wrap = (data) => {
  865. const wrapped = {
  866. ...data,
  867. source: { value: get$1(data, 'source').getOr('') },
  868. altsource: { value: get$1(data, 'altsource').getOr('') },
  869. poster: { value: get$1(data, 'poster').getOr('') }
  870. };
  871. // Add additional size values that may or may not have been in the html
  872. each$1(['width', 'height'], (prop) => {
  873. get$1(data, prop).each((value) => {
  874. const dimensions = wrapped.dimensions || {};
  875. dimensions[prop] = value;
  876. wrapped.dimensions = dimensions;
  877. });
  878. });
  879. return wrapped;
  880. };
  881. const handleError = (editor) => (error) => {
  882. const errorMessage = error && error.msg ?
  883. 'Media embed handler error: ' + error.msg :
  884. 'Media embed handler threw unknown error.';
  885. editor.notificationManager.open({ type: 'error', text: errorMessage });
  886. };
  887. const getEditorData = (editor) => {
  888. const element = editor.selection.getNode();
  889. const snippet = isMediaElement(element) ? editor.serializer.serialize(element, { selection: true }) : '';
  890. const data = htmlToData(snippet, editor.schema);
  891. const getDimensionsOfElement = () => {
  892. if (isEmbedIframe(data.source, data.type)) {
  893. const rect = editor.dom.getRect(element);
  894. return {
  895. width: rect.w.toString().replace(/px$/, ''),
  896. height: rect.h.toString().replace(/px$/, ''),
  897. };
  898. }
  899. else {
  900. return {};
  901. }
  902. };
  903. const dimensions = getDimensionsOfElement();
  904. return {
  905. embed: snippet,
  906. ...data,
  907. ...dimensions
  908. };
  909. };
  910. const addEmbedHtml = (api, editor) => (response) => {
  911. // Only set values if a URL has been defined
  912. if (isString(response.url) && response.url.trim().length > 0) {
  913. const html = response.html;
  914. const snippetData = htmlToData(html, editor.schema);
  915. const nuData = {
  916. ...snippetData,
  917. source: response.url,
  918. embed: html
  919. };
  920. api.setData(wrap(nuData));
  921. }
  922. };
  923. const selectPlaceholder = (editor, beforeObjects) => {
  924. const afterObjects = editor.dom.select('*[data-mce-object]');
  925. // Find new image placeholder so we can select it
  926. for (let i = 0; i < beforeObjects.length; i++) {
  927. for (let y = afterObjects.length - 1; y >= 0; y--) {
  928. if (beforeObjects[i] === afterObjects[y]) {
  929. afterObjects.splice(y, 1);
  930. }
  931. }
  932. }
  933. editor.selection.select(afterObjects[0]);
  934. };
  935. const handleInsert = (editor, html) => {
  936. const beforeObjects = editor.dom.select('*[data-mce-object]');
  937. editor.insertContent(html);
  938. selectPlaceholder(editor, beforeObjects);
  939. editor.nodeChanged();
  940. };
  941. const isEmbedIframe = (url, mediaDataType) => isNonNullable(mediaDataType) && mediaDataType === 'ephox-embed-iri' && isNonNullable(matchPattern(url));
  942. const shouldInsertAsNewIframe = (prevData, newData) => {
  943. const hasDimensionsChanged = (prevData, newData) => prevData.width !== newData.width || prevData.height !== newData.height;
  944. return hasDimensionsChanged(prevData, newData) && isEmbedIframe(newData.source, prevData.type);
  945. };
  946. const submitForm = (prevData, newData, editor) => {
  947. var _a;
  948. newData.embed =
  949. shouldInsertAsNewIframe(prevData, newData) && hasDimensions(editor)
  950. ? dataToHtml(editor, { ...newData, embed: '' })
  951. : updateHtml((_a = newData.embed) !== null && _a !== void 0 ? _a : '', newData, false, editor.schema);
  952. // Only fetch the embed HTML content if the URL has changed from what it previously was
  953. if (newData.embed && (prevData.source === newData.source || isCached(newData.source))) {
  954. handleInsert(editor, newData.embed);
  955. }
  956. else {
  957. getEmbedHtml(editor, newData)
  958. .then((response) => {
  959. handleInsert(editor, response.html);
  960. }).catch(handleError(editor));
  961. }
  962. };
  963. const showDialog = (editor) => {
  964. const editorData = getEditorData(editor);
  965. const currentData = Cell(editorData);
  966. const initialData = wrap(editorData);
  967. const handleSource = (prevData, api) => {
  968. const serviceData = unwrap(api.getData(), 'source');
  969. // If a new URL is entered, then clear the embed html and fetch the new data
  970. if (prevData.source !== serviceData.source) {
  971. addEmbedHtml(win, editor)({ url: serviceData.source, html: '' });
  972. getEmbedHtml(editor, serviceData)
  973. .then(addEmbedHtml(win, editor))
  974. .catch(handleError(editor));
  975. }
  976. };
  977. const handleEmbed = (api) => {
  978. var _a;
  979. const data = unwrap(api.getData());
  980. const dataFromEmbed = htmlToData((_a = data.embed) !== null && _a !== void 0 ? _a : '', editor.schema);
  981. api.setData(wrap(dataFromEmbed));
  982. };
  983. const handleUpdate = (api, sourceInput, prevData) => {
  984. const dialogData = unwrap(api.getData(), sourceInput);
  985. const data = shouldInsertAsNewIframe(prevData, dialogData) && hasDimensions(editor)
  986. ? { ...dialogData, embed: '' }
  987. : dialogData;
  988. const embed = dataToHtml(editor, data);
  989. api.setData(wrap({
  990. ...data,
  991. embed
  992. }));
  993. };
  994. const mediaInput = [{
  995. name: 'source',
  996. type: 'urlinput',
  997. filetype: 'media',
  998. label: 'Source',
  999. picker_text: 'Browse files'
  1000. }];
  1001. const sizeInput = !hasDimensions(editor) ? [] : [{
  1002. type: 'sizeinput',
  1003. name: 'dimensions',
  1004. label: 'Constrain proportions',
  1005. constrain: true
  1006. }];
  1007. const generalTab = {
  1008. title: 'General',
  1009. name: 'general',
  1010. items: flatten([mediaInput, sizeInput])
  1011. };
  1012. const embedTextarea = {
  1013. type: 'textarea',
  1014. name: 'embed',
  1015. label: 'Paste your embed code below:'
  1016. };
  1017. const embedTab = {
  1018. title: 'Embed',
  1019. items: [
  1020. embedTextarea
  1021. ]
  1022. };
  1023. const advancedFormItems = [];
  1024. if (hasAltSource(editor)) {
  1025. advancedFormItems.push({
  1026. name: 'altsource',
  1027. type: 'urlinput',
  1028. filetype: 'media',
  1029. label: 'Alternative source URL'
  1030. });
  1031. }
  1032. if (hasPoster(editor)) {
  1033. advancedFormItems.push({
  1034. name: 'poster',
  1035. type: 'urlinput',
  1036. filetype: 'image',
  1037. label: 'Media poster (Image URL)'
  1038. });
  1039. }
  1040. const advancedTab = {
  1041. title: 'Advanced',
  1042. name: 'advanced',
  1043. items: advancedFormItems
  1044. };
  1045. const tabs = [
  1046. generalTab,
  1047. embedTab
  1048. ];
  1049. if (advancedFormItems.length > 0) {
  1050. tabs.push(advancedTab);
  1051. }
  1052. const body = {
  1053. type: 'tabpanel',
  1054. tabs
  1055. };
  1056. const win = editor.windowManager.open({
  1057. title: 'Insert/Edit Media',
  1058. size: 'normal',
  1059. body,
  1060. buttons: [
  1061. {
  1062. type: 'cancel',
  1063. name: 'cancel',
  1064. text: 'Cancel'
  1065. },
  1066. {
  1067. type: 'submit',
  1068. name: 'save',
  1069. text: 'Save',
  1070. primary: true
  1071. }
  1072. ],
  1073. onSubmit: (api) => {
  1074. const serviceData = unwrap(api.getData());
  1075. submitForm(currentData.get(), serviceData, editor);
  1076. api.close();
  1077. },
  1078. onChange: (api, detail) => {
  1079. switch (detail.name) {
  1080. case 'source':
  1081. handleSource(currentData.get(), api);
  1082. break;
  1083. case 'embed':
  1084. handleEmbed(api);
  1085. break;
  1086. case 'dimensions':
  1087. case 'altsource':
  1088. case 'poster':
  1089. handleUpdate(api, detail.name, currentData.get());
  1090. break;
  1091. }
  1092. currentData.set(unwrap(api.getData()));
  1093. },
  1094. initialData
  1095. });
  1096. };
  1097. const get = (editor) => {
  1098. const showDialog$1 = () => {
  1099. showDialog(editor);
  1100. };
  1101. return {
  1102. showDialog: showDialog$1
  1103. };
  1104. };
  1105. const register$1 = (editor) => {
  1106. const showDialog$1 = () => {
  1107. showDialog(editor);
  1108. };
  1109. editor.addCommand('mceMedia', showDialog$1);
  1110. };
  1111. var global = tinymce.util.Tools.resolve('tinymce.Env');
  1112. const isLiveEmbedNode = (node) => {
  1113. const name = node.name;
  1114. return name === 'iframe' || name === 'video' || name === 'audio';
  1115. };
  1116. const getDimension = (node, styles, dimension, defaultValue = null) => {
  1117. const value = node.attr(dimension);
  1118. if (isNonNullable(value)) {
  1119. return value;
  1120. }
  1121. else if (!has(styles, dimension)) {
  1122. return defaultValue;
  1123. }
  1124. else {
  1125. return null;
  1126. }
  1127. };
  1128. const setDimensions = (node, previewNode, styles) => {
  1129. // Apply dimensions for video elements to maintain legacy behaviour
  1130. const useDefaults = previewNode.name === 'img' || node.name === 'video';
  1131. // Determine the defaults
  1132. const defaultWidth = useDefaults ? '300' : null;
  1133. const fallbackHeight = node.name === 'audio' ? '30' : '150';
  1134. const defaultHeight = useDefaults ? fallbackHeight : null;
  1135. previewNode.attr({
  1136. width: getDimension(node, styles, 'width', defaultWidth),
  1137. height: getDimension(node, styles, 'height', defaultHeight)
  1138. });
  1139. };
  1140. const appendNodeContent = (editor, nodeName, previewNode, html) => {
  1141. const newNode = Parser(editor.schema).parse(html, { context: nodeName });
  1142. while (newNode.firstChild) {
  1143. previewNode.append(newNode.firstChild);
  1144. }
  1145. };
  1146. const createPlaceholderNode = (editor, node) => {
  1147. const name = node.name;
  1148. const placeHolder = new global$2('img', 1);
  1149. retainAttributesAndInnerHtml(editor, node, placeHolder);
  1150. setDimensions(node, placeHolder, {});
  1151. placeHolder.attr({
  1152. 'style': node.attr('style'),
  1153. 'src': global.transparentSrc,
  1154. 'data-mce-object': name,
  1155. 'class': 'mce-object mce-object-' + name
  1156. });
  1157. return placeHolder;
  1158. };
  1159. const createPreviewNode = (editor, node) => {
  1160. var _a;
  1161. const name = node.name;
  1162. const previewWrapper = new global$2('span', 1);
  1163. previewWrapper.attr({
  1164. 'contentEditable': 'false',
  1165. 'style': node.attr('style'),
  1166. 'data-mce-object': name,
  1167. 'class': 'mce-preview-object mce-object-' + name
  1168. });
  1169. retainAttributesAndInnerHtml(editor, node, previewWrapper);
  1170. const styles = editor.dom.parseStyle((_a = node.attr('style')) !== null && _a !== void 0 ? _a : '');
  1171. const previewNode = new global$2(name, 1);
  1172. setDimensions(node, previewNode, styles);
  1173. previewNode.attr({
  1174. src: node.attr('src'),
  1175. style: node.attr('style'),
  1176. class: node.attr('class')
  1177. });
  1178. if (name === 'iframe') {
  1179. previewNode.attr({
  1180. allowfullscreen: node.attr('allowfullscreen'),
  1181. frameborder: '0',
  1182. sandbox: node.attr('sandbox'),
  1183. referrerpolicy: node.attr('referrerpolicy')
  1184. });
  1185. }
  1186. else {
  1187. // Exclude autoplay as we don't want video/audio to play by default
  1188. const attrs = ['controls', 'crossorigin', 'currentTime', 'loop', 'muted', 'poster', 'preload'];
  1189. each$1(attrs, (attrName) => {
  1190. previewNode.attr(attrName, node.attr(attrName));
  1191. });
  1192. // Recreate the child nodes using the sanitized inner HTML
  1193. const sanitizedHtml = previewWrapper.attr('data-mce-html');
  1194. if (isNonNullable(sanitizedHtml)) {
  1195. appendNodeContent(editor, name, previewNode, unescape(sanitizedHtml));
  1196. }
  1197. }
  1198. const shimNode = new global$2('span', 1);
  1199. shimNode.attr('class', 'mce-shim');
  1200. previewWrapper.append(previewNode);
  1201. previewWrapper.append(shimNode);
  1202. return previewWrapper;
  1203. };
  1204. const retainAttributesAndInnerHtml = (editor, sourceNode, targetNode) => {
  1205. var _a;
  1206. // Prefix all attributes except internal (data-mce-*), width, height and style since we
  1207. // will add these to the placeholder
  1208. const attribs = (_a = sourceNode.attributes) !== null && _a !== void 0 ? _a : [];
  1209. let ai = attribs.length;
  1210. while (ai--) {
  1211. const attrName = attribs[ai].name;
  1212. let attrValue = attribs[ai].value;
  1213. if (attrName !== 'width' && attrName !== 'height' && attrName !== 'style' && !startsWith(attrName, 'data-mce-')) {
  1214. if (attrName === 'data' || attrName === 'src') {
  1215. attrValue = editor.convertURL(attrValue, attrName);
  1216. }
  1217. targetNode.attr('data-mce-p-' + attrName, attrValue);
  1218. }
  1219. }
  1220. // Place the inner HTML contents inside an escaped attribute
  1221. // This enables us to copy/paste the fake object
  1222. const serializer = global$1({ inner: true }, editor.schema);
  1223. const tempNode = new global$2('div', 1);
  1224. each$1(sourceNode.children(), (child) => tempNode.append(child));
  1225. const innerHtml = serializer.serialize(tempNode);
  1226. if (innerHtml) {
  1227. targetNode.attr('data-mce-html', escape(innerHtml));
  1228. targetNode.empty();
  1229. }
  1230. };
  1231. const isPageEmbedWrapper = (node) => {
  1232. const nodeClass = node.attr('class');
  1233. return isString(nodeClass) && /\btiny-pageembed\b/.test(nodeClass);
  1234. };
  1235. const isWithinEmbedWrapper = (node) => {
  1236. let tempNode = node;
  1237. while ((tempNode = tempNode.parent)) {
  1238. if (tempNode.attr('data-ephox-embed-iri') || isPageEmbedWrapper(tempNode)) {
  1239. return true;
  1240. }
  1241. }
  1242. return false;
  1243. };
  1244. const placeHolderConverter = (editor) => (nodes) => {
  1245. let i = nodes.length;
  1246. let node;
  1247. while (i--) {
  1248. node = nodes[i];
  1249. if (!node.parent) {
  1250. continue;
  1251. }
  1252. if (node.parent.attr('data-mce-object')) {
  1253. continue;
  1254. }
  1255. if (isLiveEmbedNode(node) && hasLiveEmbeds(editor)) {
  1256. if (!isWithinEmbedWrapper(node)) {
  1257. node.replace(createPreviewNode(editor, node));
  1258. }
  1259. }
  1260. else {
  1261. if (!isWithinEmbedWrapper(node)) {
  1262. node.replace(createPlaceholderNode(editor, node));
  1263. }
  1264. }
  1265. }
  1266. };
  1267. const parseAndSanitize = (editor, context, html) => {
  1268. const getEditorOption = editor.options.get;
  1269. const sanitize = getEditorOption('xss_sanitization');
  1270. const validate = shouldFilterHtml(editor);
  1271. return Parser(editor.schema, { sanitize, validate }).parse(html, { context });
  1272. };
  1273. const setup$1 = (editor) => {
  1274. editor.on('PreInit', () => {
  1275. const { schema, serializer, parser } = editor;
  1276. // Set browser specific allowFullscreen attribs as boolean
  1277. const boolAttrs = schema.getBoolAttrs();
  1278. each$1('webkitallowfullscreen mozallowfullscreen'.split(' '), (name) => {
  1279. boolAttrs[name] = {};
  1280. });
  1281. // Add some non-standard attributes to the schema
  1282. each({
  1283. embed: ['wmode']
  1284. }, (attrs, name) => {
  1285. const rule = schema.getElementRule(name);
  1286. if (rule) {
  1287. each$1(attrs, (attr) => {
  1288. rule.attributes[attr] = {};
  1289. rule.attributesOrder.push(attr);
  1290. });
  1291. }
  1292. });
  1293. // Converts iframe, video etc into placeholder images
  1294. parser.addNodeFilter('iframe,video,audio,object,embed', placeHolderConverter(editor));
  1295. // Replaces placeholder images with real elements for video, object, iframe etc
  1296. serializer.addAttributeFilter('data-mce-object', (nodes, name) => {
  1297. var _a;
  1298. let i = nodes.length;
  1299. while (i--) {
  1300. const node = nodes[i];
  1301. if (!node.parent) {
  1302. continue;
  1303. }
  1304. const realElmName = node.attr(name);
  1305. const realElm = new global$2(realElmName, 1);
  1306. // Add width/height to everything but audio
  1307. if (realElmName !== 'audio') {
  1308. const className = node.attr('class');
  1309. if (className && className.indexOf('mce-preview-object') !== -1 && node.firstChild) {
  1310. realElm.attr({
  1311. width: node.firstChild.attr('width'),
  1312. height: node.firstChild.attr('height')
  1313. });
  1314. }
  1315. else {
  1316. realElm.attr({
  1317. width: node.attr('width'),
  1318. height: node.attr('height')
  1319. });
  1320. }
  1321. }
  1322. realElm.attr({
  1323. style: node.attr('style')
  1324. });
  1325. // Unprefix all placeholder attributes
  1326. const attribs = (_a = node.attributes) !== null && _a !== void 0 ? _a : [];
  1327. let ai = attribs.length;
  1328. while (ai--) {
  1329. const attrName = attribs[ai].name;
  1330. if (attrName.indexOf('data-mce-p-') === 0) {
  1331. realElm.attr(attrName.substr(11), attribs[ai].value);
  1332. }
  1333. }
  1334. // Inject innerhtml
  1335. const innerHtml = node.attr('data-mce-html');
  1336. if (innerHtml) {
  1337. const fragment = parseAndSanitize(editor, realElmName, unescape(innerHtml));
  1338. each$1(fragment.children(), (child) => realElm.append(child));
  1339. }
  1340. node.replace(realElm);
  1341. }
  1342. });
  1343. });
  1344. editor.on('SetContent', () => {
  1345. // TODO: This shouldn't be needed there should be a way to mark bogus
  1346. // elements so they are never removed except external save
  1347. const dom = editor.dom;
  1348. each$1(dom.select('span.mce-preview-object'), (elm) => {
  1349. if (dom.select('span.mce-shim', elm).length === 0) {
  1350. dom.add(elm, 'span', { class: 'mce-shim' });
  1351. }
  1352. });
  1353. });
  1354. };
  1355. const setup = (editor) => {
  1356. editor.on('ResolveName', (e) => {
  1357. let name;
  1358. if (e.target.nodeType === 1 && (name = e.target.getAttribute('data-mce-object'))) {
  1359. e.name = name;
  1360. }
  1361. });
  1362. };
  1363. const onSetupEditable = (editor) => (api) => {
  1364. const nodeChanged = () => {
  1365. api.setEnabled(editor.selection.isEditable());
  1366. };
  1367. editor.on('NodeChange', nodeChanged);
  1368. nodeChanged();
  1369. return () => {
  1370. editor.off('NodeChange', nodeChanged);
  1371. };
  1372. };
  1373. const register = (editor) => {
  1374. const onAction = () => editor.execCommand('mceMedia');
  1375. editor.ui.registry.addToggleButton('media', {
  1376. tooltip: 'Insert/edit media',
  1377. icon: 'embed',
  1378. onAction,
  1379. onSetup: (buttonApi) => {
  1380. const selection = editor.selection;
  1381. buttonApi.setActive(isMediaElement(selection.getNode()));
  1382. const unbindSelectorChanged = selection.selectorChangedWithUnbind('img[data-mce-object],span[data-mce-object],div[data-ephox-embed-iri]', buttonApi.setActive).unbind;
  1383. const unbindEditable = onSetupEditable(editor)(buttonApi);
  1384. return () => {
  1385. unbindSelectorChanged();
  1386. unbindEditable();
  1387. };
  1388. }
  1389. });
  1390. editor.ui.registry.addMenuItem('media', {
  1391. icon: 'embed',
  1392. text: 'Media...',
  1393. onAction,
  1394. onSetup: onSetupEditable(editor)
  1395. });
  1396. };
  1397. var Plugin = () => {
  1398. global$6.add('media', (editor) => {
  1399. register$2(editor);
  1400. register$1(editor);
  1401. register(editor);
  1402. setup(editor);
  1403. setup$1(editor);
  1404. setup$2(editor);
  1405. return get(editor);
  1406. });
  1407. };
  1408. Plugin();
  1409. /** *****
  1410. * DO NOT EXPORT ANYTHING
  1411. *
  1412. * IF YOU DO ROLLUP WILL LEAVE A GLOBAL ON THE PAGE
  1413. *******/
  1414. })();