plugin.js 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. /**
  2. * TinyMCE version 8.0.2 (2025-08-14)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global$5 = 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 eq = (t) => (a) => t === a;
  36. const isString = isType('string');
  37. const isObject = isType('object');
  38. const isArray = isType('array');
  39. const isNull = eq(null);
  40. const isBoolean = isSimpleType('boolean');
  41. const isNullable = (a) => a === null || a === undefined;
  42. const isNonNullable = (a) => !isNullable(a);
  43. const isFunction = isSimpleType('function');
  44. const isArrayOf = (value, pred) => {
  45. if (isArray(value)) {
  46. for (let i = 0, len = value.length; i < len; ++i) {
  47. if (!(pred(value[i]))) {
  48. return false;
  49. }
  50. }
  51. return true;
  52. }
  53. return false;
  54. };
  55. const noop = () => { };
  56. const constant = (value) => {
  57. return () => {
  58. return value;
  59. };
  60. };
  61. const tripleEquals = (a, b) => {
  62. return a === b;
  63. };
  64. /**
  65. * The `Optional` type represents a value (of any type) that potentially does
  66. * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the
  67. * value does exist) or a `None` (in which case the value does not exist). This
  68. * module defines a whole lot of FP-inspired utility functions for dealing with
  69. * `Optional` objects.
  70. *
  71. * Comparison with null or undefined:
  72. * - We don't get fancy null coalescing operators with `Optional`
  73. * - We do get fancy helper functions with `Optional`
  74. * - `Optional` support nesting, and allow for the type to still be nullable (or
  75. * another `Optional`)
  76. * - There is no option to turn off strict-optional-checks like there is for
  77. * strict-null-checks
  78. */
  79. class Optional {
  80. // The internal representation has a `tag` and a `value`, but both are
  81. // private: able to be console.logged, but not able to be accessed by code
  82. constructor(tag, value) {
  83. this.tag = tag;
  84. this.value = value;
  85. }
  86. // --- Identities ---
  87. /**
  88. * Creates a new `Optional<T>` that **does** contain a value.
  89. */
  90. static some(value) {
  91. return new Optional(true, value);
  92. }
  93. /**
  94. * Create a new `Optional<T>` that **does not** contain a value. `T` can be
  95. * any type because we don't actually have a `T`.
  96. */
  97. static none() {
  98. return Optional.singletonNone;
  99. }
  100. /**
  101. * Perform a transform on an `Optional` type. Regardless of whether this
  102. * `Optional` contains a value or not, `fold` will return a value of type `U`.
  103. * If this `Optional` does not contain a value, the `U` will be created by
  104. * calling `onNone`. If this `Optional` does contain a value, the `U` will be
  105. * created by calling `onSome`.
  106. *
  107. * For the FP enthusiasts in the room, this function:
  108. * 1. Could be used to implement all of the functions below
  109. * 2. Forms a catamorphism
  110. */
  111. fold(onNone, onSome) {
  112. if (this.tag) {
  113. return onSome(this.value);
  114. }
  115. else {
  116. return onNone();
  117. }
  118. }
  119. /**
  120. * Determine if this `Optional` object contains a value.
  121. */
  122. isSome() {
  123. return this.tag;
  124. }
  125. /**
  126. * Determine if this `Optional` object **does not** contain a value.
  127. */
  128. isNone() {
  129. return !this.tag;
  130. }
  131. // --- Functor (name stolen from Haskell / maths) ---
  132. /**
  133. * Perform a transform on an `Optional` object, **if** there is a value. If
  134. * you provide a function to turn a T into a U, this is the function you use
  135. * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain
  136. * a value then the output will also contain a value (that value being the
  137. * output of `mapper(this.value)`), and if this **does not** contain a value
  138. * then neither will the output.
  139. */
  140. map(mapper) {
  141. if (this.tag) {
  142. return Optional.some(mapper(this.value));
  143. }
  144. else {
  145. return Optional.none();
  146. }
  147. }
  148. // --- Monad (name stolen from Haskell / maths) ---
  149. /**
  150. * Perform a transform on an `Optional` object, **if** there is a value.
  151. * Unlike `map`, here the transform itself also returns an `Optional`.
  152. */
  153. bind(binder) {
  154. if (this.tag) {
  155. return binder(this.value);
  156. }
  157. else {
  158. return Optional.none();
  159. }
  160. }
  161. // --- Traversable (name stolen from Haskell / maths) ---
  162. /**
  163. * For a given predicate, this function finds out if there **exists** a value
  164. * inside this `Optional` object that meets the predicate. In practice, this
  165. * means that for `Optional`s that do not contain a value it returns false (as
  166. * no predicate-meeting value exists).
  167. */
  168. exists(predicate) {
  169. return this.tag && predicate(this.value);
  170. }
  171. /**
  172. * For a given predicate, this function finds out if **all** the values inside
  173. * this `Optional` object meet the predicate. In practice, this means that
  174. * for `Optional`s that do not contain a value it returns true (as all 0
  175. * objects do meet the predicate).
  176. */
  177. forall(predicate) {
  178. return !this.tag || predicate(this.value);
  179. }
  180. filter(predicate) {
  181. if (!this.tag || predicate(this.value)) {
  182. return this;
  183. }
  184. else {
  185. return Optional.none();
  186. }
  187. }
  188. // --- Getters ---
  189. /**
  190. * Get the value out of the inside of the `Optional` object, using a default
  191. * `replacement` value if the provided `Optional` object does not contain a
  192. * value.
  193. */
  194. getOr(replacement) {
  195. return this.tag ? this.value : replacement;
  196. }
  197. /**
  198. * Get the value out of the inside of the `Optional` object, using a default
  199. * `replacement` value if the provided `Optional` object does not contain a
  200. * value. Unlike `getOr`, in this method the `replacement` object is also
  201. * `Optional` - meaning that this method will always return an `Optional`.
  202. */
  203. or(replacement) {
  204. return this.tag ? this : replacement;
  205. }
  206. /**
  207. * Get the value out of the inside of the `Optional` object, using a default
  208. * `replacement` value if the provided `Optional` object does not contain a
  209. * value. Unlike `getOr`, in this method the `replacement` value is
  210. * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you
  211. * pass a function which (if called) will **return** the `value` you want to
  212. * use.
  213. */
  214. getOrThunk(thunk) {
  215. return this.tag ? this.value : thunk();
  216. }
  217. /**
  218. * Get the value out of the inside of the `Optional` object, using a default
  219. * `replacement` value if the provided Optional object does not contain a
  220. * value.
  221. *
  222. * Unlike `or`, in this method the `replacement` value is "thunked" - that is
  223. * to say that you don't pass a value to `orThunk`, you pass a function which
  224. * (if called) will **return** the `value` you want to use.
  225. *
  226. * Unlike `getOrThunk`, in this method the `replacement` value is also
  227. * `Optional`, meaning that this method will always return an `Optional`.
  228. */
  229. orThunk(thunk) {
  230. return this.tag ? this : thunk();
  231. }
  232. /**
  233. * Get the value out of the inside of the `Optional` object, throwing an
  234. * exception if the provided `Optional` object does not contain a value.
  235. *
  236. * WARNING:
  237. * You should only be using this function if you know that the `Optional`
  238. * object **is not** empty (otherwise you're throwing exceptions in production
  239. * code, which is bad).
  240. *
  241. * In tests this is more acceptable.
  242. *
  243. * Prefer other methods to this, such as `.each`.
  244. */
  245. getOrDie(message) {
  246. if (!this.tag) {
  247. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  248. }
  249. else {
  250. return this.value;
  251. }
  252. }
  253. // --- Interop with null and undefined ---
  254. /**
  255. * Creates an `Optional` value from a nullable (or undefined-able) input.
  256. * Null, or undefined, is converted to `None`, and anything else is converted
  257. * to `Some`.
  258. */
  259. static from(value) {
  260. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  261. }
  262. /**
  263. * Converts an `Optional` to a nullable type, by getting the value if it
  264. * exists, or returning `null` if it does not.
  265. */
  266. getOrNull() {
  267. return this.tag ? this.value : null;
  268. }
  269. /**
  270. * Converts an `Optional` to an undefined-able type, by getting the value if
  271. * it exists, or returning `undefined` if it does not.
  272. */
  273. getOrUndefined() {
  274. return this.value;
  275. }
  276. // --- Utilities ---
  277. /**
  278. * If the `Optional` contains a value, perform an action on that value.
  279. * Unlike the rest of the methods on this type, `.each` has side-effects. If
  280. * you want to transform an `Optional<T>` **into** something, then this is not
  281. * the method for you. If you want to use an `Optional<T>` to **do**
  282. * something, then this is the method for you - provided you're okay with not
  283. * doing anything in the case where the `Optional` doesn't have a value inside
  284. * it. If you're not sure whether your use-case fits into transforming
  285. * **into** something or **doing** something, check whether it has a return
  286. * value. If it does, you should be performing a transform.
  287. */
  288. each(worker) {
  289. if (this.tag) {
  290. worker(this.value);
  291. }
  292. }
  293. /**
  294. * Turn the `Optional` object into an array that contains all of the values
  295. * stored inside the `Optional`. In practice, this means the output will have
  296. * either 0 or 1 elements.
  297. */
  298. toArray() {
  299. return this.tag ? [this.value] : [];
  300. }
  301. /**
  302. * Turn the `Optional` object into a string for debugging or printing. Not
  303. * recommended for production code, but good for debugging. Also note that
  304. * these days an `Optional` object can be logged to the console directly, and
  305. * its inner value (if it exists) will be visible.
  306. */
  307. toString() {
  308. return this.tag ? `some(${this.value})` : 'none()';
  309. }
  310. }
  311. // Sneaky optimisation: every instance of Optional.none is identical, so just
  312. // reuse the same object
  313. Optional.singletonNone = new Optional(false);
  314. const nativeSlice = Array.prototype.slice;
  315. const nativeIndexOf = Array.prototype.indexOf;
  316. const nativePush = Array.prototype.push;
  317. const rawIndexOf = (ts, t) => nativeIndexOf.call(ts, t);
  318. const contains = (xs, x) => rawIndexOf(xs, x) > -1;
  319. const map = (xs, f) => {
  320. // pre-allocating array size when it's guaranteed to be known
  321. // http://jsperf.com/push-allocated-vs-dynamic/22
  322. const len = xs.length;
  323. const r = new Array(len);
  324. for (let i = 0; i < len; i++) {
  325. const x = xs[i];
  326. r[i] = f(x, i);
  327. }
  328. return r;
  329. };
  330. // Unwound implementing other functions in terms of each.
  331. // The code size is roughly the same, and it should allow for better optimisation.
  332. // const each = function<T, U>(xs: T[], f: (x: T, i?: number, xs?: T[]) => void): void {
  333. const each$1 = (xs, f) => {
  334. for (let i = 0, len = xs.length; i < len; i++) {
  335. const x = xs[i];
  336. f(x, i);
  337. }
  338. };
  339. const foldl = (xs, f, acc) => {
  340. each$1(xs, (x, i) => {
  341. acc = f(acc, x, i);
  342. });
  343. return acc;
  344. };
  345. const flatten = (xs) => {
  346. // Note, this is possible because push supports multiple arguments:
  347. // http://jsperf.com/concat-push/6
  348. // Note that in the past, concat() would silently work (very slowly) for array-like objects.
  349. // With this change it will throw an error.
  350. const r = [];
  351. for (let i = 0, len = xs.length; i < len; ++i) {
  352. // Ensure that each value is an array itself
  353. if (!isArray(xs[i])) {
  354. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  355. }
  356. nativePush.apply(r, xs[i]);
  357. }
  358. return r;
  359. };
  360. const bind = (xs, f) => flatten(map(xs, f));
  361. isFunction(Array.from) ? Array.from : (x) => nativeSlice.call(x);
  362. const findMap = (arr, f) => {
  363. for (let i = 0; i < arr.length; i++) {
  364. const r = f(arr[i], i);
  365. if (r.isSome()) {
  366. return r;
  367. }
  368. }
  369. return Optional.none();
  370. };
  371. // There are many variations of Object iteration that are faster than the 'for-in' style:
  372. // http://jsperf.com/object-keys-iteration/107
  373. //
  374. // Use the native keys if it is available (IE9+), otherwise fall back to manually filtering
  375. const keys = Object.keys;
  376. const hasOwnProperty = Object.hasOwnProperty;
  377. const each = (obj, f) => {
  378. const props = keys(obj);
  379. for (let k = 0, len = props.length; k < len; k++) {
  380. const i = props[k];
  381. const x = obj[i];
  382. f(x, i);
  383. }
  384. };
  385. const objAcc = (r) => (x, i) => {
  386. r[i] = x;
  387. };
  388. const internalFilter = (obj, pred, onTrue, onFalse) => {
  389. each(obj, (x, i) => {
  390. (pred(x, i) ? onTrue : onFalse)(x, i);
  391. });
  392. };
  393. const filter = (obj, pred) => {
  394. const t = {};
  395. internalFilter(obj, pred, objAcc(t), noop);
  396. return t;
  397. };
  398. const has = (obj, key) => hasOwnProperty.call(obj, key);
  399. const hasNonNullableKey = (obj, key) => has(obj, key) && obj[key] !== undefined && obj[key] !== null;
  400. const Cell = (initial) => {
  401. let value = initial;
  402. const get = () => {
  403. return value;
  404. };
  405. const set = (v) => {
  406. value = v;
  407. };
  408. return {
  409. get,
  410. set
  411. };
  412. };
  413. /**
  414. * **Is** the value stored inside this Optional object equal to `rhs`?
  415. */
  416. const is = (lhs, rhs, comparator = tripleEquals) => lhs.exists((left) => comparator(left, rhs));
  417. const cat = (arr) => {
  418. const r = [];
  419. const push = (x) => {
  420. r.push(x);
  421. };
  422. for (let i = 0; i < arr.length; i++) {
  423. arr[i].each(push);
  424. }
  425. return r;
  426. };
  427. // This can help with type inference, by specifying the type param on the none case, so the caller doesn't have to.
  428. const someIf = (b, a) => b ? Optional.some(a) : Optional.none();
  429. const singleton = (doRevoke) => {
  430. const subject = Cell(Optional.none());
  431. const revoke = () => subject.get().each(doRevoke);
  432. const clear = () => {
  433. revoke();
  434. subject.set(Optional.none());
  435. };
  436. const isSet = () => subject.get().isSome();
  437. const get = () => subject.get();
  438. const set = (s) => {
  439. revoke();
  440. subject.set(Optional.some(s));
  441. };
  442. return {
  443. clear,
  444. isSet,
  445. get,
  446. set
  447. };
  448. };
  449. const value = () => {
  450. const subject = singleton(noop);
  451. const on = (f) => subject.get().each(f);
  452. return {
  453. ...subject,
  454. on
  455. };
  456. };
  457. const removeFromStart = (str, numChars) => {
  458. return str.substring(numChars);
  459. };
  460. const checkRange = (str, substr, start) => substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  461. const removeLeading = (str, prefix) => {
  462. return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str;
  463. };
  464. /** Does 'str' start with 'prefix'?
  465. * Note: all strings start with the empty string.
  466. * More formally, for all strings x, startsWith(x, "").
  467. * This is so that for all strings x and y, startsWith(y + x, y)
  468. */
  469. const startsWith = (str, prefix) => {
  470. return checkRange(str, prefix, 0);
  471. };
  472. const option = (name) => (editor) => editor.options.get(name);
  473. const register$1 = (editor) => {
  474. const registerOption = editor.options.register;
  475. registerOption('link_assume_external_targets', {
  476. processor: (value) => {
  477. const valid = isString(value) || isBoolean(value);
  478. if (valid) {
  479. if (value === true) {
  480. return { value: 1 /* AssumeExternalTargets.WARN */, valid };
  481. }
  482. else if (value === "http" /* AssumeExternalTargets.ALWAYS_HTTP */ || value === "https" /* AssumeExternalTargets.ALWAYS_HTTPS */) {
  483. return { value, valid };
  484. }
  485. else {
  486. return { value: 0 /* AssumeExternalTargets.OFF */, valid };
  487. }
  488. }
  489. else {
  490. return { valid: false, message: 'Must be a string or a boolean.' };
  491. }
  492. },
  493. default: false
  494. });
  495. registerOption('link_context_toolbar', {
  496. processor: 'boolean',
  497. default: false
  498. });
  499. registerOption('link_list', {
  500. processor: (value) => isString(value) || isFunction(value) || isArrayOf(value, isObject)
  501. });
  502. registerOption('link_default_target', {
  503. processor: 'string'
  504. });
  505. registerOption('link_default_protocol', {
  506. processor: 'string',
  507. default: 'https'
  508. });
  509. registerOption('link_target_list', {
  510. processor: (value) => isBoolean(value) || isArrayOf(value, isObject),
  511. default: true
  512. });
  513. registerOption('link_rel_list', {
  514. processor: 'object[]',
  515. default: []
  516. });
  517. registerOption('link_class_list', {
  518. processor: 'object[]',
  519. default: []
  520. });
  521. registerOption('link_title', {
  522. processor: 'boolean',
  523. default: true
  524. });
  525. registerOption('allow_unsafe_link_target', {
  526. processor: 'boolean',
  527. default: false
  528. });
  529. registerOption('link_quicklink', {
  530. processor: 'boolean',
  531. default: false
  532. });
  533. registerOption('link_attributes_postprocess', {
  534. processor: 'function',
  535. });
  536. };
  537. const assumeExternalTargets = option('link_assume_external_targets');
  538. const hasContextToolbar = option('link_context_toolbar');
  539. const getLinkList = option('link_list');
  540. const getDefaultLinkTarget = option('link_default_target');
  541. const getDefaultLinkProtocol = option('link_default_protocol');
  542. const getTargetList = option('link_target_list');
  543. const getRelList = option('link_rel_list');
  544. const getLinkClassList = option('link_class_list');
  545. const shouldShowLinkTitle = option('link_title');
  546. const allowUnsafeLinkTarget = option('allow_unsafe_link_target');
  547. const useQuickLink = option('link_quicklink');
  548. const attributesPostProcess = option('link_attributes_postprocess');
  549. var global$4 = tinymce.util.Tools.resolve('tinymce.util.URI');
  550. var global$3 = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
  551. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  552. const isAnchor = (elm) => isNonNullable(elm) && elm.nodeName.toLowerCase() === 'a';
  553. const isLink = (elm) => isAnchor(elm) && !!getHref(elm);
  554. const collectNodesInRange = (rng, predicate) => {
  555. if (rng.collapsed) {
  556. return [];
  557. }
  558. else {
  559. const contents = rng.cloneContents();
  560. const firstChild = contents.firstChild;
  561. const walker = new global$3(firstChild, contents);
  562. const elements = [];
  563. let current = firstChild;
  564. do {
  565. if (predicate(current)) {
  566. elements.push(current);
  567. }
  568. } while ((current = walker.next()));
  569. return elements;
  570. }
  571. };
  572. const hasProtocol = (url) => /^\w+:/i.test(url);
  573. const getHref = (elm) => {
  574. var _a, _b;
  575. // Returns the real href value not the resolved a.href value
  576. return (_b = (_a = elm.getAttribute('data-mce-href')) !== null && _a !== void 0 ? _a : elm.getAttribute('href')) !== null && _b !== void 0 ? _b : '';
  577. };
  578. const applyRelTargetRules = (rel, isUnsafe) => {
  579. const rules = ['noopener'];
  580. const rels = rel ? rel.split(/\s+/) : [];
  581. const toString = (rels) => global$2.trim(rels.sort().join(' '));
  582. const addTargetRules = (rels) => {
  583. rels = removeTargetRules(rels);
  584. return rels.length > 0 ? rels.concat(rules) : rules;
  585. };
  586. const removeTargetRules = (rels) => rels.filter((val) => global$2.inArray(rules, val) === -1);
  587. const newRels = isUnsafe ? addTargetRules(rels) : removeTargetRules(rels);
  588. return newRels.length > 0 ? toString(newRels) : '';
  589. };
  590. const trimCaretContainers = (text) => text.replace(/\uFEFF/g, '');
  591. const getAnchorElement = (editor, selectedElm) => {
  592. selectedElm = selectedElm || getLinksInSelection(editor.selection.getRng())[0] || editor.selection.getNode();
  593. if (isImageFigure(selectedElm)) {
  594. // for an image contained in a figure we look for a link inside the selected element
  595. return Optional.from(editor.dom.select('a[href]', selectedElm)[0]);
  596. }
  597. else {
  598. return Optional.from(editor.dom.getParent(selectedElm, 'a[href]'));
  599. }
  600. };
  601. const isInAnchor = (editor, selectedElm) => getAnchorElement(editor, selectedElm).isSome();
  602. const getAnchorText = (selection, anchorElm) => {
  603. const text = anchorElm.fold(() => selection.getContent({ format: 'text' }), (anchorElm) => anchorElm.innerText || anchorElm.textContent || '');
  604. return trimCaretContainers(text);
  605. };
  606. const getLinksInSelection = (rng) => collectNodesInRange(rng, isLink);
  607. const getLinks$1 = (elements) => global$2.grep(elements, isLink);
  608. const hasLinks = (elements) => getLinks$1(elements).length > 0;
  609. const hasLinksInSelection = (rng) => getLinksInSelection(rng).length > 0;
  610. const isOnlyTextSelected = (editor) => {
  611. // Allow anchor and inline text elements to be in the selection but nothing else
  612. const inlineTextElements = editor.schema.getTextInlineElements();
  613. const isElement = (elm) => elm.nodeType === 1 && !isAnchor(elm) && !has(inlineTextElements, elm.nodeName.toLowerCase());
  614. // If selection is inside a block anchor then always treat it as non text only
  615. const isInBlockAnchor = getAnchorElement(editor).exists((anchor) => anchor.hasAttribute('data-mce-block'));
  616. if (isInBlockAnchor) {
  617. return false;
  618. }
  619. const rng = editor.selection.getRng();
  620. if (!rng.collapsed) {
  621. // Collect all non inline text elements in the range and make sure no elements were found
  622. const elements = collectNodesInRange(rng, isElement);
  623. return elements.length === 0;
  624. }
  625. else {
  626. return true;
  627. }
  628. };
  629. const isImageFigure = (elm) => isNonNullable(elm) && elm.nodeName === 'FIGURE' && /\bimage\b/i.test(elm.className);
  630. const getLinkAttrs = (data) => {
  631. const attrs = ['title', 'rel', 'class', 'target'];
  632. return foldl(attrs, (acc, key) => {
  633. data[key].each((value) => {
  634. // If dealing with an empty string, then treat that as being null so the attribute is removed
  635. acc[key] = value.length > 0 ? value : null;
  636. });
  637. return acc;
  638. }, {
  639. href: data.href
  640. });
  641. };
  642. const handleExternalTargets = (href, assumeExternalTargets) => {
  643. if ((assumeExternalTargets === "http" /* AssumeExternalTargets.ALWAYS_HTTP */
  644. || assumeExternalTargets === "https" /* AssumeExternalTargets.ALWAYS_HTTPS */)
  645. && !hasProtocol(href)) {
  646. return assumeExternalTargets + '://' + href;
  647. }
  648. return href;
  649. };
  650. const applyLinkOverrides = (editor, linkAttrs) => {
  651. const newLinkAttrs = { ...linkAttrs };
  652. if (getRelList(editor).length === 0 && !allowUnsafeLinkTarget(editor)) {
  653. const newRel = applyRelTargetRules(newLinkAttrs.rel, newLinkAttrs.target === '_blank');
  654. newLinkAttrs.rel = newRel ? newRel : null;
  655. }
  656. if (Optional.from(newLinkAttrs.target).isNone() && getTargetList(editor) === false) {
  657. newLinkAttrs.target = getDefaultLinkTarget(editor);
  658. }
  659. newLinkAttrs.href = handleExternalTargets(newLinkAttrs.href, assumeExternalTargets(editor));
  660. return newLinkAttrs;
  661. };
  662. const updateLink = (editor, anchorElm, text, linkAttrs) => {
  663. // If we have text, then update the anchor elements text content
  664. text.each((text) => {
  665. if (has(anchorElm, 'innerText')) {
  666. anchorElm.innerText = text;
  667. }
  668. else {
  669. anchorElm.textContent = text;
  670. }
  671. });
  672. editor.dom.setAttribs(anchorElm, linkAttrs);
  673. // Move the cursor behind the updated link, so the user can go on typing.
  674. const rng = editor.dom.createRng();
  675. rng.setStartAfter(anchorElm);
  676. rng.setEndAfter(anchorElm);
  677. editor.selection.setRng(rng);
  678. };
  679. const createLink = (editor, selectedElm, text, linkAttrs) => {
  680. const dom = editor.dom;
  681. if (isImageFigure(selectedElm)) {
  682. linkImageFigure(dom, selectedElm, linkAttrs);
  683. }
  684. else {
  685. text.fold(() => {
  686. editor.execCommand('mceInsertLink', false, linkAttrs);
  687. // Now the newly inserted link is selected. Move the cursor behind the new link, so the user can go on typing.
  688. const end = editor.selection.getEnd();
  689. const rng = dom.createRng();
  690. rng.setStartAfter(end);
  691. rng.setEndAfter(end);
  692. editor.selection.setRng(rng);
  693. }, (text) => {
  694. editor.insertContent(dom.createHTML('a', linkAttrs, dom.encode(text)));
  695. });
  696. }
  697. };
  698. const linkDomMutation = (editor, attachState, data) => {
  699. const selectedElm = editor.selection.getNode();
  700. const anchorElm = getAnchorElement(editor, selectedElm);
  701. const linkAttrs = applyLinkOverrides(editor, getLinkAttrs(data));
  702. const attributesPostProcess$1 = attributesPostProcess(editor);
  703. if (isNonNullable(attributesPostProcess$1)) {
  704. attributesPostProcess$1(linkAttrs);
  705. }
  706. editor.undoManager.transact(() => {
  707. if (data.href === attachState.href) {
  708. attachState.attach();
  709. }
  710. anchorElm.fold(() => {
  711. createLink(editor, selectedElm, data.text, linkAttrs);
  712. }, (elm) => {
  713. editor.focus();
  714. updateLink(editor, elm, data.text, linkAttrs);
  715. });
  716. });
  717. };
  718. const unlinkSelection = (editor) => {
  719. const dom = editor.dom, selection = editor.selection;
  720. const bookmark = selection.getBookmark();
  721. const rng = selection.getRng().cloneRange();
  722. // Extend the selection out to the entire anchor element
  723. const startAnchorElm = dom.getParent(rng.startContainer, 'a[href]', editor.getBody());
  724. const endAnchorElm = dom.getParent(rng.endContainer, 'a[href]', editor.getBody());
  725. if (startAnchorElm) {
  726. rng.setStartBefore(startAnchorElm);
  727. }
  728. if (endAnchorElm) {
  729. rng.setEndAfter(endAnchorElm);
  730. }
  731. selection.setRng(rng);
  732. // Remove the link
  733. editor.execCommand('unlink');
  734. selection.moveToBookmark(bookmark);
  735. };
  736. const unlinkDomMutation = (editor) => {
  737. editor.undoManager.transact(() => {
  738. const node = editor.selection.getNode();
  739. if (isImageFigure(node)) {
  740. unlinkImageFigure(editor, node);
  741. }
  742. else {
  743. unlinkSelection(editor);
  744. }
  745. editor.focus();
  746. });
  747. };
  748. /*
  749. * RTC uses unwrapped options.
  750. *
  751. * To best simulate this, we unwrap to null and filter out empty values.
  752. */
  753. const unwrapOptions = (data) => {
  754. const { class: cls, href, rel, target, text, title } = data;
  755. return filter({
  756. class: cls.getOrNull(),
  757. href,
  758. rel: rel.getOrNull(),
  759. target: target.getOrNull(),
  760. text: text.getOrNull(),
  761. title: title.getOrNull()
  762. }, (v, _k) => isNull(v) === false);
  763. };
  764. const sanitizeData = (editor, data) => {
  765. const getOption = editor.options.get;
  766. const uriOptions = {
  767. allow_html_data_urls: getOption('allow_html_data_urls'),
  768. allow_script_urls: getOption('allow_script_urls'),
  769. allow_svg_data_urls: getOption('allow_svg_data_urls')
  770. };
  771. // Sanitize the URL
  772. const href = data.href;
  773. return {
  774. ...data,
  775. href: global$4.isDomSafe(href, 'a', uriOptions) ? href : ''
  776. };
  777. };
  778. const link = (editor, attachState, data) => {
  779. const sanitizedData = sanitizeData(editor, data);
  780. editor.hasPlugin('rtc', true) ? editor.execCommand('createlink', false, unwrapOptions(sanitizedData)) : linkDomMutation(editor, attachState, sanitizedData);
  781. };
  782. const unlink = (editor) => {
  783. editor.hasPlugin('rtc', true) ? editor.execCommand('unlink') : unlinkDomMutation(editor);
  784. };
  785. const unlinkImageFigure = (editor, fig) => {
  786. var _a;
  787. const img = editor.dom.select('img', fig)[0];
  788. if (img) {
  789. const a = editor.dom.getParents(img, 'a[href]', fig)[0];
  790. if (a) {
  791. (_a = a.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(img, a);
  792. editor.dom.remove(a);
  793. }
  794. }
  795. };
  796. const linkImageFigure = (dom, fig, attrs) => {
  797. var _a;
  798. const img = dom.select('img', fig)[0];
  799. if (img) {
  800. const a = dom.create('a', attrs);
  801. (_a = img.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(a, img);
  802. a.appendChild(img);
  803. }
  804. };
  805. const getValue = (item) => isString(item.value) ? item.value : '';
  806. const getText = (item) => {
  807. if (isString(item.text)) {
  808. return item.text;
  809. }
  810. else if (isString(item.title)) {
  811. return item.title;
  812. }
  813. else {
  814. return '';
  815. }
  816. };
  817. const sanitizeList = (list, extractValue) => {
  818. const out = [];
  819. global$2.each(list, (item) => {
  820. const text = getText(item);
  821. if (item.menu !== undefined) {
  822. const items = sanitizeList(item.menu, extractValue);
  823. out.push({ text, items }); // list group
  824. }
  825. else {
  826. const value = extractValue(item);
  827. out.push({ text, value }); // list value
  828. }
  829. });
  830. return out;
  831. };
  832. const sanitizeWith = (extracter = getValue) => (list) => Optional.from(list).map((list) => sanitizeList(list, extracter));
  833. const sanitize = (list) => sanitizeWith(getValue)(list);
  834. // NOTE: May need to care about flattening.
  835. const createUi = (name, label) => (items) => ({
  836. name,
  837. type: 'listbox',
  838. label,
  839. items
  840. });
  841. const ListOptions = {
  842. sanitize,
  843. sanitizeWith,
  844. createUi,
  845. getValue
  846. };
  847. const isListGroup = (item) => hasNonNullableKey(item, 'items');
  848. const findTextByValue = (value, catalog) => findMap(catalog, (item) => {
  849. if (isListGroup(item)) {
  850. return findTextByValue(value, item.items);
  851. }
  852. else {
  853. return someIf(item.value === value, item);
  854. }
  855. });
  856. const getDelta = (persistentText, fieldName, catalog, data) => {
  857. const value = data[fieldName];
  858. const hasPersistentText = persistentText.length > 0;
  859. return value !== undefined ? findTextByValue(value, catalog).map((i) => ({
  860. url: {
  861. value: i.value,
  862. meta: {
  863. text: hasPersistentText ? persistentText : i.text,
  864. attach: noop
  865. }
  866. },
  867. text: hasPersistentText ? persistentText : i.text
  868. })) : Optional.none();
  869. };
  870. const findCatalog = (catalogs, fieldName) => {
  871. if (fieldName === 'link') {
  872. return catalogs.link;
  873. }
  874. else if (fieldName === 'anchor') {
  875. return catalogs.anchor;
  876. }
  877. else {
  878. return Optional.none();
  879. }
  880. };
  881. const init = (initialData, linkCatalog) => {
  882. const persistentData = {
  883. text: initialData.text,
  884. title: initialData.title
  885. };
  886. const getTitleFromUrlChange = (url) => { var _a; return someIf(persistentData.title.length <= 0, Optional.from((_a = url.meta) === null || _a === void 0 ? void 0 : _a.title).getOr('')); };
  887. const getTextFromUrlChange = (url) => { var _a; return someIf(persistentData.text.length <= 0, Optional.from((_a = url.meta) === null || _a === void 0 ? void 0 : _a.text).getOr(url.value)); };
  888. const onUrlChange = (data) => {
  889. const text = getTextFromUrlChange(data.url);
  890. const title = getTitleFromUrlChange(data.url);
  891. // We are going to change the text/title because it has not been manually entered by the user.
  892. if (text.isSome() || title.isSome()) {
  893. return Optional.some({
  894. ...text.map((text) => ({ text })).getOr({}),
  895. ...title.map((title) => ({ title })).getOr({})
  896. });
  897. }
  898. else {
  899. return Optional.none();
  900. }
  901. };
  902. const onCatalogChange = (data, change) => {
  903. const catalog = findCatalog(linkCatalog, change).getOr([]);
  904. return getDelta(persistentData.text, change, catalog, data);
  905. };
  906. const onChange = (getData, change) => {
  907. const name = change.name;
  908. if (name === 'url') {
  909. return onUrlChange(getData());
  910. }
  911. else if (contains(['anchor', 'link'], name)) {
  912. return onCatalogChange(getData(), name);
  913. }
  914. else if (name === 'text' || name === 'title') {
  915. // Update the persistent text/title state, as a user has input custom text
  916. persistentData[name] = getData()[name];
  917. return Optional.none();
  918. }
  919. else {
  920. return Optional.none();
  921. }
  922. };
  923. return {
  924. onChange
  925. };
  926. };
  927. const DialogChanges = {
  928. init,
  929. getDelta
  930. };
  931. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  932. // Delay confirm since onSubmit will move focus
  933. const delayedConfirm = (editor, message, callback) => {
  934. const rng = editor.selection.getRng();
  935. global$1.setEditorTimeout(editor, () => {
  936. editor.windowManager.confirm(message, (state) => {
  937. editor.selection.setRng(rng);
  938. callback(state);
  939. });
  940. });
  941. };
  942. const tryEmailTransform = (data) => {
  943. const url = data.href;
  944. const suggestMailTo = url.indexOf('@') > 0 && url.indexOf('/') === -1 && url.indexOf('mailto:') === -1;
  945. return suggestMailTo ? Optional.some({
  946. message: 'The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?',
  947. preprocess: (oldData) => ({ ...oldData, href: 'mailto:' + url })
  948. }) : Optional.none();
  949. };
  950. const tryProtocolTransform = (assumeExternalTargets, defaultLinkProtocol) => (data) => {
  951. const url = data.href;
  952. const suggestProtocol = (assumeExternalTargets === 1 /* AssumeExternalTargets.WARN */ && !hasProtocol(url) ||
  953. assumeExternalTargets === 0 /* AssumeExternalTargets.OFF */ && /^\s*www(\.|\d\.)/i.test(url));
  954. return suggestProtocol ? Optional.some({
  955. message: `The URL you entered seems to be an external link. Do you want to add the required ${defaultLinkProtocol}:// prefix?`,
  956. preprocess: (oldData) => ({ ...oldData, href: defaultLinkProtocol + '://' + url })
  957. }) : Optional.none();
  958. };
  959. const preprocess = (editor, data) => findMap([tryEmailTransform, tryProtocolTransform(assumeExternalTargets(editor), getDefaultLinkProtocol(editor))], (f) => f(data)).fold(() => Promise.resolve(data), (transform) => new Promise((callback) => {
  960. delayedConfirm(editor, transform.message, (state) => {
  961. callback(state ? transform.preprocess(data) : data);
  962. });
  963. }));
  964. const DialogConfirms = {
  965. preprocess
  966. };
  967. // NOTE: you currently need anchors in the content for this field to appear
  968. const getAnchors = (editor) => {
  969. const anchorNodes = editor.dom.select('a:not([href])');
  970. const anchors = bind(anchorNodes, (anchor) => {
  971. const id = anchor.name || anchor.id;
  972. return id ? [{ text: id, value: '#' + id }] : [];
  973. });
  974. return anchors.length > 0 ? Optional.some([{ text: 'None', value: '' }].concat(anchors)) : Optional.none();
  975. };
  976. const AnchorListOptions = {
  977. getAnchors
  978. };
  979. // Looks like tinymce currently renders menus, but doesn't
  980. // let you choose from one.
  981. const getClasses = (editor) => {
  982. const list = getLinkClassList(editor);
  983. if (list.length > 0) {
  984. return ListOptions.sanitize(list);
  985. }
  986. return Optional.none();
  987. };
  988. const ClassListOptions = {
  989. getClasses
  990. };
  991. const parseJson = (text) => {
  992. // Do some proper modelling.
  993. try {
  994. return Optional.some(JSON.parse(text));
  995. }
  996. catch (_a) {
  997. return Optional.none();
  998. }
  999. };
  1000. const getLinks = (editor) => {
  1001. const extractor = (item) => editor.convertURL(item.value || item.url || '', 'href');
  1002. const linkList = getLinkList(editor);
  1003. return new Promise((resolve) => {
  1004. // TODO - better handling of failure
  1005. if (isString(linkList)) {
  1006. fetch(linkList)
  1007. .then((res) => res.ok ? res.text().then(parseJson) : Promise.reject())
  1008. .then(resolve, () => resolve(Optional.none()));
  1009. }
  1010. else if (isFunction(linkList)) {
  1011. linkList((output) => resolve(Optional.some(output)));
  1012. }
  1013. else {
  1014. resolve(Optional.from(linkList));
  1015. }
  1016. }).then((optItems) => optItems.bind(ListOptions.sanitizeWith(extractor)).map((items) => {
  1017. if (items.length > 0) {
  1018. const noneItem = [{ text: 'None', value: '' }];
  1019. return noneItem.concat(items);
  1020. }
  1021. else {
  1022. return items;
  1023. }
  1024. }));
  1025. };
  1026. const LinkListOptions = {
  1027. getLinks
  1028. };
  1029. const getRels = (editor, initialTarget) => {
  1030. const list = getRelList(editor);
  1031. if (list.length > 0) {
  1032. const isTargetBlank = is(initialTarget, '_blank');
  1033. const enforceSafe = allowUnsafeLinkTarget(editor) === false;
  1034. const safeRelExtractor = (item) => applyRelTargetRules(ListOptions.getValue(item), isTargetBlank);
  1035. const sanitizer = enforceSafe ? ListOptions.sanitizeWith(safeRelExtractor) : ListOptions.sanitize;
  1036. return sanitizer(list);
  1037. }
  1038. return Optional.none();
  1039. };
  1040. const RelOptions = {
  1041. getRels
  1042. };
  1043. // In current tinymce, targets can be nested menus.
  1044. // Do we really want to support that?
  1045. const fallbacks = [
  1046. { text: 'Current window', value: '' },
  1047. { text: 'New window', value: '_blank' }
  1048. ];
  1049. const getTargets = (editor) => {
  1050. const list = getTargetList(editor);
  1051. if (isArray(list)) {
  1052. return ListOptions.sanitize(list).orThunk(() => Optional.some(fallbacks));
  1053. }
  1054. else if (list === false) {
  1055. return Optional.none();
  1056. }
  1057. return Optional.some(fallbacks);
  1058. };
  1059. const TargetOptions = {
  1060. getTargets
  1061. };
  1062. const nonEmptyAttr = (dom, elem, name) => {
  1063. const val = dom.getAttrib(elem, name);
  1064. return val !== null && val.length > 0 ? Optional.some(val) : Optional.none();
  1065. };
  1066. const extractFromAnchor = (editor, anchor) => {
  1067. const dom = editor.dom;
  1068. const onlyText = isOnlyTextSelected(editor);
  1069. const text = onlyText ? Optional.some(getAnchorText(editor.selection, anchor)) : Optional.none();
  1070. const url = anchor.bind((anchorElm) => Optional.from(dom.getAttrib(anchorElm, 'href')));
  1071. const target = anchor.bind((anchorElm) => Optional.from(dom.getAttrib(anchorElm, 'target')));
  1072. const rel = anchor.bind((anchorElm) => nonEmptyAttr(dom, anchorElm, 'rel'));
  1073. const linkClass = anchor.bind((anchorElm) => nonEmptyAttr(dom, anchorElm, 'class'));
  1074. const title = anchor.bind((anchorElm) => nonEmptyAttr(dom, anchorElm, 'title'));
  1075. return {
  1076. url,
  1077. text,
  1078. title,
  1079. target,
  1080. rel,
  1081. linkClass
  1082. };
  1083. };
  1084. const collect = (editor, linkNode) => LinkListOptions.getLinks(editor).then((links) => {
  1085. const anchor = extractFromAnchor(editor, linkNode);
  1086. return {
  1087. anchor,
  1088. catalogs: {
  1089. targets: TargetOptions.getTargets(editor),
  1090. // This should be initial target. Is anchor.target that?
  1091. rels: RelOptions.getRels(editor, anchor.target),
  1092. classes: ClassListOptions.getClasses(editor),
  1093. anchor: AnchorListOptions.getAnchors(editor),
  1094. link: links
  1095. },
  1096. optNode: linkNode,
  1097. flags: {
  1098. titleEnabled: shouldShowLinkTitle(editor)
  1099. }
  1100. };
  1101. });
  1102. const DialogInfo = {
  1103. collect
  1104. };
  1105. const handleSubmit = (editor, info) => (api) => {
  1106. const data = api.getData();
  1107. if (!data.url.value) {
  1108. unlink(editor);
  1109. // Temporary fix. TODO: TINY-2811
  1110. api.close();
  1111. return;
  1112. }
  1113. // Check if a key is defined, meaning it was a field in the dialog. If it is,
  1114. // then check if it's changed and return none if nothing has changed.
  1115. const getChangedValue = (key) => Optional.from(data[key]).filter((value) => !is(info.anchor[key], value));
  1116. const changedData = {
  1117. href: data.url.value,
  1118. text: getChangedValue('text'),
  1119. target: getChangedValue('target'),
  1120. rel: getChangedValue('rel'),
  1121. class: getChangedValue('linkClass'),
  1122. title: getChangedValue('title')
  1123. };
  1124. const attachState = {
  1125. href: data.url.value,
  1126. attach: data.url.meta !== undefined && data.url.meta.attach ? data.url.meta.attach : noop
  1127. };
  1128. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1129. DialogConfirms.preprocess(editor, changedData).then((pData) => {
  1130. link(editor, attachState, pData);
  1131. });
  1132. api.close();
  1133. };
  1134. const collectData = (editor) => {
  1135. const anchorNode = getAnchorElement(editor);
  1136. return DialogInfo.collect(editor, anchorNode);
  1137. };
  1138. const getInitialData = (info, defaultTarget) => {
  1139. const anchor = info.anchor;
  1140. const url = anchor.url.getOr('');
  1141. return {
  1142. url: {
  1143. value: url,
  1144. meta: {
  1145. original: {
  1146. value: url
  1147. }
  1148. }
  1149. },
  1150. text: anchor.text.getOr(''),
  1151. title: anchor.title.getOr(''),
  1152. anchor: url,
  1153. link: url,
  1154. rel: anchor.rel.getOr(''),
  1155. target: anchor.target.or(defaultTarget).getOr(''),
  1156. linkClass: anchor.linkClass.getOr('')
  1157. };
  1158. };
  1159. const makeDialog = (settings, onSubmit, editor) => {
  1160. const urlInput = [
  1161. {
  1162. name: 'url',
  1163. type: 'urlinput',
  1164. filetype: 'file',
  1165. label: 'URL',
  1166. picker_text: 'Browse links'
  1167. }
  1168. ];
  1169. const displayText = settings.anchor.text.map(() => ({
  1170. name: 'text',
  1171. type: 'input',
  1172. label: 'Text to display'
  1173. })).toArray();
  1174. const titleText = settings.flags.titleEnabled ? [
  1175. {
  1176. name: 'title',
  1177. type: 'input',
  1178. label: 'Title'
  1179. }
  1180. ] : [];
  1181. const defaultTarget = Optional.from(getDefaultLinkTarget(editor));
  1182. const initialData = getInitialData(settings, defaultTarget);
  1183. const catalogs = settings.catalogs;
  1184. const dialogDelta = DialogChanges.init(initialData, catalogs);
  1185. const body = {
  1186. type: 'panel',
  1187. items: flatten([
  1188. urlInput,
  1189. displayText,
  1190. titleText,
  1191. cat([
  1192. catalogs.anchor.map(ListOptions.createUi('anchor', 'Anchors')),
  1193. catalogs.rels.map(ListOptions.createUi('rel', 'Rel')),
  1194. catalogs.targets.map(ListOptions.createUi('target', 'Open link in...')),
  1195. catalogs.link.map(ListOptions.createUi('link', 'Link list')),
  1196. catalogs.classes.map(ListOptions.createUi('linkClass', 'Class'))
  1197. ])
  1198. ])
  1199. };
  1200. return {
  1201. title: 'Insert/Edit Link',
  1202. size: 'normal',
  1203. body,
  1204. buttons: [
  1205. {
  1206. type: 'cancel',
  1207. name: 'cancel',
  1208. text: 'Cancel'
  1209. },
  1210. {
  1211. type: 'submit',
  1212. name: 'save',
  1213. text: 'Save',
  1214. primary: true
  1215. }
  1216. ],
  1217. initialData,
  1218. onChange: (api, { name }) => {
  1219. dialogDelta.onChange(api.getData, { name }).each((newData) => {
  1220. api.setData(newData);
  1221. });
  1222. },
  1223. onSubmit
  1224. };
  1225. };
  1226. const open = (editor) => {
  1227. const data = collectData(editor);
  1228. // eslint-disable-next-line @typescript-eslint/no-floating-promises
  1229. data.then((info) => {
  1230. const onSubmit = handleSubmit(editor, info);
  1231. return makeDialog(info, onSubmit, editor);
  1232. }).then((spec) => {
  1233. editor.windowManager.open(spec);
  1234. });
  1235. };
  1236. const register = (editor) => {
  1237. editor.addCommand('mceLink', (_ui, value) => {
  1238. if ((value === null || value === void 0 ? void 0 : value.dialog) === true || !useQuickLink(editor)) {
  1239. open(editor);
  1240. }
  1241. else {
  1242. editor.dispatch('contexttoolbar-show', {
  1243. toolbarKey: 'quicklink'
  1244. });
  1245. }
  1246. });
  1247. };
  1248. const setup$2 = (editor) => {
  1249. editor.addShortcut('Meta+K', '', () => {
  1250. editor.execCommand('mceLink');
  1251. });
  1252. };
  1253. var global = tinymce.util.Tools.resolve('tinymce.util.VK');
  1254. const appendClickRemove = (link, evt) => {
  1255. document.body.appendChild(link);
  1256. link.dispatchEvent(evt);
  1257. document.body.removeChild(link);
  1258. };
  1259. const openLink = (url) => {
  1260. const link = document.createElement('a');
  1261. link.target = '_blank';
  1262. link.href = url;
  1263. link.rel = 'noreferrer noopener';
  1264. const evt = new MouseEvent('click', {
  1265. bubbles: true,
  1266. cancelable: true,
  1267. view: window
  1268. });
  1269. document.dispatchEvent(evt);
  1270. appendClickRemove(link, evt);
  1271. };
  1272. const hasOnlyAltModifier = (e) => {
  1273. return e.altKey === true && e.shiftKey === false && e.ctrlKey === false && e.metaKey === false;
  1274. };
  1275. const gotoLink = (editor, a) => {
  1276. if (a) {
  1277. const href = getHref(a);
  1278. if (/^#/.test(href)) {
  1279. const targetEl = editor.dom.select(`${href},[name="${removeLeading(href, '#')}"]`);
  1280. if (targetEl.length) {
  1281. editor.selection.scrollIntoView(targetEl[0], true);
  1282. }
  1283. }
  1284. else {
  1285. openLink(a.href);
  1286. }
  1287. }
  1288. };
  1289. const isSelectionOnImageWithEmbeddedLink = (editor) => {
  1290. const rng = editor.selection.getRng();
  1291. const node = rng.startContainer;
  1292. // Handle a case where an image embedded with a link is selected
  1293. return isLink(node) && rng.startContainer === rng.endContainer && editor.dom.select('img', node).length === 1;
  1294. };
  1295. const getLinkFromElement = (editor, element) => {
  1296. const links = getLinks$1(editor.dom.getParents(element));
  1297. return someIf(links.length === 1, links[0]);
  1298. };
  1299. const getLinkInSelection = (editor) => {
  1300. const links = getLinksInSelection(editor.selection.getRng());
  1301. return someIf(links.length > 0, links[0]).or(getLinkFromElement(editor, editor.selection.getNode()));
  1302. };
  1303. const getLinkFromSelection = (editor) => editor.selection.isCollapsed() || isSelectionOnImageWithEmbeddedLink(editor)
  1304. ? getLinkFromElement(editor, editor.selection.getStart())
  1305. : getLinkInSelection(editor);
  1306. const setup$1 = (editor) => {
  1307. const selectedLink = value();
  1308. const getSelectedLink = () => selectedLink.get().or(getLinkFromSelection(editor));
  1309. const gotoSelectedLink = () => getSelectedLink().each((link) => gotoLink(editor, link));
  1310. editor.on('contextmenu', (e) => {
  1311. getLinkFromElement(editor, e.target).each(selectedLink.set);
  1312. });
  1313. editor.on('SelectionChange', () => {
  1314. if (!selectedLink.isSet()) {
  1315. getLinkFromSelection(editor).each(selectedLink.set);
  1316. }
  1317. });
  1318. editor.on('click', (e) => {
  1319. selectedLink.clear();
  1320. const links = getLinks$1(editor.dom.getParents(e.target));
  1321. if (links.length === 1 && global.metaKeyPressed(e)) {
  1322. e.preventDefault();
  1323. gotoLink(editor, links[0]);
  1324. }
  1325. });
  1326. editor.on('keydown', (e) => {
  1327. selectedLink.clear();
  1328. if (!e.isDefaultPrevented() && e.keyCode === 13 && hasOnlyAltModifier(e)) {
  1329. getSelectedLink().each((link) => {
  1330. e.preventDefault();
  1331. gotoLink(editor, link);
  1332. });
  1333. }
  1334. });
  1335. return {
  1336. gotoSelectedLink
  1337. };
  1338. };
  1339. const openDialog = (editor) => () => {
  1340. editor.execCommand('mceLink', false, { dialog: true });
  1341. };
  1342. const toggleState = (editor, toggler) => {
  1343. editor.on('NodeChange', toggler);
  1344. return () => editor.off('NodeChange', toggler);
  1345. };
  1346. const toggleLinkState = (editor) => (api) => {
  1347. const updateState = () => {
  1348. api.setActive(!editor.mode.isReadOnly() && isInAnchor(editor, editor.selection.getNode()));
  1349. api.setEnabled(editor.selection.isEditable());
  1350. };
  1351. updateState();
  1352. return toggleState(editor, updateState);
  1353. };
  1354. const toggleLinkMenuState = (editor) => (api) => {
  1355. const updateState = () => {
  1356. api.setEnabled(editor.selection.isEditable());
  1357. };
  1358. updateState();
  1359. return toggleState(editor, updateState);
  1360. };
  1361. const toggleRequiresLinkState = (editor) => (api) => {
  1362. const hasLinks$1 = (parents) => hasLinks(parents) || hasLinksInSelection(editor.selection.getRng());
  1363. const parents = editor.dom.getParents(editor.selection.getStart());
  1364. const updateEnabled = (parents) => {
  1365. api.setEnabled(hasLinks$1(parents) && editor.selection.isEditable());
  1366. };
  1367. updateEnabled(parents);
  1368. return toggleState(editor, (e) => updateEnabled(e.parents));
  1369. };
  1370. const setupButtons = (editor, openLink) => {
  1371. editor.ui.registry.addToggleButton('link', {
  1372. icon: 'link',
  1373. tooltip: 'Insert/edit link',
  1374. shortcut: 'Meta+K',
  1375. onAction: openDialog(editor),
  1376. onSetup: toggleLinkState(editor)
  1377. });
  1378. editor.ui.registry.addButton('openlink', {
  1379. icon: 'new-tab',
  1380. tooltip: 'Open link',
  1381. onAction: openLink.gotoSelectedLink,
  1382. onSetup: toggleRequiresLinkState(editor)
  1383. });
  1384. editor.ui.registry.addButton('unlink', {
  1385. icon: 'unlink',
  1386. tooltip: 'Remove link',
  1387. onAction: () => unlink(editor),
  1388. onSetup: toggleRequiresLinkState(editor)
  1389. });
  1390. };
  1391. const setupMenuItems = (editor, openLink) => {
  1392. editor.ui.registry.addMenuItem('openlink', {
  1393. text: 'Open link',
  1394. icon: 'new-tab',
  1395. onAction: openLink.gotoSelectedLink,
  1396. onSetup: toggleRequiresLinkState(editor)
  1397. });
  1398. editor.ui.registry.addMenuItem('link', {
  1399. icon: 'link',
  1400. text: 'Link...',
  1401. shortcut: 'Meta+K',
  1402. onAction: openDialog(editor),
  1403. onSetup: toggleLinkMenuState(editor)
  1404. });
  1405. editor.ui.registry.addMenuItem('unlink', {
  1406. icon: 'unlink',
  1407. text: 'Remove link',
  1408. onAction: () => unlink(editor),
  1409. onSetup: toggleRequiresLinkState(editor)
  1410. });
  1411. };
  1412. const setupContextMenu = (editor) => {
  1413. const inLink = 'link unlink openlink';
  1414. const noLink = 'link';
  1415. editor.ui.registry.addContextMenu('link', {
  1416. update: (element) => {
  1417. const isEditable = editor.dom.isEditable(element);
  1418. if (!isEditable) {
  1419. return '';
  1420. }
  1421. return hasLinks(editor.dom.getParents(element, 'a')) ? inLink : noLink;
  1422. }
  1423. });
  1424. };
  1425. const setupContextToolbars = (editor, openLink) => {
  1426. const collapseSelectionToEnd = (editor) => {
  1427. editor.selection.collapse(false);
  1428. };
  1429. const onSetupLink = (buttonApi) => {
  1430. const node = editor.selection.getNode();
  1431. buttonApi.setEnabled(isInAnchor(editor, node) && editor.selection.isEditable());
  1432. return noop;
  1433. };
  1434. /**
  1435. * if we're editing a link, don't change the text.
  1436. * if anything other than text is selected, don't change the text.
  1437. * TINY-9593: If there is a text selection return `Optional.none`
  1438. * because `mceInsertLink` command will handle the selection.
  1439. */
  1440. const getLinkText = (value) => {
  1441. const anchor = getAnchorElement(editor);
  1442. const onlyText = isOnlyTextSelected(editor);
  1443. if (anchor.isNone() && onlyText) {
  1444. const text = getAnchorText(editor.selection, anchor);
  1445. return someIf(text.length === 0, value);
  1446. }
  1447. else {
  1448. return Optional.none();
  1449. }
  1450. };
  1451. editor.ui.registry.addContextForm('quicklink', {
  1452. launch: {
  1453. type: 'contextformtogglebutton',
  1454. icon: 'link',
  1455. tooltip: 'Link',
  1456. onSetup: toggleLinkState(editor)
  1457. },
  1458. label: 'Link',
  1459. predicate: (node) => hasContextToolbar(editor) && isInAnchor(editor, node),
  1460. initValue: () => {
  1461. const elm = getAnchorElement(editor);
  1462. return elm.fold(constant(''), getHref);
  1463. },
  1464. commands: [
  1465. {
  1466. type: 'contextformtogglebutton',
  1467. icon: 'link',
  1468. tooltip: 'Link',
  1469. primary: true,
  1470. onSetup: (buttonApi) => {
  1471. const node = editor.selection.getNode();
  1472. // TODO: Make a test for this later.
  1473. buttonApi.setActive(isInAnchor(editor, node));
  1474. return toggleLinkState(editor)(buttonApi);
  1475. },
  1476. onAction: (formApi) => {
  1477. const value = formApi.getValue();
  1478. const text = getLinkText(value);
  1479. const attachState = { href: value, attach: noop };
  1480. link(editor, attachState, {
  1481. href: value,
  1482. text,
  1483. title: Optional.none(),
  1484. rel: Optional.none(),
  1485. target: Optional.from(getDefaultLinkTarget(editor)),
  1486. class: Optional.none()
  1487. });
  1488. collapseSelectionToEnd(editor);
  1489. formApi.hide();
  1490. }
  1491. },
  1492. {
  1493. type: 'contextformbutton',
  1494. icon: 'unlink',
  1495. tooltip: 'Remove link',
  1496. onSetup: onSetupLink,
  1497. // TODO: The original inlite action was quite complex. Are we missing something with this?
  1498. onAction: (formApi) => {
  1499. unlink(editor);
  1500. formApi.hide();
  1501. }
  1502. },
  1503. {
  1504. type: 'contextformbutton',
  1505. icon: 'new-tab',
  1506. tooltip: 'Open link',
  1507. onSetup: onSetupLink,
  1508. onAction: (formApi) => {
  1509. openLink.gotoSelectedLink();
  1510. formApi.hide();
  1511. }
  1512. }
  1513. ]
  1514. });
  1515. };
  1516. const setup = (editor) => {
  1517. const openLink = setup$1(editor);
  1518. setupButtons(editor, openLink);
  1519. setupMenuItems(editor, openLink);
  1520. setupContextMenu(editor);
  1521. setupContextToolbars(editor, openLink);
  1522. };
  1523. var Plugin = () => {
  1524. global$5.add('link', (editor) => {
  1525. register$1(editor);
  1526. register(editor);
  1527. setup(editor);
  1528. setup$2(editor);
  1529. });
  1530. };
  1531. Plugin();
  1532. /** *****
  1533. * DO NOT EXPORT ANYTHING
  1534. *
  1535. * IF YOU DO ROLLUP WILL LEAVE A GLOBAL ON THE PAGE
  1536. *******/
  1537. })();