plugin.js 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368
  1. /**
  2. * TinyMCE version 8.0.2 (2025-08-14)
  3. */
  4. (function () {
  5. 'use strict';
  6. /* eslint-disable @typescript-eslint/no-wrapper-object-types */
  7. const hasProto = (v, constructor, predicate) => {
  8. var _a;
  9. if (predicate(v, constructor.prototype)) {
  10. return true;
  11. }
  12. else {
  13. // String-based fallback time
  14. return ((_a = v.constructor) === null || _a === void 0 ? void 0 : _a.name) === constructor.name;
  15. }
  16. };
  17. const typeOf = (x) => {
  18. const t = typeof x;
  19. if (x === null) {
  20. return 'null';
  21. }
  22. else if (t === 'object' && Array.isArray(x)) {
  23. return 'array';
  24. }
  25. else if (t === 'object' && hasProto(x, String, (o, proto) => proto.isPrototypeOf(o))) {
  26. return 'string';
  27. }
  28. else {
  29. return t;
  30. }
  31. };
  32. const isType$1 = (type) => (value) => typeOf(value) === type;
  33. const isSimpleType = (type) => (value) => typeof value === type;
  34. const isString = isType$1('string');
  35. const isArray = isType$1('array');
  36. const isBoolean = isSimpleType('boolean');
  37. const isNullable = (a) => a === null || a === undefined;
  38. const isNonNullable = (a) => !isNullable(a);
  39. const isNumber = isSimpleType('number');
  40. const noop = () => { };
  41. const constant = (value) => {
  42. return () => {
  43. return value;
  44. };
  45. };
  46. const always = constant(true);
  47. /**
  48. * The `Optional` type represents a value (of any type) that potentially does
  49. * not exist. Any `Optional<T>` can either be a `Some<T>` (in which case the
  50. * value does exist) or a `None` (in which case the value does not exist). This
  51. * module defines a whole lot of FP-inspired utility functions for dealing with
  52. * `Optional` objects.
  53. *
  54. * Comparison with null or undefined:
  55. * - We don't get fancy null coalescing operators with `Optional`
  56. * - We do get fancy helper functions with `Optional`
  57. * - `Optional` support nesting, and allow for the type to still be nullable (or
  58. * another `Optional`)
  59. * - There is no option to turn off strict-optional-checks like there is for
  60. * strict-null-checks
  61. */
  62. class Optional {
  63. // The internal representation has a `tag` and a `value`, but both are
  64. // private: able to be console.logged, but not able to be accessed by code
  65. constructor(tag, value) {
  66. this.tag = tag;
  67. this.value = value;
  68. }
  69. // --- Identities ---
  70. /**
  71. * Creates a new `Optional<T>` that **does** contain a value.
  72. */
  73. static some(value) {
  74. return new Optional(true, value);
  75. }
  76. /**
  77. * Create a new `Optional<T>` that **does not** contain a value. `T` can be
  78. * any type because we don't actually have a `T`.
  79. */
  80. static none() {
  81. return Optional.singletonNone;
  82. }
  83. /**
  84. * Perform a transform on an `Optional` type. Regardless of whether this
  85. * `Optional` contains a value or not, `fold` will return a value of type `U`.
  86. * If this `Optional` does not contain a value, the `U` will be created by
  87. * calling `onNone`. If this `Optional` does contain a value, the `U` will be
  88. * created by calling `onSome`.
  89. *
  90. * For the FP enthusiasts in the room, this function:
  91. * 1. Could be used to implement all of the functions below
  92. * 2. Forms a catamorphism
  93. */
  94. fold(onNone, onSome) {
  95. if (this.tag) {
  96. return onSome(this.value);
  97. }
  98. else {
  99. return onNone();
  100. }
  101. }
  102. /**
  103. * Determine if this `Optional` object contains a value.
  104. */
  105. isSome() {
  106. return this.tag;
  107. }
  108. /**
  109. * Determine if this `Optional` object **does not** contain a value.
  110. */
  111. isNone() {
  112. return !this.tag;
  113. }
  114. // --- Functor (name stolen from Haskell / maths) ---
  115. /**
  116. * Perform a transform on an `Optional` object, **if** there is a value. If
  117. * you provide a function to turn a T into a U, this is the function you use
  118. * to turn an `Optional<T>` into an `Optional<U>`. If this **does** contain
  119. * a value then the output will also contain a value (that value being the
  120. * output of `mapper(this.value)`), and if this **does not** contain a value
  121. * then neither will the output.
  122. */
  123. map(mapper) {
  124. if (this.tag) {
  125. return Optional.some(mapper(this.value));
  126. }
  127. else {
  128. return Optional.none();
  129. }
  130. }
  131. // --- Monad (name stolen from Haskell / maths) ---
  132. /**
  133. * Perform a transform on an `Optional` object, **if** there is a value.
  134. * Unlike `map`, here the transform itself also returns an `Optional`.
  135. */
  136. bind(binder) {
  137. if (this.tag) {
  138. return binder(this.value);
  139. }
  140. else {
  141. return Optional.none();
  142. }
  143. }
  144. // --- Traversable (name stolen from Haskell / maths) ---
  145. /**
  146. * For a given predicate, this function finds out if there **exists** a value
  147. * inside this `Optional` object that meets the predicate. In practice, this
  148. * means that for `Optional`s that do not contain a value it returns false (as
  149. * no predicate-meeting value exists).
  150. */
  151. exists(predicate) {
  152. return this.tag && predicate(this.value);
  153. }
  154. /**
  155. * For a given predicate, this function finds out if **all** the values inside
  156. * this `Optional` object meet the predicate. In practice, this means that
  157. * for `Optional`s that do not contain a value it returns true (as all 0
  158. * objects do meet the predicate).
  159. */
  160. forall(predicate) {
  161. return !this.tag || predicate(this.value);
  162. }
  163. filter(predicate) {
  164. if (!this.tag || predicate(this.value)) {
  165. return this;
  166. }
  167. else {
  168. return Optional.none();
  169. }
  170. }
  171. // --- Getters ---
  172. /**
  173. * Get the value out of the inside of the `Optional` object, using a default
  174. * `replacement` value if the provided `Optional` object does not contain a
  175. * value.
  176. */
  177. getOr(replacement) {
  178. return this.tag ? this.value : replacement;
  179. }
  180. /**
  181. * Get the value out of the inside of the `Optional` object, using a default
  182. * `replacement` value if the provided `Optional` object does not contain a
  183. * value. Unlike `getOr`, in this method the `replacement` object is also
  184. * `Optional` - meaning that this method will always return an `Optional`.
  185. */
  186. or(replacement) {
  187. return this.tag ? this : replacement;
  188. }
  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. Unlike `getOr`, in this method the `replacement` value is
  193. * "thunked" - that is to say that you don't pass a value to `getOrThunk`, you
  194. * pass a function which (if called) will **return** the `value` you want to
  195. * use.
  196. */
  197. getOrThunk(thunk) {
  198. return this.tag ? this.value : thunk();
  199. }
  200. /**
  201. * Get the value out of the inside of the `Optional` object, using a default
  202. * `replacement` value if the provided Optional object does not contain a
  203. * value.
  204. *
  205. * Unlike `or`, in this method the `replacement` value is "thunked" - that is
  206. * to say that you don't pass a value to `orThunk`, you pass a function which
  207. * (if called) will **return** the `value` you want to use.
  208. *
  209. * Unlike `getOrThunk`, in this method the `replacement` value is also
  210. * `Optional`, meaning that this method will always return an `Optional`.
  211. */
  212. orThunk(thunk) {
  213. return this.tag ? this : thunk();
  214. }
  215. /**
  216. * Get the value out of the inside of the `Optional` object, throwing an
  217. * exception if the provided `Optional` object does not contain a value.
  218. *
  219. * WARNING:
  220. * You should only be using this function if you know that the `Optional`
  221. * object **is not** empty (otherwise you're throwing exceptions in production
  222. * code, which is bad).
  223. *
  224. * In tests this is more acceptable.
  225. *
  226. * Prefer other methods to this, such as `.each`.
  227. */
  228. getOrDie(message) {
  229. if (!this.tag) {
  230. throw new Error(message !== null && message !== void 0 ? message : 'Called getOrDie on None');
  231. }
  232. else {
  233. return this.value;
  234. }
  235. }
  236. // --- Interop with null and undefined ---
  237. /**
  238. * Creates an `Optional` value from a nullable (or undefined-able) input.
  239. * Null, or undefined, is converted to `None`, and anything else is converted
  240. * to `Some`.
  241. */
  242. static from(value) {
  243. return isNonNullable(value) ? Optional.some(value) : Optional.none();
  244. }
  245. /**
  246. * Converts an `Optional` to a nullable type, by getting the value if it
  247. * exists, or returning `null` if it does not.
  248. */
  249. getOrNull() {
  250. return this.tag ? this.value : null;
  251. }
  252. /**
  253. * Converts an `Optional` to an undefined-able type, by getting the value if
  254. * it exists, or returning `undefined` if it does not.
  255. */
  256. getOrUndefined() {
  257. return this.value;
  258. }
  259. // --- Utilities ---
  260. /**
  261. * If the `Optional` contains a value, perform an action on that value.
  262. * Unlike the rest of the methods on this type, `.each` has side-effects. If
  263. * you want to transform an `Optional<T>` **into** something, then this is not
  264. * the method for you. If you want to use an `Optional<T>` to **do**
  265. * something, then this is the method for you - provided you're okay with not
  266. * doing anything in the case where the `Optional` doesn't have a value inside
  267. * it. If you're not sure whether your use-case fits into transforming
  268. * **into** something or **doing** something, check whether it has a return
  269. * value. If it does, you should be performing a transform.
  270. */
  271. each(worker) {
  272. if (this.tag) {
  273. worker(this.value);
  274. }
  275. }
  276. /**
  277. * Turn the `Optional` object into an array that contains all of the values
  278. * stored inside the `Optional`. In practice, this means the output will have
  279. * either 0 or 1 elements.
  280. */
  281. toArray() {
  282. return this.tag ? [this.value] : [];
  283. }
  284. /**
  285. * Turn the `Optional` object into a string for debugging or printing. Not
  286. * recommended for production code, but good for debugging. Also note that
  287. * these days an `Optional` object can be logged to the console directly, and
  288. * its inner value (if it exists) will be visible.
  289. */
  290. toString() {
  291. return this.tag ? `some(${this.value})` : 'none()';
  292. }
  293. }
  294. // Sneaky optimisation: every instance of Optional.none is identical, so just
  295. // reuse the same object
  296. Optional.singletonNone = new Optional(false);
  297. const nativeSlice = Array.prototype.slice;
  298. const nativePush = Array.prototype.push;
  299. const map = (xs, f) => {
  300. // pre-allocating array size when it's guaranteed to be known
  301. // http://jsperf.com/push-allocated-vs-dynamic/22
  302. const len = xs.length;
  303. const r = new Array(len);
  304. for (let i = 0; i < len; i++) {
  305. const x = xs[i];
  306. r[i] = f(x, i);
  307. }
  308. return r;
  309. };
  310. // Unwound implementing other functions in terms of each.
  311. // The code size is roughly the same, and it should allow for better optimisation.
  312. // const each = function<T, U>(xs: T[], f: (x: T, i?: number, xs?: T[]) => void): void {
  313. const each = (xs, f) => {
  314. for (let i = 0, len = xs.length; i < len; i++) {
  315. const x = xs[i];
  316. f(x, i);
  317. }
  318. };
  319. const eachr = (xs, f) => {
  320. for (let i = xs.length - 1; i >= 0; i--) {
  321. const x = xs[i];
  322. f(x, i);
  323. }
  324. };
  325. /*
  326. * Groups an array into contiguous arrays of like elements. Whether an element is like or not depends on f.
  327. *
  328. * f is a function that derives a value from an element - e.g. true or false, or a string.
  329. * Elements are like if this function generates the same value for them (according to ===).
  330. *
  331. *
  332. * Order of the elements is preserved. Arr.flatten() on the result will return the original list, as with Haskell groupBy function.
  333. * For a good explanation, see the group function (which is a special case of groupBy)
  334. * http://hackage.haskell.org/package/base-4.7.0.0/docs/Data-List.html#v:group
  335. */
  336. const groupBy = (xs, f) => {
  337. if (xs.length === 0) {
  338. return [];
  339. }
  340. else {
  341. let wasType = f(xs[0]); // initial case for matching
  342. const r = [];
  343. let group = [];
  344. for (let i = 0, len = xs.length; i < len; i++) {
  345. const x = xs[i];
  346. const type = f(x);
  347. if (type !== wasType) {
  348. r.push(group);
  349. group = [];
  350. }
  351. wasType = type;
  352. group.push(x);
  353. }
  354. if (group.length !== 0) {
  355. r.push(group);
  356. }
  357. return r;
  358. }
  359. };
  360. const foldl = (xs, f, acc) => {
  361. each(xs, (x, i) => {
  362. acc = f(acc, x, i);
  363. });
  364. return acc;
  365. };
  366. const flatten = (xs) => {
  367. // Note, this is possible because push supports multiple arguments:
  368. // http://jsperf.com/concat-push/6
  369. // Note that in the past, concat() would silently work (very slowly) for array-like objects.
  370. // With this change it will throw an error.
  371. const r = [];
  372. for (let i = 0, len = xs.length; i < len; ++i) {
  373. // Ensure that each value is an array itself
  374. if (!isArray(xs[i])) {
  375. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  376. }
  377. nativePush.apply(r, xs[i]);
  378. }
  379. return r;
  380. };
  381. const bind = (xs, f) => flatten(map(xs, f));
  382. const sort = (xs, comparator) => {
  383. const copy = nativeSlice.call(xs, 0);
  384. copy.sort(comparator);
  385. return copy;
  386. };
  387. const hasOwnProperty = Object.hasOwnProperty;
  388. const has = (obj, key) => hasOwnProperty.call(obj, key);
  389. const Cell = (initial) => {
  390. let value = initial;
  391. const get = () => {
  392. return value;
  393. };
  394. const set = (v) => {
  395. value = v;
  396. };
  397. return {
  398. get,
  399. set
  400. };
  401. };
  402. const singleton = (doRevoke) => {
  403. const subject = Cell(Optional.none());
  404. const revoke = () => subject.get().each(doRevoke);
  405. const clear = () => {
  406. revoke();
  407. subject.set(Optional.none());
  408. };
  409. const isSet = () => subject.get().isSome();
  410. const get = () => subject.get();
  411. const set = (s) => {
  412. revoke();
  413. subject.set(Optional.some(s));
  414. };
  415. return {
  416. clear,
  417. isSet,
  418. get,
  419. set
  420. };
  421. };
  422. const value = () => {
  423. const subject = singleton(noop);
  424. const on = (f) => subject.get().each(f);
  425. return {
  426. ...subject,
  427. on
  428. };
  429. };
  430. var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
  431. /* eslint-disable max-len */
  432. const punctuationStr = `[~№|!-*+-\\/:;?@\\[-\`{}\u00A1\u00AB\u00B7\u00BB\u00BF;\u00B7\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1361-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u3008\u3009\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30\u2E31\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]`;
  433. const punctuation$1 = constant(punctuationStr);
  434. // tslint:disable-next-line:variable-name
  435. const Custom = (regex, prefix, suffix, flags) => {
  436. const term = () => {
  437. return new RegExp(regex, flags.getOr('g'));
  438. };
  439. return {
  440. term,
  441. prefix,
  442. suffix
  443. };
  444. };
  445. Custom;
  446. const punctuation = punctuation$1;
  447. var global$2 = tinymce.util.Tools.resolve('tinymce.Env');
  448. var global$1 = tinymce.util.Tools.resolve('tinymce.util.Tools');
  449. const fromHtml = (html, scope) => {
  450. const doc = scope || document;
  451. const div = doc.createElement('div');
  452. div.innerHTML = html;
  453. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  454. const message = 'HTML does not have a single root node';
  455. // eslint-disable-next-line no-console
  456. console.error(message, html);
  457. throw new Error(message);
  458. }
  459. return fromDom(div.childNodes[0]);
  460. };
  461. const fromTag = (tag, scope) => {
  462. const doc = scope || document;
  463. const node = doc.createElement(tag);
  464. return fromDom(node);
  465. };
  466. const fromText = (text, scope) => {
  467. const doc = scope || document;
  468. const node = doc.createTextNode(text);
  469. return fromDom(node);
  470. };
  471. const fromDom = (node) => {
  472. // TODO: Consider removing this check, but left atm for safety
  473. if (node === null || node === undefined) {
  474. throw new Error('Node cannot be null or undefined');
  475. }
  476. return {
  477. dom: node
  478. };
  479. };
  480. const fromPoint = (docElm, x, y) => Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  481. // tslint:disable-next-line:variable-name
  482. const SugarElement = {
  483. fromHtml,
  484. fromTag,
  485. fromText,
  486. fromDom,
  487. fromPoint
  488. };
  489. const DOCUMENT = 9;
  490. const DOCUMENT_FRAGMENT = 11;
  491. const ELEMENT = 1;
  492. const TEXT = 3;
  493. const bypassSelector = (dom) =>
  494. // Only elements, documents and shadow roots support querySelector
  495. // shadow root element type is DOCUMENT_FRAGMENT
  496. dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT ||
  497. // IE fix for complex queries on empty nodes: http://jsfiddle.net/spyder/fv9ptr5L/
  498. dom.childElementCount === 0;
  499. const all = (selector, scope) => {
  500. const base = scope === undefined ? document : scope.dom;
  501. return bypassSelector(base) ? [] : map(base.querySelectorAll(selector), SugarElement.fromDom);
  502. };
  503. /*
  504. * Most of sand doesn't alter the methods on the object.
  505. * We're making an exception for Node, because bitwise and is so easy to get wrong.
  506. *
  507. * Might be nice to ADT this at some point instead of having individual methods.
  508. */
  509. const compareDocumentPosition = (a, b, match) => {
  510. // Returns: 0 if e1 and e2 are the same node, or a bitmask comparing the positions
  511. // of nodes e1 and e2 in their documents. See the URL below for bitmask interpretation
  512. // https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
  513. // eslint-disable-next-line no-bitwise
  514. return (a.compareDocumentPosition(b) & match) !== 0;
  515. };
  516. const documentPositionPreceding = (a, b) => {
  517. return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_PRECEDING);
  518. };
  519. const type = (element) => element.dom.nodeType;
  520. const isType = (t) => (element) => type(element) === t;
  521. const isText$1 = isType(TEXT);
  522. const parent = (element) => Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  523. const children = (element) => map(element.dom.childNodes, SugarElement.fromDom);
  524. const spot = (element, offset) => ({
  525. element,
  526. offset
  527. });
  528. const leaf = (element, offset) => {
  529. const cs = children(element);
  530. return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset);
  531. };
  532. const before = (marker, element) => {
  533. const parent$1 = parent(marker);
  534. parent$1.each((v) => {
  535. v.dom.insertBefore(element.dom, marker.dom);
  536. });
  537. };
  538. const append = (parent, element) => {
  539. parent.dom.appendChild(element.dom);
  540. };
  541. const wrap = (element, wrapper) => {
  542. before(element, wrapper);
  543. append(wrapper, element);
  544. };
  545. const rawSet = (dom, key, value) => {
  546. /*
  547. * JQuery coerced everything to a string, and silently did nothing on text node/null/undefined.
  548. *
  549. * We fail on those invalid cases, only allowing numbers and booleans.
  550. */
  551. if (isString(value) || isBoolean(value) || isNumber(value)) {
  552. dom.setAttribute(key, value + '');
  553. }
  554. else {
  555. // eslint-disable-next-line no-console
  556. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  557. throw new Error('Attribute value was not simple');
  558. }
  559. };
  560. const set = (element, key, value) => {
  561. rawSet(element.dom, key, value);
  562. };
  563. const NodeValue = (is, name) => {
  564. const get = (element) => {
  565. if (!is(element)) {
  566. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  567. }
  568. return getOption(element).getOr('');
  569. };
  570. const getOption = (element) => is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  571. const set = (element, value) => {
  572. if (!is(element)) {
  573. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  574. }
  575. element.dom.nodeValue = value;
  576. };
  577. return {
  578. get,
  579. getOption,
  580. set
  581. };
  582. };
  583. const api = NodeValue(isText$1, 'text');
  584. const get$1 = (element) => api.get(element);
  585. const descendants = (scope, selector) => all(selector, scope);
  586. var global = tinymce.util.Tools.resolve('tinymce.dom.TreeWalker');
  587. const isSimpleBoundary = (dom, node) => dom.isBlock(node) || has(dom.schema.getVoidElements(), node.nodeName);
  588. const isContentEditableFalse = (dom, node) => !dom.isEditable(node);
  589. const isContentEditableTrueInCef = (dom, node) => dom.getContentEditable(node) === 'true' && node.parentNode && !dom.isEditable(node.parentNode);
  590. const isHidden = (dom, node) => !dom.isBlock(node) && has(dom.schema.getWhitespaceElements(), node.nodeName);
  591. const isBoundary = (dom, node) => isSimpleBoundary(dom, node) || isContentEditableFalse(dom, node) || isHidden(dom, node) || isContentEditableTrueInCef(dom, node);
  592. const isText = (node) => node.nodeType === 3;
  593. const nuSection = () => ({
  594. sOffset: 0,
  595. fOffset: 0,
  596. elements: []
  597. });
  598. const toLeaf = (node, offset) => leaf(SugarElement.fromDom(node), offset);
  599. const walk = (dom, walkerFn, startNode, callbacks, endNode, skipStart = true) => {
  600. let next = skipStart ? walkerFn(false) : startNode;
  601. while (next) {
  602. // Walk over content editable or hidden elements
  603. const isCefNode = isContentEditableFalse(dom, next);
  604. if (isCefNode || isHidden(dom, next)) {
  605. const stopWalking = isCefNode ? callbacks.cef(next) : callbacks.boundary(next);
  606. if (stopWalking) {
  607. break;
  608. }
  609. else {
  610. next = walkerFn(true);
  611. continue;
  612. }
  613. }
  614. else if (isSimpleBoundary(dom, next)) {
  615. if (callbacks.boundary(next)) {
  616. break;
  617. }
  618. }
  619. else if (isText(next)) {
  620. callbacks.text(next);
  621. }
  622. if (next === endNode) {
  623. break;
  624. }
  625. else {
  626. next = walkerFn(false);
  627. }
  628. }
  629. };
  630. const collectTextToBoundary = (dom, section, node, rootNode, forwards) => {
  631. var _a;
  632. // Don't bother collecting text nodes if we're already at a boundary
  633. if (isBoundary(dom, node)) {
  634. return;
  635. }
  636. const rootBlock = (_a = dom.getParent(rootNode, dom.isBlock)) !== null && _a !== void 0 ? _a : dom.getRoot();
  637. const walker = new global(node, rootBlock);
  638. const walkerFn = forwards ? walker.next.bind(walker) : walker.prev.bind(walker);
  639. // Walk over and add text nodes to the section and increase the offsets
  640. // so we know to ignore the additional text when matching
  641. walk(dom, walkerFn, node, {
  642. boundary: always,
  643. cef: always,
  644. text: (next) => {
  645. if (forwards) {
  646. section.fOffset += next.length;
  647. }
  648. else {
  649. section.sOffset += next.length;
  650. }
  651. section.elements.push(SugarElement.fromDom(next));
  652. }
  653. });
  654. };
  655. const collect = (dom, rootNode, startNode, endNode, callbacks, skipStart = true) => {
  656. const walker = new global(startNode, rootNode);
  657. const sections = [];
  658. let current = nuSection();
  659. // Find any text between the start node and the closest boundary
  660. collectTextToBoundary(dom, current, startNode, rootNode, false);
  661. const finishSection = () => {
  662. if (current.elements.length > 0) {
  663. sections.push(current);
  664. current = nuSection();
  665. }
  666. return false;
  667. };
  668. // Collect all the text nodes in the specified range and create sections from the
  669. // boundaries within the range
  670. walk(dom, walker.next.bind(walker), startNode, {
  671. boundary: finishSection,
  672. cef: (node) => {
  673. finishSection();
  674. // Collect additional nested contenteditable true content
  675. if (callbacks) {
  676. sections.push(...callbacks.cef(node));
  677. }
  678. return false;
  679. },
  680. text: (next) => {
  681. current.elements.push(SugarElement.fromDom(next));
  682. if (callbacks) {
  683. callbacks.text(next, current);
  684. }
  685. }
  686. }, endNode, skipStart);
  687. // Find any text between the end node and the closest boundary, then finalise the section
  688. if (endNode) {
  689. collectTextToBoundary(dom, current, endNode, rootNode, true);
  690. }
  691. finishSection();
  692. return sections;
  693. };
  694. const collectRangeSections = (dom, rng) => {
  695. const start = toLeaf(rng.startContainer, rng.startOffset);
  696. const startNode = start.element.dom;
  697. const end = toLeaf(rng.endContainer, rng.endOffset);
  698. const endNode = end.element.dom;
  699. return collect(dom, rng.commonAncestorContainer, startNode, endNode, {
  700. text: (node, section) => {
  701. // Set the start/end offset of the section
  702. if (node === endNode) {
  703. section.fOffset += node.length - end.offset;
  704. }
  705. else if (node === startNode) {
  706. section.sOffset += start.offset;
  707. }
  708. },
  709. cef: (node) => {
  710. // Collect the sections and then order them appropriately, as nested sections maybe out of order
  711. // TODO: See if we can improve this to avoid the sort overhead
  712. const sections = bind(descendants(SugarElement.fromDom(node), '*[contenteditable=true]'), (e) => {
  713. const ceTrueNode = e.dom;
  714. return collect(dom, ceTrueNode, ceTrueNode);
  715. });
  716. return sort(sections, (a, b) => (documentPositionPreceding(a.elements[0].dom, b.elements[0].dom)) ? 1 : -1);
  717. }
  718. }, false);
  719. };
  720. const fromRng = (dom, rng) => rng.collapsed ? [] : collectRangeSections(dom, rng);
  721. const fromNode = (dom, node) => {
  722. const rng = dom.createRng();
  723. rng.selectNode(node);
  724. return fromRng(dom, rng);
  725. };
  726. const fromNodes = (dom, nodes) => bind(nodes, (node) => fromNode(dom, node));
  727. const find$2 = (text, pattern, start = 0, finish = text.length) => {
  728. const regex = pattern.regex;
  729. regex.lastIndex = start;
  730. const results = [];
  731. let match;
  732. while ((match = regex.exec(text))) {
  733. const matchedText = match[pattern.matchIndex];
  734. const matchStart = match.index + match[0].indexOf(matchedText);
  735. const matchFinish = matchStart + matchedText.length;
  736. // Stop finding matches if we've hit the finish mark
  737. if (matchFinish > finish) {
  738. break;
  739. }
  740. results.push({
  741. start: matchStart,
  742. finish: matchFinish
  743. });
  744. regex.lastIndex = matchFinish;
  745. }
  746. return results;
  747. };
  748. const extract = (elements, matches) => {
  749. // Walk over each text node and compare with the matches
  750. const nodePositions = foldl(elements, (acc, element) => {
  751. const content = get$1(element);
  752. const start = acc.last;
  753. const finish = start + content.length;
  754. // Find positions for any matches in the current text node
  755. const positions = bind(matches, (match, matchIdx) => {
  756. // Check to see if the match overlaps with the text position
  757. if (match.start < finish && match.finish > start) {
  758. return [{
  759. element,
  760. start: Math.max(start, match.start) - start,
  761. finish: Math.min(finish, match.finish) - start,
  762. matchId: matchIdx
  763. }];
  764. }
  765. else {
  766. return [];
  767. }
  768. });
  769. return {
  770. results: acc.results.concat(positions),
  771. last: finish
  772. };
  773. }, { results: [], last: 0 }).results;
  774. // Group the positions by the match id
  775. return groupBy(nodePositions, (position) => position.matchId);
  776. };
  777. const find$1 = (pattern, sections) => bind(sections, (section) => {
  778. const elements = section.elements;
  779. const content = map(elements, get$1).join('');
  780. const positions = find$2(content, pattern, section.sOffset, content.length - section.fOffset);
  781. return extract(elements, positions);
  782. });
  783. const mark = (matches, replacementNode) => {
  784. // Walk backwards and mark the positions
  785. // Note: We need to walk backwards so the position indexes don't change
  786. eachr(matches, (match, idx) => {
  787. eachr(match, (pos) => {
  788. const wrapper = SugarElement.fromDom(replacementNode.cloneNode(false));
  789. set(wrapper, 'data-mce-index', idx);
  790. const textNode = pos.element.dom;
  791. if (textNode.length === pos.finish && pos.start === 0) {
  792. wrap(pos.element, wrapper);
  793. }
  794. else {
  795. if (textNode.length !== pos.finish) {
  796. textNode.splitText(pos.finish);
  797. }
  798. const matchNode = textNode.splitText(pos.start);
  799. wrap(SugarElement.fromDom(matchNode), wrapper);
  800. }
  801. });
  802. });
  803. };
  804. const findAndMark = (dom, pattern, node, replacementNode) => {
  805. const textSections = fromNode(dom, node);
  806. const matches = find$1(pattern, textSections);
  807. mark(matches, replacementNode);
  808. return matches.length;
  809. };
  810. const findAndMarkInSelection = (dom, pattern, selection, replacementNode) => {
  811. const bookmark = selection.getBookmark();
  812. // Handle table cell selection as the table plugin enables
  813. // you to fake select table cells and perform actions on them
  814. const nodes = dom.select('td[data-mce-selected],th[data-mce-selected]');
  815. const textSections = nodes.length > 0 ? fromNodes(dom, nodes) : fromRng(dom, selection.getRng());
  816. // Find and mark matches
  817. const matches = find$1(pattern, textSections);
  818. mark(matches, replacementNode);
  819. // Restore the selection
  820. selection.moveToBookmark(bookmark);
  821. return matches.length;
  822. };
  823. const getElmIndex = (elm) => {
  824. return elm.getAttribute('data-mce-index');
  825. };
  826. const markAllMatches = (editor, currentSearchState, pattern, inSelection) => {
  827. const marker = editor.dom.create('span', {
  828. 'data-mce-bogus': 1
  829. });
  830. marker.className = 'mce-match-marker';
  831. const node = editor.getBody();
  832. done(editor, currentSearchState, false);
  833. if (inSelection) {
  834. return findAndMarkInSelection(editor.dom, pattern, editor.selection, marker);
  835. }
  836. else {
  837. return findAndMark(editor.dom, pattern, node, marker);
  838. }
  839. };
  840. const unwrap = (node) => {
  841. var _a;
  842. const parentNode = node.parentNode;
  843. if (node.firstChild) {
  844. parentNode.insertBefore(node.firstChild, node);
  845. }
  846. (_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(node);
  847. };
  848. const findSpansByIndex = (editor, index) => {
  849. const spans = [];
  850. const nodes = global$1.toArray(editor.getBody().getElementsByTagName('span'));
  851. if (nodes.length) {
  852. for (let i = 0; i < nodes.length; i++) {
  853. const nodeIndex = getElmIndex(nodes[i]);
  854. if (nodeIndex === null || !nodeIndex.length) {
  855. continue;
  856. }
  857. if (nodeIndex === index.toString()) {
  858. spans.push(nodes[i]);
  859. }
  860. }
  861. }
  862. return spans;
  863. };
  864. const moveSelection = (editor, currentSearchState, forward) => {
  865. const searchState = currentSearchState.get();
  866. let testIndex = searchState.index;
  867. const dom = editor.dom;
  868. if (forward) {
  869. if (testIndex + 1 === searchState.count) {
  870. testIndex = 0;
  871. }
  872. else {
  873. testIndex++;
  874. }
  875. }
  876. else {
  877. if (testIndex - 1 === -1) {
  878. testIndex = searchState.count - 1;
  879. }
  880. else {
  881. testIndex--;
  882. }
  883. }
  884. dom.removeClass(findSpansByIndex(editor, searchState.index), 'mce-match-marker-selected');
  885. const spans = findSpansByIndex(editor, testIndex);
  886. if (spans.length) {
  887. dom.addClass(findSpansByIndex(editor, testIndex), 'mce-match-marker-selected');
  888. editor.selection.scrollIntoView(spans[0]);
  889. return testIndex;
  890. }
  891. return -1;
  892. };
  893. const removeNode = (dom, node) => {
  894. const parent = node.parentNode;
  895. dom.remove(node);
  896. if (parent && dom.isEmpty(parent)) {
  897. dom.remove(parent);
  898. }
  899. };
  900. const escapeSearchText = (text, wholeWord) => {
  901. const escapedText = text.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&').replace(/\s/g, '[^\\S\\r\\n\\uFEFF]');
  902. const wordRegex = '(' + escapedText + ')';
  903. return wholeWord ? `(?:^|\\s|${punctuation()})` + wordRegex + `(?=$|\\s|${punctuation()})` : wordRegex;
  904. };
  905. const find = (editor, currentSearchState, text, matchCase, wholeWord, inSelection) => {
  906. const selection = editor.selection;
  907. const escapedText = escapeSearchText(text, wholeWord);
  908. const isForwardSelection = selection.isForward();
  909. const pattern = {
  910. regex: new RegExp(escapedText, matchCase ? 'g' : 'gi'),
  911. matchIndex: 1
  912. };
  913. const count = markAllMatches(editor, currentSearchState, pattern, inSelection);
  914. // Safari has a bug whereby splitting text nodes breaks the selection (which is done when marking matches).
  915. // As such we need to manually reset it after doing a find action. See https://bugs.webkit.org/show_bug.cgi?id=230594
  916. if (global$2.browser.isSafari()) {
  917. selection.setRng(selection.getRng(), isForwardSelection);
  918. }
  919. if (count) {
  920. const newIndex = moveSelection(editor, currentSearchState, true);
  921. currentSearchState.set({
  922. index: newIndex,
  923. count,
  924. text,
  925. matchCase,
  926. wholeWord,
  927. inSelection
  928. });
  929. }
  930. return count;
  931. };
  932. const next = (editor, currentSearchState) => {
  933. const index = moveSelection(editor, currentSearchState, true);
  934. currentSearchState.set({ ...currentSearchState.get(), index });
  935. };
  936. const prev = (editor, currentSearchState) => {
  937. const index = moveSelection(editor, currentSearchState, false);
  938. currentSearchState.set({ ...currentSearchState.get(), index });
  939. };
  940. const isMatchSpan = (node) => {
  941. const matchIndex = getElmIndex(node);
  942. return matchIndex !== null && matchIndex.length > 0;
  943. };
  944. const replace = (editor, currentSearchState, text, forward, all) => {
  945. const searchState = currentSearchState.get();
  946. const currentIndex = searchState.index;
  947. let currentMatchIndex, nextIndex = currentIndex;
  948. forward = forward !== false;
  949. const node = editor.getBody();
  950. const nodes = global$1.grep(global$1.toArray(node.getElementsByTagName('span')), isMatchSpan);
  951. for (let i = 0; i < nodes.length; i++) {
  952. const nodeIndex = getElmIndex(nodes[i]);
  953. let matchIndex = currentMatchIndex = parseInt(nodeIndex, 10);
  954. if (all || matchIndex === searchState.index) {
  955. if (text.length) {
  956. nodes[i].innerText = text;
  957. unwrap(nodes[i]);
  958. }
  959. else {
  960. removeNode(editor.dom, nodes[i]);
  961. }
  962. while (nodes[++i]) {
  963. matchIndex = parseInt(getElmIndex(nodes[i]), 10);
  964. if (matchIndex === currentMatchIndex) {
  965. removeNode(editor.dom, nodes[i]);
  966. }
  967. else {
  968. i--;
  969. break;
  970. }
  971. }
  972. if (forward) {
  973. nextIndex--;
  974. }
  975. }
  976. else if (currentMatchIndex > currentIndex) {
  977. nodes[i].setAttribute('data-mce-index', String(currentMatchIndex - 1));
  978. }
  979. }
  980. currentSearchState.set({
  981. ...searchState,
  982. count: all ? 0 : searchState.count - 1,
  983. index: nextIndex
  984. });
  985. if (forward) {
  986. next(editor, currentSearchState);
  987. }
  988. else {
  989. prev(editor, currentSearchState);
  990. }
  991. return !all && currentSearchState.get().count > 0;
  992. };
  993. const done = (editor, currentSearchState, keepEditorSelection) => {
  994. let startContainer;
  995. let endContainer;
  996. const searchState = currentSearchState.get();
  997. const nodes = global$1.toArray(editor.getBody().getElementsByTagName('span'));
  998. for (let i = 0; i < nodes.length; i++) {
  999. const nodeIndex = getElmIndex(nodes[i]);
  1000. if (nodeIndex !== null && nodeIndex.length) {
  1001. if (nodeIndex === searchState.index.toString()) {
  1002. // Note: The first child of the span node will be the highlighted text node
  1003. if (!startContainer) {
  1004. startContainer = nodes[i].firstChild;
  1005. }
  1006. endContainer = nodes[i].firstChild;
  1007. }
  1008. unwrap(nodes[i]);
  1009. }
  1010. }
  1011. // Reset the search state
  1012. currentSearchState.set({
  1013. ...searchState,
  1014. index: -1,
  1015. count: 0,
  1016. text: ''
  1017. });
  1018. if (startContainer && endContainer) {
  1019. const rng = editor.dom.createRng();
  1020. rng.setStart(startContainer, 0);
  1021. rng.setEnd(endContainer, endContainer.data.length);
  1022. if (keepEditorSelection !== false) {
  1023. editor.selection.setRng(rng);
  1024. }
  1025. return rng;
  1026. }
  1027. else {
  1028. return undefined;
  1029. }
  1030. };
  1031. const hasNext = (editor, currentSearchState) => currentSearchState.get().count > 1;
  1032. const hasPrev = (editor, currentSearchState) => currentSearchState.get().count > 1;
  1033. const get = (editor, currentState) => {
  1034. const done$1 = (keepEditorSelection) => {
  1035. return done(editor, currentState, keepEditorSelection);
  1036. };
  1037. const find$1 = (text, matchCase, wholeWord, inSelection = false) => {
  1038. return find(editor, currentState, text, matchCase, wholeWord, inSelection);
  1039. };
  1040. const next$1 = () => {
  1041. return next(editor, currentState);
  1042. };
  1043. const prev$1 = () => {
  1044. return prev(editor, currentState);
  1045. };
  1046. const replace$1 = (text, forward, all) => {
  1047. return replace(editor, currentState, text, forward, all);
  1048. };
  1049. return {
  1050. done: done$1,
  1051. find: find$1,
  1052. next: next$1,
  1053. prev: prev$1,
  1054. replace: replace$1
  1055. };
  1056. };
  1057. const open = (editor, currentSearchState) => {
  1058. const dialogApi = value();
  1059. editor.undoManager.add();
  1060. const selectedText = global$1.trim(editor.selection.getContent({ format: 'text' }));
  1061. const updateButtonStates = (api) => {
  1062. api.setEnabled('next', hasNext(editor, currentSearchState));
  1063. api.setEnabled('prev', hasPrev(editor, currentSearchState));
  1064. };
  1065. const updateSearchState = (api) => {
  1066. const data = api.getData();
  1067. const current = currentSearchState.get();
  1068. currentSearchState.set({
  1069. ...current,
  1070. matchCase: data.matchcase,
  1071. wholeWord: data.wholewords,
  1072. inSelection: data.inselection
  1073. });
  1074. };
  1075. const disableAll = (api, disable) => {
  1076. const buttons = ['replace', 'replaceall', 'prev', 'next'];
  1077. const toggle = (name) => api.setEnabled(name, !disable);
  1078. each(buttons, toggle);
  1079. };
  1080. const toggleNotFoundAlert = (isVisible, api) => {
  1081. api.redial(getDialogSpec(isVisible, api.getData()));
  1082. };
  1083. // Temporarily workaround for iOS/iPadOS dialog placement to hide the keyboard
  1084. // TODO: Remove in 5.2 once iOS fixed positioning is fixed. See TINY-4441
  1085. const focusButtonIfRequired = (api, name) => {
  1086. if (global$2.browser.isSafari() && global$2.deviceType.isTouch() && (name === 'find' || name === 'replace' || name === 'replaceall')) {
  1087. api.focus(name);
  1088. }
  1089. };
  1090. const reset = (api) => {
  1091. // Clean up the markers if required
  1092. done(editor, currentSearchState, false);
  1093. // Disable the buttons
  1094. disableAll(api, true);
  1095. updateButtonStates(api);
  1096. };
  1097. const doFind = (api) => {
  1098. const data = api.getData();
  1099. const last = currentSearchState.get();
  1100. if (!data.findtext.length) {
  1101. reset(api);
  1102. return;
  1103. }
  1104. // Same search text, so treat the find as a next click instead
  1105. if (last.text === data.findtext && last.matchCase === data.matchcase && last.wholeWord === data.wholewords) {
  1106. next(editor, currentSearchState);
  1107. }
  1108. else {
  1109. // Find new matches
  1110. const count = find(editor, currentSearchState, data.findtext, data.matchcase, data.wholewords, data.inselection);
  1111. if (count <= 0) {
  1112. toggleNotFoundAlert(true, api);
  1113. }
  1114. disableAll(api, count === 0);
  1115. }
  1116. updateButtonStates(api);
  1117. };
  1118. const initialState = currentSearchState.get();
  1119. const initialData = {
  1120. findtext: selectedText,
  1121. replacetext: '',
  1122. wholewords: initialState.wholeWord,
  1123. matchcase: initialState.matchCase,
  1124. inselection: initialState.inSelection
  1125. };
  1126. const getPanelItems = (error) => {
  1127. const items = [
  1128. {
  1129. type: 'label',
  1130. label: 'Find',
  1131. for: 'findtext',
  1132. items: [
  1133. {
  1134. type: 'bar',
  1135. items: [
  1136. {
  1137. type: 'input',
  1138. name: 'findtext',
  1139. maximized: true,
  1140. inputMode: 'search'
  1141. },
  1142. {
  1143. type: 'button',
  1144. name: 'prev',
  1145. text: 'Previous',
  1146. icon: 'action-prev',
  1147. enabled: false,
  1148. borderless: true
  1149. },
  1150. {
  1151. type: 'button',
  1152. name: 'next',
  1153. text: 'Next',
  1154. icon: 'action-next',
  1155. enabled: false,
  1156. borderless: true
  1157. }
  1158. ]
  1159. }
  1160. ]
  1161. },
  1162. {
  1163. type: 'input',
  1164. name: 'replacetext',
  1165. label: 'Replace with',
  1166. inputMode: 'search'
  1167. },
  1168. ];
  1169. if (error) {
  1170. items.push({
  1171. type: 'alertbanner',
  1172. level: 'error',
  1173. text: 'Could not find the specified string.',
  1174. icon: 'warning',
  1175. });
  1176. }
  1177. return items;
  1178. };
  1179. const getDialogSpec = (showNoMatchesAlertBanner, initialData) => ({
  1180. title: 'Find and Replace',
  1181. size: 'normal',
  1182. body: {
  1183. type: 'panel',
  1184. items: getPanelItems(showNoMatchesAlertBanner)
  1185. },
  1186. buttons: [
  1187. {
  1188. type: 'menu',
  1189. name: 'options',
  1190. icon: 'preferences',
  1191. tooltip: 'Preferences',
  1192. align: 'start',
  1193. items: [
  1194. {
  1195. type: 'togglemenuitem',
  1196. name: 'matchcase',
  1197. text: 'Match case'
  1198. }, {
  1199. type: 'togglemenuitem',
  1200. name: 'wholewords',
  1201. text: 'Find whole words only'
  1202. },
  1203. {
  1204. type: 'togglemenuitem',
  1205. name: 'inselection',
  1206. text: 'Find in selection'
  1207. }
  1208. ]
  1209. },
  1210. {
  1211. type: 'custom',
  1212. name: 'find',
  1213. text: 'Find',
  1214. primary: true
  1215. },
  1216. {
  1217. type: 'custom',
  1218. name: 'replace',
  1219. text: 'Replace',
  1220. enabled: false
  1221. },
  1222. {
  1223. type: 'custom',
  1224. name: 'replaceall',
  1225. text: 'Replace all',
  1226. enabled: false,
  1227. }
  1228. ],
  1229. initialData,
  1230. onChange: (api, details) => {
  1231. if (showNoMatchesAlertBanner) {
  1232. toggleNotFoundAlert(false, api);
  1233. }
  1234. if (details.name === 'findtext' && currentSearchState.get().count > 0) {
  1235. reset(api);
  1236. }
  1237. },
  1238. onAction: (api, details) => {
  1239. const data = api.getData();
  1240. switch (details.name) {
  1241. case 'find':
  1242. doFind(api);
  1243. break;
  1244. case 'replace':
  1245. if (!replace(editor, currentSearchState, data.replacetext)) {
  1246. reset(api);
  1247. }
  1248. else {
  1249. updateButtonStates(api);
  1250. }
  1251. break;
  1252. case 'replaceall':
  1253. replace(editor, currentSearchState, data.replacetext, true, true);
  1254. reset(api);
  1255. break;
  1256. case 'prev':
  1257. prev(editor, currentSearchState);
  1258. updateButtonStates(api);
  1259. break;
  1260. case 'next':
  1261. next(editor, currentSearchState);
  1262. updateButtonStates(api);
  1263. break;
  1264. case 'matchcase':
  1265. case 'wholewords':
  1266. case 'inselection':
  1267. toggleNotFoundAlert(false, api);
  1268. updateSearchState(api);
  1269. reset(api);
  1270. break;
  1271. }
  1272. focusButtonIfRequired(api, details.name);
  1273. },
  1274. onSubmit: (api) => {
  1275. doFind(api);
  1276. focusButtonIfRequired(api, 'find');
  1277. },
  1278. onClose: () => {
  1279. editor.focus();
  1280. done(editor, currentSearchState);
  1281. editor.undoManager.add();
  1282. }
  1283. });
  1284. dialogApi.set(editor.windowManager.open(getDialogSpec(false, initialData), { inline: 'toolbar' }));
  1285. };
  1286. const register$1 = (editor, currentSearchState) => {
  1287. editor.addCommand('SearchReplace', () => {
  1288. open(editor, currentSearchState);
  1289. });
  1290. };
  1291. const showDialog = (editor, currentSearchState) => () => {
  1292. open(editor, currentSearchState);
  1293. };
  1294. const register = (editor, currentSearchState) => {
  1295. editor.ui.registry.addMenuItem('searchreplace', {
  1296. text: 'Find and replace...',
  1297. shortcut: 'Meta+F',
  1298. onAction: showDialog(editor, currentSearchState),
  1299. icon: 'search'
  1300. });
  1301. editor.ui.registry.addButton('searchreplace', {
  1302. tooltip: 'Find and replace',
  1303. onAction: showDialog(editor, currentSearchState),
  1304. icon: 'search',
  1305. shortcut: 'Meta+F'
  1306. });
  1307. editor.shortcuts.add('Meta+F', '', showDialog(editor, currentSearchState));
  1308. };
  1309. var Plugin = () => {
  1310. global$3.add('searchreplace', (editor) => {
  1311. const currentSearchState = Cell({
  1312. index: -1,
  1313. count: 0,
  1314. text: '',
  1315. matchCase: false,
  1316. wholeWord: false,
  1317. inSelection: false
  1318. });
  1319. register$1(editor, currentSearchState);
  1320. register(editor, currentSearchState);
  1321. return get(editor, currentSearchState);
  1322. });
  1323. };
  1324. Plugin();
  1325. /** *****
  1326. * DO NOT EXPORT ANYTHING
  1327. *
  1328. * IF YOU DO ROLLUP WILL LEAVE A GLOBAL ON THE PAGE
  1329. *******/
  1330. })();