plugin.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /**
  2. * TinyMCE version 8.0.2 (2025-08-14)
  3. */
  4. (function () {
  5. 'use strict';
  6. var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
  7. const get = (editor) => ({
  8. backspaceDelete: (isForward) => {
  9. editor.execCommand('mceListBackspaceDelete', false, isForward);
  10. }
  11. });
  12. /* eslint-disable @typescript-eslint/no-wrapper-object-types */
  13. const isSimpleType = (type) => (value) => typeof value === type;
  14. const isNullable = (a) => a === null || a === undefined;
  15. const isNonNullable = (a) => !isNullable(a);
  16. const isFunction = isSimpleType('function');
  17. const constant = (value) => {
  18. return () => {
  19. return value;
  20. };
  21. };
  22. const tripleEquals = (a, b) => {
  23. return a === b;
  24. };
  25. const never = constant(false);
  26. /**
  27. * The `Optional` type represents a value (of any type) that potentially does
  28. * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the
  29. * value does exist) or a `None` (in which case the value does not exist). This
  30. * module defines a whole lot of FP-inspired utility functions for dealing with
  31. * `Optional` objects.
  32. *
  33. * Comparison with null or undefined:
  34. * - We don't get fancy null coalescing operators with `Optional`
  35. * - We do get fancy helper functions with `Optional`
  36. * - `Optional` support nesting, and allow for the type to still be nullable (or
  37. * another `Optional`)
  38. * - There is no option to turn off strict-optional-checks like there is for
  39. * strict-null-checks
  40. */
  41. class Optional {
  42. // The internal representation has a `tag` and a `value`, but both are
  43. // private: able to be console.logged, but not able to be accessed by code
  44. constructor(tag, value) {
  45. this.tag = tag;
  46. this.value = value;
  47. }
  48. // --- Identities ---
  49. /**
  50. * Creates a new `Optional<T>` that **does** contain a value.
  51. */
  52. static some(value) {
  53. return new Optional(true, value);
  54. }
  55. /**
  56. * Create a new `Optional<T>` that **does not** contain a value. `T` can be
  57. * any type because we don't actually have a `T`.
  58. */
  59. static none() {
  60. return Optional.singletonNone;
  61. }
  62. /**
  63. * Perform a transform on an `Optional` type. Regardless of whether this
  64. * `Optional` contains a value or not, `fold` will return a value of type `U`.
  65. * If this `Optional` does not contain a value, the `U` will be created by
  66. * calling `onNone`. If this `Optional` does contain a value, the `U` will be
  67. * created by calling `onSome`.
  68. *
  69. * For the FP enthusiasts in the room, this function:
  70. * 1. Could be used to implement all of the functions below
  71. * 2. Forms a catamorphism
  72. */
  73. fold(onNone, onSome) {
  74. if (this.tag) {
  75. return onSome(this.value);
  76. }
  77. else {
  78. return onNone();
  79. }
  80. }
  81. /**
  82. * Determine if this `Optional` object contains a value.
  83. */
  84. isSome() {
  85. return this.tag;
  86. }
  87. /**
  88. * Determine if this `Optional` object **does not** contain a value.
  89. */
  90. isNone() {
  91. return !this.tag;
  92. }
  93. // --- Functor (name stolen from Haskell / maths) ---
  94. /**
  95. * Perform a transform on an `Optional` object, **if** there is a value. If
  96. * you provide a function to turn a T into a U, this is the function you use
  97. * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain
  98. * a value then the output will also contain a value (that value being the
  99. * output of `mapper(this.value)`), and if this **does not** contain a value
  100. * then neither will the output.
  101. */
  102. map(mapper) {
  103. if (this.tag) {
  104. return Optional.some(mapper(this.value));
  105. }
  106. else {
  107. return Optional.none();
  108. }
  109. }
  110. // --- Monad (name stolen from Haskell / maths) ---
  111. /**
  112. * Perform a transform on an `Optional` object, **if** there is a value.
  113. * Unlike `map`, here the transform itself also returns an `Optional`.
  114. */
  115. bind(binder) {
  116. if (this.tag) {
  117. return binder(this.value);
  118. }
  119. else {
  120. return Optional.none();
  121. }
  122. }
  123. // --- Traversable (name stolen from Haskell / maths) ---
  124. /**
  125. * For a given predicate, this function finds out if there **exists** a value
  126. * inside this `Optional` object that meets the predicate. In practice, this
  127. * means that for `Optional`s that do not contain a value it returns false (as
  128. * no predicate-meeting value exists).
  129. */
  130. exists(predicate) {
  131. return this.tag && predicate(this.value);
  132. }
  133. /**
  134. * For a given predicate, this function finds out if **all** the values inside
  135. * this `Optional` object meet the predicate. In practice, this means that
  136. * for `Optional`s that do not contain a value it returns true (as all 0
  137. * objects do meet the predicate).
  138. */
  139. forall(predicate) {
  140. return !this.tag || predicate(this.value);
  141. }
  142. filter(predicate) {
  143. if (!this.tag || predicate(this.value)) {
  144. return this;
  145. }
  146. else {
  147. return Optional.none();
  148. }
  149. }
  150. // --- Getters ---
  151. /**
  152. * Get the value out of the inside of the `Optional` object, using a default
  153. * `replacement` value if the provided `Optional` object does not contain a
  154. * value.
  155. */
  156. getOr(replacement) {
  157. return this.tag ? this.value : replacement;
  158. }
  159. /**
  160. * Get the value out of the inside of the `Optional` object, using a default
  161. * `replacement` value if the provided `Optional` object does not contain a
  162. * value. Unlike `getOr`, in this method the `replacement` object is also
  163. * `Optional` - meaning that this method will always return an `Optional`.
  164. */
  165. or(replacement) {
  166. return this.tag ? this : replacement;
  167. }
  168. /**
  169. * Get the value out of the inside of the `Optional` object, using a default
  170. * `replacement` value if the provided `Optional` object does not contain a
  171. * value. Unlike `getOr`, in this method the `replacement` value is
  172. * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you
  173. * pass a function which (if called) will **return** the `value` you want to
  174. * use.
  175. */
  176. getOrThunk(thunk) {
  177. return this.tag ? this.value : thunk();
  178. }
  179. /**
  180. * Get the value out of the inside of the `Optional` object, using a default
  181. * `replacement` value if the provided Optional object does not contain a
  182. * value.
  183. *
  184. * Unlike `or`, in this method the `replacement` value is "thunked" - that is
  185. * to say that you don't pass a value to `orThunk`, you pass a function which
  186. * (if called) will **return** the `value` you want to use.
  187. *
  188. * Unlike `getOrThunk`, in this method the `replacement` value is also
  189. * `Optional`, meaning that this method will always return an `Optional`.
  190. */
  191. orThunk(thunk) {
  192. return this.tag ? this : thunk();
  193. }
  194. /**
  195. * Get the value out of the inside of the `Optional` object, throwing an
  196. * exception if the provided `Optional` object does not contain a value.
  197. *
  198. * WARNING:
  199. * You should only be using this function if you know that the `Optional`
  200. * object **is not** empty (otherwise you're throwing exceptions in production
  201. * code, which is bad).
  202. *
  203. * In tests this is more acceptable.
  204. *
  205. * Prefer other methods to this, such as `.each`.
  206. */
  207. getOrDie(message) {
  208. if (!this.tag) {
  209. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  210. }
  211. else {
  212. return this.value;
  213. }
  214. }
  215. // --- Interop with null and undefined ---
  216. /**
  217. * Creates an `Optional` value from a nullable (or undefined-able) input.
  218. * Null, or undefined, is converted to `None`, and anything else is converted
  219. * to `Some`.
  220. */
  221. static from(value) {
  222. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  223. }
  224. /**
  225. * Converts an `Optional` to a nullable type, by getting the value if it
  226. * exists, or returning `null` if it does not.
  227. */
  228. getOrNull() {
  229. return this.tag ? this.value : null;
  230. }
  231. /**
  232. * Converts an `Optional` to an undefined-able type, by getting the value if
  233. * it exists, or returning `undefined` if it does not.
  234. */
  235. getOrUndefined() {
  236. return this.value;
  237. }
  238. // --- Utilities ---
  239. /**
  240. * If the `Optional` contains a value, perform an action on that value.
  241. * Unlike the rest of the methods on this type, `.each` has side-effects. If
  242. * you want to transform an `Optional<T>` **into** something, then this is not
  243. * the method for you. If you want to use an `Optional<T>` to **do**
  244. * something, then this is the method for you - provided you're okay with not
  245. * doing anything in the case where the `Optional` doesn't have a value inside
  246. * it. If you're not sure whether your use-case fits into transforming
  247. * **into** something or **doing** something, check whether it has a return
  248. * value. If it does, you should be performing a transform.
  249. */
  250. each(worker) {
  251. if (this.tag) {
  252. worker(this.value);
  253. }
  254. }
  255. /**
  256. * Turn the `Optional` object into an array that contains all of the values
  257. * stored inside the `Optional`. In practice, this means the output will have
  258. * either 0 or 1 elements.
  259. */
  260. toArray() {
  261. return this.tag ? [this.value] : [];
  262. }
  263. /**
  264. * Turn the `Optional` object into a string for debugging or printing. Not
  265. * recommended for production code, but good for debugging. Also note that
  266. * these days an `Optional` object can be logged to the console directly, and
  267. * its inner value (if it exists) will be visible.
  268. */
  269. toString() {
  270. return this.tag ? `some(${this.value})` : 'none()';
  271. }
  272. }
  273. // Sneaky optimisation: every instance of Optional.none is identical, so just
  274. // reuse the same object
  275. Optional.singletonNone = new Optional(false);
  276. const nativeSlice = Array.prototype.slice;
  277. const exists = (xs, pred) => {
  278. for (let i = 0, len = xs.length; i < len; i++) {
  279. const x = xs[i];
  280. if (pred(x, i)) {
  281. return true;
  282. }
  283. }
  284. return false;
  285. };
  286. const map = (xs, f) => {
  287. // pre-allocating array size when it's guaranteed to be known
  288. // http://jsperf.com/push-allocated-vs-dynamic/22
  289. const len = xs.length;
  290. const r = new Array(len);
  291. for (let i = 0; i < len; i++) {
  292. const x = xs[i];
  293. r[i] = f(x, i);
  294. }
  295. return r;
  296. };
  297. // Unwound implementing other functions in terms of each.
  298. // The code size is roughly the same, and it should allow for better optimisation.
  299. // const each = function<T, U>(xs: T[], f: (x: T, i?: number, xs?: T[]) => void): void {
  300. const each = (xs, f) => {
  301. for (let i = 0, len = xs.length; i < len; i++) {
  302. const x = xs[i];
  303. f(x, i);
  304. }
  305. };
  306. const foldl = (xs, f, acc) => {
  307. each(xs, (x, i) => {
  308. acc = f(acc, x, i);
  309. });
  310. return acc;
  311. };
  312. const findUntil = (xs, pred, until) => {
  313. for (let i = 0, len = xs.length; i < len; i++) {
  314. const x = xs[i];
  315. if (pred(x, i)) {
  316. return Optional.some(x);
  317. }
  318. else if (until(x, i)) {
  319. break;
  320. }
  321. }
  322. return Optional.none();
  323. };
  324. const find = (xs, pred) => {
  325. return findUntil(xs, pred, never);
  326. };
  327. const reverse = (xs) => {
  328. const r = nativeSlice.call(xs, 0);
  329. r.reverse();
  330. return r;
  331. };
  332. isFunction(Array.from) ? Array.from : (x) => nativeSlice.call(x);
  333. /**
  334. * **Is** the value stored inside this Optional object equal to `rhs`?
  335. */
  336. const is = (lhs, rhs, comparator = tripleEquals) => lhs.exists((left) => comparator(left, rhs));
  337. const blank = (r) => (s) => s.replace(r, '');
  338. /** removes all leading and trailing spaces */
  339. const trim = blank(/^\s+|\s+$/g);
  340. const isNotEmpty = (s) => s.length > 0;
  341. const isEmpty = (s) => !isNotEmpty(s);
  342. // Example: 'AB' -> 28
  343. const parseAlphabeticBase26 = (str) => {
  344. const chars = reverse(trim(str).split(''));
  345. const values = map(chars, (char, i) => {
  346. const charValue = char.toUpperCase().charCodeAt(0) - 'A'.charCodeAt(0) + 1;
  347. return Math.pow(26, i) * charValue;
  348. });
  349. return foldl(values, (sum, v) => sum + v, 0);
  350. };
  351. // Example: 28 -> 'AB'
  352. const composeAlphabeticBase26 = (value) => {
  353. value--;
  354. if (value < 0) {
  355. return '';
  356. }
  357. else {
  358. const remainder = value % 26;
  359. const quotient = Math.floor(value / 26);
  360. const rest = composeAlphabeticBase26(quotient);
  361. const char = String.fromCharCode('A'.charCodeAt(0) + remainder);
  362. return rest + char;
  363. }
  364. };
  365. const isUppercase = (str) => /^[A-Z]+$/.test(str);
  366. const isLowercase = (str) => /^[a-z]+$/.test(str);
  367. const isNumeric = (str) => /^[0-9]+$/.test(str);
  368. const deduceListType = (start) => {
  369. if (isNumeric(start)) {
  370. return 2 /* ListType.Numeric */;
  371. }
  372. else if (isUppercase(start)) {
  373. return 0 /* ListType.UpperAlpha */;
  374. }
  375. else if (isLowercase(start)) {
  376. return 1 /* ListType.LowerAlpha */;
  377. }
  378. else if (isEmpty(start)) {
  379. return 3 /* ListType.None */;
  380. }
  381. else {
  382. return 4 /* ListType.Unknown */;
  383. }
  384. };
  385. const parseStartValue = (start) => {
  386. switch (deduceListType(start)) {
  387. case 2 /* ListType.Numeric */:
  388. return Optional.some({
  389. listStyleType: Optional.none(),
  390. start
  391. });
  392. case 0 /* ListType.UpperAlpha */:
  393. return Optional.some({
  394. listStyleType: Optional.some('upper-alpha'),
  395. start: parseAlphabeticBase26(start).toString()
  396. });
  397. case 1 /* ListType.LowerAlpha */:
  398. return Optional.some({
  399. listStyleType: Optional.some('lower-alpha'),
  400. start: parseAlphabeticBase26(start).toString()
  401. });
  402. case 3 /* ListType.None */:
  403. return Optional.some({
  404. listStyleType: Optional.none(),
  405. start: ''
  406. });
  407. case 4 /* ListType.Unknown */:
  408. return Optional.none();
  409. }
  410. };
  411. const parseDetail = (detail) => {
  412. const start = parseInt(detail.start, 10);
  413. if (is(detail.listStyleType, 'upper-alpha')) {
  414. return composeAlphabeticBase26(start);
  415. }
  416. else if (is(detail.listStyleType, 'lower-alpha')) {
  417. return composeAlphabeticBase26(start).toLowerCase();
  418. }
  419. else {
  420. return detail.start;
  421. }
  422. };
  423. const option = (name) => (editor) => editor.options.get(name);
  424. const getForcedRootBlock = option('forced_root_block');
  425. const isCustomList = (list) => /\btox\-/.test(list.className);
  426. const matchNodeNames = (regex) => (node) => isNonNullable(node) && regex.test(node.nodeName);
  427. const matchNodeName = (name) => (node) => isNonNullable(node) && node.nodeName.toLowerCase() === name;
  428. const isListNode = matchNodeNames(/^(OL|UL|DL)$/);
  429. const isTableCellNode = matchNodeNames(/^(TH|TD)$/);
  430. const isListItemNode = matchNodeNames(/^(LI|DT|DD)$/);
  431. const inList = (parents, listName) => findUntil(parents, isListNode, isTableCellNode)
  432. .exists((list) => list.nodeName === listName && !isCustomList(list));
  433. const setNodeChangeHandler = (editor, nodeChangeHandler) => {
  434. const initialNode = editor.selection.getNode();
  435. // Set the initial state
  436. nodeChangeHandler({
  437. parents: editor.dom.getParents(initialNode),
  438. element: initialNode
  439. });
  440. editor.on('NodeChange', nodeChangeHandler);
  441. return () => editor.off('NodeChange', nodeChangeHandler);
  442. };
  443. const isWithinNonEditable = (editor, element) => element !== null && !editor.dom.isEditable(element);
  444. const isWithinNonEditableList = (editor, element) => {
  445. const parentList = editor.dom.getParent(element, 'ol,ul,dl');
  446. return isWithinNonEditable(editor, parentList) || !editor.selection.isEditable();
  447. };
  448. const isOlNode = matchNodeName('ol');
  449. const listNames = ['OL', 'UL', 'DL'];
  450. const listSelector = listNames.join(',');
  451. const getParentList = (editor, node) => {
  452. const selectionStart = node || editor.selection.getStart(true);
  453. return editor.dom.getParent(selectionStart, listSelector, getClosestListHost(editor, selectionStart));
  454. };
  455. const getClosestListHost = (editor, elm) => {
  456. const parentBlocks = editor.dom.getParents(elm, editor.dom.isBlock);
  457. const isNotForcedRootBlock = (elm) => elm.nodeName.toLowerCase() !== getForcedRootBlock(editor);
  458. const parentBlock = find(parentBlocks, (elm) => isNotForcedRootBlock(elm) && isListHost(editor.schema, elm));
  459. return parentBlock.getOr(editor.getBody());
  460. };
  461. const isListHost = (schema, node) => !isListNode(node) && !isListItemNode(node) && exists(listNames, (listName) => schema.isValidChild(node.nodeName, listName));
  462. const open = (editor) => {
  463. // Find the current list and skip opening if the selection isn't in an ordered list
  464. const currentList = getParentList(editor);
  465. if (!isOlNode(currentList) || isWithinNonEditableList(editor, currentList)) {
  466. return;
  467. }
  468. editor.windowManager.open({
  469. title: 'List Properties',
  470. body: {
  471. type: 'panel',
  472. items: [
  473. {
  474. type: 'input',
  475. name: 'start',
  476. label: 'Start list at number',
  477. inputMode: 'numeric'
  478. }
  479. ]
  480. },
  481. initialData: {
  482. start: parseDetail({
  483. start: editor.dom.getAttrib(currentList, 'start', '1'),
  484. listStyleType: Optional.from(editor.dom.getStyle(currentList, 'list-style-type'))
  485. })
  486. },
  487. buttons: [
  488. {
  489. type: 'cancel',
  490. name: 'cancel',
  491. text: 'Cancel'
  492. },
  493. {
  494. type: 'submit',
  495. name: 'save',
  496. text: 'Save',
  497. primary: true
  498. }
  499. ],
  500. onSubmit: (api) => {
  501. const data = api.getData();
  502. parseStartValue(data.start).each((detail) => {
  503. editor.execCommand('mceListUpdate', false, {
  504. attrs: {
  505. start: detail.start === '1' ? '' : detail.start
  506. },
  507. styles: {
  508. 'list-style-type': detail.listStyleType.getOr('')
  509. }
  510. });
  511. });
  512. api.close();
  513. }
  514. });
  515. };
  516. const register$2 = (editor) => {
  517. editor.addCommand('mceListProps', () => {
  518. open(editor);
  519. });
  520. };
  521. const setupToggleButtonHandler = (editor, listName) => (api) => {
  522. const toggleButtonHandler = (e) => {
  523. api.setActive(inList(e.parents, listName));
  524. api.setEnabled(!isWithinNonEditableList(editor, e.element) && editor.selection.isEditable());
  525. };
  526. api.setEnabled(editor.selection.isEditable());
  527. return setNodeChangeHandler(editor, toggleButtonHandler);
  528. };
  529. const register$1 = (editor) => {
  530. const exec = (command) => () => editor.execCommand(command);
  531. if (!editor.hasPlugin('advlist')) {
  532. editor.ui.registry.addToggleButton('numlist', {
  533. icon: 'ordered-list',
  534. active: false,
  535. tooltip: 'Numbered list',
  536. onAction: exec('InsertOrderedList'),
  537. onSetup: setupToggleButtonHandler(editor, 'OL')
  538. });
  539. editor.ui.registry.addToggleButton('bullist', {
  540. icon: 'unordered-list',
  541. active: false,
  542. tooltip: 'Bullet list',
  543. onAction: exec('InsertUnorderedList'),
  544. onSetup: setupToggleButtonHandler(editor, 'UL')
  545. });
  546. }
  547. };
  548. const setupMenuButtonHandler = (editor, listName) => (api) => {
  549. const menuButtonHandler = (e) => api.setEnabled(inList(e.parents, listName) && !isWithinNonEditableList(editor, e.element));
  550. return setNodeChangeHandler(editor, menuButtonHandler);
  551. };
  552. const register = (editor) => {
  553. const listProperties = {
  554. text: 'List properties...',
  555. icon: 'ordered-list',
  556. onAction: () => editor.execCommand('mceListProps'),
  557. onSetup: setupMenuButtonHandler(editor, 'OL')
  558. };
  559. editor.ui.registry.addMenuItem('listprops', listProperties);
  560. editor.ui.registry.addContextMenu('lists', {
  561. update: (node) => {
  562. const parentList = getParentList(editor, node);
  563. return isOlNode(parentList) ? ['listprops'] : [];
  564. }
  565. });
  566. };
  567. var Plugin = () => {
  568. global.add('lists', (editor) => {
  569. register$2(editor);
  570. register$1(editor);
  571. register(editor);
  572. return get(editor);
  573. });
  574. };
  575. Plugin();
  576. /** *****
  577. * DO NOT EXPORT ANYTHING
  578. *
  579. * IF YOU DO ROLLUP WILL LEAVE A GLOBAL ON THE PAGE
  580. *******/
  581. })();