plugin.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. /**
  2. * TinyMCE version 6.4.2 (2023-04-26)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global$5 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  7. const hasProto = (v, constructor, predicate) => {
  8. var _a;
  9. if (predicate(v, constructor.prototype)) {
  10. return true;
  11. } else {
  12. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  13. }
  14. };
  15. const typeOf = x => {
  16. const t = typeof x;
  17. if (x === null) {
  18. return 'null';
  19. } else if (t === 'object' && Array.isArray(x)) {
  20. return 'array';
  21. } else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  22. return 'string';
  23. } else {
  24. return t;
  25. }
  26. };
  27. const isType = type => value => typeOf(value) === type;
  28. const isSimpleType = type => value => typeof value === type;
  29. const eq = t => a => t === a;
  30. const isString = isType('string');
  31. const isObject = isType('object');
  32. const isArray = isType('array');
  33. const isNull = eq(null);
  34. const isBoolean = isSimpleType('boolean');
  35. const isNullable = a => a === null || a === undefined;
  36. const isNonNullable = a => !isNullable(a);
  37. const isFunction = isSimpleType('function');
  38. const isArrayOf = (value, pred) => {
  39. if (isArray(value)) {
  40. for (let i = 0, len = value.length; i < len; ++i) {
  41. if (!pred(value[i])) {
  42. return false;
  43. }
  44. }
  45. return true;
  46. }
  47. return false;
  48. };
  49. const noop = () => {
  50. };
  51. const constant = value => {
  52. return () => {
  53. return value;
  54. };
  55. };
  56. const tripleEquals = (a, b) => {
  57. return a === b;
  58. };
  59. class Optional {
  60. constructor(tag, value) {
  61. this.tag = tag;
  62. this.value = value;
  63. }
  64. static some(value) {
  65. return new Optional(true, value);
  66. }
  67. static none() {
  68. return Optional.singletonNone;
  69. }
  70. fold(onNone, onSome) {
  71. if (this.tag) {
  72. return onSome(this.value);
  73. } else {
  74. return onNone();
  75. }
  76. }
  77. isSome() {
  78. return this.tag;
  79. }
  80. isNone() {
  81. return !this.tag;
  82. }
  83. map(mapper) {
  84. if (this.tag) {
  85. return Optional.some(mapper(this.value));
  86. } else {
  87. return Optional.none();
  88. }
  89. }
  90. bind(binder) {
  91. if (this.tag) {
  92. return binder(this.value);
  93. } else {
  94. return Optional.none();
  95. }
  96. }
  97. exists(predicate) {
  98. return this.tag && predicate(this.value);
  99. }
  100. forall(predicate) {
  101. return !this.tag || predicate(this.value);
  102. }
  103. filter(predicate) {
  104. if (!this.tag || predicate(this.value)) {
  105. return this;
  106. } else {
  107. return Optional.none();
  108. }
  109. }
  110. getOr(replacement) {
  111. return this.tag ? this.value : replacement;
  112. }
  113. or(replacement) {
  114. return this.tag ? this : replacement;
  115. }
  116. getOrThunk(thunk) {
  117. return this.tag ? this.value : thunk();
  118. }
  119. orThunk(thunk) {
  120. return this.tag ? this : thunk();
  121. }
  122. getOrDie(message) {
  123. if (!this.tag) {
  124. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  125. } else {
  126. return this.value;
  127. }
  128. }
  129. static from(value) {
  130. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  131. }
  132. getOrNull() {
  133. return this.tag ? this.value : null;
  134. }
  135. getOrUndefined() {
  136. return this.value;
  137. }
  138. each(worker) {
  139. if (this.tag) {
  140. worker(this.value);
  141. }
  142. }
  143. toArray() {
  144. return this.tag ? [this.value] : [];
  145. }
  146. toString() {
  147. return this.tag ? `some(${ this.value })` : 'none()';
  148. }
  149. }
  150. Optional.singletonNone = new Optional(false);
  151. const nativeIndexOf = Array.prototype.indexOf;
  152. const nativePush = Array.prototype.push;
  153. const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t);
  154. const contains = (xs, x) => rawIndexOf(xs, x) > -1;
  155. const map = (xs, f) => {
  156. const len = xs.length;
  157. const r = new Array(len);
  158. for (let i = 0; i < len; i++) {
  159. const x = xs[i];
  160. r[i] = f(x, i);
  161. }
  162. return r;
  163. };
  164. const each$1 = (xs, f) => {
  165. for (let i = 0, len = xs.length; i < len; i++) {
  166. const x = xs[i];
  167. f(x, i);
  168. }
  169. };
  170. const foldl = (xs, f, acc) => {
  171. each$1(xs, (x, i) => {
  172. acc = f(acc, x, i);
  173. });
  174. return acc;
  175. };
  176. const flatten = xs => {
  177. const r = [];
  178. for (let i = 0, len = xs.length; i < len; ++i) {
  179. if (!isArray(xs[i])) {
  180. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  181. }
  182. nativePush.apply(r, xs[i]);
  183. }
  184. return r;
  185. };
  186. const bind = (xs, f) => flatten(map(xs, f));
  187. const findMap = (arr, f) => {
  188. for (let i = 0; i < arr.length; i++) {
  189. const r = f(arr[i], i);
  190. if (r.isSome()) {
  191. return r;
  192. }
  193. }
  194. return Optional.none();
  195. };
  196. const is = (lhs, rhs, comparator = tripleEquals) => lhs.exists(left => comparator(left, rhs));
  197. const cat = arr => {
  198. const r = [];
  199. const push = x => {
  200. r.push(x);
  201. };
  202. for (let i = 0; i < arr.length; i++) {
  203. arr[i].each(push);
  204. }
  205. return r;
  206. };
  207. const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
  208. const option = name => editor => editor.options.get(name);
  209. const register$1 = editor => {
  210. const registerOption = editor.options.register;
  211. registerOption('link_assume_external_targets', {
  212. processor: value => {
  213. const valid = isString(value) || isBoolean(value);
  214. if (valid) {
  215. if (value === true) {
  216. return {
  217. value: 1,
  218. valid
  219. };
  220. } else if (value === 'http' || value === 'https') {
  221. return {
  222. value,
  223. valid
  224. };
  225. } else {
  226. return {
  227. value: 0,
  228. valid
  229. };
  230. }
  231. } else {
  232. return {
  233. valid: false,
  234. message: 'Must be a string or a boolean.'
  235. };
  236. }
  237. },
  238. default: false
  239. });
  240. registerOption('link_context_toolbar', {
  241. processor: 'boolean',
  242. default: false
  243. });
  244. registerOption('link_list', { processor: value => isString(value) || isFunction(value) || isArrayOf(value, isObject) });
  245. registerOption('link_default_target', { processor: 'string' });
  246. registerOption('link_default_protocol', {
  247. processor: 'string',
  248. default: 'https'
  249. });
  250. registerOption('link_target_list', {
  251. processor: value => isBoolean(value) || isArrayOf(value, isObject),
  252. default: true
  253. });
  254. registerOption('link_rel_list', {
  255. processor: 'object[]',
  256. default: []
  257. });
  258. registerOption('link_class_list', {
  259. processor: 'object[]',
  260. default: []
  261. });
  262. registerOption('link_title', {
  263. processor: 'boolean',
  264. default: true
  265. });
  266. registerOption('allow_unsafe_link_target', {
  267. processor: 'boolean',
  268. default: false
  269. });
  270. registerOption('link_quicklink', {
  271. processor: 'boolean',
  272. default: false
  273. });
  274. };
  275. const assumeExternalTargets = option('link_assume_external_targets');
  276. const hasContextToolbar = option('link_context_toolbar');
  277. const getLinkList = option('link_list');
  278. const getDefaultLinkTarget = option('link_default_target');
  279. const getDefaultLinkProtocol = option('link_default_protocol');
  280. const getTargetList = option('link_target_list');
  281. const getRelList = option('link_rel_list');
  282. const getLinkClassList = option('link_class_list');
  283. const shouldShowLinkTitle = option('link_title');
  284. const allowUnsafeLinkTarget = option('allow_unsafe_link_target');
  285. const useQuickLink = option('link_quicklink');
  286. var global$4 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  287. const getValue = item => isString(item.value) ? item.value : '';
  288. const getText = item => {
  289. if (isString(item.text)) {
  290. return item.text;
  291. } else if (isString(item.title)) {
  292. return item.title;
  293. } else {
  294. return '';
  295. }
  296. };
  297. const sanitizeList = (list, extractValue) => {
  298. const out = [];
  299. global$4.each(list, item => {
  300. const text = getText(item);
  301. if (item.menu !== undefined) {
  302. const items = sanitizeList(item.menu, extractValue);
  303. out.push({
  304. text,
  305. items
  306. });
  307. } else {
  308. const value = extractValue(item);
  309. out.push({
  310. text,
  311. value
  312. });
  313. }
  314. });
  315. return out;
  316. };
  317. const sanitizeWith = (extracter = getValue) => list => Optional.from(list).map(list => sanitizeList(list, extracter));
  318. const sanitize = list => sanitizeWith(getValue)(list);
  319. const createUi = (name, label) => items => ({
  320. name,
  321. type: 'listbox',
  322. label,
  323. items
  324. });
  325. const ListOptions = {
  326. sanitize,
  327. sanitizeWith,
  328. createUi,
  329. getValue
  330. };
  331. const keys = Object.keys;
  332. const hasOwnProperty = Object.hasOwnProperty;
  333. const each = (obj, f) => {
  334. const props = keys(obj);
  335. for (let k = 0, len = props.length; k < len; k++) {
  336. const i = props[k];
  337. const x = obj[i];
  338. f(x, i);
  339. }
  340. };
  341. const objAcc = r => (x, i) => {
  342. r[i] = x;
  343. };
  344. const internalFilter = (obj, pred, onTrue, onFalse) => {
  345. each(obj, (x, i) => {
  346. (pred(x, i) ? onTrue : onFalse)(x, i);
  347. });
  348. };
  349. const filter = (obj, pred) => {
  350. const t = {};
  351. internalFilter(obj, pred, objAcc(t), noop);
  352. return t;
  353. };
  354. const has = (obj, key) => hasOwnProperty.call(obj, key);
  355. const hasNonNullableKey = (obj, key) => has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  356. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
  357. var global$2 = tinymce.util.Tools.resolve('tinymce.util.URI');
  358. const isAnchor = elm => isNonNullable(elm) && elm.nodeName.toLowerCase() === 'a';
  359. const isLink = elm => isAnchor(elm) && !!getHref(elm);
  360. const collectNodesInRange = (rng, predicate) => {
  361. if (rng.collapsed) {
  362. return [];
  363. } else {
  364. const contents = rng.cloneContents();
  365. const firstChild = contents.firstChild;
  366. const walker = new global$3(firstChild, contents);
  367. const elements = [];
  368. let current = firstChild;
  369. do {
  370. if (predicate(current)) {
  371. elements.push(current);
  372. }
  373. } while (current = walker.next());
  374. return elements;
  375. }
  376. };
  377. const hasProtocol = url => /^\w+:/i.test(url);
  378. const getHref = elm => {
  379. var _a, _b;
  380. return (_b = (_a = elm.getAttribute('data-mce-href')) !== null && _a !== void 0 ? _a : elm.getAttribute('href')) !== null && _b !== void 0 ? _b : '';
  381. };
  382. const applyRelTargetRules = (rel, isUnsafe) => {
  383. const rules = ['noopener'];
  384. const rels = rel ? rel.split(/\s+/) : [];
  385. const toString = rels => global$4.trim(rels.sort().join(' '));
  386. const addTargetRules = rels => {
  387. rels = removeTargetRules(rels);
  388. return rels.length > 0 ? rels.concat(rules) : rules;
  389. };
  390. const removeTargetRules = rels => rels.filter(val => global$4.inArray(rules, val) === -1);
  391. const newRels = isUnsafe ? addTargetRules(rels) : removeTargetRules(rels);
  392. return newRels.length > 0 ? toString(newRels) : '';
  393. };
  394. const trimCaretContainers = text => text.replace(/\uFEFF/g, '');
  395. const getAnchorElement = (editor, selectedElm) => {
  396. selectedElm = selectedElm || getLinksInSelection(editor.selection.getRng())[0] || editor.selection.getNode();
  397. if (isImageFigure(selectedElm)) {
  398. return Optional.from(editor.dom.select('a[href]', selectedElm)[0]);
  399. } else {
  400. return Optional.from(editor.dom.getParent(selectedElm, 'a[href]'));
  401. }
  402. };
  403. const isInAnchor = (editor, selectedElm) => getAnchorElement(editor, selectedElm).isSome();
  404. const getAnchorText = (selection, anchorElm) => {
  405. const text = anchorElm.fold(() => selection.getContent({ format: 'text' }), anchorElm => anchorElm.innerText || anchorElm.textContent || '');
  406. return trimCaretContainers(text);
  407. };
  408. const getLinksInSelection = rng => collectNodesInRange(rng, isLink);
  409. const getLinks$1 = elements => global$4.grep(elements, isLink);
  410. const hasLinks = elements => getLinks$1(elements).length > 0;
  411. const hasLinksInSelection = rng => getLinksInSelection(rng).length > 0;
  412. const isOnlyTextSelected = editor => {
  413. const inlineTextElements = editor.schema.getTextInlineElements();
  414. const isElement = elm => elm.nodeType === 1 && !isAnchor(elm) && !has(inlineTextElements, elm.nodeName.toLowerCase());
  415. const isInBlockAnchor = getAnchorElement(editor).exists(anchor => anchor.hasAttribute('data-mce-block'));
  416. if (isInBlockAnchor) {
  417. return false;
  418. }
  419. const rng = editor.selection.getRng();
  420. if (!rng.collapsed) {
  421. const elements = collectNodesInRange(rng, isElement);
  422. return elements.length === 0;
  423. } else {
  424. return true;
  425. }
  426. };
  427. const isImageFigure = elm => isNonNullable(elm) && elm.nodeName === 'FIGURE' && /\bimage\b/i.test(elm.className);
  428. const getLinkAttrs = data => {
  429. const attrs = [
  430. 'title',
  431. 'rel',
  432. 'class',
  433. 'target'
  434. ];
  435. return foldl(attrs, (acc, key) => {
  436. data[key].each(value => {
  437. acc[key] = value.length > 0 ? value : null;
  438. });
  439. return acc;
  440. }, { href: data.href });
  441. };
  442. const handleExternalTargets = (href, assumeExternalTargets) => {
  443. if ((assumeExternalTargets === 'http' || assumeExternalTargets === 'https') && !hasProtocol(href)) {
  444. return assumeExternalTargets + '://' + href;
  445. }
  446. return href;
  447. };
  448. const applyLinkOverrides = (editor, linkAttrs) => {
  449. const newLinkAttrs = { ...linkAttrs };
  450. if (getRelList(editor).length === 0 && !allowUnsafeLinkTarget(editor)) {
  451. const newRel = applyRelTargetRules(newLinkAttrs.rel, newLinkAttrs.target === '_blank');
  452. newLinkAttrs.rel = newRel ? newRel : null;
  453. }
  454. if (Optional.from(newLinkAttrs.target).isNone() && getTargetList(editor) === false) {
  455. newLinkAttrs.target = getDefaultLinkTarget(editor);
  456. }
  457. newLinkAttrs.href = handleExternalTargets(newLinkAttrs.href, assumeExternalTargets(editor));
  458. return newLinkAttrs;
  459. };
  460. const updateLink = (editor, anchorElm, text, linkAttrs) => {
  461. text.each(text => {
  462. if (has(anchorElm, 'innerText')) {
  463. anchorElm.innerText = text;
  464. } else {
  465. anchorElm.textContent = text;
  466. }
  467. });
  468. editor.dom.setAttribs(anchorElm, linkAttrs);
  469. editor.selection.select(anchorElm);
  470. };
  471. const createLink = (editor, selectedElm, text, linkAttrs) => {
  472. const dom = editor.dom;
  473. if (isImageFigure(selectedElm)) {
  474. linkImageFigure(dom, selectedElm, linkAttrs);
  475. } else {
  476. text.fold(() => {
  477. editor.execCommand('mceInsertLink', false, linkAttrs);
  478. }, text => {
  479. editor.insertContent(dom.createHTML('a', linkAttrs, dom.encode(text)));
  480. });
  481. }
  482. };
  483. const linkDomMutation = (editor, attachState, data) => {
  484. const selectedElm = editor.selection.getNode();
  485. const anchorElm = getAnchorElement(editor, selectedElm);
  486. const linkAttrs = applyLinkOverrides(editor, getLinkAttrs(data));
  487. editor.undoManager.transact(() => {
  488. if (data.href === attachState.href) {
  489. attachState.attach();
  490. }
  491. anchorElm.fold(() => {
  492. createLink(editor, selectedElm, data.text, linkAttrs);
  493. }, elm => {
  494. editor.focus();
  495. updateLink(editor, elm, data.text, linkAttrs);
  496. });
  497. });
  498. };
  499. const unlinkSelection = editor => {
  500. const dom = editor.dom, selection = editor.selection;
  501. const bookmark = selection.getBookmark();
  502. const rng = selection.getRng().cloneRange();
  503. const startAnchorElm = dom.getParent(rng.startContainer, 'a[href]', editor.getBody());
  504. const endAnchorElm = dom.getParent(rng.endContainer, 'a[href]', editor.getBody());
  505. if (startAnchorElm) {
  506. rng.setStartBefore(startAnchorElm);
  507. }
  508. if (endAnchorElm) {
  509. rng.setEndAfter(endAnchorElm);
  510. }
  511. selection.setRng(rng);
  512. editor.execCommand('unlink');
  513. selection.moveToBookmark(bookmark);
  514. };
  515. const unlinkDomMutation = editor => {
  516. editor.undoManager.transact(() => {
  517. const node = editor.selection.getNode();
  518. if (isImageFigure(node)) {
  519. unlinkImageFigure(editor, node);
  520. } else {
  521. unlinkSelection(editor);
  522. }
  523. editor.focus();
  524. });
  525. };
  526. const unwrapOptions = data => {
  527. const {
  528. class: cls,
  529. href,
  530. rel,
  531. target,
  532. text,
  533. title
  534. } = data;
  535. return filter({
  536. class: cls.getOrNull(),
  537. href,
  538. rel: rel.getOrNull(),
  539. target: target.getOrNull(),
  540. text: text.getOrNull(),
  541. title: title.getOrNull()
  542. }, (v, _k) => isNull(v) === false);
  543. };
  544. const sanitizeData = (editor, data) => {
  545. const getOption = editor.options.get;
  546. const uriOptions = {
  547. allow_html_data_urls: getOption('allow_html_data_urls'),
  548. allow_script_urls: getOption('allow_script_urls'),
  549. allow_svg_data_urls: getOption('allow_svg_data_urls')
  550. };
  551. const href = data.href;
  552. return {
  553. ...data,
  554. href: global$2.isDomSafe(href, 'a', uriOptions) ? href : ''
  555. };
  556. };
  557. const link = (editor, attachState, data) => {
  558. const sanitizedData = sanitizeData(editor, data);
  559. editor.hasPlugin('rtc', true) ? editor.execCommand('createlink', false, unwrapOptions(sanitizedData)) : linkDomMutation(editor, attachState, sanitizedData);
  560. };
  561. const unlink = editor => {
  562. editor.hasPlugin('rtc', true) ? editor.execCommand('unlink') : unlinkDomMutation(editor);
  563. };
  564. const unlinkImageFigure = (editor, fig) => {
  565. var _a;
  566. const img = editor.dom.select('img', fig)[0];
  567. if (img) {
  568. const a = editor.dom.getParents(img, 'a[href]', fig)[0];
  569. if (a) {
  570. (_a = a.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(img, a);
  571. editor.dom.remove(a);
  572. }
  573. }
  574. };
  575. const linkImageFigure = (dom, fig, attrs) => {
  576. var _a;
  577. const img = dom.select('img', fig)[0];
  578. if (img) {
  579. const a = dom.create('a', attrs);
  580. (_a = img.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(a, img);
  581. a.appendChild(img);
  582. }
  583. };
  584. const isListGroup = item => hasNonNullableKey(item, 'items');
  585. const findTextByValue = (value, catalog) => findMap(catalog, item => {
  586. if (isListGroup(item)) {
  587. return findTextByValue(value, item.items);
  588. } else {
  589. return someIf(item.value === value, item);
  590. }
  591. });
  592. const getDelta = (persistentText, fieldName, catalog, data) => {
  593. const value = data[fieldName];
  594. const hasPersistentText = persistentText.length > 0;
  595. return value !== undefined ? findTextByValue(value, catalog).map(i => ({
  596. url: {
  597. value: i.value,
  598. meta: {
  599. text: hasPersistentText ? persistentText : i.text,
  600. attach: noop
  601. }
  602. },
  603. text: hasPersistentText ? persistentText : i.text
  604. })) : Optional.none();
  605. };
  606. const findCatalog = (catalogs, fieldName) => {
  607. if (fieldName === 'link') {
  608. return catalogs.link;
  609. } else if (fieldName === 'anchor') {
  610. return catalogs.anchor;
  611. } else {
  612. return Optional.none();
  613. }
  614. };
  615. const init = (initialData, linkCatalog) => {
  616. const persistentData = {
  617. text: initialData.text,
  618. title: initialData.title
  619. };
  620. const getTitleFromUrlChange = url => {
  621. var _a;
  622. return someIf(persistentData.title.length <= 0, Optional.from((_a = url.meta) === null || _a === void 0 ? void 0 : _a.title).getOr(''));
  623. };
  624. const getTextFromUrlChange = url => {
  625. var _a;
  626. return someIf(persistentData.text.length <= 0, Optional.from((_a = url.meta) === null || _a === void 0 ? void 0 : _a.text).getOr(url.value));
  627. };
  628. const onUrlChange = data => {
  629. const text = getTextFromUrlChange(data.url);
  630. const title = getTitleFromUrlChange(data.url);
  631. if (text.isSome() || title.isSome()) {
  632. return Optional.some({
  633. ...text.map(text => ({ text })).getOr({}),
  634. ...title.map(title => ({ title })).getOr({})
  635. });
  636. } else {
  637. return Optional.none();
  638. }
  639. };
  640. const onCatalogChange = (data, change) => {
  641. const catalog = findCatalog(linkCatalog, change).getOr([]);
  642. return getDelta(persistentData.text, change, catalog, data);
  643. };
  644. const onChange = (getData, change) => {
  645. const name = change.name;
  646. if (name === 'url') {
  647. return onUrlChange(getData());
  648. } else if (contains([
  649. 'anchor',
  650. 'link'
  651. ], name)) {
  652. return onCatalogChange(getData(), name);
  653. } else if (name === 'text' || name === 'title') {
  654. persistentData[name] = getData()[name];
  655. return Optional.none();
  656. } else {
  657. return Optional.none();
  658. }
  659. };
  660. return { onChange };
  661. };
  662. const DialogChanges = {
  663. init,
  664. getDelta
  665. };
  666. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  667. const delayedConfirm = (editor, message, callback) => {
  668. const rng = editor.selection.getRng();
  669. global$1.setEditorTimeout(editor, () => {
  670. editor.windowManager.confirm(message, state => {
  671. editor.selection.setRng(rng);
  672. callback(state);
  673. });
  674. });
  675. };
  676. const tryEmailTransform = data => {
  677. const url = data.href;
  678. const suggestMailTo = url.indexOf('@') > 0 && url.indexOf('/') === -1 && url.indexOf('mailto:') === -1;
  679. return suggestMailTo ? Optional.some({
  680. message: 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?',
  681. preprocess: oldData => ({
  682. ...oldData,
  683. href: 'mailto:' + url
  684. })
  685. }) : Optional.none();
  686. };
  687. const tryProtocolTransform = (assumeExternalTargets, defaultLinkProtocol) => data => {
  688. const url = data.href;
  689. const suggestProtocol = assumeExternalTargets === 1 && !hasProtocol(url) || assumeExternalTargets === 0 && /^\s*www(\.|\d\.)/i.test(url);
  690. return suggestProtocol ? Optional.some({
  691. message: `The URL you entered seems to be an external link. Do you want to add the required ${ defaultLinkProtocol }:// prefix?`,
  692. preprocess: oldData => ({
  693. ...oldData,
  694. href: defaultLinkProtocol + '://' + url
  695. })
  696. }) : Optional.none();
  697. };
  698. const preprocess = (editor, data) => findMap([
  699. tryEmailTransform,
  700. tryProtocolTransform(assumeExternalTargets(editor), getDefaultLinkProtocol(editor))
  701. ], f => f(data)).fold(() => Promise.resolve(data), transform => new Promise(callback => {
  702. delayedConfirm(editor, transform.message, state => {
  703. callback(state ? transform.preprocess(data) : data);
  704. });
  705. }));
  706. const DialogConfirms = { preprocess };
  707. const getAnchors = editor => {
  708. const anchorNodes = editor.dom.select('a:not([href])');
  709. const anchors = bind(anchorNodes, anchor => {
  710. const id = anchor.name || anchor.id;
  711. return id ? [{
  712. text: id,
  713. value: '#' + id
  714. }] : [];
  715. });
  716. return anchors.length > 0 ? Optional.some([{
  717. text: 'None',
  718. value: ''
  719. }].concat(anchors)) : Optional.none();
  720. };
  721. const AnchorListOptions = { getAnchors };
  722. const getClasses = editor => {
  723. const list = getLinkClassList(editor);
  724. if (list.length > 0) {
  725. return ListOptions.sanitize(list);
  726. }
  727. return Optional.none();
  728. };
  729. const ClassListOptions = { getClasses };
  730. const parseJson = text => {
  731. try {
  732. return Optional.some(JSON.parse(text));
  733. } catch (err) {
  734. return Optional.none();
  735. }
  736. };
  737. const getLinks = editor => {
  738. const extractor = item => editor.convertURL(item.value || item.url || '', 'href');
  739. const linkList = getLinkList(editor);
  740. return new Promise(resolve => {
  741. if (isString(linkList)) {
  742. fetch(linkList).then(res => res.ok ? res.text().then(parseJson) : Promise.reject()).then(resolve, () => resolve(Optional.none()));
  743. } else if (isFunction(linkList)) {
  744. linkList(output => resolve(Optional.some(output)));
  745. } else {
  746. resolve(Optional.from(linkList));
  747. }
  748. }).then(optItems => optItems.bind(ListOptions.sanitizeWith(extractor)).map(items => {
  749. if (items.length > 0) {
  750. const noneItem = [{
  751. text: 'None',
  752. value: ''
  753. }];
  754. return noneItem.concat(items);
  755. } else {
  756. return items;
  757. }
  758. }));
  759. };
  760. const LinkListOptions = { getLinks };
  761. const getRels = (editor, initialTarget) => {
  762. const list = getRelList(editor);
  763. if (list.length > 0) {
  764. const isTargetBlank = is(initialTarget, '_blank');
  765. const enforceSafe = allowUnsafeLinkTarget(editor) === false;
  766. const safeRelExtractor = item => applyRelTargetRules(ListOptions.getValue(item), isTargetBlank);
  767. const sanitizer = enforceSafe ? ListOptions.sanitizeWith(safeRelExtractor) : ListOptions.sanitize;
  768. return sanitizer(list);
  769. }
  770. return Optional.none();
  771. };
  772. const RelOptions = { getRels };
  773. const fallbacks = [
  774. {
  775. text: 'Current window',
  776. value: ''
  777. },
  778. {
  779. text: 'New window',
  780. value: '_blank'
  781. }
  782. ];
  783. const getTargets = editor => {
  784. const list = getTargetList(editor);
  785. if (isArray(list)) {
  786. return ListOptions.sanitize(list).orThunk(() => Optional.some(fallbacks));
  787. } else if (list === false) {
  788. return Optional.none();
  789. }
  790. return Optional.some(fallbacks);
  791. };
  792. const TargetOptions = { getTargets };
  793. const nonEmptyAttr = (dom, elem, name) => {
  794. const val = dom.getAttrib(elem, name);
  795. return val !== null && val.length > 0 ? Optional.some(val) : Optional.none();
  796. };
  797. const extractFromAnchor = (editor, anchor) => {
  798. const dom = editor.dom;
  799. const onlyText = isOnlyTextSelected(editor);
  800. const text = onlyText ? Optional.some(getAnchorText(editor.selection, anchor)) : Optional.none();
  801. const url = anchor.bind(anchorElm => Optional.from(dom.getAttrib(anchorElm, 'href')));
  802. const target = anchor.bind(anchorElm => Optional.from(dom.getAttrib(anchorElm, 'target')));
  803. const rel = anchor.bind(anchorElm => nonEmptyAttr(dom, anchorElm, 'rel'));
  804. const linkClass = anchor.bind(anchorElm => nonEmptyAttr(dom, anchorElm, 'class'));
  805. const title = anchor.bind(anchorElm => nonEmptyAttr(dom, anchorElm, 'title'));
  806. return {
  807. url,
  808. text,
  809. title,
  810. target,
  811. rel,
  812. linkClass
  813. };
  814. };
  815. const collect = (editor, linkNode) => LinkListOptions.getLinks(editor).then(links => {
  816. const anchor = extractFromAnchor(editor, linkNode);
  817. return {
  818. anchor,
  819. catalogs: {
  820. targets: TargetOptions.getTargets(editor),
  821. rels: RelOptions.getRels(editor, anchor.target),
  822. classes: ClassListOptions.getClasses(editor),
  823. anchor: AnchorListOptions.getAnchors(editor),
  824. link: links
  825. },
  826. optNode: linkNode,
  827. flags: { titleEnabled: shouldShowLinkTitle(editor) }
  828. };
  829. });
  830. const DialogInfo = { collect };
  831. const handleSubmit = (editor, info) => api => {
  832. const data = api.getData();
  833. if (!data.url.value) {
  834. unlink(editor);
  835. api.close();
  836. return;
  837. }
  838. const getChangedValue = key => Optional.from(data[key]).filter(value => !is(info.anchor[key], value));
  839. const changedData = {
  840. href: data.url.value,
  841. text: getChangedValue('text'),
  842. target: getChangedValue('target'),
  843. rel: getChangedValue('rel'),
  844. class: getChangedValue('linkClass'),
  845. title: getChangedValue('title')
  846. };
  847. const attachState = {
  848. href: data.url.value,
  849. attach: data.url.meta !== undefined && data.url.meta.attach ? data.url.meta.attach : noop
  850. };
  851. DialogConfirms.preprocess(editor, changedData).then(pData => {
  852. link(editor, attachState, pData);
  853. });
  854. api.close();
  855. };
  856. const collectData = editor => {
  857. const anchorNode = getAnchorElement(editor);
  858. return DialogInfo.collect(editor, anchorNode);
  859. };
  860. const getInitialData = (info, defaultTarget) => {
  861. const anchor = info.anchor;
  862. const url = anchor.url.getOr('');
  863. return {
  864. url: {
  865. value: url,
  866. meta: { original: { value: url } }
  867. },
  868. text: anchor.text.getOr(''),
  869. title: anchor.title.getOr(''),
  870. anchor: url,
  871. link: url,
  872. rel: anchor.rel.getOr(''),
  873. target: anchor.target.or(defaultTarget).getOr(''),
  874. linkClass: anchor.linkClass.getOr('')
  875. };
  876. };
  877. const makeDialog = (settings, onSubmit, editor) => {
  878. const urlInput = [{
  879. name: 'url',
  880. type: 'urlinput',
  881. filetype: 'file',
  882. label: 'URL'
  883. }];
  884. const displayText = settings.anchor.text.map(() => ({
  885. name: 'text',
  886. type: 'input',
  887. label: 'Text to display'
  888. })).toArray();
  889. const titleText = settings.flags.titleEnabled ? [{
  890. name: 'title',
  891. type: 'input',
  892. label: 'Title'
  893. }] : [];
  894. const defaultTarget = Optional.from(getDefaultLinkTarget(editor));
  895. const initialData = getInitialData(settings, defaultTarget);
  896. const catalogs = settings.catalogs;
  897. const dialogDelta = DialogChanges.init(initialData, catalogs);
  898. const body = {
  899. type: 'panel',
  900. items: flatten([
  901. urlInput,
  902. displayText,
  903. titleText,
  904. cat([
  905. catalogs.anchor.map(ListOptions.createUi('anchor', 'Anchors')),
  906. catalogs.rels.map(ListOptions.createUi('rel', 'Rel')),
  907. catalogs.targets.map(ListOptions.createUi('target', 'Open link in...')),
  908. catalogs.link.map(ListOptions.createUi('link', 'Link list')),
  909. catalogs.classes.map(ListOptions.createUi('linkClass', 'Class'))
  910. ])
  911. ])
  912. };
  913. return {
  914. title: 'Insert/Edit Link',
  915. size: 'normal',
  916. body,
  917. buttons: [
  918. {
  919. type: 'cancel',
  920. name: 'cancel',
  921. text: 'Cancel'
  922. },
  923. {
  924. type: 'submit',
  925. name: 'save',
  926. text: 'Save',
  927. primary: true
  928. }
  929. ],
  930. initialData,
  931. onChange: (api, {name}) => {
  932. dialogDelta.onChange(api.getData, { name }).each(newData => {
  933. api.setData(newData);
  934. });
  935. },
  936. onSubmit
  937. };
  938. };
  939. const open$1 = editor => {
  940. const data = collectData(editor);
  941. data.then(info => {
  942. const onSubmit = handleSubmit(editor, info);
  943. return makeDialog(info, onSubmit, editor);
  944. }).then(spec => {
  945. editor.windowManager.open(spec);
  946. });
  947. };
  948. const register = editor => {
  949. editor.addCommand('mceLink', (_ui, value) => {
  950. if ((value === null || value === void 0 ? void 0 : value.dialog) === true || !useQuickLink(editor)) {
  951. open$1(editor);
  952. } else {
  953. editor.dispatch('contexttoolbar-show', { toolbarKey: 'quicklink' });
  954. }
  955. });
  956. };
  957. var global = tinymce.util.Tools.resolve('tinymce.util.VK');
  958. const appendClickRemove = (link, evt) => {
  959. document.body.appendChild(link);
  960. link.dispatchEvent(evt);
  961. document.body.removeChild(link);
  962. };
  963. const open = url => {
  964. const link = document.createElement('a');
  965. link.target = '_blank';
  966. link.href = url;
  967. link.rel = 'noreferrer noopener';
  968. const evt = document.createEvent('MouseEvents');
  969. evt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  970. appendClickRemove(link, evt);
  971. };
  972. const getLink = (editor, elm) => editor.dom.getParent(elm, 'a[href]');
  973. const getSelectedLink = editor => getLink(editor, editor.selection.getStart());
  974. const hasOnlyAltModifier = e => {
  975. return e.altKey === true && e.shiftKey === false && e.ctrlKey === false && e.metaKey === false;
  976. };
  977. const gotoLink = (editor, a) => {
  978. if (a) {
  979. const href = getHref(a);
  980. if (/^#/.test(href)) {
  981. const targetEl = editor.dom.select(href);
  982. if (targetEl.length) {
  983. editor.selection.scrollIntoView(targetEl[0], true);
  984. }
  985. } else {
  986. open(a.href);
  987. }
  988. }
  989. };
  990. const openDialog = editor => () => {
  991. editor.execCommand('mceLink', false, { dialog: true });
  992. };
  993. const gotoSelectedLink = editor => () => {
  994. gotoLink(editor, getSelectedLink(editor));
  995. };
  996. const setupGotoLinks = editor => {
  997. editor.on('click', e => {
  998. const link = getLink(editor, e.target);
  999. if (link && global.metaKeyPressed(e)) {
  1000. e.preventDefault();
  1001. gotoLink(editor, link);
  1002. }
  1003. });
  1004. editor.on('keydown', e => {
  1005. if (!e.isDefaultPrevented() && e.keyCode === 13 && hasOnlyAltModifier(e)) {
  1006. const link = getSelectedLink(editor);
  1007. if (link) {
  1008. e.preventDefault();
  1009. gotoLink(editor, link);
  1010. }
  1011. }
  1012. });
  1013. };
  1014. const toggleState = (editor, toggler) => {
  1015. editor.on('NodeChange', toggler);
  1016. return () => editor.off('NodeChange', toggler);
  1017. };
  1018. const toggleActiveState = editor => api => {
  1019. const updateState = () => api.setActive(!editor.mode.isReadOnly() && isInAnchor(editor, editor.selection.getNode()));
  1020. updateState();
  1021. return toggleState(editor, updateState);
  1022. };
  1023. const hasExactlyOneLinkInSelection = editor => {
  1024. const links = editor.selection.isCollapsed() ? getLinks$1(editor.dom.getParents(editor.selection.getStart())) : getLinksInSelection(editor.selection.getRng());
  1025. return links.length === 1;
  1026. };
  1027. const toggleEnabledState = editor => api => {
  1028. const updateState = () => api.setEnabled(hasExactlyOneLinkInSelection(editor));
  1029. updateState();
  1030. return toggleState(editor, updateState);
  1031. };
  1032. const toggleUnlinkState = editor => api => {
  1033. const hasLinks$1 = parents => hasLinks(parents) || hasLinksInSelection(editor.selection.getRng());
  1034. const parents = editor.dom.getParents(editor.selection.getStart());
  1035. api.setEnabled(hasLinks$1(parents));
  1036. return toggleState(editor, e => api.setEnabled(hasLinks$1(e.parents)));
  1037. };
  1038. const setup = editor => {
  1039. editor.addShortcut('Meta+K', '', () => {
  1040. editor.execCommand('mceLink');
  1041. });
  1042. };
  1043. const setupButtons = editor => {
  1044. editor.ui.registry.addToggleButton('link', {
  1045. icon: 'link',
  1046. tooltip: 'Insert/edit link',
  1047. onAction: openDialog(editor),
  1048. onSetup: toggleActiveState(editor)
  1049. });
  1050. editor.ui.registry.addButton('openlink', {
  1051. icon: 'new-tab',
  1052. tooltip: 'Open link',
  1053. onAction: gotoSelectedLink(editor),
  1054. onSetup: toggleEnabledState(editor)
  1055. });
  1056. editor.ui.registry.addButton('unlink', {
  1057. icon: 'unlink',
  1058. tooltip: 'Remove link',
  1059. onAction: () => unlink(editor),
  1060. onSetup: toggleUnlinkState(editor)
  1061. });
  1062. };
  1063. const setupMenuItems = editor => {
  1064. editor.ui.registry.addMenuItem('openlink', {
  1065. text: 'Open link',
  1066. icon: 'new-tab',
  1067. onAction: gotoSelectedLink(editor),
  1068. onSetup: toggleEnabledState(editor)
  1069. });
  1070. editor.ui.registry.addMenuItem('link', {
  1071. icon: 'link',
  1072. text: 'Link...',
  1073. shortcut: 'Meta+K',
  1074. onAction: openDialog(editor)
  1075. });
  1076. editor.ui.registry.addMenuItem('unlink', {
  1077. icon: 'unlink',
  1078. text: 'Remove link',
  1079. onAction: () => unlink(editor),
  1080. onSetup: toggleUnlinkState(editor)
  1081. });
  1082. };
  1083. const setupContextMenu = editor => {
  1084. const inLink = 'link unlink openlink';
  1085. const noLink = 'link';
  1086. editor.ui.registry.addContextMenu('link', {
  1087. update: element => {
  1088. const isEditable = editor.dom.isEditable(element);
  1089. if (!isEditable) {
  1090. return '';
  1091. }
  1092. return hasLinks(editor.dom.getParents(element, 'a')) ? inLink : noLink;
  1093. }
  1094. });
  1095. };
  1096. const setupContextToolbars = editor => {
  1097. const collapseSelectionToEnd = editor => {
  1098. editor.selection.collapse(false);
  1099. };
  1100. const onSetupLink = buttonApi => {
  1101. const node = editor.selection.getNode();
  1102. buttonApi.setEnabled(isInAnchor(editor, node));
  1103. return noop;
  1104. };
  1105. const getLinkText = value => {
  1106. const anchor = getAnchorElement(editor);
  1107. const onlyText = isOnlyTextSelected(editor);
  1108. if (anchor.isNone() && onlyText) {
  1109. const text = getAnchorText(editor.selection, anchor);
  1110. return someIf(text.length === 0, value);
  1111. } else {
  1112. return Optional.none();
  1113. }
  1114. };
  1115. editor.ui.registry.addContextForm('quicklink', {
  1116. launch: {
  1117. type: 'contextformtogglebutton',
  1118. icon: 'link',
  1119. tooltip: 'Link',
  1120. onSetup: toggleActiveState(editor)
  1121. },
  1122. label: 'Link',
  1123. predicate: node => hasContextToolbar(editor) && isInAnchor(editor, node),
  1124. initValue: () => {
  1125. const elm = getAnchorElement(editor);
  1126. return elm.fold(constant(''), getHref);
  1127. },
  1128. commands: [
  1129. {
  1130. type: 'contextformtogglebutton',
  1131. icon: 'link',
  1132. tooltip: 'Link',
  1133. primary: true,
  1134. onSetup: buttonApi => {
  1135. const node = editor.selection.getNode();
  1136. buttonApi.setActive(isInAnchor(editor, node));
  1137. return toggleActiveState(editor)(buttonApi);
  1138. },
  1139. onAction: formApi => {
  1140. const value = formApi.getValue();
  1141. const text = getLinkText(value);
  1142. const attachState = {
  1143. href: value,
  1144. attach: noop
  1145. };
  1146. link(editor, attachState, {
  1147. href: value,
  1148. text,
  1149. title: Optional.none(),
  1150. rel: Optional.none(),
  1151. target: Optional.none(),
  1152. class: Optional.none()
  1153. });
  1154. collapseSelectionToEnd(editor);
  1155. formApi.hide();
  1156. }
  1157. },
  1158. {
  1159. type: 'contextformbutton',
  1160. icon: 'unlink',
  1161. tooltip: 'Remove link',
  1162. onSetup: onSetupLink,
  1163. onAction: formApi => {
  1164. unlink(editor);
  1165. formApi.hide();
  1166. }
  1167. },
  1168. {
  1169. type: 'contextformbutton',
  1170. icon: 'new-tab',
  1171. tooltip: 'Open link',
  1172. onSetup: onSetupLink,
  1173. onAction: formApi => {
  1174. gotoSelectedLink(editor)();
  1175. formApi.hide();
  1176. }
  1177. }
  1178. ]
  1179. });
  1180. };
  1181. var Plugin = () => {
  1182. global$5.add('link', editor => {
  1183. register$1(editor);
  1184. setupButtons(editor);
  1185. setupMenuItems(editor);
  1186. setupContextMenu(editor);
  1187. setupContextToolbars(editor);
  1188. setupGotoLinks(editor);
  1189. register(editor);
  1190. setup(editor);
  1191. });
  1192. };
  1193. Plugin();
  1194. })();