You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

13130 lines
428 KiB

2 years ago
2 years ago
2 years ago
  1. /**
  2. * Copyright (c) Tiny Technologies, Inc. All rights reserved.
  3. * Licensed under the LGPL or a commercial license.
  4. * For LGPL see License.txt in the project root for license information.
  5. * For commercial licenses see https://www.tiny.cloud/
  6. *
  7. * Version: 5.10.0 (2021-10-11)
  8. */
  9. (function () {
  10. 'use strict';
  11. var __assign = function () {
  12. __assign = Object.assign || function __assign(t) {
  13. for (var s, i = 1, n = arguments.length; i < n; i++) {
  14. s = arguments[i];
  15. for (var p in s)
  16. if (Object.prototype.hasOwnProperty.call(s, p))
  17. t[p] = s[p];
  18. }
  19. return t;
  20. };
  21. return __assign.apply(this, arguments);
  22. };
  23. function __rest(s, e) {
  24. var t = {};
  25. for (var p in s)
  26. if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  27. t[p] = s[p];
  28. if (s != null && typeof Object.getOwnPropertySymbols === 'function')
  29. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  30. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  31. t[p[i]] = s[p[i]];
  32. }
  33. return t;
  34. }
  35. function __spreadArray(to, from, pack) {
  36. if (pack || arguments.length === 2)
  37. for (var i = 0, l = from.length, ar; i < l; i++) {
  38. if (ar || !(i in from)) {
  39. if (!ar)
  40. ar = Array.prototype.slice.call(from, 0, i);
  41. ar[i] = from[i];
  42. }
  43. }
  44. return to.concat(ar || Array.prototype.slice.call(from));
  45. }
  46. var typeOf = function (x) {
  47. var t = typeof x;
  48. if (x === null) {
  49. return 'null';
  50. } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) {
  51. return 'array';
  52. } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) {
  53. return 'string';
  54. } else {
  55. return t;
  56. }
  57. };
  58. var isType$1 = function (type) {
  59. return function (value) {
  60. return typeOf(value) === type;
  61. };
  62. };
  63. var isSimpleType = function (type) {
  64. return function (value) {
  65. return typeof value === type;
  66. };
  67. };
  68. var eq$1 = function (t) {
  69. return function (a) {
  70. return t === a;
  71. };
  72. };
  73. var isString = isType$1('string');
  74. var isObject = isType$1('object');
  75. var isArray = isType$1('array');
  76. var isNull = eq$1(null);
  77. var isBoolean = isSimpleType('boolean');
  78. var isUndefined = eq$1(undefined);
  79. var isNullable = function (a) {
  80. return a === null || a === undefined;
  81. };
  82. var isNonNullable = function (a) {
  83. return !isNullable(a);
  84. };
  85. var isFunction = isSimpleType('function');
  86. var isNumber = isSimpleType('number');
  87. var noop = function () {
  88. };
  89. var compose = function (fa, fb) {
  90. return function () {
  91. var args = [];
  92. for (var _i = 0; _i < arguments.length; _i++) {
  93. args[_i] = arguments[_i];
  94. }
  95. return fa(fb.apply(null, args));
  96. };
  97. };
  98. var compose1 = function (fbc, fab) {
  99. return function (a) {
  100. return fbc(fab(a));
  101. };
  102. };
  103. var constant$1 = function (value) {
  104. return function () {
  105. return value;
  106. };
  107. };
  108. var identity = function (x) {
  109. return x;
  110. };
  111. var tripleEquals = function (a, b) {
  112. return a === b;
  113. };
  114. function curry(fn) {
  115. var initialArgs = [];
  116. for (var _i = 1; _i < arguments.length; _i++) {
  117. initialArgs[_i - 1] = arguments[_i];
  118. }
  119. return function () {
  120. var restArgs = [];
  121. for (var _i = 0; _i < arguments.length; _i++) {
  122. restArgs[_i] = arguments[_i];
  123. }
  124. var all = initialArgs.concat(restArgs);
  125. return fn.apply(null, all);
  126. };
  127. }
  128. var not = function (f) {
  129. return function (t) {
  130. return !f(t);
  131. };
  132. };
  133. var die = function (msg) {
  134. return function () {
  135. throw new Error(msg);
  136. };
  137. };
  138. var apply$1 = function (f) {
  139. return f();
  140. };
  141. var never = constant$1(false);
  142. var always = constant$1(true);
  143. var none = function () {
  144. return NONE;
  145. };
  146. var NONE = function () {
  147. var call = function (thunk) {
  148. return thunk();
  149. };
  150. var id = identity;
  151. var me = {
  152. fold: function (n, _s) {
  153. return n();
  154. },
  155. isSome: never,
  156. isNone: always,
  157. getOr: id,
  158. getOrThunk: call,
  159. getOrDie: function (msg) {
  160. throw new Error(msg || 'error: getOrDie called on none.');
  161. },
  162. getOrNull: constant$1(null),
  163. getOrUndefined: constant$1(undefined),
  164. or: id,
  165. orThunk: call,
  166. map: none,
  167. each: noop,
  168. bind: none,
  169. exists: never,
  170. forall: always,
  171. filter: function () {
  172. return none();
  173. },
  174. toArray: function () {
  175. return [];
  176. },
  177. toString: constant$1('none()')
  178. };
  179. return me;
  180. }();
  181. var some = function (a) {
  182. var constant_a = constant$1(a);
  183. var self = function () {
  184. return me;
  185. };
  186. var bind = function (f) {
  187. return f(a);
  188. };
  189. var me = {
  190. fold: function (n, s) {
  191. return s(a);
  192. },
  193. isSome: always,
  194. isNone: never,
  195. getOr: constant_a,
  196. getOrThunk: constant_a,
  197. getOrDie: constant_a,
  198. getOrNull: constant_a,
  199. getOrUndefined: constant_a,
  200. or: self,
  201. orThunk: self,
  202. map: function (f) {
  203. return some(f(a));
  204. },
  205. each: function (f) {
  206. f(a);
  207. },
  208. bind: bind,
  209. exists: bind,
  210. forall: bind,
  211. filter: function (f) {
  212. return f(a) ? me : NONE;
  213. },
  214. toArray: function () {
  215. return [a];
  216. },
  217. toString: function () {
  218. return 'some(' + a + ')';
  219. }
  220. };
  221. return me;
  222. };
  223. var from = function (value) {
  224. return value === null || value === undefined ? NONE : some(value);
  225. };
  226. var Optional = {
  227. some: some,
  228. none: none,
  229. from: from
  230. };
  231. var cached = function (f) {
  232. var called = false;
  233. var r;
  234. return function () {
  235. var args = [];
  236. for (var _i = 0; _i < arguments.length; _i++) {
  237. args[_i] = arguments[_i];
  238. }
  239. if (!called) {
  240. called = true;
  241. r = f.apply(null, args);
  242. }
  243. return r;
  244. };
  245. };
  246. var DeviceType = function (os, browser, userAgent, mediaMatch) {
  247. var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
  248. var isiPhone = os.isiOS() && !isiPad;
  249. var isMobile = os.isiOS() || os.isAndroid();
  250. var isTouch = isMobile || mediaMatch('(pointer:coarse)');
  251. var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)');
  252. var isPhone = isiPhone || isMobile && !isTablet;
  253. var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
  254. var isDesktop = !isPhone && !isTablet && !iOSwebview;
  255. return {
  256. isiPad: constant$1(isiPad),
  257. isiPhone: constant$1(isiPhone),
  258. isTablet: constant$1(isTablet),
  259. isPhone: constant$1(isPhone),
  260. isTouch: constant$1(isTouch),
  261. isAndroid: os.isAndroid,
  262. isiOS: os.isiOS,
  263. isWebView: constant$1(iOSwebview),
  264. isDesktop: constant$1(isDesktop)
  265. };
  266. };
  267. var nativeSlice = Array.prototype.slice;
  268. var nativeIndexOf = Array.prototype.indexOf;
  269. var nativePush = Array.prototype.push;
  270. var rawIndexOf = function (ts, t) {
  271. return nativeIndexOf.call(ts, t);
  272. };
  273. var contains$1 = function (xs, x) {
  274. return rawIndexOf(xs, x) > -1;
  275. };
  276. var exists = function (xs, pred) {
  277. for (var i = 0, len = xs.length; i < len; i++) {
  278. var x = xs[i];
  279. if (pred(x, i)) {
  280. return true;
  281. }
  282. }
  283. return false;
  284. };
  285. var map$2 = function (xs, f) {
  286. var len = xs.length;
  287. var r = new Array(len);
  288. for (var i = 0; i < len; i++) {
  289. var x = xs[i];
  290. r[i] = f(x, i);
  291. }
  292. return r;
  293. };
  294. var each$1 = function (xs, f) {
  295. for (var i = 0, len = xs.length; i < len; i++) {
  296. var x = xs[i];
  297. f(x, i);
  298. }
  299. };
  300. var eachr = function (xs, f) {
  301. for (var i = xs.length - 1; i >= 0; i--) {
  302. var x = xs[i];
  303. f(x, i);
  304. }
  305. };
  306. var filter$2 = function (xs, pred) {
  307. var r = [];
  308. for (var i = 0, len = xs.length; i < len; i++) {
  309. var x = xs[i];
  310. if (pred(x, i)) {
  311. r.push(x);
  312. }
  313. }
  314. return r;
  315. };
  316. var foldr = function (xs, f, acc) {
  317. eachr(xs, function (x, i) {
  318. acc = f(acc, x, i);
  319. });
  320. return acc;
  321. };
  322. var foldl = function (xs, f, acc) {
  323. each$1(xs, function (x, i) {
  324. acc = f(acc, x, i);
  325. });
  326. return acc;
  327. };
  328. var findUntil = function (xs, pred, until) {
  329. for (var i = 0, len = xs.length; i < len; i++) {
  330. var x = xs[i];
  331. if (pred(x, i)) {
  332. return Optional.some(x);
  333. } else if (until(x, i)) {
  334. break;
  335. }
  336. }
  337. return Optional.none();
  338. };
  339. var find$2 = function (xs, pred) {
  340. return findUntil(xs, pred, never);
  341. };
  342. var findIndex$1 = function (xs, pred) {
  343. for (var i = 0, len = xs.length; i < len; i++) {
  344. var x = xs[i];
  345. if (pred(x, i)) {
  346. return Optional.some(i);
  347. }
  348. }
  349. return Optional.none();
  350. };
  351. var flatten = function (xs) {
  352. var r = [];
  353. for (var i = 0, len = xs.length; i < len; ++i) {
  354. if (!isArray(xs[i])) {
  355. throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
  356. }
  357. nativePush.apply(r, xs[i]);
  358. }
  359. return r;
  360. };
  361. var bind$3 = function (xs, f) {
  362. return flatten(map$2(xs, f));
  363. };
  364. var forall = function (xs, pred) {
  365. for (var i = 0, len = xs.length; i < len; ++i) {
  366. var x = xs[i];
  367. if (pred(x, i) !== true) {
  368. return false;
  369. }
  370. }
  371. return true;
  372. };
  373. var reverse = function (xs) {
  374. var r = nativeSlice.call(xs, 0);
  375. r.reverse();
  376. return r;
  377. };
  378. var difference = function (a1, a2) {
  379. return filter$2(a1, function (x) {
  380. return !contains$1(a2, x);
  381. });
  382. };
  383. var pure$2 = function (x) {
  384. return [x];
  385. };
  386. var sort = function (xs, comparator) {
  387. var copy = nativeSlice.call(xs, 0);
  388. copy.sort(comparator);
  389. return copy;
  390. };
  391. var get$d = function (xs, i) {
  392. return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none();
  393. };
  394. var head = function (xs) {
  395. return get$d(xs, 0);
  396. };
  397. var findMap = function (arr, f) {
  398. for (var i = 0; i < arr.length; i++) {
  399. var r = f(arr[i], i);
  400. if (r.isSome()) {
  401. return r;
  402. }
  403. }
  404. return Optional.none();
  405. };
  406. var firstMatch = function (regexes, s) {
  407. for (var i = 0; i < regexes.length; i++) {
  408. var x = regexes[i];
  409. if (x.test(s)) {
  410. return x;
  411. }
  412. }
  413. return undefined;
  414. };
  415. var find$1 = function (regexes, agent) {
  416. var r = firstMatch(regexes, agent);
  417. if (!r) {
  418. return {
  419. major: 0,
  420. minor: 0
  421. };
  422. }
  423. var group = function (i) {
  424. return Number(agent.replace(r, '$' + i));
  425. };
  426. return nu$8(group(1), group(2));
  427. };
  428. var detect$4 = function (versionRegexes, agent) {
  429. var cleanedAgent = String(agent).toLowerCase();
  430. if (versionRegexes.length === 0) {
  431. return unknown$3();
  432. }
  433. return find$1(versionRegexes, cleanedAgent);
  434. };
  435. var unknown$3 = function () {
  436. return nu$8(0, 0);
  437. };
  438. var nu$8 = function (major, minor) {
  439. return {
  440. major: major,
  441. minor: minor
  442. };
  443. };
  444. var Version = {
  445. nu: nu$8,
  446. detect: detect$4,
  447. unknown: unknown$3
  448. };
  449. var detectBrowser$1 = function (browsers, userAgentData) {
  450. return findMap(userAgentData.brands, function (uaBrand) {
  451. var lcBrand = uaBrand.brand.toLowerCase();
  452. return find$2(browsers, function (browser) {
  453. var _a;
  454. return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase());
  455. }).map(function (info) {
  456. return {
  457. current: info.name,
  458. version: Version.nu(parseInt(uaBrand.version, 10), 0)
  459. };
  460. });
  461. });
  462. };
  463. var detect$3 = function (candidates, userAgent) {
  464. var agent = String(userAgent).toLowerCase();
  465. return find$2(candidates, function (candidate) {
  466. return candidate.search(agent);
  467. });
  468. };
  469. var detectBrowser = function (browsers, userAgent) {
  470. return detect$3(browsers, userAgent).map(function (browser) {
  471. var version = Version.detect(browser.versionRegexes, userAgent);
  472. return {
  473. current: browser.name,
  474. version: version
  475. };
  476. });
  477. };
  478. var detectOs = function (oses, userAgent) {
  479. return detect$3(oses, userAgent).map(function (os) {
  480. var version = Version.detect(os.versionRegexes, userAgent);
  481. return {
  482. current: os.name,
  483. version: version
  484. };
  485. });
  486. };
  487. var checkRange = function (str, substr, start) {
  488. return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
  489. };
  490. var supplant = function (str, obj) {
  491. var isStringOrNumber = function (a) {
  492. var t = typeof a;
  493. return t === 'string' || t === 'number';
  494. };
  495. return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
  496. var value = obj[key];
  497. return isStringOrNumber(value) ? value.toString() : fullMatch;
  498. });
  499. };
  500. var contains = function (str, substr) {
  501. return str.indexOf(substr) !== -1;
  502. };
  503. var endsWith = function (str, suffix) {
  504. return checkRange(str, suffix, str.length - suffix.length);
  505. };
  506. var blank = function (r) {
  507. return function (s) {
  508. return s.replace(r, '');
  509. };
  510. };
  511. var trim = blank(/^\s+|\s+$/g);
  512. var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
  513. var checkContains = function (target) {
  514. return function (uastring) {
  515. return contains(uastring, target);
  516. };
  517. };
  518. var browsers = [
  519. {
  520. name: 'Edge',
  521. versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
  522. search: function (uastring) {
  523. return contains(uastring, 'edge/') && contains(uastring, 'chrome') && contains(uastring, 'safari') && contains(uastring, 'applewebkit');
  524. }
  525. },
  526. {
  527. name: 'Chrome',
  528. brand: 'Chromium',
  529. versionRegexes: [
  530. /.*?chrome\/([0-9]+)\.([0-9]+).*/,
  531. normalVersionRegex
  532. ],
  533. search: function (uastring) {
  534. return contains(uastring, 'chrome') && !contains(uastring, 'chromeframe');
  535. }
  536. },
  537. {
  538. name: 'IE',
  539. versionRegexes: [
  540. /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
  541. /.*?rv:([0-9]+)\.([0-9]+).*/
  542. ],
  543. search: function (uastring) {
  544. return contains(uastring, 'msie') || contains(uastring, 'trident');
  545. }
  546. },
  547. {
  548. name: 'Opera',
  549. versionRegexes: [
  550. normalVersionRegex,
  551. /.*?opera\/([0-9]+)\.([0-9]+).*/
  552. ],
  553. search: checkContains('opera')
  554. },
  555. {
  556. name: 'Firefox',
  557. versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
  558. search: checkContains('firefox')
  559. },
  560. {
  561. name: 'Safari',
  562. versionRegexes: [
  563. normalVersionRegex,
  564. /.*?cpu os ([0-9]+)_([0-9]+).*/
  565. ],
  566. search: function (uastring) {
  567. return (contains(uastring, 'safari') || contains(uastring, 'mobile/')) && contains(uastring, 'applewebkit');
  568. }
  569. }
  570. ];
  571. var oses = [
  572. {
  573. name: 'Windows',
  574. search: checkContains('win'),
  575. versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
  576. },
  577. {
  578. name: 'iOS',
  579. search: function (uastring) {
  580. return contains(uastring, 'iphone') || contains(uastring, 'ipad');
  581. },
  582. versionRegexes: [
  583. /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
  584. /.*cpu os ([0-9]+)_([0-9]+).*/,
  585. /.*cpu iphone os ([0-9]+)_([0-9]+).*/
  586. ]
  587. },
  588. {
  589. name: 'Android',
  590. search: checkContains('android'),
  591. versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
  592. },
  593. {
  594. name: 'OSX',
  595. search: checkContains('mac os x'),
  596. versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/]
  597. },
  598. {
  599. name: 'Linux',
  600. search: checkContains('linux'),
  601. versionRegexes: []
  602. },
  603. {
  604. name: 'Solaris',
  605. search: checkContains('sunos'),
  606. versionRegexes: []
  607. },
  608. {
  609. name: 'FreeBSD',
  610. search: checkContains('freebsd'),
  611. versionRegexes: []
  612. },
  613. {
  614. name: 'ChromeOS',
  615. search: checkContains('cros'),
  616. versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/]
  617. }
  618. ];
  619. var PlatformInfo = {
  620. browsers: constant$1(browsers),
  621. oses: constant$1(oses)
  622. };
  623. var edge = 'Edge';
  624. var chrome = 'Chrome';
  625. var ie = 'IE';
  626. var opera = 'Opera';
  627. var firefox = 'Firefox';
  628. var safari = 'Safari';
  629. var unknown$2 = function () {
  630. return nu$7({
  631. current: undefined,
  632. version: Version.unknown()
  633. });
  634. };
  635. var nu$7 = function (info) {
  636. var current = info.current;
  637. var version = info.version;
  638. var isBrowser = function (name) {
  639. return function () {
  640. return current === name;
  641. };
  642. };
  643. return {
  644. current: current,
  645. version: version,
  646. isEdge: isBrowser(edge),
  647. isChrome: isBrowser(chrome),
  648. isIE: isBrowser(ie),
  649. isOpera: isBrowser(opera),
  650. isFirefox: isBrowser(firefox),
  651. isSafari: isBrowser(safari)
  652. };
  653. };
  654. var Browser = {
  655. unknown: unknown$2,
  656. nu: nu$7,
  657. edge: constant$1(edge),
  658. chrome: constant$1(chrome),
  659. ie: constant$1(ie),
  660. opera: constant$1(opera),
  661. firefox: constant$1(firefox),
  662. safari: constant$1(safari)
  663. };
  664. var windows = 'Windows';
  665. var ios = 'iOS';
  666. var android = 'Android';
  667. var linux = 'Linux';
  668. var osx = 'OSX';
  669. var solaris = 'Solaris';
  670. var freebsd = 'FreeBSD';
  671. var chromeos = 'ChromeOS';
  672. var unknown$1 = function () {
  673. return nu$6({
  674. current: undefined,
  675. version: Version.unknown()
  676. });
  677. };
  678. var nu$6 = function (info) {
  679. var current = info.current;
  680. var version = info.version;
  681. var isOS = function (name) {
  682. return function () {
  683. return current === name;
  684. };
  685. };
  686. return {
  687. current: current,
  688. version: version,
  689. isWindows: isOS(windows),
  690. isiOS: isOS(ios),
  691. isAndroid: isOS(android),
  692. isOSX: isOS(osx),
  693. isLinux: isOS(linux),
  694. isSolaris: isOS(solaris),
  695. isFreeBSD: isOS(freebsd),
  696. isChromeOS: isOS(chromeos)
  697. };
  698. };
  699. var OperatingSystem = {
  700. unknown: unknown$1,
  701. nu: nu$6,
  702. windows: constant$1(windows),
  703. ios: constant$1(ios),
  704. android: constant$1(android),
  705. linux: constant$1(linux),
  706. osx: constant$1(osx),
  707. solaris: constant$1(solaris),
  708. freebsd: constant$1(freebsd),
  709. chromeos: constant$1(chromeos)
  710. };
  711. var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) {
  712. var browsers = PlatformInfo.browsers();
  713. var oses = PlatformInfo.oses();
  714. var browser = userAgentDataOpt.bind(function (userAgentData) {
  715. return detectBrowser$1(browsers, userAgentData);
  716. }).orThunk(function () {
  717. return detectBrowser(browsers, userAgent);
  718. }).fold(Browser.unknown, Browser.nu);
  719. var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
  720. var deviceType = DeviceType(os, browser, userAgent, mediaMatch);
  721. return {
  722. browser: browser,
  723. os: os,
  724. deviceType: deviceType
  725. };
  726. };
  727. var PlatformDetection = { detect: detect$2 };
  728. var mediaMatch = function (query) {
  729. return window.matchMedia(query).matches;
  730. };
  731. var platform$1 = cached(function () {
  732. return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch);
  733. });
  734. var detect$1 = function () {
  735. return platform$1();
  736. };
  737. var constant = constant$1;
  738. var touchstart = constant('touchstart');
  739. var touchmove = constant('touchmove');
  740. var touchend = constant('touchend');
  741. var mousedown = constant('mousedown');
  742. var mousemove = constant('mousemove');
  743. var mouseup = constant('mouseup');
  744. var mouseover = constant('mouseover');
  745. var keydown = constant('keydown');
  746. var keyup = constant('keyup');
  747. var input$1 = constant('input');
  748. var change = constant('change');
  749. var click = constant('click');
  750. var transitionend = constant('transitionend');
  751. var selectstart = constant('selectstart');
  752. var prefixName = function (name) {
  753. return constant$1('alloy.' + name);
  754. };
  755. var alloy = { tap: prefixName('tap') };
  756. var focus$4 = prefixName('focus');
  757. var postBlur = prefixName('blur.post');
  758. var postPaste = prefixName('paste.post');
  759. var receive$1 = prefixName('receive');
  760. var execute$5 = prefixName('execute');
  761. var focusItem = prefixName('focus.item');
  762. var tap = alloy.tap;
  763. var longpress = prefixName('longpress');
  764. var systemInit = prefixName('system.init');
  765. var attachedToDom = prefixName('system.attached');
  766. var detachedFromDom = prefixName('system.detached');
  767. var focusShifted = prefixName('focusmanager.shifted');
  768. var highlight$1 = prefixName('highlight');
  769. var dehighlight$1 = prefixName('dehighlight');
  770. var emit = function (component, event) {
  771. dispatchWith(component, component.element, event, {});
  772. };
  773. var emitWith = function (component, event, properties) {
  774. dispatchWith(component, component.element, event, properties);
  775. };
  776. var emitExecute = function (component) {
  777. emit(component, execute$5());
  778. };
  779. var dispatch = function (component, target, event) {
  780. dispatchWith(component, target, event, {});
  781. };
  782. var dispatchWith = function (component, target, event, properties) {
  783. var data = __assign({ target: target }, properties);
  784. component.getSystem().triggerEvent(event, target, data);
  785. };
  786. var dispatchEvent = function (component, target, event, simulatedEvent) {
  787. component.getSystem().triggerEvent(event, target, simulatedEvent.event);
  788. };
  789. var dispatchFocus = function (component, target) {
  790. component.getSystem().triggerFocus(target, component.element);
  791. };
  792. var DOCUMENT = 9;
  793. var DOCUMENT_FRAGMENT = 11;
  794. var ELEMENT = 1;
  795. var TEXT = 3;
  796. var fromHtml$2 = function (html, scope) {
  797. var doc = scope || document;
  798. var div = doc.createElement('div');
  799. div.innerHTML = html;
  800. if (!div.hasChildNodes() || div.childNodes.length > 1) {
  801. console.error('HTML does not have a single root node', html);
  802. throw new Error('HTML must have a single root node');
  803. }
  804. return fromDom(div.childNodes[0]);
  805. };
  806. var fromTag = function (tag, scope) {
  807. var doc = scope || document;
  808. var node = doc.createElement(tag);
  809. return fromDom(node);
  810. };
  811. var fromText = function (text, scope) {
  812. var doc = scope || document;
  813. var node = doc.createTextNode(text);
  814. return fromDom(node);
  815. };
  816. var fromDom = function (node) {
  817. if (node === null || node === undefined) {
  818. throw new Error('Node cannot be null or undefined');
  819. }
  820. return { dom: node };
  821. };
  822. var fromPoint = function (docElm, x, y) {
  823. return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom);
  824. };
  825. var SugarElement = {
  826. fromHtml: fromHtml$2,
  827. fromTag: fromTag,
  828. fromText: fromText,
  829. fromDom: fromDom,
  830. fromPoint: fromPoint
  831. };
  832. var is$1 = function (element, selector) {
  833. var dom = element.dom;
  834. if (dom.nodeType !== ELEMENT) {
  835. return false;
  836. } else {
  837. var elem = dom;
  838. if (elem.matches !== undefined) {
  839. return elem.matches(selector);
  840. } else if (elem.msMatchesSelector !== undefined) {
  841. return elem.msMatchesSelector(selector);
  842. } else if (elem.webkitMatchesSelector !== undefined) {
  843. return elem.webkitMatchesSelector(selector);
  844. } else if (elem.mozMatchesSelector !== undefined) {
  845. return elem.mozMatchesSelector(selector);
  846. } else {
  847. throw new Error('Browser lacks native selectors');
  848. }
  849. }
  850. };
  851. var bypassSelector = function (dom) {
  852. return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0;
  853. };
  854. var all$2 = function (selector, scope) {
  855. var base = scope === undefined ? document : scope.dom;
  856. return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom);
  857. };
  858. var one = function (selector, scope) {
  859. var base = scope === undefined ? document : scope.dom;
  860. return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom);
  861. };
  862. var eq = function (e1, e2) {
  863. return e1.dom === e2.dom;
  864. };
  865. typeof window !== 'undefined' ? window : Function('return this;')();
  866. var name$1 = function (element) {
  867. var r = element.dom.nodeName;
  868. return r.toLowerCase();
  869. };
  870. var type = function (element) {
  871. return element.dom.nodeType;
  872. };
  873. var isType = function (t) {
  874. return function (element) {
  875. return type(element) === t;
  876. };
  877. };
  878. var isElement = isType(ELEMENT);
  879. var isText = isType(TEXT);
  880. var isDocument = isType(DOCUMENT);
  881. var isDocumentFragment = isType(DOCUMENT_FRAGMENT);
  882. var owner$2 = function (element) {
  883. return SugarElement.fromDom(element.dom.ownerDocument);
  884. };
  885. var documentOrOwner = function (dos) {
  886. return isDocument(dos) ? dos : owner$2(dos);
  887. };
  888. var defaultView = function (element) {
  889. return SugarElement.fromDom(documentOrOwner(element).dom.defaultView);
  890. };
  891. var parent = function (element) {
  892. return Optional.from(element.dom.parentNode).map(SugarElement.fromDom);
  893. };
  894. var parents = function (element, isRoot) {
  895. var stop = isFunction(isRoot) ? isRoot : never;
  896. var dom = element.dom;
  897. var ret = [];
  898. while (dom.parentNode !== null && dom.parentNode !== undefined) {
  899. var rawParent = dom.parentNode;
  900. var p = SugarElement.fromDom(rawParent);
  901. ret.push(p);
  902. if (stop(p) === true) {
  903. break;
  904. } else {
  905. dom = rawParent;
  906. }
  907. }
  908. return ret;
  909. };
  910. var siblings$2 = function (element) {
  911. var filterSelf = function (elements) {
  912. return filter$2(elements, function (x) {
  913. return !eq(element, x);
  914. });
  915. };
  916. return parent(element).map(children).map(filterSelf).getOr([]);
  917. };
  918. var nextSibling = function (element) {
  919. return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom);
  920. };
  921. var children = function (element) {
  922. return map$2(element.dom.childNodes, SugarElement.fromDom);
  923. };
  924. var child = function (element, index) {
  925. var cs = element.dom.childNodes;
  926. return Optional.from(cs[index]).map(SugarElement.fromDom);
  927. };
  928. var firstChild = function (element) {
  929. return child(element, 0);
  930. };
  931. var before$1 = function (marker, element) {
  932. var parent$1 = parent(marker);
  933. parent$1.each(function (v) {
  934. v.dom.insertBefore(element.dom, marker.dom);
  935. });
  936. };
  937. var after$2 = function (marker, element) {
  938. var sibling = nextSibling(marker);
  939. sibling.fold(function () {
  940. var parent$1 = parent(marker);
  941. parent$1.each(function (v) {
  942. append$2(v, element);
  943. });
  944. }, function (v) {
  945. before$1(v, element);
  946. });
  947. };
  948. var prepend$1 = function (parent, element) {
  949. var firstChild$1 = firstChild(parent);
  950. firstChild$1.fold(function () {
  951. append$2(parent, element);
  952. }, function (v) {
  953. parent.dom.insertBefore(element.dom, v.dom);
  954. });
  955. };
  956. var append$2 = function (parent, element) {
  957. parent.dom.appendChild(element.dom);
  958. };
  959. var appendAt = function (parent, element, index) {
  960. child(parent, index).fold(function () {
  961. append$2(parent, element);
  962. }, function (v) {
  963. before$1(v, element);
  964. });
  965. };
  966. var append$1 = function (parent, elements) {
  967. each$1(elements, function (x) {
  968. append$2(parent, x);
  969. });
  970. };
  971. var empty = function (element) {
  972. element.dom.textContent = '';
  973. each$1(children(element), function (rogue) {
  974. remove$7(rogue);
  975. });
  976. };
  977. var remove$7 = function (element) {
  978. var dom = element.dom;
  979. if (dom.parentNode !== null) {
  980. dom.parentNode.removeChild(dom);
  981. }
  982. };
  983. var isShadowRoot = function (dos) {
  984. return isDocumentFragment(dos) && isNonNullable(dos.dom.host);
  985. };
  986. var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode);
  987. var isSupported$1 = constant$1(supported);
  988. var getRootNode = supported ? function (e) {
  989. return SugarElement.fromDom(e.dom.getRootNode());
  990. } : documentOrOwner;
  991. var getShadowRoot = function (e) {
  992. var r = getRootNode(e);
  993. return isShadowRoot(r) ? Optional.some(r) : Optional.none();
  994. };
  995. var getShadowHost = function (e) {
  996. return SugarElement.fromDom(e.dom.host);
  997. };
  998. var getOriginalEventTarget = function (event) {
  999. if (isSupported$1() && isNonNullable(event.target)) {
  1000. var el = SugarElement.fromDom(event.target);
  1001. if (isElement(el) && isOpenShadowHost(el)) {
  1002. if (event.composed && event.composedPath) {
  1003. var composedPath = event.composedPath();
  1004. if (composedPath) {
  1005. return head(composedPath);
  1006. }
  1007. }
  1008. }
  1009. }
  1010. return Optional.from(event.target);
  1011. };
  1012. var isOpenShadowHost = function (element) {
  1013. return isNonNullable(element.dom.shadowRoot);
  1014. };
  1015. var inBody = function (element) {
  1016. var dom = isText(element) ? element.dom.parentNode : element.dom;
  1017. if (dom === undefined || dom === null || dom.ownerDocument === null) {
  1018. return false;
  1019. }
  1020. var doc = dom.ownerDocument;
  1021. return getShadowRoot(SugarElement.fromDom(dom)).fold(function () {
  1022. return doc.body.contains(dom);
  1023. }, compose1(inBody, getShadowHost));
  1024. };
  1025. var body = function () {
  1026. return getBody(SugarElement.fromDom(document));
  1027. };
  1028. var getBody = function (doc) {
  1029. var b = doc.dom.body;
  1030. if (b === null || b === undefined) {
  1031. throw new Error('Body is not available yet');
  1032. }
  1033. return SugarElement.fromDom(b);
  1034. };
  1035. var fireDetaching = function (component) {
  1036. emit(component, detachedFromDom());
  1037. var children = component.components();
  1038. each$1(children, fireDetaching);
  1039. };
  1040. var fireAttaching = function (component) {
  1041. var children = component.components();
  1042. each$1(children, fireAttaching);
  1043. emit(component, attachedToDom());
  1044. };
  1045. var attach$1 = function (parent, child) {
  1046. append$2(parent.element, child.element);
  1047. };
  1048. var detachChildren = function (component) {
  1049. each$1(component.components(), function (childComp) {
  1050. return remove$7(childComp.element);
  1051. });
  1052. empty(component.element);
  1053. component.syncComponents();
  1054. };
  1055. var replaceChildren = function (component, newChildren) {
  1056. var subs = component.components();
  1057. detachChildren(component);
  1058. var deleted = difference(subs, newChildren);
  1059. each$1(deleted, function (comp) {
  1060. fireDetaching(comp);
  1061. component.getSystem().removeFromWorld(comp);
  1062. });
  1063. each$1(newChildren, function (childComp) {
  1064. if (!childComp.getSystem().isConnected()) {
  1065. component.getSystem().addToWorld(childComp);
  1066. attach$1(component, childComp);
  1067. if (inBody(component.element)) {
  1068. fireAttaching(childComp);
  1069. }
  1070. } else {
  1071. attach$1(component, childComp);
  1072. }
  1073. component.syncComponents();
  1074. });
  1075. };
  1076. var attach = function (parent, child) {
  1077. attachWith(parent, child, append$2);
  1078. };
  1079. var attachWith = function (parent, child, insertion) {
  1080. parent.getSystem().addToWorld(child);
  1081. insertion(parent.element, child.element);
  1082. if (inBody(parent.element)) {
  1083. fireAttaching(child);
  1084. }
  1085. parent.syncComponents();
  1086. };
  1087. var doDetach = function (component) {
  1088. fireDetaching(component);
  1089. remove$7(component.element);
  1090. component.getSystem().removeFromWorld(component);
  1091. };
  1092. var detach = function (component) {
  1093. var parent$1 = parent(component.element).bind(function (p) {
  1094. return component.getSystem().getByDom(p).toOptional();
  1095. });
  1096. doDetach(component);
  1097. parent$1.each(function (p) {
  1098. p.syncComponents();
  1099. });
  1100. };
  1101. var attachSystemAfter = function (element, guiSystem) {
  1102. attachSystemWith(element, guiSystem, after$2);
  1103. };
  1104. var attachSystemWith = function (element, guiSystem, inserter) {
  1105. inserter(element, guiSystem.element);
  1106. var children$1 = children(guiSystem.element);
  1107. each$1(children$1, function (child) {
  1108. guiSystem.getByDom(child).each(fireAttaching);
  1109. });
  1110. };
  1111. var detachSystem = function (guiSystem) {
  1112. var children$1 = children(guiSystem.element);
  1113. each$1(children$1, function (child) {
  1114. guiSystem.getByDom(child).each(fireDetaching);
  1115. });
  1116. remove$7(guiSystem.element);
  1117. };
  1118. var keys = Object.keys;
  1119. var hasOwnProperty = Object.hasOwnProperty;
  1120. var each = function (obj, f) {
  1121. var props = keys(obj);
  1122. for (var k = 0, len = props.length; k < len; k++) {
  1123. var i = props[k];
  1124. var x = obj[i];
  1125. f(x, i);
  1126. }
  1127. };
  1128. var map$1 = function (obj, f) {
  1129. return tupleMap(obj, function (x, i) {
  1130. return {
  1131. k: i,
  1132. v: f(x, i)
  1133. };
  1134. });
  1135. };
  1136. var tupleMap = function (obj, f) {
  1137. var r = {};
  1138. each(obj, function (x, i) {
  1139. var tuple = f(x, i);
  1140. r[tuple.k] = tuple.v;
  1141. });
  1142. return r;
  1143. };
  1144. var objAcc = function (r) {
  1145. return function (x, i) {
  1146. r[i] = x;
  1147. };
  1148. };
  1149. var internalFilter = function (obj, pred, onTrue, onFalse) {
  1150. var r = {};
  1151. each(obj, function (x, i) {
  1152. (pred(x, i) ? onTrue : onFalse)(x, i);
  1153. });
  1154. return r;
  1155. };
  1156. var filter$1 = function (obj, pred) {
  1157. var t = {};
  1158. internalFilter(obj, pred, objAcc(t), noop);
  1159. return t;
  1160. };
  1161. var mapToArray = function (obj, f) {
  1162. var r = [];
  1163. each(obj, function (value, name) {
  1164. r.push(f(value, name));
  1165. });
  1166. return r;
  1167. };
  1168. var find = function (obj, pred) {
  1169. var props = keys(obj);
  1170. for (var k = 0, len = props.length; k < len; k++) {
  1171. var i = props[k];
  1172. var x = obj[i];
  1173. if (pred(x, i, obj)) {
  1174. return Optional.some(x);
  1175. }
  1176. }
  1177. return Optional.none();
  1178. };
  1179. var values = function (obj) {
  1180. return mapToArray(obj, identity);
  1181. };
  1182. var get$c = function (obj, key) {
  1183. return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none();
  1184. };
  1185. var has$2 = function (obj, key) {
  1186. return hasOwnProperty.call(obj, key);
  1187. };
  1188. var hasNonNullableKey = function (obj, key) {
  1189. return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null;
  1190. };
  1191. var rawSet = function (dom, key, value) {
  1192. if (isString(value) || isBoolean(value) || isNumber(value)) {
  1193. dom.setAttribute(key, value + '');
  1194. } else {
  1195. console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom);
  1196. throw new Error('Attribute value was not simple');
  1197. }
  1198. };
  1199. var set$8 = function (element, key, value) {
  1200. rawSet(element.dom, key, value);
  1201. };
  1202. var setAll$1 = function (element, attrs) {
  1203. var dom = element.dom;
  1204. each(attrs, function (v, k) {
  1205. rawSet(dom, k, v);
  1206. });
  1207. };
  1208. var get$b = function (element, key) {
  1209. var v = element.dom.getAttribute(key);
  1210. return v === null ? undefined : v;
  1211. };
  1212. var getOpt = function (element, key) {
  1213. return Optional.from(get$b(element, key));
  1214. };
  1215. var has$1 = function (element, key) {
  1216. var dom = element.dom;
  1217. return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
  1218. };
  1219. var remove$6 = function (element, key) {
  1220. element.dom.removeAttribute(key);
  1221. };
  1222. var read$2 = function (element, attr) {
  1223. var value = get$b(element, attr);
  1224. return value === undefined || value === '' ? [] : value.split(' ');
  1225. };
  1226. var add$3 = function (element, attr, id) {
  1227. var old = read$2(element, attr);
  1228. var nu = old.concat([id]);
  1229. set$8(element, attr, nu.join(' '));
  1230. return true;
  1231. };
  1232. var remove$5 = function (element, attr, id) {
  1233. var nu = filter$2(read$2(element, attr), function (v) {
  1234. return v !== id;
  1235. });
  1236. if (nu.length > 0) {
  1237. set$8(element, attr, nu.join(' '));
  1238. } else {
  1239. remove$6(element, attr);
  1240. }
  1241. return false;
  1242. };
  1243. var supports = function (element) {
  1244. return element.dom.classList !== undefined;
  1245. };
  1246. var get$a = function (element) {
  1247. return read$2(element, 'class');
  1248. };
  1249. var add$2 = function (element, clazz) {
  1250. return add$3(element, 'class', clazz);
  1251. };
  1252. var remove$4 = function (element, clazz) {
  1253. return remove$5(element, 'class', clazz);
  1254. };
  1255. var add$1 = function (element, clazz) {
  1256. if (supports(element)) {
  1257. element.dom.classList.add(clazz);
  1258. } else {
  1259. add$2(element, clazz);
  1260. }
  1261. };
  1262. var cleanClass = function (element) {
  1263. var classList = supports(element) ? element.dom.classList : get$a(element);
  1264. if (classList.length === 0) {
  1265. remove$6(element, 'class');
  1266. }
  1267. };
  1268. var remove$3 = function (element, clazz) {
  1269. if (supports(element)) {
  1270. var classList = element.dom.classList;
  1271. classList.remove(clazz);
  1272. } else {
  1273. remove$4(element, clazz);
  1274. }
  1275. cleanClass(element);
  1276. };
  1277. var has = function (element, clazz) {
  1278. return supports(element) && element.dom.classList.contains(clazz);
  1279. };
  1280. var swap = function (element, addCls, removeCls) {
  1281. remove$3(element, removeCls);
  1282. add$1(element, addCls);
  1283. };
  1284. var toAlpha = function (component, swapConfig, _swapState) {
  1285. swap(component.element, swapConfig.alpha, swapConfig.omega);
  1286. };
  1287. var toOmega = function (component, swapConfig, _swapState) {
  1288. swap(component.element, swapConfig.omega, swapConfig.alpha);
  1289. };
  1290. var clear$1 = function (component, swapConfig, _swapState) {
  1291. remove$3(component.element, swapConfig.alpha);
  1292. remove$3(component.element, swapConfig.omega);
  1293. };
  1294. var isAlpha = function (component, swapConfig, _swapState) {
  1295. return has(component.element, swapConfig.alpha);
  1296. };
  1297. var isOmega = function (component, swapConfig, _swapState) {
  1298. return has(component.element, swapConfig.omega);
  1299. };
  1300. var SwapApis = /*#__PURE__*/Object.freeze({
  1301. __proto__: null,
  1302. toAlpha: toAlpha,
  1303. toOmega: toOmega,
  1304. isAlpha: isAlpha,
  1305. isOmega: isOmega,
  1306. clear: clear$1
  1307. });
  1308. var value$2 = function (o) {
  1309. var or = function (_opt) {
  1310. return value$2(o);
  1311. };
  1312. var orThunk = function (_f) {
  1313. return value$2(o);
  1314. };
  1315. var map = function (f) {
  1316. return value$2(f(o));
  1317. };
  1318. var mapError = function (_f) {
  1319. return value$2(o);
  1320. };
  1321. var each = function (f) {
  1322. f(o);
  1323. };
  1324. var bind = function (f) {
  1325. return f(o);
  1326. };
  1327. var fold = function (_, onValue) {
  1328. return onValue(o);
  1329. };
  1330. var exists = function (f) {
  1331. return f(o);
  1332. };
  1333. var forall = function (f) {
  1334. return f(o);
  1335. };
  1336. var toOptional = function () {
  1337. return Optional.some(o);
  1338. };
  1339. return {
  1340. isValue: always,
  1341. isError: never,
  1342. getOr: constant$1(o),
  1343. getOrThunk: constant$1(o),
  1344. getOrDie: constant$1(o),
  1345. or: or,
  1346. orThunk: orThunk,
  1347. fold: fold,
  1348. map: map,
  1349. mapError: mapError,
  1350. each: each,
  1351. bind: bind,
  1352. exists: exists,
  1353. forall: forall,
  1354. toOptional: toOptional
  1355. };
  1356. };
  1357. var error = function (message) {
  1358. var getOrThunk = function (f) {
  1359. return f();
  1360. };
  1361. var getOrDie = function () {
  1362. return die(String(message))();
  1363. };
  1364. var or = identity;
  1365. var orThunk = function (f) {
  1366. return f();
  1367. };
  1368. var map = function (_f) {
  1369. return error(message);
  1370. };
  1371. var mapError = function (f) {
  1372. return error(f(message));
  1373. };
  1374. var bind = function (_f) {
  1375. return error(message);
  1376. };
  1377. var fold = function (onError, _) {
  1378. return onError(message);
  1379. };
  1380. return {
  1381. isValue: never,
  1382. isError: always,
  1383. getOr: identity,
  1384. getOrThunk: getOrThunk,
  1385. getOrDie: getOrDie,
  1386. or: or,
  1387. orThunk: orThunk,
  1388. fold: fold,
  1389. map: map,
  1390. mapError: mapError,
  1391. each: noop,
  1392. bind: bind,
  1393. exists: never,
  1394. forall: always,
  1395. toOptional: Optional.none
  1396. };
  1397. };
  1398. var fromOption = function (opt, err) {
  1399. return opt.fold(function () {
  1400. return error(err);
  1401. }, value$2);
  1402. };
  1403. var Result = {
  1404. value: value$2,
  1405. error: error,
  1406. fromOption: fromOption
  1407. };
  1408. var SimpleResultType;
  1409. (function (SimpleResultType) {
  1410. SimpleResultType[SimpleResultType['Error'] = 0] = 'Error';
  1411. SimpleResultType[SimpleResultType['Value'] = 1] = 'Value';
  1412. }(SimpleResultType || (SimpleResultType = {})));
  1413. var fold$1 = function (res, onError, onValue) {
  1414. return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue);
  1415. };
  1416. var partition$1 = function (results) {
  1417. var values = [];
  1418. var errors = [];
  1419. each$1(results, function (obj) {
  1420. fold$1(obj, function (err) {
  1421. return errors.push(err);
  1422. }, function (val) {
  1423. return values.push(val);
  1424. });
  1425. });
  1426. return {
  1427. values: values,
  1428. errors: errors
  1429. };
  1430. };
  1431. var mapError = function (res, f) {
  1432. if (res.stype === SimpleResultType.Error) {
  1433. return {
  1434. stype: SimpleResultType.Error,
  1435. serror: f(res.serror)
  1436. };
  1437. } else {
  1438. return res;
  1439. }
  1440. };
  1441. var map = function (res, f) {
  1442. if (res.stype === SimpleResultType.Value) {
  1443. return {
  1444. stype: SimpleResultType.Value,
  1445. svalue: f(res.svalue)
  1446. };
  1447. } else {
  1448. return res;
  1449. }
  1450. };
  1451. var bind$2 = function (res, f) {
  1452. if (res.stype === SimpleResultType.Value) {
  1453. return f(res.svalue);
  1454. } else {
  1455. return res;
  1456. }
  1457. };
  1458. var bindError = function (res, f) {
  1459. if (res.stype === SimpleResultType.Error) {
  1460. return f(res.serror);
  1461. } else {
  1462. return res;
  1463. }
  1464. };
  1465. var svalue = function (v) {
  1466. return {
  1467. stype: SimpleResultType.Value,
  1468. svalue: v
  1469. };
  1470. };
  1471. var serror = function (e) {
  1472. return {
  1473. stype: SimpleResultType.Error,
  1474. serror: e
  1475. };
  1476. };
  1477. var toResult$1 = function (res) {
  1478. return fold$1(res, Result.error, Result.value);
  1479. };
  1480. var fromResult = function (res) {
  1481. return res.fold(serror, svalue);
  1482. };
  1483. var SimpleResult = {
  1484. fromResult: fromResult,
  1485. toResult: toResult$1,
  1486. svalue: svalue,
  1487. partition: partition$1,
  1488. serror: serror,
  1489. bind: bind$2,
  1490. bindError: bindError,
  1491. map: map,
  1492. mapError: mapError,
  1493. fold: fold$1
  1494. };
  1495. var field$3 = function (key, newKey, presence, prop) {
  1496. return {
  1497. tag: 'field',
  1498. key: key,
  1499. newKey: newKey,
  1500. presence: presence,
  1501. prop: prop
  1502. };
  1503. };
  1504. var customField$1 = function (newKey, instantiator) {
  1505. return {
  1506. tag: 'custom',
  1507. newKey: newKey,
  1508. instantiator: instantiator
  1509. };
  1510. };
  1511. var fold = function (value, ifField, ifCustom) {
  1512. switch (value.tag) {
  1513. case 'field':
  1514. return ifField(value.key, value.newKey, value.presence, value.prop);
  1515. case 'custom':
  1516. return ifCustom(value.newKey, value.instantiator);
  1517. }
  1518. };
  1519. var shallow$1 = function (old, nu) {
  1520. return nu;
  1521. };
  1522. var deep = function (old, nu) {
  1523. var bothObjects = isObject(old) && isObject(nu);
  1524. return bothObjects ? deepMerge(old, nu) : nu;
  1525. };
  1526. var baseMerge = function (merger) {
  1527. return function () {
  1528. var objects = [];
  1529. for (var _i = 0; _i < arguments.length; _i++) {
  1530. objects[_i] = arguments[_i];
  1531. }
  1532. if (objects.length === 0) {
  1533. throw new Error('Can\'t merge zero objects');
  1534. }
  1535. var ret = {};
  1536. for (var j = 0; j < objects.length; j++) {
  1537. var curObject = objects[j];
  1538. for (var key in curObject) {
  1539. if (has$2(curObject, key)) {
  1540. ret[key] = merger(ret[key], curObject[key]);
  1541. }
  1542. }
  1543. }
  1544. return ret;
  1545. };
  1546. };
  1547. var deepMerge = baseMerge(deep);
  1548. var merge$1 = baseMerge(shallow$1);
  1549. var required$2 = function () {
  1550. return {
  1551. tag: 'required',
  1552. process: {}
  1553. };
  1554. };
  1555. var defaultedThunk = function (fallbackThunk) {
  1556. return {
  1557. tag: 'defaultedThunk',
  1558. process: fallbackThunk
  1559. };
  1560. };
  1561. var defaulted$1 = function (fallback) {
  1562. return defaultedThunk(constant$1(fallback));
  1563. };
  1564. var asOption = function () {
  1565. return {
  1566. tag: 'option',
  1567. process: {}
  1568. };
  1569. };
  1570. var mergeWithThunk = function (baseThunk) {
  1571. return {
  1572. tag: 'mergeWithThunk',
  1573. process: baseThunk
  1574. };
  1575. };
  1576. var mergeWith = function (base) {
  1577. return mergeWithThunk(constant$1(base));
  1578. };
  1579. var mergeValues$1 = function (values, base) {
  1580. return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base);
  1581. };
  1582. var mergeErrors$1 = function (errors) {
  1583. return compose(SimpleResult.serror, flatten)(errors);
  1584. };
  1585. var consolidateObj = function (objects, base) {
  1586. var partition = SimpleResult.partition(objects);
  1587. return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base);
  1588. };
  1589. var consolidateArr = function (objects) {
  1590. var partitions = SimpleResult.partition(objects);
  1591. return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values);
  1592. };
  1593. var ResultCombine = {
  1594. consolidateObj: consolidateObj,
  1595. consolidateArr: consolidateArr
  1596. };
  1597. var formatObj = function (input) {
  1598. return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2);
  1599. };
  1600. var formatErrors = function (errors) {
  1601. var es = errors.length > 10 ? errors.slice(0, 10).concat([{
  1602. path: [],
  1603. getErrorInfo: constant$1('... (only showing first ten failures)')
  1604. }]) : errors;
  1605. return map$2(es, function (e) {
  1606. return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
  1607. });
  1608. };
  1609. var nu$5 = function (path, getErrorInfo) {
  1610. return SimpleResult.serror([{
  1611. path: path,
  1612. getErrorInfo: getErrorInfo
  1613. }]);
  1614. };
  1615. var missingRequired = function (path, key, obj) {
  1616. return nu$5(path, function () {
  1617. return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj);
  1618. });
  1619. };
  1620. var missingKey = function (path, key) {
  1621. return nu$5(path, function () {
  1622. return 'Choice schema did not contain choice key: "' + key + '"';
  1623. });
  1624. };
  1625. var missingBranch = function (path, branches, branch) {
  1626. return nu$5(path, function () {
  1627. return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
  1628. });
  1629. };
  1630. var unsupportedFields = function (path, unsupported) {
  1631. return nu$5(path, function () {
  1632. return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
  1633. });
  1634. };
  1635. var custom = function (path, err) {
  1636. return nu$5(path, constant$1(err));
  1637. };
  1638. var value$1 = function (validator) {
  1639. var extract = function (path, val) {
  1640. return SimpleResult.bindError(validator(val), function (err) {
  1641. return custom(path, err);
  1642. });
  1643. };
  1644. var toString = constant$1('val');
  1645. return {
  1646. extract: extract,
  1647. toString: toString
  1648. };
  1649. };
  1650. var anyValue$1 = value$1(SimpleResult.svalue);
  1651. var requiredAccess = function (path, obj, key, bundle) {
  1652. return get$c(obj, key).fold(function () {
  1653. return missingRequired(path, key, obj);
  1654. }, bundle);
  1655. };
  1656. var fallbackAccess = function (obj, key, fallback, bundle) {
  1657. var v = get$c(obj, key).getOrThunk(function () {
  1658. return fallback(obj);
  1659. });
  1660. return bundle(v);
  1661. };
  1662. var optionAccess = function (obj, key, bundle) {
  1663. return bundle(get$c(obj, key));
  1664. };
  1665. var optionDefaultedAccess = function (obj, key, fallback, bundle) {
  1666. var opt = get$c(obj, key).map(function (val) {
  1667. return val === true ? fallback(obj) : val;
  1668. });
  1669. return bundle(opt);
  1670. };
  1671. var extractField = function (field, path, obj, key, prop) {
  1672. var bundle = function (av) {
  1673. return prop.extract(path.concat([key]), av);
  1674. };
  1675. var bundleAsOption = function (optValue) {
  1676. return optValue.fold(function () {
  1677. return SimpleResult.svalue(Optional.none());
  1678. }, function (ov) {
  1679. var result = prop.extract(path.concat([key]), ov);
  1680. return SimpleResult.map(result, Optional.some);
  1681. });
  1682. };
  1683. switch (field.tag) {
  1684. case 'required':
  1685. return requiredAccess(path, obj, key, bundle);
  1686. case 'defaultedThunk':
  1687. return fallbackAccess(obj, key, field.process, bundle);
  1688. case 'option':
  1689. return optionAccess(obj, key, bundleAsOption);
  1690. case 'defaultedOptionThunk':
  1691. return optionDefaultedAccess(obj, key, field.process, bundleAsOption);
  1692. case 'mergeWithThunk': {
  1693. return fallbackAccess(obj, key, constant$1({}), function (v) {
  1694. var result = deepMerge(field.process(obj), v);
  1695. return bundle(result);
  1696. });
  1697. }
  1698. }
  1699. };
  1700. var extractFields = function (path, obj, fields) {
  1701. var success = {};
  1702. var errors = [];
  1703. for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
  1704. var field = fields_1[_i];
  1705. fold(field, function (key, newKey, presence, prop) {
  1706. var result = extractField(presence, path, obj, key, prop);
  1707. SimpleResult.fold(result, function (err) {
  1708. errors.push.apply(errors, err);
  1709. }, function (res) {
  1710. success[newKey] = res;
  1711. });
  1712. }, function (newKey, instantiator) {
  1713. success[newKey] = instantiator(obj);
  1714. });
  1715. }
  1716. return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success);
  1717. };
  1718. var getSetKeys = function (obj) {
  1719. return keys(filter$1(obj, isNonNullable));
  1720. };
  1721. var objOfOnly = function (fields) {
  1722. var delegate = objOf(fields);
  1723. var fieldNames = foldr(fields, function (acc, value) {
  1724. return fold(value, function (key) {
  1725. var _a;
  1726. return deepMerge(acc, (_a = {}, _a[key] = true, _a));
  1727. }, constant$1(acc));
  1728. }, {});
  1729. var extract = function (path, o) {
  1730. var keys = isBoolean(o) ? [] : getSetKeys(o);
  1731. var extra = filter$2(keys, function (k) {
  1732. return !hasNonNullableKey(fieldNames, k);
  1733. });
  1734. return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra);
  1735. };
  1736. return {
  1737. extract: extract,
  1738. toString: delegate.toString
  1739. };
  1740. };
  1741. var objOf = function (values) {
  1742. var extract = function (path, o) {
  1743. return extractFields(path, o, values);
  1744. };
  1745. var toString = function () {
  1746. var fieldStrings = map$2(values, function (value) {
  1747. return fold(value, function (key, _okey, _presence, prop) {
  1748. return key + ' -> ' + prop.toString();
  1749. }, function (newKey, _instantiator) {
  1750. return 'state(' + newKey + ')';
  1751. });
  1752. });
  1753. return 'obj{\n' + fieldStrings.join('\n') + '}';
  1754. };
  1755. return {
  1756. extract: extract,
  1757. toString: toString
  1758. };
  1759. };
  1760. var arrOf = function (prop) {
  1761. var extract = function (path, array) {
  1762. var results = map$2(array, function (a, i) {
  1763. return prop.extract(path.concat(['[' + i + ']']), a);
  1764. });
  1765. return ResultCombine.consolidateArr(results);
  1766. };
  1767. var toString = function () {
  1768. return 'array(' + prop.toString() + ')';
  1769. };
  1770. return {
  1771. extract: extract,
  1772. toString: toString
  1773. };
  1774. };
  1775. var setOf$1 = function (validator, prop) {
  1776. var validateKeys = function (path, keys) {
  1777. return arrOf(value$1(validator)).extract(path, keys);
  1778. };
  1779. var extract = function (path, o) {
  1780. var keys$1 = keys(o);
  1781. var validatedKeys = validateKeys(path, keys$1);
  1782. return SimpleResult.bind(validatedKeys, function (validKeys) {
  1783. var schema = map$2(validKeys, function (vk) {
  1784. return field$3(vk, vk, required$2(), prop);
  1785. });
  1786. return objOf(schema).extract(path, o);
  1787. });
  1788. };
  1789. var toString = function () {
  1790. return 'setOf(' + prop.toString() + ')';
  1791. };
  1792. return {
  1793. extract: extract,
  1794. toString: toString
  1795. };
  1796. };
  1797. var anyValue = constant$1(anyValue$1);
  1798. var typedValue = function (validator, expectedType) {
  1799. return value$1(function (a) {
  1800. var actualType = typeof a;
  1801. return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType);
  1802. });
  1803. };
  1804. var functionProcessor = typedValue(isFunction, 'function');
  1805. var chooseFrom = function (path, input, branches, ch) {
  1806. var fields = get$c(branches, ch);
  1807. return fields.fold(function () {
  1808. return missingBranch(path, branches, ch);
  1809. }, function (vp) {
  1810. return vp.extract(path.concat(['branch: ' + ch]), input);
  1811. });
  1812. };
  1813. var choose$2 = function (key, branches) {
  1814. var extract = function (path, input) {
  1815. var choice = get$c(input, key);
  1816. return choice.fold(function () {
  1817. return missingKey(path, key);
  1818. }, function (chosen) {
  1819. return chooseFrom(path, input, branches, chosen);
  1820. });
  1821. };
  1822. var toString = function () {
  1823. return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
  1824. };
  1825. return {
  1826. extract: extract,
  1827. toString: toString
  1828. };
  1829. };
  1830. var valueOf = function (validator) {
  1831. return value$1(function (v) {
  1832. return validator(v).fold(SimpleResult.serror, SimpleResult.svalue);
  1833. });
  1834. };
  1835. var setOf = function (validator, prop) {
  1836. return setOf$1(function (v) {
  1837. return SimpleResult.fromResult(validator(v));
  1838. }, prop);
  1839. };
  1840. var extractValue = function (label, prop, obj) {
  1841. var res = prop.extract([label], obj);
  1842. return SimpleResult.mapError(res, function (errs) {
  1843. return {
  1844. input: obj,
  1845. errors: errs
  1846. };
  1847. });
  1848. };
  1849. var asRaw = function (label, prop, obj) {
  1850. return SimpleResult.toResult(extractValue(label, prop, obj));
  1851. };
  1852. var getOrDie = function (extraction) {
  1853. return extraction.fold(function (errInfo) {
  1854. throw new Error(formatError(errInfo));
  1855. }, identity);
  1856. };
  1857. var asRawOrDie$1 = function (label, prop, obj) {
  1858. return getOrDie(asRaw(label, prop, obj));
  1859. };
  1860. var formatError = function (errInfo) {
  1861. return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input);
  1862. };
  1863. var choose$1 = function (key, branches) {
  1864. return choose$2(key, map$1(branches, objOf));
  1865. };
  1866. var field$2 = field$3;
  1867. var customField = customField$1;
  1868. var required$1 = function (key) {
  1869. return field$2(key, key, required$2(), anyValue());
  1870. };
  1871. var requiredOf = function (key, schema) {
  1872. return field$2(key, key, required$2(), schema);
  1873. };
  1874. var forbid = function (key, message) {
  1875. return field$2(key, key, asOption(), value$1(function (_v) {
  1876. return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message);
  1877. }));
  1878. };
  1879. var requiredObjOf = function (key, objSchema) {
  1880. return field$2(key, key, required$2(), objOf(objSchema));
  1881. };
  1882. var option = function (key) {
  1883. return field$2(key, key, asOption(), anyValue());
  1884. };
  1885. var optionOf = function (key, schema) {
  1886. return field$2(key, key, asOption(), schema);
  1887. };
  1888. var optionObjOf = function (key, objSchema) {
  1889. return optionOf(key, objOf(objSchema));
  1890. };
  1891. var optionObjOfOnly = function (key, objSchema) {
  1892. return optionOf(key, objOfOnly(objSchema));
  1893. };
  1894. var defaulted = function (key, fallback) {
  1895. return field$2(key, key, defaulted$1(fallback), anyValue());
  1896. };
  1897. var defaultedOf = function (key, fallback, schema) {
  1898. return field$2(key, key, defaulted$1(fallback), schema);
  1899. };
  1900. var defaultedFunction = function (key, fallback) {
  1901. return defaultedOf(key, fallback, functionProcessor);
  1902. };
  1903. var defaultedObjOf = function (key, fallback, objSchema) {
  1904. return defaultedOf(key, fallback, objOf(objSchema));
  1905. };
  1906. var SwapSchema = [
  1907. required$1('alpha'),
  1908. required$1('omega')
  1909. ];
  1910. var generate$5 = function (cases) {
  1911. if (!isArray(cases)) {
  1912. throw new Error('cases must be an array');
  1913. }
  1914. if (cases.length === 0) {
  1915. throw new Error('there must be at least one case');
  1916. }
  1917. var constructors = [];
  1918. var adt = {};
  1919. each$1(cases, function (acase, count) {
  1920. var keys$1 = keys(acase);
  1921. if (keys$1.length !== 1) {
  1922. throw new Error('one and only one name per case');
  1923. }
  1924. var key = keys$1[0];
  1925. var value = acase[key];
  1926. if (adt[key] !== undefined) {
  1927. throw new Error('duplicate key detected:' + key);
  1928. } else if (key === 'cata') {
  1929. throw new Error('cannot have a case named cata (sorry)');
  1930. } else if (!isArray(value)) {
  1931. throw new Error('case arguments must be an array');
  1932. }
  1933. constructors.push(key);
  1934. adt[key] = function () {
  1935. var args = [];
  1936. for (var _i = 0; _i < arguments.length; _i++) {
  1937. args[_i] = arguments[_i];
  1938. }
  1939. var argLength = args.length;
  1940. if (argLength !== value.length) {
  1941. throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
  1942. }
  1943. var match = function (branches) {
  1944. var branchKeys = keys(branches);
  1945. if (constructors.length !== branchKeys.length) {
  1946. throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
  1947. }
  1948. var allReqd = forall(constructors, function (reqKey) {
  1949. return contains$1(branchKeys, reqKey);
  1950. });
  1951. if (!allReqd) {
  1952. throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
  1953. }
  1954. return branches[key].apply(null, args);
  1955. };
  1956. return {
  1957. fold: function () {
  1958. var foldArgs = [];
  1959. for (var _i = 0; _i < arguments.length; _i++) {
  1960. foldArgs[_i] = arguments[_i];
  1961. }
  1962. if (foldArgs.length !== cases.length) {
  1963. throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length);
  1964. }
  1965. var target = foldArgs[count];
  1966. return target.apply(null, args);
  1967. },
  1968. match: match,
  1969. log: function (label) {
  1970. console.log(label, {
  1971. constructors: constructors,
  1972. constructor: key,
  1973. params: args
  1974. });
  1975. }
  1976. };
  1977. };
  1978. });
  1979. return adt;
  1980. };
  1981. var Adt = { generate: generate$5 };
  1982. Adt.generate([
  1983. {
  1984. bothErrors: [
  1985. 'error1',
  1986. 'error2'
  1987. ]
  1988. },
  1989. {
  1990. firstError: [
  1991. 'error1',
  1992. 'value2'
  1993. ]
  1994. },
  1995. {
  1996. secondError: [
  1997. 'value1',
  1998. 'error2'
  1999. ]
  2000. },
  2001. {
  2002. bothValues: [
  2003. 'value1',
  2004. 'value2'
  2005. ]
  2006. }
  2007. ]);
  2008. var partition = function (results) {
  2009. var errors = [];
  2010. var values = [];
  2011. each$1(results, function (result) {
  2012. result.fold(function (err) {
  2013. errors.push(err);
  2014. }, function (value) {
  2015. values.push(value);
  2016. });
  2017. });
  2018. return {
  2019. errors: errors,
  2020. values: values
  2021. };
  2022. };
  2023. var exclude$1 = function (obj, fields) {
  2024. var r = {};
  2025. each(obj, function (v, k) {
  2026. if (!contains$1(fields, k)) {
  2027. r[k] = v;
  2028. }
  2029. });
  2030. return r;
  2031. };
  2032. var wrap$1 = function (key, value) {
  2033. var _a;
  2034. return _a = {}, _a[key] = value, _a;
  2035. };
  2036. var wrapAll$1 = function (keyvalues) {
  2037. var r = {};
  2038. each$1(keyvalues, function (kv) {
  2039. r[kv.key] = kv.value;
  2040. });
  2041. return r;
  2042. };
  2043. var exclude = function (obj, fields) {
  2044. return exclude$1(obj, fields);
  2045. };
  2046. var wrap = function (key, value) {
  2047. return wrap$1(key, value);
  2048. };
  2049. var wrapAll = function (keyvalues) {
  2050. return wrapAll$1(keyvalues);
  2051. };
  2052. var mergeValues = function (values, base) {
  2053. return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values)));
  2054. };
  2055. var mergeErrors = function (errors) {
  2056. return Result.error(flatten(errors));
  2057. };
  2058. var consolidate = function (objs, base) {
  2059. var partitions = partition(objs);
  2060. return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
  2061. };
  2062. var is = function (lhs, rhs, comparator) {
  2063. if (comparator === void 0) {
  2064. comparator = tripleEquals;
  2065. }
  2066. return lhs.exists(function (left) {
  2067. return comparator(left, rhs);
  2068. });
  2069. };
  2070. var cat = function (arr) {
  2071. var r = [];
  2072. var push = function (x) {
  2073. r.push(x);
  2074. };
  2075. for (var i = 0; i < arr.length; i++) {
  2076. arr[i].each(push);
  2077. }
  2078. return r;
  2079. };
  2080. var sequence = function (arr) {
  2081. var r = [];
  2082. for (var i = 0; i < arr.length; i++) {
  2083. var x = arr[i];
  2084. if (x.isSome()) {
  2085. r.push(x.getOrDie());
  2086. } else {
  2087. return Optional.none();
  2088. }
  2089. }
  2090. return Optional.some(r);
  2091. };
  2092. var lift2 = function (oa, ob, f) {
  2093. return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none();
  2094. };
  2095. var someIf = function (b, a) {
  2096. return b ? Optional.some(a) : Optional.none();
  2097. };
  2098. var ensureIsRoot = function (isRoot) {
  2099. return isFunction(isRoot) ? isRoot : never;
  2100. };
  2101. var ancestor$2 = function (scope, transform, isRoot) {
  2102. var element = scope.dom;
  2103. var stop = ensureIsRoot(isRoot);
  2104. while (element.parentNode) {
  2105. element = element.parentNode;
  2106. var el = SugarElement.fromDom(element);
  2107. var transformed = transform(el);
  2108. if (transformed.isSome()) {
  2109. return transformed;
  2110. } else if (stop(el)) {
  2111. break;
  2112. }
  2113. }
  2114. return Optional.none();
  2115. };
  2116. var closest$3 = function (scope, transform, isRoot) {
  2117. var current = transform(scope);
  2118. var stop = ensureIsRoot(isRoot);
  2119. return current.orThunk(function () {
  2120. return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop);
  2121. });
  2122. };
  2123. var isSource = function (component, simulatedEvent) {
  2124. return eq(component.element, simulatedEvent.event.target);
  2125. };
  2126. var defaultEventHandler = {
  2127. can: always,
  2128. abort: never,
  2129. run: noop
  2130. };
  2131. var nu$4 = function (parts) {
  2132. if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) {
  2133. throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!');
  2134. }
  2135. return __assign(__assign({}, defaultEventHandler), parts);
  2136. };
  2137. var all$1 = function (handlers, f) {
  2138. return function () {
  2139. var args = [];
  2140. for (var _i = 0; _i < arguments.length; _i++) {
  2141. args[_i] = arguments[_i];
  2142. }
  2143. return foldl(handlers, function (acc, handler) {
  2144. return acc && f(handler).apply(undefined, args);
  2145. }, true);
  2146. };
  2147. };
  2148. var any = function (handlers, f) {
  2149. return function () {
  2150. var args = [];
  2151. for (var _i = 0; _i < arguments.length; _i++) {
  2152. args[_i] = arguments[_i];
  2153. }
  2154. return foldl(handlers, function (acc, handler) {
  2155. return acc || f(handler).apply(undefined, args);
  2156. }, false);
  2157. };
  2158. };
  2159. var read$1 = function (handler) {
  2160. return isFunction(handler) ? {
  2161. can: always,
  2162. abort: never,
  2163. run: handler
  2164. } : handler;
  2165. };
  2166. var fuse$1 = function (handlers) {
  2167. var can = all$1(handlers, function (handler) {
  2168. return handler.can;
  2169. });
  2170. var abort = any(handlers, function (handler) {
  2171. return handler.abort;
  2172. });
  2173. var run = function () {
  2174. var args = [];
  2175. for (var _i = 0; _i < arguments.length; _i++) {
  2176. args[_i] = arguments[_i];
  2177. }
  2178. each$1(handlers, function (handler) {
  2179. handler.run.apply(undefined, args);
  2180. });
  2181. };
  2182. return {
  2183. can: can,
  2184. abort: abort,
  2185. run: run
  2186. };
  2187. };
  2188. var derive$3 = function (configs) {
  2189. return wrapAll(configs);
  2190. };
  2191. var abort = function (name, predicate) {
  2192. return {
  2193. key: name,
  2194. value: nu$4({ abort: predicate })
  2195. };
  2196. };
  2197. var can = function (name, predicate) {
  2198. return {
  2199. key: name,
  2200. value: nu$4({ can: predicate })
  2201. };
  2202. };
  2203. var run = function (name, handler) {
  2204. return {
  2205. key: name,
  2206. value: nu$4({ run: handler })
  2207. };
  2208. };
  2209. var runActionExtra = function (name, action, extra) {
  2210. return {
  2211. key: name,
  2212. value: nu$4({
  2213. run: function (component, simulatedEvent) {
  2214. action.apply(undefined, [
  2215. component,
  2216. simulatedEvent
  2217. ].concat(extra));
  2218. }
  2219. })
  2220. };
  2221. };
  2222. var runOnName = function (name) {
  2223. return function (handler) {
  2224. return run(name, handler);
  2225. };
  2226. };
  2227. var runOnSourceName = function (name) {
  2228. return function (handler) {
  2229. return {
  2230. key: name,
  2231. value: nu$4({
  2232. run: function (component, simulatedEvent) {
  2233. if (isSource(component, simulatedEvent)) {
  2234. handler(component, simulatedEvent);
  2235. }
  2236. }
  2237. })
  2238. };
  2239. };
  2240. };
  2241. var redirectToUid = function (name, uid) {
  2242. return run(name, function (component, simulatedEvent) {
  2243. component.getSystem().getByUid(uid).each(function (redirectee) {
  2244. dispatchEvent(redirectee, redirectee.element, name, simulatedEvent);
  2245. });
  2246. });
  2247. };
  2248. var redirectToPart = function (name, detail, partName) {
  2249. var uid = detail.partUids[partName];
  2250. return redirectToUid(name, uid);
  2251. };
  2252. var cutter = function (name) {
  2253. return run(name, function (component, simulatedEvent) {
  2254. simulatedEvent.cut();
  2255. });
  2256. };
  2257. var stopper = function (name) {
  2258. return run(name, function (component, simulatedEvent) {
  2259. simulatedEvent.stop();
  2260. });
  2261. };
  2262. var runOnSource = function (name, f) {
  2263. return runOnSourceName(name)(f);
  2264. };
  2265. var runOnAttached = runOnSourceName(attachedToDom());
  2266. var runOnDetached = runOnSourceName(detachedFromDom());
  2267. var runOnInit = runOnSourceName(systemInit());
  2268. var runOnExecute = runOnName(execute$5());
  2269. var markAsBehaviourApi = function (f, apiName, apiFunction) {
  2270. var delegate = apiFunction.toString();
  2271. var endIndex = delegate.indexOf(')') + 1;
  2272. var openBracketIndex = delegate.indexOf('(');
  2273. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2274. f.toFunctionAnnotation = function () {
  2275. return {
  2276. name: apiName,
  2277. parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
  2278. };
  2279. };
  2280. return f;
  2281. };
  2282. var cleanParameters = function (parameters) {
  2283. return map$2(parameters, function (p) {
  2284. return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
  2285. });
  2286. };
  2287. var markAsExtraApi = function (f, extraName) {
  2288. var delegate = f.toString();
  2289. var endIndex = delegate.indexOf(')') + 1;
  2290. var openBracketIndex = delegate.indexOf('(');
  2291. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2292. f.toFunctionAnnotation = function () {
  2293. return {
  2294. name: extraName,
  2295. parameters: cleanParameters(parameters)
  2296. };
  2297. };
  2298. return f;
  2299. };
  2300. var markAsSketchApi = function (f, apiFunction) {
  2301. var delegate = apiFunction.toString();
  2302. var endIndex = delegate.indexOf(')') + 1;
  2303. var openBracketIndex = delegate.indexOf('(');
  2304. var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
  2305. f.toFunctionAnnotation = function () {
  2306. return {
  2307. name: 'OVERRIDE',
  2308. parameters: cleanParameters(parameters.slice(1))
  2309. };
  2310. };
  2311. return f;
  2312. };
  2313. var nu$3 = function (s) {
  2314. return {
  2315. classes: isUndefined(s.classes) ? [] : s.classes,
  2316. attributes: isUndefined(s.attributes) ? {} : s.attributes,
  2317. styles: isUndefined(s.styles) ? {} : s.styles
  2318. };
  2319. };
  2320. var merge = function (defnA, mod) {
  2321. return __assign(__assign({}, defnA), {
  2322. attributes: __assign(__assign({}, defnA.attributes), mod.attributes),
  2323. styles: __assign(__assign({}, defnA.styles), mod.styles),
  2324. classes: defnA.classes.concat(mod.classes)
  2325. });
  2326. };
  2327. var executeEvent = function (bConfig, bState, executor) {
  2328. return runOnExecute(function (component) {
  2329. executor(component, bConfig, bState);
  2330. });
  2331. };
  2332. var loadEvent = function (bConfig, bState, f) {
  2333. return runOnInit(function (component, _simulatedEvent) {
  2334. f(component, bConfig, bState);
  2335. });
  2336. };
  2337. var create$6 = function (schema, name, active, apis, extra, state) {
  2338. var configSchema = objOfOnly(schema);
  2339. var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
  2340. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2341. };
  2342. var createModes$1 = function (modes, name, active, apis, extra, state) {
  2343. var configSchema = modes;
  2344. var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
  2345. return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
  2346. };
  2347. var wrapApi = function (bName, apiFunction, apiName) {
  2348. var f = function (component) {
  2349. var rest = [];
  2350. for (var _i = 1; _i < arguments.length; _i++) {
  2351. rest[_i - 1] = arguments[_i];
  2352. }
  2353. var args = [component].concat(rest);
  2354. return component.config({ name: constant$1(bName) }).fold(function () {
  2355. throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
  2356. }, function (info) {
  2357. var rest = Array.prototype.slice.call(args, 1);
  2358. return apiFunction.apply(undefined, [
  2359. component,
  2360. info.config,
  2361. info.state
  2362. ].concat(rest));
  2363. });
  2364. };
  2365. return markAsBehaviourApi(f, apiName, apiFunction);
  2366. };
  2367. var revokeBehaviour = function (name) {
  2368. return {
  2369. key: name,
  2370. value: undefined
  2371. };
  2372. };
  2373. var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
  2374. var getConfig = function (info) {
  2375. return hasNonNullableKey(info, name) ? info[name]() : Optional.none();
  2376. };
  2377. var wrappedApis = map$1(apis, function (apiF, apiName) {
  2378. return wrapApi(name, apiF, apiName);
  2379. });
  2380. var wrappedExtra = map$1(extra, function (extraF, extraName) {
  2381. return markAsExtraApi(extraF, extraName);
  2382. });
  2383. var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), {
  2384. revoke: curry(revokeBehaviour, name),
  2385. config: function (spec) {
  2386. var prepared = asRawOrDie$1(name + '-config', configSchema, spec);
  2387. return {
  2388. key: name,
  2389. value: {
  2390. config: prepared,
  2391. me: me,
  2392. configAsRaw: cached(function () {
  2393. return asRawOrDie$1(name + '-config', configSchema, spec);
  2394. }),
  2395. initialConfig: spec,
  2396. state: state
  2397. }
  2398. };
  2399. },
  2400. schema: constant$1(schemaSchema),
  2401. exhibit: function (info, base) {
  2402. return lift2(getConfig(info), get$c(active, 'exhibit'), function (behaviourInfo, exhibitor) {
  2403. return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
  2404. }).getOrThunk(function () {
  2405. return nu$3({});
  2406. });
  2407. },
  2408. name: constant$1(name),
  2409. handlers: function (info) {
  2410. return getConfig(info).map(function (behaviourInfo) {
  2411. var getEvents = get$c(active, 'events').getOr(function () {
  2412. return {};
  2413. });
  2414. return getEvents(behaviourInfo.config, behaviourInfo.state);
  2415. }).getOr({});
  2416. }
  2417. });
  2418. return me;
  2419. };
  2420. var NoState = {
  2421. init: function () {
  2422. return nu$2({ readState: constant$1('No State required') });
  2423. }
  2424. };
  2425. var nu$2 = function (spec) {
  2426. return spec;
  2427. };
  2428. var derive$2 = function (capabilities) {
  2429. return wrapAll(capabilities);
  2430. };
  2431. var simpleSchema = objOfOnly([
  2432. required$1('fields'),
  2433. required$1('name'),
  2434. defaulted('active', {}),
  2435. defaulted('apis', {}),
  2436. defaulted('state', NoState),
  2437. defaulted('extra', {})
  2438. ]);
  2439. var create$5 = function (data) {
  2440. var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data);
  2441. return create$6(value.fields, value.name, value.active, value.apis, value.extra, value.state);
  2442. };
  2443. var modeSchema = objOfOnly([
  2444. required$1('branchKey'),
  2445. required$1('branches'),
  2446. required$1('name'),
  2447. defaulted('active', {}),
  2448. defaulted('apis', {}),
  2449. defaulted('state', NoState),
  2450. defaulted('extra', {})
  2451. ]);
  2452. var createModes = function (data) {
  2453. var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data);
  2454. return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
  2455. };
  2456. var revoke = constant$1(undefined);
  2457. var Swapping = create$5({
  2458. fields: SwapSchema,
  2459. name: 'swapping',
  2460. apis: SwapApis
  2461. });
  2462. var Cell = function (initial) {
  2463. var value = initial;
  2464. var get = function () {
  2465. return value;
  2466. };
  2467. var set = function (v) {
  2468. value = v;
  2469. };
  2470. return {
  2471. get: get,
  2472. set: set
  2473. };
  2474. };
  2475. var getDocument = function () {
  2476. return SugarElement.fromDom(document);
  2477. };
  2478. var focus$3 = function (element) {
  2479. return element.dom.focus();
  2480. };
  2481. var blur$1 = function (element) {
  2482. return element.dom.blur();
  2483. };
  2484. var hasFocus = function (element) {
  2485. var root = getRootNode(element).dom;
  2486. return element.dom === root.activeElement;
  2487. };
  2488. var active = function (root) {
  2489. if (root === void 0) {
  2490. root = getDocument();
  2491. }
  2492. return Optional.from(root.dom.activeElement).map(SugarElement.fromDom);
  2493. };
  2494. var search = function (element) {
  2495. return active(getRootNode(element)).filter(function (e) {
  2496. return element.dom.contains(e.dom);
  2497. });
  2498. };
  2499. var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
  2500. var global$4 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
  2501. var openLink = function (target) {
  2502. var link = document.createElement('a');
  2503. link.target = '_blank';
  2504. link.href = target.href;
  2505. link.rel = 'noreferrer noopener';
  2506. var nuEvt = document.createEvent('MouseEvents');
  2507. nuEvt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  2508. document.body.appendChild(link);
  2509. link.dispatchEvent(nuEvt);
  2510. document.body.removeChild(link);
  2511. };
  2512. var DefaultStyleFormats = [
  2513. {
  2514. title: 'Headings',
  2515. items: [
  2516. {
  2517. title: 'Heading 1',
  2518. format: 'h1'
  2519. },
  2520. {
  2521. title: 'Heading 2',
  2522. format: 'h2'
  2523. },
  2524. {
  2525. title: 'Heading 3',
  2526. format: 'h3'
  2527. },
  2528. {
  2529. title: 'Heading 4',
  2530. format: 'h4'
  2531. },
  2532. {
  2533. title: 'Heading 5',
  2534. format: 'h5'
  2535. },
  2536. {
  2537. title: 'Heading 6',
  2538. format: 'h6'
  2539. }
  2540. ]
  2541. },
  2542. {
  2543. title: 'Inline',
  2544. items: [
  2545. {
  2546. title: 'Bold',
  2547. icon: 'bold',
  2548. format: 'bold'
  2549. },
  2550. {
  2551. title: 'Italic',
  2552. icon: 'italic',
  2553. format: 'italic'
  2554. },
  2555. {
  2556. title: 'Underline',
  2557. icon: 'underline',
  2558. format: 'underline'
  2559. },
  2560. {
  2561. title: 'Strikethrough',
  2562. icon: 'strikethrough',
  2563. format: 'strikethrough'
  2564. },
  2565. {
  2566. title: 'Superscript',
  2567. icon: 'superscript',
  2568. format: 'superscript'
  2569. },
  2570. {
  2571. title: 'Subscript',
  2572. icon: 'subscript',
  2573. format: 'subscript'
  2574. },
  2575. {
  2576. title: 'Code',
  2577. icon: 'code',
  2578. format: 'code'
  2579. }
  2580. ]
  2581. },
  2582. {
  2583. title: 'Blocks',
  2584. items: [
  2585. {
  2586. title: 'Paragraph',
  2587. format: 'p'
  2588. },
  2589. {
  2590. title: 'Blockquote',
  2591. format: 'blockquote'
  2592. },
  2593. {
  2594. title: 'Div',
  2595. format: 'div'
  2596. },
  2597. {
  2598. title: 'Pre',
  2599. format: 'pre'
  2600. }
  2601. ]
  2602. },
  2603. {
  2604. title: 'Alignment',
  2605. items: [
  2606. {
  2607. title: 'Left',
  2608. icon: 'alignleft',
  2609. format: 'alignleft'
  2610. },
  2611. {
  2612. title: 'Center',
  2613. icon: 'aligncenter',
  2614. format: 'aligncenter'
  2615. },
  2616. {
  2617. title: 'Right',
  2618. icon: 'alignright',
  2619. format: 'alignright'
  2620. },
  2621. {
  2622. title: 'Justify',
  2623. icon: 'alignjustify',
  2624. format: 'alignjustify'
  2625. }
  2626. ]
  2627. }
  2628. ];
  2629. var defaults = [
  2630. 'undo',
  2631. 'bold',
  2632. 'italic',
  2633. 'link',
  2634. 'image',
  2635. 'bullist',
  2636. 'styleselect'
  2637. ];
  2638. var isSkinDisabled = function (editor) {
  2639. return editor.getParam('skin') === false;
  2640. };
  2641. var readOnlyOnInit = function (_editor) {
  2642. return false;
  2643. };
  2644. var getToolbar = function (editor) {
  2645. return editor.getParam('toolbar', defaults, 'array');
  2646. };
  2647. var getStyleFormats = function (editor) {
  2648. return editor.getParam('style_formats', DefaultStyleFormats, 'array');
  2649. };
  2650. var getSkinUrl = function (editor) {
  2651. return editor.getParam('skin_url');
  2652. };
  2653. var formatChanged = 'formatChanged';
  2654. var orientationChanged = 'orientationChanged';
  2655. var dropupDismissed = 'dropupDismissed';
  2656. var fromHtml$1 = function (html, scope) {
  2657. var doc = scope || document;
  2658. var div = doc.createElement('div');
  2659. div.innerHTML = html;
  2660. return children(SugarElement.fromDom(div));
  2661. };
  2662. var get$9 = function (element) {
  2663. return element.dom.innerHTML;
  2664. };
  2665. var set$7 = function (element, content) {
  2666. var owner = owner$2(element);
  2667. var docDom = owner.dom;
  2668. var fragment = SugarElement.fromDom(docDom.createDocumentFragment());
  2669. var contentElements = fromHtml$1(content, docDom);
  2670. append$1(fragment, contentElements);
  2671. empty(element);
  2672. append$2(element, fragment);
  2673. };
  2674. var getOuter = function (element) {
  2675. var container = SugarElement.fromTag('div');
  2676. var clone = SugarElement.fromDom(element.dom.cloneNode(true));
  2677. append$2(container, clone);
  2678. return get$9(container);
  2679. };
  2680. var clone = function (original, isDeep) {
  2681. return SugarElement.fromDom(original.dom.cloneNode(isDeep));
  2682. };
  2683. var shallow = function (original) {
  2684. return clone(original, false);
  2685. };
  2686. var getHtml = function (element) {
  2687. if (isShadowRoot(element)) {
  2688. return '#shadow-root';
  2689. } else {
  2690. var clone = shallow(element);
  2691. return getOuter(clone);
  2692. }
  2693. };
  2694. var element = function (elem) {
  2695. return getHtml(elem);
  2696. };
  2697. var chooseChannels = function (channels, message) {
  2698. return message.universal ? channels : filter$2(channels, function (ch) {
  2699. return contains$1(message.channels, ch);
  2700. });
  2701. };
  2702. var events$a = function (receiveConfig) {
  2703. return derive$3([run(receive$1(), function (component, message) {
  2704. var channelMap = receiveConfig.channels;
  2705. var channels = keys(channelMap);
  2706. var receivingData = message;
  2707. var targetChannels = chooseChannels(channels, receivingData);
  2708. each$1(targetChannels, function (ch) {
  2709. var channelInfo = channelMap[ch];
  2710. var channelSchema = channelInfo.schema;
  2711. var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data);
  2712. channelInfo.onReceive(component, data);
  2713. });
  2714. })]);
  2715. };
  2716. var ActiveReceiving = /*#__PURE__*/Object.freeze({
  2717. __proto__: null,
  2718. events: events$a
  2719. });
  2720. var unknown = 'unknown';
  2721. var EventConfiguration;
  2722. (function (EventConfiguration) {
  2723. EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP';
  2724. EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL';
  2725. EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING';
  2726. }(EventConfiguration || (EventConfiguration = {})));
  2727. var eventConfig = Cell({});
  2728. var makeEventLogger = function (eventName, initialTarget) {
  2729. var sequence = [];
  2730. var startTime = new Date().getTime();
  2731. return {
  2732. logEventCut: function (_name, target, purpose) {
  2733. sequence.push({
  2734. outcome: 'cut',
  2735. target: target,
  2736. purpose: purpose
  2737. });
  2738. },
  2739. logEventStopped: function (_name, target, purpose) {
  2740. sequence.push({
  2741. outcome: 'stopped',
  2742. target: target,
  2743. purpose: purpose
  2744. });
  2745. },
  2746. logNoParent: function (_name, target, purpose) {
  2747. sequence.push({
  2748. outcome: 'no-parent',
  2749. target: target,
  2750. purpose: purpose
  2751. });
  2752. },
  2753. logEventNoHandlers: function (_name, target) {
  2754. sequence.push({
  2755. outcome: 'no-handlers-left',
  2756. target: target
  2757. });
  2758. },
  2759. logEventResponse: function (_name, target, purpose) {
  2760. sequence.push({
  2761. outcome: 'response',
  2762. purpose: purpose,
  2763. target: target
  2764. });
  2765. },
  2766. write: function () {
  2767. var finishTime = new Date().getTime();
  2768. if (contains$1([
  2769. 'mousemove',
  2770. 'mouseover',
  2771. 'mouseout',
  2772. systemInit()
  2773. ], eventName)) {
  2774. return;
  2775. }
  2776. console.log(eventName, {
  2777. event: eventName,
  2778. time: finishTime - startTime,
  2779. target: initialTarget.dom,
  2780. sequence: map$2(sequence, function (s) {
  2781. if (!contains$1([
  2782. 'cut',
  2783. 'stopped',
  2784. 'response'
  2785. ], s.outcome)) {
  2786. return s.outcome;
  2787. } else {
  2788. return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
  2789. }
  2790. })
  2791. });
  2792. }
  2793. };
  2794. };
  2795. var processEvent = function (eventName, initialTarget, f) {
  2796. var status = get$c(eventConfig.get(), eventName).orThunk(function () {
  2797. var patterns = keys(eventConfig.get());
  2798. return findMap(patterns, function (p) {
  2799. return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none();
  2800. });
  2801. }).getOr(EventConfiguration.NORMAL);
  2802. switch (status) {
  2803. case EventConfiguration.NORMAL:
  2804. return f(noLogger());
  2805. case EventConfiguration.LOGGING: {
  2806. var logger = makeEventLogger(eventName, initialTarget);
  2807. var output = f(logger);
  2808. logger.write();
  2809. return output;
  2810. }
  2811. case EventConfiguration.STOP:
  2812. return true;
  2813. }
  2814. };
  2815. var path = [
  2816. 'alloy/data/Fields',
  2817. 'alloy/debugging/Debugging'
  2818. ];
  2819. var getTrace = function () {
  2820. var err = new Error();
  2821. if (err.stack !== undefined) {
  2822. var lines = err.stack.split('\n');
  2823. return find$2(lines, function (line) {
  2824. return line.indexOf('alloy') > 0 && !exists(path, function (p) {
  2825. return line.indexOf(p) > -1;
  2826. });
  2827. }).getOr(unknown);
  2828. } else {
  2829. return unknown;
  2830. }
  2831. };
  2832. var ignoreEvent = {
  2833. logEventCut: noop,
  2834. logEventStopped: noop,
  2835. logNoParent: noop,
  2836. logEventNoHandlers: noop,
  2837. logEventResponse: noop,
  2838. write: noop
  2839. };
  2840. var monitorEvent = function (eventName, initialTarget, f) {
  2841. return processEvent(eventName, initialTarget, f);
  2842. };
  2843. var noLogger = constant$1(ignoreEvent);
  2844. var menuFields = constant$1([
  2845. required$1('menu'),
  2846. required$1('selectedMenu')
  2847. ]);
  2848. var itemFields = constant$1([
  2849. required$1('item'),
  2850. required$1('selectedItem')
  2851. ]);
  2852. constant$1(objOf(itemFields().concat(menuFields())));
  2853. var itemSchema$1 = constant$1(objOf(itemFields()));
  2854. var _initSize = requiredObjOf('initSize', [
  2855. required$1('numColumns'),
  2856. required$1('numRows')
  2857. ]);
  2858. var itemMarkers = function () {
  2859. return requiredOf('markers', itemSchema$1());
  2860. };
  2861. var tieredMenuMarkers = function () {
  2862. return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
  2863. };
  2864. var markers = function (required) {
  2865. return requiredObjOf('markers', map$2(required, required$1));
  2866. };
  2867. var onPresenceHandler = function (label, fieldName, presence) {
  2868. getTrace();
  2869. return field$2(fieldName, fieldName, presence, valueOf(function (f) {
  2870. return Result.value(function () {
  2871. var args = [];
  2872. for (var _i = 0; _i < arguments.length; _i++) {
  2873. args[_i] = arguments[_i];
  2874. }
  2875. return f.apply(undefined, args);
  2876. });
  2877. }));
  2878. };
  2879. var onHandler = function (fieldName) {
  2880. return onPresenceHandler('onHandler', fieldName, defaulted$1(noop));
  2881. };
  2882. var onKeyboardHandler = function (fieldName) {
  2883. return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none));
  2884. };
  2885. var onStrictHandler = function (fieldName) {
  2886. return onPresenceHandler('onHandler', fieldName, required$2());
  2887. };
  2888. var onStrictKeyboardHandler = function (fieldName) {
  2889. return onPresenceHandler('onKeyboardHandler', fieldName, required$2());
  2890. };
  2891. var output = function (name, value) {
  2892. return customField(name, constant$1(value));
  2893. };
  2894. var snapshot = function (name) {
  2895. return customField(name, identity);
  2896. };
  2897. var initSize = constant$1(_initSize);
  2898. var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([
  2899. onStrictHandler('onReceive'),
  2900. defaulted('schema', anyValue())
  2901. ])))];
  2902. var Receiving = create$5({
  2903. fields: ReceivingSchema,
  2904. name: 'receiving',
  2905. active: ActiveReceiving
  2906. });
  2907. var SetupBehaviourCellState = function (initialState) {
  2908. var init = function () {
  2909. var cell = Cell(initialState);
  2910. var get = function () {
  2911. return cell.get();
  2912. };
  2913. var set = function (newState) {
  2914. return cell.set(newState);
  2915. };
  2916. var clear = function () {
  2917. return cell.set(initialState);
  2918. };
  2919. var readState = function () {
  2920. return cell.get();
  2921. };
  2922. return {
  2923. get: get,
  2924. set: set,
  2925. clear: clear,
  2926. readState: readState
  2927. };
  2928. };
  2929. return { init: init };
  2930. };
  2931. var updateAriaState = function (component, toggleConfig, toggleState) {
  2932. var ariaInfo = toggleConfig.aria;
  2933. ariaInfo.update(component, ariaInfo, toggleState.get());
  2934. };
  2935. var updateClass = function (component, toggleConfig, toggleState) {
  2936. toggleConfig.toggleClass.each(function (toggleClass) {
  2937. if (toggleState.get()) {
  2938. add$1(component.element, toggleClass);
  2939. } else {
  2940. remove$3(component.element, toggleClass);
  2941. }
  2942. });
  2943. };
  2944. var toggle = function (component, toggleConfig, toggleState) {
  2945. set$6(component, toggleConfig, toggleState, !toggleState.get());
  2946. };
  2947. var on$1 = function (component, toggleConfig, toggleState) {
  2948. toggleState.set(true);
  2949. updateClass(component, toggleConfig, toggleState);
  2950. updateAriaState(component, toggleConfig, toggleState);
  2951. };
  2952. var off = function (component, toggleConfig, toggleState) {
  2953. toggleState.set(false);
  2954. updateClass(component, toggleConfig, toggleState);
  2955. updateAriaState(component, toggleConfig, toggleState);
  2956. };
  2957. var set$6 = function (component, toggleConfig, toggleState, state) {
  2958. var action = state ? on$1 : off;
  2959. action(component, toggleConfig, toggleState);
  2960. };
  2961. var isOn = function (component, toggleConfig, toggleState) {
  2962. return toggleState.get();
  2963. };
  2964. var onLoad$5 = function (component, toggleConfig, toggleState) {
  2965. set$6(component, toggleConfig, toggleState, toggleConfig.selected);
  2966. };
  2967. var ToggleApis = /*#__PURE__*/Object.freeze({
  2968. __proto__: null,
  2969. onLoad: onLoad$5,
  2970. toggle: toggle,
  2971. isOn: isOn,
  2972. on: on$1,
  2973. off: off,
  2974. set: set$6
  2975. });
  2976. var exhibit$5 = function () {
  2977. return nu$3({});
  2978. };
  2979. var events$9 = function (toggleConfig, toggleState) {
  2980. var execute = executeEvent(toggleConfig, toggleState, toggle);
  2981. var load = loadEvent(toggleConfig, toggleState, onLoad$5);
  2982. return derive$3(flatten([
  2983. toggleConfig.toggleOnExecute ? [execute] : [],
  2984. [load]
  2985. ]));
  2986. };
  2987. var ActiveToggle = /*#__PURE__*/Object.freeze({
  2988. __proto__: null,
  2989. exhibit: exhibit$5,
  2990. events: events$9
  2991. });
  2992. var updatePressed = function (component, ariaInfo, status) {
  2993. set$8(component.element, 'aria-pressed', status);
  2994. if (ariaInfo.syncWithExpanded) {
  2995. updateExpanded(component, ariaInfo, status);
  2996. }
  2997. };
  2998. var updateSelected = function (component, ariaInfo, status) {
  2999. set$8(component.element, 'aria-selected', status);
  3000. };
  3001. var updateChecked = function (component, ariaInfo, status) {
  3002. set$8(component.element, 'aria-checked', status);
  3003. };
  3004. var updateExpanded = function (component, ariaInfo, status) {
  3005. set$8(component.element, 'aria-expanded', status);
  3006. };
  3007. var ToggleSchema = [
  3008. defaulted('selected', false),
  3009. option('toggleClass'),
  3010. defaulted('toggleOnExecute', true),
  3011. defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
  3012. pressed: [
  3013. defaulted('syncWithExpanded', false),
  3014. output('update', updatePressed)
  3015. ],
  3016. checked: [output('update', updateChecked)],
  3017. expanded: [output('update', updateExpanded)],
  3018. selected: [output('update', updateSelected)],
  3019. none: [output('update', noop)]
  3020. }))
  3021. ];
  3022. var Toggling = create$5({
  3023. fields: ToggleSchema,
  3024. name: 'toggling',
  3025. active: ActiveToggle,
  3026. apis: ToggleApis,
  3027. state: SetupBehaviourCellState(false)
  3028. });
  3029. var format = function (command, update) {
  3030. return Receiving.config({
  3031. channels: wrap(formatChanged, {
  3032. onReceive: function (button, data) {
  3033. if (data.command === command) {
  3034. update(button, data.state);
  3035. }
  3036. }
  3037. })
  3038. });
  3039. };
  3040. var orientation = function (onReceive) {
  3041. return Receiving.config({ channels: wrap(orientationChanged, { onReceive: onReceive }) });
  3042. };
  3043. var receive = function (channel, onReceive) {
  3044. return {
  3045. key: channel,
  3046. value: { onReceive: onReceive }
  3047. };
  3048. };
  3049. var prefix$2 = 'tinymce-mobile';
  3050. var resolve = function (p) {
  3051. return prefix$2 + '-' + p;
  3052. };
  3053. var pointerEvents = function () {
  3054. var onClick = function (component, simulatedEvent) {
  3055. simulatedEvent.stop();
  3056. emitExecute(component);
  3057. };
  3058. return [
  3059. run(click(), onClick),
  3060. run(tap(), onClick),
  3061. cutter(touchstart()),
  3062. cutter(mousedown())
  3063. ];
  3064. };
  3065. var events$8 = function (optAction) {
  3066. var executeHandler = function (action) {
  3067. return runOnExecute(function (component, simulatedEvent) {
  3068. action(component);
  3069. simulatedEvent.stop();
  3070. });
  3071. };
  3072. return derive$3(flatten([
  3073. optAction.map(executeHandler).toArray(),
  3074. pointerEvents()
  3075. ]));
  3076. };
  3077. var focus$2 = function (component, focusConfig) {
  3078. if (!focusConfig.ignore) {
  3079. focus$3(component.element);
  3080. focusConfig.onFocus(component);
  3081. }
  3082. };
  3083. var blur = function (component, focusConfig) {
  3084. if (!focusConfig.ignore) {
  3085. blur$1(component.element);
  3086. }
  3087. };
  3088. var isFocused = function (component) {
  3089. return hasFocus(component.element);
  3090. };
  3091. var FocusApis = /*#__PURE__*/Object.freeze({
  3092. __proto__: null,
  3093. focus: focus$2,
  3094. blur: blur,
  3095. isFocused: isFocused
  3096. });
  3097. var exhibit$4 = function (base, focusConfig) {
  3098. var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } };
  3099. return nu$3(mod);
  3100. };
  3101. var events$7 = function (focusConfig) {
  3102. return derive$3([run(focus$4(), function (component, simulatedEvent) {
  3103. focus$2(component, focusConfig);
  3104. simulatedEvent.stop();
  3105. })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) {
  3106. simulatedEvent.event.prevent();
  3107. })] : []));
  3108. };
  3109. var ActiveFocus = /*#__PURE__*/Object.freeze({
  3110. __proto__: null,
  3111. exhibit: exhibit$4,
  3112. events: events$7
  3113. });
  3114. var FocusSchema = [
  3115. onHandler('onFocus'),
  3116. defaulted('stopMousedown', false),
  3117. defaulted('ignore', false)
  3118. ];
  3119. var Focusing = create$5({
  3120. fields: FocusSchema,
  3121. name: 'focusing',
  3122. active: ActiveFocus,
  3123. apis: FocusApis
  3124. });
  3125. var isSupported = function (dom) {
  3126. return dom.style !== undefined && isFunction(dom.style.getPropertyValue);
  3127. };
  3128. var internalSet = function (dom, property, value) {
  3129. if (!isString(value)) {
  3130. console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom);
  3131. throw new Error('CSS value must be a string: ' + value);
  3132. }
  3133. if (isSupported(dom)) {
  3134. dom.style.setProperty(property, value);
  3135. }
  3136. };
  3137. var internalRemove = function (dom, property) {
  3138. if (isSupported(dom)) {
  3139. dom.style.removeProperty(property);
  3140. }
  3141. };
  3142. var set$5 = function (element, property, value) {
  3143. var dom = element.dom;
  3144. internalSet(dom, property, value);
  3145. };
  3146. var setAll = function (element, css) {
  3147. var dom = element.dom;
  3148. each(css, function (v, k) {
  3149. internalSet(dom, k, v);
  3150. });
  3151. };
  3152. var get$8 = function (element, property) {
  3153. var dom = element.dom;
  3154. var styles = window.getComputedStyle(dom);
  3155. var r = styles.getPropertyValue(property);
  3156. return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
  3157. };
  3158. var getUnsafeProperty = function (dom, property) {
  3159. return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
  3160. };
  3161. var getRaw = function (element, property) {
  3162. var dom = element.dom;
  3163. var raw = getUnsafeProperty(dom, property);
  3164. return Optional.from(raw).filter(function (r) {
  3165. return r.length > 0;
  3166. });
  3167. };
  3168. var remove$2 = function (element, property) {
  3169. var dom = element.dom;
  3170. internalRemove(dom, property);
  3171. if (is(getOpt(element, 'style').map(trim), '')) {
  3172. remove$6(element, 'style');
  3173. }
  3174. };
  3175. var reflow = function (e) {
  3176. return e.dom.offsetWidth;
  3177. };
  3178. var Dimension = function (name, getOffset) {
  3179. var set = function (element, h) {
  3180. if (!isNumber(h) && !h.match(/^[0-9]+$/)) {
  3181. throw new Error(name + '.set accepts only positive integer values. Value was ' + h);
  3182. }
  3183. var dom = element.dom;
  3184. if (isSupported(dom)) {
  3185. dom.style[name] = h + 'px';
  3186. }
  3187. };
  3188. var get = function (element) {
  3189. var r = getOffset(element);
  3190. if (r <= 0 || r === null) {
  3191. var css = get$8(element, name);
  3192. return parseFloat(css) || 0;
  3193. }
  3194. return r;
  3195. };
  3196. var getOuter = get;
  3197. var aggregate = function (element, properties) {
  3198. return foldl(properties, function (acc, property) {
  3199. var val = get$8(element, property);
  3200. var value = val === undefined ? 0 : parseInt(val, 10);
  3201. return isNaN(value) ? acc : acc + value;
  3202. }, 0);
  3203. };
  3204. var max = function (element, value, properties) {
  3205. var cumulativeInclusions = aggregate(element, properties);
  3206. var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
  3207. return absoluteMax;
  3208. };
  3209. return {
  3210. set: set,
  3211. get: get,
  3212. getOuter: getOuter,
  3213. aggregate: aggregate,
  3214. max: max
  3215. };
  3216. };
  3217. var api$3 = Dimension('height', function (element) {
  3218. var dom = element.dom;
  3219. return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
  3220. });
  3221. var get$7 = function (element) {
  3222. return api$3.get(element);
  3223. };
  3224. var ancestors$1 = function (scope, predicate, isRoot) {
  3225. return filter$2(parents(scope, isRoot), predicate);
  3226. };
  3227. var siblings$1 = function (scope, predicate) {
  3228. return filter$2(siblings$2(scope), predicate);
  3229. };
  3230. var all = function (selector) {
  3231. return all$2(selector);
  3232. };
  3233. var ancestors = function (scope, selector, isRoot) {
  3234. return ancestors$1(scope, function (e) {
  3235. return is$1(e, selector);
  3236. }, isRoot);
  3237. };
  3238. var siblings = function (scope, selector) {
  3239. return siblings$1(scope, function (e) {
  3240. return is$1(e, selector);
  3241. });
  3242. };
  3243. var descendants = function (scope, selector) {
  3244. return all$2(selector, scope);
  3245. };
  3246. function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
  3247. if (is(scope, a)) {
  3248. return Optional.some(scope);
  3249. } else if (isFunction(isRoot) && isRoot(scope)) {
  3250. return Optional.none();
  3251. } else {
  3252. return ancestor(scope, a, isRoot);
  3253. }
  3254. }
  3255. var ancestor$1 = function (scope, predicate, isRoot) {
  3256. var element = scope.dom;
  3257. var stop = isFunction(isRoot) ? isRoot : never;
  3258. while (element.parentNode) {
  3259. element = element.parentNode;
  3260. var el = SugarElement.fromDom(element);
  3261. if (predicate(el)) {
  3262. return Optional.some(el);
  3263. } else if (stop(el)) {
  3264. break;
  3265. }
  3266. }
  3267. return Optional.none();
  3268. };
  3269. var closest$2 = function (scope, predicate, isRoot) {
  3270. var is = function (s, test) {
  3271. return test(s);
  3272. };
  3273. return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot);
  3274. };
  3275. var descendant$1 = function (scope, predicate) {
  3276. var descend = function (node) {
  3277. for (var i = 0; i < node.childNodes.length; i++) {
  3278. var child_1 = SugarElement.fromDom(node.childNodes[i]);
  3279. if (predicate(child_1)) {
  3280. return Optional.some(child_1);
  3281. }
  3282. var res = descend(node.childNodes[i]);
  3283. if (res.isSome()) {
  3284. return res;
  3285. }
  3286. }
  3287. return Optional.none();
  3288. };
  3289. return descend(scope.dom);
  3290. };
  3291. var first$1 = function (selector) {
  3292. return one(selector);
  3293. };
  3294. var ancestor = function (scope, selector, isRoot) {
  3295. return ancestor$1(scope, function (e) {
  3296. return is$1(e, selector);
  3297. }, isRoot);
  3298. };
  3299. var descendant = function (scope, selector) {
  3300. return one(selector, scope);
  3301. };
  3302. var closest$1 = function (scope, selector, isRoot) {
  3303. var is = function (element, selector) {
  3304. return is$1(element, selector);
  3305. };
  3306. return ClosestOrAncestor(is, ancestor, scope, selector, isRoot);
  3307. };
  3308. var BACKSPACE = [8];
  3309. var TAB = [9];
  3310. var ENTER = [13];
  3311. var ESCAPE = [27];
  3312. var SPACE = [32];
  3313. var LEFT = [37];
  3314. var UP = [38];
  3315. var RIGHT = [39];
  3316. var DOWN = [40];
  3317. var cyclePrev = function (values, index, predicate) {
  3318. var before = reverse(values.slice(0, index));
  3319. var after = reverse(values.slice(index + 1));
  3320. return find$2(before.concat(after), predicate);
  3321. };
  3322. var tryPrev = function (values, index, predicate) {
  3323. var before = reverse(values.slice(0, index));
  3324. return find$2(before, predicate);
  3325. };
  3326. var cycleNext = function (values, index, predicate) {
  3327. var before = values.slice(0, index);
  3328. var after = values.slice(index + 1);
  3329. return find$2(after.concat(before), predicate);
  3330. };
  3331. var tryNext = function (values, index, predicate) {
  3332. var after = values.slice(index + 1);
  3333. return find$2(after, predicate);
  3334. };
  3335. var inSet = function (keys) {
  3336. return function (event) {
  3337. var raw = event.raw;
  3338. return contains$1(keys, raw.which);
  3339. };
  3340. };
  3341. var and = function (preds) {
  3342. return function (event) {
  3343. return forall(preds, function (pred) {
  3344. return pred(event);
  3345. });
  3346. };
  3347. };
  3348. var isShift = function (event) {
  3349. var raw = event.raw;
  3350. return raw.shiftKey === true;
  3351. };
  3352. var isControl = function (event) {
  3353. var raw = event.raw;
  3354. return raw.ctrlKey === true;
  3355. };
  3356. var isNotShift = not(isShift);
  3357. var rule = function (matches, action) {
  3358. return {
  3359. matches: matches,
  3360. classification: action
  3361. };
  3362. };
  3363. var choose = function (transitions, event) {
  3364. var transition = find$2(transitions, function (t) {
  3365. return t.matches(event);
  3366. });
  3367. return transition.map(function (t) {
  3368. return t.classification;
  3369. });
  3370. };
  3371. var cycleBy = function (value, delta, min, max) {
  3372. var r = value + delta;
  3373. if (r > max) {
  3374. return min;
  3375. } else if (r < min) {
  3376. return max;
  3377. } else {
  3378. return r;
  3379. }
  3380. };
  3381. var clamp = function (value, min, max) {
  3382. return Math.min(Math.max(value, min), max);
  3383. };
  3384. var dehighlightAllExcept = function (component, hConfig, hState, skip) {
  3385. var highlighted = descendants(component.element, '.' + hConfig.highlightClass);
  3386. each$1(highlighted, function (h) {
  3387. if (!exists(skip, function (skipComp) {
  3388. return skipComp.element === h;
  3389. })) {
  3390. remove$3(h, hConfig.highlightClass);
  3391. component.getSystem().getByDom(h).each(function (target) {
  3392. hConfig.onDehighlight(component, target);
  3393. emit(target, dehighlight$1());
  3394. });
  3395. }
  3396. });
  3397. };
  3398. var dehighlightAll = function (component, hConfig, hState) {
  3399. return dehighlightAllExcept(component, hConfig, hState, []);
  3400. };
  3401. var dehighlight = function (component, hConfig, hState, target) {
  3402. if (isHighlighted(component, hConfig, hState, target)) {
  3403. remove$3(target.element, hConfig.highlightClass);
  3404. hConfig.onDehighlight(component, target);
  3405. emit(target, dehighlight$1());
  3406. }
  3407. };
  3408. var highlight = function (component, hConfig, hState, target) {
  3409. dehighlightAllExcept(component, hConfig, hState, [target]);
  3410. if (!isHighlighted(component, hConfig, hState, target)) {
  3411. add$1(target.element, hConfig.highlightClass);
  3412. hConfig.onHighlight(component, target);
  3413. emit(target, highlight$1());
  3414. }
  3415. };
  3416. var highlightFirst = function (component, hConfig, hState) {
  3417. getFirst(component, hConfig).each(function (firstComp) {
  3418. highlight(component, hConfig, hState, firstComp);
  3419. });
  3420. };
  3421. var highlightLast = function (component, hConfig, hState) {
  3422. getLast(component, hConfig).each(function (lastComp) {
  3423. highlight(component, hConfig, hState, lastComp);
  3424. });
  3425. };
  3426. var highlightAt = function (component, hConfig, hState, index) {
  3427. getByIndex(component, hConfig, hState, index).fold(function (err) {
  3428. throw err;
  3429. }, function (firstComp) {
  3430. highlight(component, hConfig, hState, firstComp);
  3431. });
  3432. };
  3433. var highlightBy = function (component, hConfig, hState, predicate) {
  3434. var candidates = getCandidates(component, hConfig);
  3435. var targetComp = find$2(candidates, predicate);
  3436. targetComp.each(function (c) {
  3437. highlight(component, hConfig, hState, c);
  3438. });
  3439. };
  3440. var isHighlighted = function (component, hConfig, hState, queryTarget) {
  3441. return has(queryTarget.element, hConfig.highlightClass);
  3442. };
  3443. var getHighlighted = function (component, hConfig, _hState) {
  3444. return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) {
  3445. return component.getSystem().getByDom(e).toOptional();
  3446. });
  3447. };
  3448. var getByIndex = function (component, hConfig, hState, index) {
  3449. var items = descendants(component.element, '.' + hConfig.itemClass);
  3450. return Optional.from(items[index]).fold(function () {
  3451. return Result.error(new Error('No element found with index ' + index));
  3452. }, component.getSystem().getByDom);
  3453. };
  3454. var getFirst = function (component, hConfig, _hState) {
  3455. return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) {
  3456. return component.getSystem().getByDom(e).toOptional();
  3457. });
  3458. };
  3459. var getLast = function (component, hConfig, _hState) {
  3460. var items = descendants(component.element, '.' + hConfig.itemClass);
  3461. var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none();
  3462. return last.bind(function (c) {
  3463. return component.getSystem().getByDom(c).toOptional();
  3464. });
  3465. };
  3466. var getDelta = function (component, hConfig, hState, delta) {
  3467. var items = descendants(component.element, '.' + hConfig.itemClass);
  3468. var current = findIndex$1(items, function (item) {
  3469. return has(item, hConfig.highlightClass);
  3470. });
  3471. return current.bind(function (selected) {
  3472. var dest = cycleBy(selected, delta, 0, items.length - 1);
  3473. return component.getSystem().getByDom(items[dest]).toOptional();
  3474. });
  3475. };
  3476. var getPrevious = function (component, hConfig, hState) {
  3477. return getDelta(component, hConfig, hState, -1);
  3478. };
  3479. var getNext = function (component, hConfig, hState) {
  3480. return getDelta(component, hConfig, hState, +1);
  3481. };
  3482. var getCandidates = function (component, hConfig, _hState) {
  3483. var items = descendants(component.element, '.' + hConfig.itemClass);
  3484. return cat(map$2(items, function (i) {
  3485. return component.getSystem().getByDom(i).toOptional();
  3486. }));
  3487. };
  3488. var HighlightApis = /*#__PURE__*/Object.freeze({
  3489. __proto__: null,
  3490. dehighlightAll: dehighlightAll,
  3491. dehighlight: dehighlight,
  3492. highlight: highlight,
  3493. highlightFirst: highlightFirst,
  3494. highlightLast: highlightLast,
  3495. highlightAt: highlightAt,
  3496. highlightBy: highlightBy,
  3497. isHighlighted: isHighlighted,
  3498. getHighlighted: getHighlighted,
  3499. getFirst: getFirst,
  3500. getLast: getLast,
  3501. getPrevious: getPrevious,
  3502. getNext: getNext,
  3503. getCandidates: getCandidates
  3504. });
  3505. var HighlightSchema = [
  3506. required$1('highlightClass'),
  3507. required$1('itemClass'),
  3508. onHandler('onHighlight'),
  3509. onHandler('onDehighlight')
  3510. ];
  3511. var Highlighting = create$5({
  3512. fields: HighlightSchema,
  3513. name: 'highlighting',
  3514. apis: HighlightApis
  3515. });
  3516. var reportFocusShifting = function (component, prevFocus, newFocus) {
  3517. var noChange = prevFocus.exists(function (p) {
  3518. return newFocus.exists(function (n) {
  3519. return eq(n, p);
  3520. });
  3521. });
  3522. if (!noChange) {
  3523. emitWith(component, focusShifted(), {
  3524. prevFocus: prevFocus,
  3525. newFocus: newFocus
  3526. });
  3527. }
  3528. };
  3529. var dom$2 = function () {
  3530. var get = function (component) {
  3531. return search(component.element);
  3532. };
  3533. var set = function (component, focusee) {
  3534. var prevFocus = get(component);
  3535. component.getSystem().triggerFocus(focusee, component.element);
  3536. var newFocus = get(component);
  3537. reportFocusShifting(component, prevFocus, newFocus);
  3538. };
  3539. return {
  3540. get: get,
  3541. set: set
  3542. };
  3543. };
  3544. var highlights = function () {
  3545. var get = function (component) {
  3546. return Highlighting.getHighlighted(component).map(function (item) {
  3547. return item.element;
  3548. });
  3549. };
  3550. var set = function (component, element) {
  3551. var prevFocus = get(component);
  3552. component.getSystem().getByDom(element).fold(noop, function (item) {
  3553. Highlighting.highlight(component, item);
  3554. });
  3555. var newFocus = get(component);
  3556. reportFocusShifting(component, prevFocus, newFocus);
  3557. };
  3558. return {
  3559. get: get,
  3560. set: set
  3561. };
  3562. };
  3563. var FocusInsideModes;
  3564. (function (FocusInsideModes) {
  3565. FocusInsideModes['OnFocusMode'] = 'onFocus';
  3566. FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace';
  3567. FocusInsideModes['OnApiMode'] = 'onApi';
  3568. }(FocusInsideModes || (FocusInsideModes = {})));
  3569. var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) {
  3570. var schema = function () {
  3571. return infoSchema.concat([
  3572. defaulted('focusManager', dom$2()),
  3573. defaultedOf('focusInside', 'onFocus', valueOf(function (val) {
  3574. return contains$1([
  3575. 'onFocus',
  3576. 'onEnterOrSpace',
  3577. 'onApi'
  3578. ], val) ? Result.value(val) : Result.error('Invalid value for focusInside');
  3579. })),
  3580. output('handler', me),
  3581. output('state', stateInit),
  3582. output('sendFocusIn', optFocusIn)
  3583. ]);
  3584. };
  3585. var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) {
  3586. var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
  3587. return choose(rules, simulatedEvent.event).bind(function (rule) {
  3588. return rule(component, simulatedEvent, keyingConfig, keyingState);
  3589. });
  3590. };
  3591. var toEvents = function (keyingConfig, keyingState) {
  3592. var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) {
  3593. return run(focus$4(), function (component, simulatedEvent) {
  3594. focusIn(component, keyingConfig, keyingState);
  3595. simulatedEvent.stop();
  3596. });
  3597. });
  3598. var tryGoInsideComponent = function (component, simulatedEvent) {
  3599. var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event);
  3600. if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) {
  3601. optFocusIn(keyingConfig).each(function (focusIn) {
  3602. focusIn(component, keyingConfig, keyingState);
  3603. simulatedEvent.stop();
  3604. });
  3605. }
  3606. };
  3607. var keyboardEvents = [
  3608. run(keydown(), function (component, simulatedEvent) {
  3609. processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () {
  3610. tryGoInsideComponent(component, simulatedEvent);
  3611. }, function (_) {
  3612. simulatedEvent.stop();
  3613. });
  3614. }),
  3615. run(keyup(), function (component, simulatedEvent) {
  3616. processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) {
  3617. simulatedEvent.stop();
  3618. });
  3619. })
  3620. ];
  3621. return derive$3(onFocusHandler.toArray().concat(keyboardEvents));
  3622. };
  3623. var me = {
  3624. schema: schema,
  3625. processKey: processKey,
  3626. toEvents: toEvents
  3627. };
  3628. return me;
  3629. };
  3630. var create$4 = function (cyclicField) {
  3631. var schema = [
  3632. option('onEscape'),
  3633. option('onEnter'),
  3634. defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'),
  3635. defaulted('firstTabstop', 0),
  3636. defaulted('useTabstopAt', always),
  3637. option('visibilitySelector')
  3638. ].concat([cyclicField]);
  3639. var isVisible = function (tabbingConfig, element) {
  3640. var target = tabbingConfig.visibilitySelector.bind(function (sel) {
  3641. return closest$1(element, sel);
  3642. }).getOr(element);
  3643. return get$7(target) > 0;
  3644. };
  3645. var findInitial = function (component, tabbingConfig) {
  3646. var tabstops = descendants(component.element, tabbingConfig.selector);
  3647. var visibles = filter$2(tabstops, function (elem) {
  3648. return isVisible(tabbingConfig, elem);
  3649. });
  3650. return Optional.from(visibles[tabbingConfig.firstTabstop]);
  3651. };
  3652. var findCurrent = function (component, tabbingConfig) {
  3653. return tabbingConfig.focusManager.get(component).bind(function (elem) {
  3654. return closest$1(elem, tabbingConfig.selector);
  3655. });
  3656. };
  3657. var isTabstop = function (tabbingConfig, element) {
  3658. return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element);
  3659. };
  3660. var focusIn = function (component, tabbingConfig, _tabbingState) {
  3661. findInitial(component, tabbingConfig).each(function (target) {
  3662. tabbingConfig.focusManager.set(component, target);
  3663. });
  3664. };
  3665. var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
  3666. return cycle(tabstops, stopIndex, function (elem) {
  3667. return isTabstop(tabbingConfig, elem);
  3668. }).fold(function () {
  3669. return tabbingConfig.cyclic ? Optional.some(true) : Optional.none();
  3670. }, function (target) {
  3671. tabbingConfig.focusManager.set(component, target);
  3672. return Optional.some(true);
  3673. });
  3674. };
  3675. var go = function (component, _simulatedEvent, tabbingConfig, cycle) {
  3676. var tabstops = descendants(component.element, tabbingConfig.selector);
  3677. return findCurrent(component, tabbingConfig).bind(function (tabstop) {
  3678. var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop));
  3679. return optStopIndex.bind(function (stopIndex) {
  3680. return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
  3681. });
  3682. });
  3683. };
  3684. var goBackwards = function (component, simulatedEvent, tabbingConfig) {
  3685. var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev;
  3686. return go(component, simulatedEvent, tabbingConfig, navigate);
  3687. };
  3688. var goForwards = function (component, simulatedEvent, tabbingConfig) {
  3689. var navigate = tabbingConfig.cyclic ? cycleNext : tryNext;
  3690. return go(component, simulatedEvent, tabbingConfig, navigate);
  3691. };
  3692. var execute = function (component, simulatedEvent, tabbingConfig) {
  3693. return tabbingConfig.onEnter.bind(function (f) {
  3694. return f(component, simulatedEvent);
  3695. });
  3696. };
  3697. var exit = function (component, simulatedEvent, tabbingConfig) {
  3698. return tabbingConfig.onEscape.bind(function (f) {
  3699. return f(component, simulatedEvent);
  3700. });
  3701. };
  3702. var getKeydownRules = constant$1([
  3703. rule(and([
  3704. isShift,
  3705. inSet(TAB)
  3706. ]), goBackwards),
  3707. rule(inSet(TAB), goForwards),
  3708. rule(inSet(ESCAPE), exit),
  3709. rule(and([
  3710. isNotShift,
  3711. inSet(ENTER)
  3712. ]), execute)
  3713. ]);
  3714. var getKeyupRules = constant$1([]);
  3715. return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () {
  3716. return Optional.some(focusIn);
  3717. });
  3718. };
  3719. var AcyclicType = create$4(customField('cyclic', never));
  3720. var CyclicType = create$4(customField('cyclic', always));
  3721. var inside = function (target) {
  3722. return name$1(target) === 'input' && get$b(target, 'type') !== 'radio' || name$1(target) === 'textarea';
  3723. };
  3724. var doDefaultExecute = function (component, _simulatedEvent, focused) {
  3725. dispatch(component, focused, execute$5());
  3726. return Optional.some(true);
  3727. };
  3728. var defaultExecute = function (component, simulatedEvent, focused) {
  3729. var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event);
  3730. return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused);
  3731. };
  3732. var stopEventForFirefox = function (_component, _simulatedEvent) {
  3733. return Optional.some(true);
  3734. };
  3735. var schema$f = [
  3736. defaulted('execute', defaultExecute),
  3737. defaulted('useSpace', false),
  3738. defaulted('useEnter', true),
  3739. defaulted('useControlEnter', false),
  3740. defaulted('useDown', false)
  3741. ];
  3742. var execute$4 = function (component, simulatedEvent, executeConfig) {
  3743. return executeConfig.execute(component, simulatedEvent, component.element);
  3744. };
  3745. var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  3746. var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : [];
  3747. var enterExec = executeConfig.useEnter ? ENTER : [];
  3748. var downExec = executeConfig.useDown ? DOWN : [];
  3749. var execKeys = spaceExec.concat(enterExec).concat(downExec);
  3750. return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([
  3751. isControl,
  3752. inSet(ENTER)
  3753. ]), execute$4)] : []);
  3754. };
  3755. var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) {
  3756. return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  3757. };
  3758. var ExecutionType = typical(schema$f, NoState.init, getKeydownRules$5, getKeyupRules$5, function () {
  3759. return Optional.none();
  3760. });
  3761. var singleton$1 = function (doRevoke) {
  3762. var subject = Cell(Optional.none());
  3763. var revoke = function () {
  3764. return subject.get().each(doRevoke);
  3765. };
  3766. var clear = function () {
  3767. revoke();
  3768. subject.set(Optional.none());
  3769. };
  3770. var isSet = function () {
  3771. return subject.get().isSome();
  3772. };
  3773. var get = function () {
  3774. return subject.get();
  3775. };
  3776. var set = function (s) {
  3777. revoke();
  3778. subject.set(Optional.some(s));
  3779. };
  3780. return {
  3781. clear: clear,
  3782. isSet: isSet,
  3783. get: get,
  3784. set: set
  3785. };
  3786. };
  3787. var destroyable = function () {
  3788. return singleton$1(function (s) {
  3789. return s.destroy();
  3790. });
  3791. };
  3792. var api$2 = function () {
  3793. var subject = destroyable();
  3794. var run = function (f) {
  3795. return subject.get().each(f);
  3796. };
  3797. return __assign(__assign({}, subject), { run: run });
  3798. };
  3799. var value = function () {
  3800. var subject = singleton$1(noop);
  3801. var on = function (f) {
  3802. return subject.get().each(f);
  3803. };
  3804. return __assign(__assign({}, subject), { on: on });
  3805. };
  3806. var flatgrid$1 = function () {
  3807. var dimensions = value();
  3808. var setGridSize = function (numRows, numColumns) {
  3809. dimensions.set({
  3810. numRows: numRows,
  3811. numColumns: numColumns
  3812. });
  3813. };
  3814. var getNumRows = function () {
  3815. return dimensions.get().map(function (d) {
  3816. return d.numRows;
  3817. });
  3818. };
  3819. var getNumColumns = function () {
  3820. return dimensions.get().map(function (d) {
  3821. return d.numColumns;
  3822. });
  3823. };
  3824. return nu$2({
  3825. readState: function () {
  3826. return dimensions.get().map(function (d) {
  3827. return {
  3828. numRows: String(d.numRows),
  3829. numColumns: String(d.numColumns)
  3830. };
  3831. }).getOr({
  3832. numRows: '?',
  3833. numColumns: '?'
  3834. });
  3835. },
  3836. setGridSize: setGridSize,
  3837. getNumRows: getNumRows,
  3838. getNumColumns: getNumColumns
  3839. });
  3840. };
  3841. var init$5 = function (spec) {
  3842. return spec.state(spec);
  3843. };
  3844. var KeyingState = /*#__PURE__*/Object.freeze({
  3845. __proto__: null,
  3846. flatgrid: flatgrid$1,
  3847. init: init$5
  3848. });
  3849. var onDirection = function (isLtr, isRtl) {
  3850. return function (element) {
  3851. return getDirection(element) === 'rtl' ? isRtl : isLtr;
  3852. };
  3853. };
  3854. var getDirection = function (element) {
  3855. return get$8(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
  3856. };
  3857. var useH = function (movement) {
  3858. return function (component, simulatedEvent, config, state) {
  3859. var move = movement(component.element);
  3860. return use(move, component, simulatedEvent, config, state);
  3861. };
  3862. };
  3863. var west = function (moveLeft, moveRight) {
  3864. var movement = onDirection(moveLeft, moveRight);
  3865. return useH(movement);
  3866. };
  3867. var east = function (moveLeft, moveRight) {
  3868. var movement = onDirection(moveRight, moveLeft);
  3869. return useH(movement);
  3870. };
  3871. var useV = function (move) {
  3872. return function (component, simulatedEvent, config, state) {
  3873. return use(move, component, simulatedEvent, config, state);
  3874. };
  3875. };
  3876. var use = function (move, component, simulatedEvent, config, state) {
  3877. var outcome = config.focusManager.get(component).bind(function (focused) {
  3878. return move(component.element, focused, config, state);
  3879. });
  3880. return outcome.map(function (newFocus) {
  3881. config.focusManager.set(component, newFocus);
  3882. return true;
  3883. });
  3884. };
  3885. var north = useV;
  3886. var south = useV;
  3887. var move$1 = useV;
  3888. var isHidden = function (dom) {
  3889. return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
  3890. };
  3891. var isVisible = function (element) {
  3892. return !isHidden(element.dom);
  3893. };
  3894. var locate = function (candidates, predicate) {
  3895. return findIndex$1(candidates, predicate).map(function (index) {
  3896. return {
  3897. index: index,
  3898. candidates: candidates
  3899. };
  3900. });
  3901. };
  3902. var locateVisible = function (container, current, selector) {
  3903. var predicate = function (x) {
  3904. return eq(x, current);
  3905. };
  3906. var candidates = descendants(container, selector);
  3907. var visible = filter$2(candidates, isVisible);
  3908. return locate(visible, predicate);
  3909. };
  3910. var findIndex = function (elements, target) {
  3911. return findIndex$1(elements, function (elem) {
  3912. return eq(target, elem);
  3913. });
  3914. };
  3915. var withGrid = function (values, index, numCols, f) {
  3916. var oldRow = Math.floor(index / numCols);
  3917. var oldColumn = index % numCols;
  3918. return f(oldRow, oldColumn).bind(function (address) {
  3919. var newIndex = address.row * numCols + address.column;
  3920. return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none();
  3921. });
  3922. };
  3923. var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) {
  3924. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3925. var onLastRow = oldRow === numRows - 1;
  3926. var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
  3927. var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
  3928. return Optional.some({
  3929. row: oldRow,
  3930. column: newColumn
  3931. });
  3932. });
  3933. };
  3934. var cycleVertical$1 = function (values, index, numRows, numCols, delta) {
  3935. return withGrid(values, index, numCols, function (oldRow, oldColumn) {
  3936. var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
  3937. var onLastRow = newRow === numRows - 1;
  3938. var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
  3939. var newCol = clamp(oldColumn, 0, colsInRow - 1);
  3940. return Optional.some({
  3941. row: newRow,
  3942. column: newCol
  3943. });
  3944. });
  3945. };
  3946. var cycleRight$1 = function (values, index, numRows, numCols) {
  3947. return cycleHorizontal$1(values, index, numRows, numCols, +1);
  3948. };
  3949. var cycleLeft$1 = function (values, index, numRows, numCols) {
  3950. return cycleHorizontal$1(values, index, numRows, numCols, -1);
  3951. };
  3952. var cycleUp$1 = function (values, index, numRows, numCols) {
  3953. return cycleVertical$1(values, index, numRows, numCols, -1);
  3954. };
  3955. var cycleDown$1 = function (values, index, numRows, numCols) {
  3956. return cycleVertical$1(values, index, numRows, numCols, +1);
  3957. };
  3958. var schema$e = [
  3959. required$1('selector'),
  3960. defaulted('execute', defaultExecute),
  3961. onKeyboardHandler('onEscape'),
  3962. defaulted('captureTab', false),
  3963. initSize()
  3964. ];
  3965. var focusIn$3 = function (component, gridConfig, _gridState) {
  3966. descendant(component.element, gridConfig.selector).each(function (first) {
  3967. gridConfig.focusManager.set(component, first);
  3968. });
  3969. };
  3970. var findCurrent$1 = function (component, gridConfig) {
  3971. return gridConfig.focusManager.get(component).bind(function (elem) {
  3972. return closest$1(elem, gridConfig.selector);
  3973. });
  3974. };
  3975. var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) {
  3976. return findCurrent$1(component, gridConfig).bind(function (focused) {
  3977. return gridConfig.execute(component, simulatedEvent, focused);
  3978. });
  3979. };
  3980. var doMove$2 = function (cycle) {
  3981. return function (element, focused, gridConfig, gridState) {
  3982. return locateVisible(element, focused, gridConfig.selector).bind(function (identified) {
  3983. return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns));
  3984. });
  3985. };
  3986. };
  3987. var handleTab = function (_component, _simulatedEvent, gridConfig) {
  3988. return gridConfig.captureTab ? Optional.some(true) : Optional.none();
  3989. };
  3990. var doEscape$1 = function (component, simulatedEvent, gridConfig) {
  3991. return gridConfig.onEscape(component, simulatedEvent);
  3992. };
  3993. var moveLeft$3 = doMove$2(cycleLeft$1);
  3994. var moveRight$3 = doMove$2(cycleRight$1);
  3995. var moveNorth$1 = doMove$2(cycleUp$1);
  3996. var moveSouth$1 = doMove$2(cycleDown$1);
  3997. var getKeydownRules$4 = constant$1([
  3998. rule(inSet(LEFT), west(moveLeft$3, moveRight$3)),
  3999. rule(inSet(RIGHT), east(moveLeft$3, moveRight$3)),
  4000. rule(inSet(UP), north(moveNorth$1)),
  4001. rule(inSet(DOWN), south(moveSouth$1)),
  4002. rule(and([
  4003. isShift,
  4004. inSet(TAB)
  4005. ]), handleTab),
  4006. rule(and([
  4007. isNotShift,
  4008. inSet(TAB)
  4009. ]), handleTab),
  4010. rule(inSet(ESCAPE), doEscape$1),
  4011. rule(inSet(SPACE.concat(ENTER)), execute$3)
  4012. ]);
  4013. var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4014. var FlatgridType = typical(schema$e, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () {
  4015. return Optional.some(focusIn$3);
  4016. });
  4017. var horizontal = function (container, selector, current, delta) {
  4018. var isDisabledButton = function (candidate) {
  4019. return name$1(candidate) === 'button' && get$b(candidate, 'disabled') === 'disabled';
  4020. };
  4021. var tryCycle = function (initial, index, candidates) {
  4022. var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
  4023. if (newIndex === initial) {
  4024. return Optional.none();
  4025. } else {
  4026. return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]);
  4027. }
  4028. };
  4029. return locateVisible(container, current, selector).bind(function (identified) {
  4030. var index = identified.index;
  4031. var candidates = identified.candidates;
  4032. return tryCycle(index, index, candidates);
  4033. });
  4034. };
  4035. var schema$d = [
  4036. required$1('selector'),
  4037. defaulted('getInitial', Optional.none),
  4038. defaulted('execute', defaultExecute),
  4039. onKeyboardHandler('onEscape'),
  4040. defaulted('executeOnMove', false),
  4041. defaulted('allowVertical', true)
  4042. ];
  4043. var findCurrent = function (component, flowConfig) {
  4044. return flowConfig.focusManager.get(component).bind(function (elem) {
  4045. return closest$1(elem, flowConfig.selector);
  4046. });
  4047. };
  4048. var execute$2 = function (component, simulatedEvent, flowConfig) {
  4049. return findCurrent(component, flowConfig).bind(function (focused) {
  4050. return flowConfig.execute(component, simulatedEvent, focused);
  4051. });
  4052. };
  4053. var focusIn$2 = function (component, flowConfig, _state) {
  4054. flowConfig.getInitial(component).orThunk(function () {
  4055. return descendant(component.element, flowConfig.selector);
  4056. }).each(function (first) {
  4057. flowConfig.focusManager.set(component, first);
  4058. });
  4059. };
  4060. var moveLeft$2 = function (element, focused, info) {
  4061. return horizontal(element, info.selector, focused, -1);
  4062. };
  4063. var moveRight$2 = function (element, focused, info) {
  4064. return horizontal(element, info.selector, focused, +1);
  4065. };
  4066. var doMove$1 = function (movement) {
  4067. return function (component, simulatedEvent, flowConfig, flowState) {
  4068. return movement(component, simulatedEvent, flowConfig, flowState).bind(function () {
  4069. return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true);
  4070. });
  4071. };
  4072. };
  4073. var doEscape = function (component, simulatedEvent, flowConfig) {
  4074. return flowConfig.onEscape(component, simulatedEvent);
  4075. };
  4076. var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) {
  4077. var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []);
  4078. var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []);
  4079. return [
  4080. rule(inSet(westMovers), doMove$1(west(moveLeft$2, moveRight$2))),
  4081. rule(inSet(eastMovers), doMove$1(east(moveLeft$2, moveRight$2))),
  4082. rule(inSet(ENTER), execute$2),
  4083. rule(inSet(SPACE), execute$2),
  4084. rule(inSet(ESCAPE), doEscape)
  4085. ];
  4086. };
  4087. var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4088. var FlowType = typical(schema$d, NoState.init, getKeydownRules$3, getKeyupRules$3, function () {
  4089. return Optional.some(focusIn$2);
  4090. });
  4091. var toCell = function (matrix, rowIndex, columnIndex) {
  4092. return Optional.from(matrix[rowIndex]).bind(function (row) {
  4093. return Optional.from(row[columnIndex]).map(function (cell) {
  4094. return {
  4095. rowIndex: rowIndex,
  4096. columnIndex: columnIndex,
  4097. cell: cell
  4098. };
  4099. });
  4100. });
  4101. };
  4102. var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4103. var row = matrix[rowIndex];
  4104. var colsInRow = row.length;
  4105. var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
  4106. return toCell(matrix, rowIndex, newColIndex);
  4107. };
  4108. var cycleVertical = function (matrix, colIndex, startRow, deltaRow) {
  4109. var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
  4110. var colsInNextRow = matrix[nextRowIndex].length;
  4111. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4112. return toCell(matrix, nextRowIndex, nextColIndex);
  4113. };
  4114. var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
  4115. var row = matrix[rowIndex];
  4116. var colsInRow = row.length;
  4117. var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1);
  4118. return toCell(matrix, rowIndex, newColIndex);
  4119. };
  4120. var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
  4121. var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1);
  4122. var colsInNextRow = matrix[nextRowIndex].length;
  4123. var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1);
  4124. return toCell(matrix, nextRowIndex, nextColIndex);
  4125. };
  4126. var cycleRight = function (matrix, startRow, startCol) {
  4127. return cycleHorizontal(matrix, startRow, startCol, +1);
  4128. };
  4129. var cycleLeft = function (matrix, startRow, startCol) {
  4130. return cycleHorizontal(matrix, startRow, startCol, -1);
  4131. };
  4132. var cycleUp = function (matrix, startRow, startCol) {
  4133. return cycleVertical(matrix, startCol, startRow, -1);
  4134. };
  4135. var cycleDown = function (matrix, startRow, startCol) {
  4136. return cycleVertical(matrix, startCol, startRow, +1);
  4137. };
  4138. var moveLeft$1 = function (matrix, startRow, startCol) {
  4139. return moveHorizontal(matrix, startRow, startCol, -1);
  4140. };
  4141. var moveRight$1 = function (matrix, startRow, startCol) {
  4142. return moveHorizontal(matrix, startRow, startCol, +1);
  4143. };
  4144. var moveUp$1 = function (matrix, startRow, startCol) {
  4145. return moveVertical(matrix, startCol, startRow, -1);
  4146. };
  4147. var moveDown$1 = function (matrix, startRow, startCol) {
  4148. return moveVertical(matrix, startCol, startRow, +1);
  4149. };
  4150. var schema$c = [
  4151. requiredObjOf('selectors', [
  4152. required$1('row'),
  4153. required$1('cell')
  4154. ]),
  4155. defaulted('cycles', true),
  4156. defaulted('previousSelector', Optional.none),
  4157. defaulted('execute', defaultExecute)
  4158. ];
  4159. var focusIn$1 = function (component, matrixConfig, _state) {
  4160. var focused = matrixConfig.previousSelector(component).orThunk(function () {
  4161. var selectors = matrixConfig.selectors;
  4162. return descendant(component.element, selectors.cell);
  4163. });
  4164. focused.each(function (cell) {
  4165. matrixConfig.focusManager.set(component, cell);
  4166. });
  4167. };
  4168. var execute$1 = function (component, simulatedEvent, matrixConfig) {
  4169. return search(component.element).bind(function (focused) {
  4170. return matrixConfig.execute(component, simulatedEvent, focused);
  4171. });
  4172. };
  4173. var toMatrix = function (rows, matrixConfig) {
  4174. return map$2(rows, function (row) {
  4175. return descendants(row, matrixConfig.selectors.cell);
  4176. });
  4177. };
  4178. var doMove = function (ifCycle, ifMove) {
  4179. return function (element, focused, matrixConfig) {
  4180. var move = matrixConfig.cycles ? ifCycle : ifMove;
  4181. return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) {
  4182. var cellsInRow = descendants(inRow, matrixConfig.selectors.cell);
  4183. return findIndex(cellsInRow, focused).bind(function (colIndex) {
  4184. var allRows = descendants(element, matrixConfig.selectors.row);
  4185. return findIndex(allRows, inRow).bind(function (rowIndex) {
  4186. var matrix = toMatrix(allRows, matrixConfig);
  4187. return move(matrix, rowIndex, colIndex).map(function (next) {
  4188. return next.cell;
  4189. });
  4190. });
  4191. });
  4192. });
  4193. };
  4194. };
  4195. var moveLeft = doMove(cycleLeft, moveLeft$1);
  4196. var moveRight = doMove(cycleRight, moveRight$1);
  4197. var moveNorth = doMove(cycleUp, moveUp$1);
  4198. var moveSouth = doMove(cycleDown, moveDown$1);
  4199. var getKeydownRules$2 = constant$1([
  4200. rule(inSet(LEFT), west(moveLeft, moveRight)),
  4201. rule(inSet(RIGHT), east(moveLeft, moveRight)),
  4202. rule(inSet(UP), north(moveNorth)),
  4203. rule(inSet(DOWN), south(moveSouth)),
  4204. rule(inSet(SPACE.concat(ENTER)), execute$1)
  4205. ]);
  4206. var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4207. var MatrixType = typical(schema$c, NoState.init, getKeydownRules$2, getKeyupRules$2, function () {
  4208. return Optional.some(focusIn$1);
  4209. });
  4210. var schema$b = [
  4211. required$1('selector'),
  4212. defaulted('execute', defaultExecute),
  4213. defaulted('moveOnTab', false)
  4214. ];
  4215. var execute = function (component, simulatedEvent, menuConfig) {
  4216. return menuConfig.focusManager.get(component).bind(function (focused) {
  4217. return menuConfig.execute(component, simulatedEvent, focused);
  4218. });
  4219. };
  4220. var focusIn = function (component, menuConfig, _state) {
  4221. descendant(component.element, menuConfig.selector).each(function (first) {
  4222. menuConfig.focusManager.set(component, first);
  4223. });
  4224. };
  4225. var moveUp = function (element, focused, info) {
  4226. return horizontal(element, info.selector, focused, -1);
  4227. };
  4228. var moveDown = function (element, focused, info) {
  4229. return horizontal(element, info.selector, focused, +1);
  4230. };
  4231. var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) {
  4232. return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4233. };
  4234. var fireTab = function (component, simulatedEvent, menuConfig, menuState) {
  4235. return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none();
  4236. };
  4237. var getKeydownRules$1 = constant$1([
  4238. rule(inSet(UP), move$1(moveUp)),
  4239. rule(inSet(DOWN), move$1(moveDown)),
  4240. rule(and([
  4241. isShift,
  4242. inSet(TAB)
  4243. ]), fireShiftTab),
  4244. rule(and([
  4245. isNotShift,
  4246. inSet(TAB)
  4247. ]), fireTab),
  4248. rule(inSet(ENTER), execute),
  4249. rule(inSet(SPACE), execute)
  4250. ]);
  4251. var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]);
  4252. var MenuType = typical(schema$b, NoState.init, getKeydownRules$1, getKeyupRules$1, function () {
  4253. return Optional.some(focusIn);
  4254. });
  4255. var schema$a = [
  4256. onKeyboardHandler('onSpace'),
  4257. onKeyboardHandler('onEnter'),
  4258. onKeyboardHandler('onShiftEnter'),
  4259. onKeyboardHandler('onLeft'),
  4260. onKeyboardHandler('onRight'),
  4261. onKeyboardHandler('onTab'),
  4262. onKeyboardHandler('onShiftTab'),
  4263. onKeyboardHandler('onUp'),
  4264. onKeyboardHandler('onDown'),
  4265. onKeyboardHandler('onEscape'),
  4266. defaulted('stopSpaceKeyup', false),
  4267. option('focusIn')
  4268. ];
  4269. var getKeydownRules = function (component, simulatedEvent, specialInfo) {
  4270. return [
  4271. rule(inSet(SPACE), specialInfo.onSpace),
  4272. rule(and([
  4273. isNotShift,
  4274. inSet(ENTER)
  4275. ]), specialInfo.onEnter),
  4276. rule(and([
  4277. isShift,
  4278. inSet(ENTER)
  4279. ]), specialInfo.onShiftEnter),
  4280. rule(and([
  4281. isShift,
  4282. inSet(TAB)
  4283. ]), specialInfo.onShiftTab),
  4284. rule(and([
  4285. isNotShift,
  4286. inSet(TAB)
  4287. ]), specialInfo.onTab),
  4288. rule(inSet(UP), specialInfo.onUp),
  4289. rule(inSet(DOWN), specialInfo.onDown),
  4290. rule(inSet(LEFT), specialInfo.onLeft),
  4291. rule(inSet(RIGHT), specialInfo.onRight),
  4292. rule(inSet(SPACE), specialInfo.onSpace),
  4293. rule(inSet(ESCAPE), specialInfo.onEscape)
  4294. ];
  4295. };
  4296. var getKeyupRules = function (component, simulatedEvent, specialInfo) {
  4297. return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : [];
  4298. };
  4299. var SpecialType = typical(schema$a, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) {
  4300. return specialInfo.focusIn;
  4301. });
  4302. var acyclic = AcyclicType.schema();
  4303. var cyclic = CyclicType.schema();
  4304. var flow = FlowType.schema();
  4305. var flatgrid = FlatgridType.schema();
  4306. var matrix = MatrixType.schema();
  4307. var execution = ExecutionType.schema();
  4308. var menu = MenuType.schema();
  4309. var special = SpecialType.schema();
  4310. var KeyboardBranches = /*#__PURE__*/Object.freeze({
  4311. __proto__: null,
  4312. acyclic: acyclic,
  4313. cyclic: cyclic,
  4314. flow: flow,
  4315. flatgrid: flatgrid,
  4316. matrix: matrix,
  4317. execution: execution,
  4318. menu: menu,
  4319. special: special
  4320. });
  4321. var isFlatgridState = function (keyState) {
  4322. return hasNonNullableKey(keyState, 'setGridSize');
  4323. };
  4324. var Keying = createModes({
  4325. branchKey: 'mode',
  4326. branches: KeyboardBranches,
  4327. name: 'keying',
  4328. active: {
  4329. events: function (keyingConfig, keyingState) {
  4330. var handler = keyingConfig.handler;
  4331. return handler.toEvents(keyingConfig, keyingState);
  4332. }
  4333. },
  4334. apis: {
  4335. focusIn: function (component, keyConfig, keyState) {
  4336. keyConfig.sendFocusIn(keyConfig).fold(function () {
  4337. component.getSystem().triggerFocus(component.element, component.element);
  4338. }, function (sendFocusIn) {
  4339. sendFocusIn(component, keyConfig, keyState);
  4340. });
  4341. },
  4342. setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
  4343. if (!isFlatgridState(keyState)) {
  4344. console.error('Layout does not support setGridSize');
  4345. } else {
  4346. keyState.setGridSize(numRows, numColumns);
  4347. }
  4348. }
  4349. },
  4350. state: KeyingState
  4351. });
  4352. var field$1 = function (name, forbidden) {
  4353. return defaultedObjOf(name, {}, map$2(forbidden, function (f) {
  4354. return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
  4355. }).concat([customField('dump', identity)]));
  4356. };
  4357. var get$6 = function (data) {
  4358. return data.dump;
  4359. };
  4360. var augment = function (data, original) {
  4361. return __assign(__assign({}, derive$2(original)), data.dump);
  4362. };
  4363. var SketchBehaviours = {
  4364. field: field$1,
  4365. augment: augment,
  4366. get: get$6
  4367. };
  4368. var _placeholder = 'placeholder';
  4369. var adt$5 = Adt.generate([
  4370. {
  4371. single: [
  4372. 'required',
  4373. 'valueThunk'
  4374. ]
  4375. },
  4376. {
  4377. multiple: [
  4378. 'required',
  4379. 'valueThunks'
  4380. ]
  4381. }
  4382. ]);
  4383. var isSubstituted = function (spec) {
  4384. return has$2(spec, 'uiType');
  4385. };
  4386. var subPlaceholder = function (owner, detail, compSpec, placeholders) {
  4387. if (owner.exists(function (o) {
  4388. return o !== compSpec.owner;
  4389. })) {
  4390. return adt$5.single(true, constant$1(compSpec));
  4391. }
  4392. return get$c(placeholders, compSpec.name).fold(function () {
  4393. throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2));
  4394. }, function (newSpec) {
  4395. return newSpec.replace();
  4396. });
  4397. };
  4398. var scan = function (owner, detail, compSpec, placeholders) {
  4399. if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) {
  4400. return subPlaceholder(owner, detail, compSpec, placeholders);
  4401. } else {
  4402. return adt$5.single(false, constant$1(compSpec));
  4403. }
  4404. };
  4405. var substitute = function (owner, detail, compSpec, placeholders) {
  4406. var base = scan(owner, detail, compSpec, placeholders);
  4407. return base.fold(function (req, valueThunk) {
  4408. var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail);
  4409. var childSpecs = get$c(value, 'components').getOr([]);
  4410. var substituted = bind$3(childSpecs, function (c) {
  4411. return substitute(owner, detail, c, placeholders);
  4412. });
  4413. return [__assign(__assign({}, value), { components: substituted })];
  4414. }, function (req, valuesThunk) {
  4415. if (isSubstituted(compSpec)) {
  4416. var values = valuesThunk(detail, compSpec.config, compSpec.validated);
  4417. var preprocessor = compSpec.validated.preprocess.getOr(identity);
  4418. return preprocessor(values);
  4419. } else {
  4420. return valuesThunk(detail);
  4421. }
  4422. });
  4423. };
  4424. var substituteAll = function (owner, detail, components, placeholders) {
  4425. return bind$3(components, function (c) {
  4426. return substitute(owner, detail, c, placeholders);
  4427. });
  4428. };
  4429. var oneReplace = function (label, replacements) {
  4430. var called = false;
  4431. var used = function () {
  4432. return called;
  4433. };
  4434. var replace = function () {
  4435. if (called) {
  4436. throw new Error('Trying to use the same placeholder more than once: ' + label);
  4437. }
  4438. called = true;
  4439. return replacements;
  4440. };
  4441. var required = function () {
  4442. return replacements.fold(function (req, _) {
  4443. return req;
  4444. }, function (req, _) {
  4445. return req;
  4446. });
  4447. };
  4448. return {
  4449. name: constant$1(label),
  4450. required: required,
  4451. used: used,
  4452. replace: replace
  4453. };
  4454. };
  4455. var substitutePlaces = function (owner, detail, components, placeholders) {
  4456. var ps = map$1(placeholders, function (ph, name) {
  4457. return oneReplace(name, ph);
  4458. });
  4459. var outcome = substituteAll(owner, detail, components, ps);
  4460. each(ps, function (p) {
  4461. if (p.used() === false && p.required()) {
  4462. throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2));
  4463. }
  4464. });
  4465. return outcome;
  4466. };
  4467. var single$2 = adt$5.single;
  4468. var multiple = adt$5.multiple;
  4469. var placeholder = constant$1(_placeholder);
  4470. var unique = 0;
  4471. var generate$4 = function (prefix) {
  4472. var date = new Date();
  4473. var time = date.getTime();
  4474. var random = Math.floor(Math.random() * 1000000000);
  4475. unique++;
  4476. return prefix + '_' + random + unique + String(time);
  4477. };
  4478. var adt$4 = Adt.generate([
  4479. { required: ['data'] },
  4480. { external: ['data'] },
  4481. { optional: ['data'] },
  4482. { group: ['data'] }
  4483. ]);
  4484. var fFactory = defaulted('factory', { sketch: identity });
  4485. var fSchema = defaulted('schema', []);
  4486. var fName = required$1('name');
  4487. var fPname = field$2('pname', 'pname', defaultedThunk(function (typeSpec) {
  4488. return '<alloy.' + generate$4(typeSpec.name) + '>';
  4489. }), anyValue());
  4490. var fGroupSchema = customField('schema', function () {
  4491. return [option('preprocess')];
  4492. });
  4493. var fDefaults = defaulted('defaults', constant$1({}));
  4494. var fOverrides = defaulted('overrides', constant$1({}));
  4495. var requiredSpec = objOf([
  4496. fFactory,
  4497. fSchema,
  4498. fName,
  4499. fPname,
  4500. fDefaults,
  4501. fOverrides
  4502. ]);
  4503. var externalSpec = objOf([
  4504. fFactory,
  4505. fSchema,
  4506. fName,
  4507. fDefaults,
  4508. fOverrides
  4509. ]);
  4510. var optionalSpec = objOf([
  4511. fFactory,
  4512. fSchema,
  4513. fName,
  4514. fPname,
  4515. fDefaults,
  4516. fOverrides
  4517. ]);
  4518. var groupSpec = objOf([
  4519. fFactory,
  4520. fGroupSchema,
  4521. fName,
  4522. required$1('unit'),
  4523. fPname,
  4524. fDefaults,
  4525. fOverrides
  4526. ]);
  4527. var asNamedPart = function (part) {
  4528. return part.fold(Optional.some, Optional.none, Optional.some, Optional.some);
  4529. };
  4530. var name = function (part) {
  4531. var get = function (data) {
  4532. return data.name;
  4533. };
  4534. return part.fold(get, get, get, get);
  4535. };
  4536. var convert$1 = function (adtConstructor, partSchema) {
  4537. return function (spec) {
  4538. var data = asRawOrDie$1('Converting part type', partSchema, spec);
  4539. return adtConstructor(data);
  4540. };
  4541. };
  4542. var required = convert$1(adt$4.required, requiredSpec);
  4543. convert$1(adt$4.external, externalSpec);
  4544. var optional = convert$1(adt$4.optional, optionalSpec);
  4545. var group = convert$1(adt$4.group, groupSpec);
  4546. var original = constant$1('entirety');
  4547. var combine$2 = function (detail, data, partSpec, partValidated) {
  4548. return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated));
  4549. };
  4550. var subs = function (owner, detail, parts) {
  4551. var internals = {};
  4552. var externals = {};
  4553. each$1(parts, function (part) {
  4554. part.fold(function (data) {
  4555. internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) {
  4556. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  4557. });
  4558. }, function (data) {
  4559. var partSpec = detail.parts[data.name];
  4560. externals[data.name] = constant$1(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec));
  4561. }, function (data) {
  4562. internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) {
  4563. return data.factory.sketch(combine$2(detail, data, partSpec, partValidated));
  4564. });
  4565. }, function (data) {
  4566. internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) {
  4567. var units = detail[data.name];
  4568. return map$2(units, function (u) {
  4569. return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u)));
  4570. });
  4571. });
  4572. });
  4573. });
  4574. return {
  4575. internals: constant$1(internals),
  4576. externals: constant$1(externals)
  4577. };
  4578. };
  4579. var generate$3 = function (owner, parts) {
  4580. var r = {};
  4581. each$1(parts, function (part) {
  4582. asNamedPart(part).each(function (np) {
  4583. var g = doGenerateOne(owner, np.pname);
  4584. r[np.name] = function (config) {
  4585. var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config);
  4586. return __assign(__assign({}, g), {
  4587. config: config,
  4588. validated: validated
  4589. });
  4590. };
  4591. });
  4592. });
  4593. return r;
  4594. };
  4595. var doGenerateOne = function (owner, pname) {
  4596. return {
  4597. uiType: placeholder(),
  4598. owner: owner,
  4599. name: pname
  4600. };
  4601. };
  4602. var generateOne = function (owner, pname, config) {
  4603. return {
  4604. uiType: placeholder(),
  4605. owner: owner,
  4606. name: pname,
  4607. config: config,
  4608. validated: {}
  4609. };
  4610. };
  4611. var schemas = function (parts) {
  4612. return bind$3(parts, function (part) {
  4613. return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) {
  4614. return requiredObjOf(data.name, data.schema.concat([snapshot(original())]));
  4615. }).toArray();
  4616. });
  4617. };
  4618. var names = function (parts) {
  4619. return map$2(parts, name);
  4620. };
  4621. var substitutes = function (owner, detail, parts) {
  4622. return subs(owner, detail, parts);
  4623. };
  4624. var components = function (owner, detail, internals) {
  4625. return substitutePlaces(Optional.some(owner), detail, detail.components, internals);
  4626. };
  4627. var getPart = function (component, detail, partKey) {
  4628. var uid = detail.partUids[partKey];
  4629. return component.getSystem().getByUid(uid).toOptional();
  4630. };
  4631. var getPartOrDie = function (component, detail, partKey) {
  4632. return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
  4633. };
  4634. var getAllParts = function (component, detail) {
  4635. var system = component.getSystem();
  4636. return map$1(detail.partUids, function (pUid, _k) {
  4637. return constant$1(system.getByUid(pUid));
  4638. });
  4639. };
  4640. var defaultUids = function (baseUid, partTypes) {
  4641. var partNames = names(partTypes);
  4642. return wrapAll(map$2(partNames, function (pn) {
  4643. return {
  4644. key: pn,
  4645. value: baseUid + '-' + pn
  4646. };
  4647. }));
  4648. };
  4649. var defaultUidsSchema = function (partTypes) {
  4650. return field$2('partUids', 'partUids', mergeWithThunk(function (spec) {
  4651. return defaultUids(spec.uid, partTypes);
  4652. }), anyValue());
  4653. };
  4654. var premadeTag = generate$4('alloy-premade');
  4655. var premade$1 = function (comp) {
  4656. return wrap(premadeTag, comp);
  4657. };
  4658. var getPremade = function (spec) {
  4659. return get$c(spec, premadeTag);
  4660. };
  4661. var makeApi = function (f) {
  4662. return markAsSketchApi(function (component) {
  4663. var rest = [];
  4664. for (var _i = 1; _i < arguments.length; _i++) {
  4665. rest[_i - 1] = arguments[_i];
  4666. }
  4667. return f.apply(void 0, __spreadArray([
  4668. component.getApis(),
  4669. component
  4670. ], rest, false));
  4671. }, f);
  4672. };
  4673. var prefix$1 = constant$1('alloy-id-');
  4674. var idAttr$1 = constant$1('data-alloy-id');
  4675. var prefix = prefix$1();
  4676. var idAttr = idAttr$1();
  4677. var write = function (label, elem) {
  4678. var id = generate$4(prefix + label);
  4679. writeOnly(elem, id);
  4680. return id;
  4681. };
  4682. var writeOnly = function (elem, uid) {
  4683. Object.defineProperty(elem.dom, idAttr, {
  4684. value: uid,
  4685. writable: true
  4686. });
  4687. };
  4688. var read = function (elem) {
  4689. var id = isElement(elem) ? elem.dom[idAttr] : null;
  4690. return Optional.from(id);
  4691. };
  4692. var generate$2 = function (prefix) {
  4693. return generate$4(prefix);
  4694. };
  4695. var base = function (partSchemas, partUidsSchemas) {
  4696. var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : [];
  4697. return ps.concat([
  4698. required$1('uid'),
  4699. defaulted('dom', {}),
  4700. defaulted('components', []),
  4701. snapshot('originalSpec'),
  4702. defaulted('debug.sketcher', {})
  4703. ]).concat(partUidsSchemas);
  4704. };
  4705. var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) {
  4706. var baseS = base(partSchemas, partUidsSchemas);
  4707. return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
  4708. };
  4709. var single$1 = function (owner, schema, factory, spec) {
  4710. var specWithUid = supplyUid(spec);
  4711. var detail = asRawOrDie(owner, schema, specWithUid, [], []);
  4712. return factory(detail, specWithUid);
  4713. };
  4714. var composite$1 = function (owner, schema, partTypes, factory, spec) {
  4715. var specWithUid = supplyUid(spec);
  4716. var partSchemas = schemas(partTypes);
  4717. var partUidsSchema = defaultUidsSchema(partTypes);
  4718. var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
  4719. var subs = substitutes(owner, detail, partTypes);
  4720. var components$1 = components(owner, detail, subs.internals());
  4721. return factory(detail, components$1, specWithUid, subs.externals());
  4722. };
  4723. var hasUid = function (spec) {
  4724. return has$2(spec, 'uid');
  4725. };
  4726. var supplyUid = function (spec) {
  4727. return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') });
  4728. };
  4729. var isSketchSpec$1 = function (spec) {
  4730. return spec.uid !== undefined;
  4731. };
  4732. var singleSchema = objOfOnly([
  4733. required$1('name'),
  4734. required$1('factory'),
  4735. required$1('configFields'),
  4736. defaulted('apis', {}),
  4737. defaulted('extraApis', {})
  4738. ]);
  4739. var compositeSchema = objOfOnly([
  4740. required$1('name'),
  4741. required$1('factory'),
  4742. required$1('configFields'),
  4743. required$1('partFields'),
  4744. defaulted('apis', {}),
  4745. defaulted('extraApis', {})
  4746. ]);
  4747. var single = function (rawConfig) {
  4748. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
  4749. var sketch = function (spec) {
  4750. return single$1(config.name, config.configFields, config.factory, spec);
  4751. };
  4752. var apis = map$1(config.apis, makeApi);
  4753. var extraApis = map$1(config.extraApis, function (f, k) {
  4754. return markAsExtraApi(f, k);
  4755. });
  4756. return __assign(__assign({
  4757. name: config.name,
  4758. configFields: config.configFields,
  4759. sketch: sketch
  4760. }, apis), extraApis);
  4761. };
  4762. var composite = function (rawConfig) {
  4763. var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
  4764. var sketch = function (spec) {
  4765. return composite$1(config.name, config.configFields, config.partFields, config.factory, spec);
  4766. };
  4767. var parts = generate$3(config.name, config.partFields);
  4768. var apis = map$1(config.apis, makeApi);
  4769. var extraApis = map$1(config.extraApis, function (f, k) {
  4770. return markAsExtraApi(f, k);
  4771. });
  4772. return __assign(__assign({
  4773. name: config.name,
  4774. partFields: config.partFields,
  4775. configFields: config.configFields,
  4776. sketch: sketch,
  4777. parts: parts
  4778. }, apis), extraApis);
  4779. };
  4780. var factory$5 = function (detail) {
  4781. var events = events$8(detail.action);
  4782. var tag = detail.dom.tag;
  4783. var lookupAttr = function (attr) {
  4784. return get$c(detail.dom, 'attributes').bind(function (attrs) {
  4785. return get$c(attrs, attr);
  4786. });
  4787. };
  4788. var getModAttributes = function () {
  4789. if (tag === 'button') {
  4790. var type = lookupAttr('type').getOr('button');
  4791. var roleAttrs = lookupAttr('role').map(function (role) {
  4792. return { role: role };
  4793. }).getOr({});
  4794. return __assign({ type: type }, roleAttrs);
  4795. } else {
  4796. var role = lookupAttr('role').getOr('button');
  4797. return { role: role };
  4798. }
  4799. };
  4800. return {
  4801. uid: detail.uid,
  4802. dom: detail.dom,
  4803. components: detail.components,
  4804. events: events,
  4805. behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [
  4806. Focusing.config({}),
  4807. Keying.config({
  4808. mode: 'execution',
  4809. useSpace: true,
  4810. useEnter: true
  4811. })
  4812. ]),
  4813. domModification: { attributes: getModAttributes() },
  4814. eventOrder: detail.eventOrder
  4815. };
  4816. };
  4817. var Button = single({
  4818. name: 'Button',
  4819. factory: factory$5,
  4820. configFields: [
  4821. defaulted('uid', undefined),
  4822. required$1('dom'),
  4823. defaulted('components', []),
  4824. SketchBehaviours.field('buttonBehaviours', [
  4825. Focusing,
  4826. Keying
  4827. ]),
  4828. option('action'),
  4829. option('role'),
  4830. defaulted('eventOrder', {})
  4831. ]
  4832. });
  4833. var exhibit$3 = function () {
  4834. return nu$3({
  4835. styles: {
  4836. '-webkit-user-select': 'none',
  4837. 'user-select': 'none',
  4838. '-ms-user-select': 'none',
  4839. '-moz-user-select': '-moz-none'
  4840. },
  4841. attributes: { unselectable: 'on' }
  4842. });
  4843. };
  4844. var events$6 = function () {
  4845. return derive$3([abort(selectstart(), always)]);
  4846. };
  4847. var ActiveUnselecting = /*#__PURE__*/Object.freeze({
  4848. __proto__: null,
  4849. events: events$6,
  4850. exhibit: exhibit$3
  4851. });
  4852. var Unselecting = create$5({
  4853. fields: [],
  4854. name: 'unselecting',
  4855. active: ActiveUnselecting
  4856. });
  4857. var getAttrs$1 = function (elem) {
  4858. var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : [];
  4859. return foldl(attributes, function (b, attr) {
  4860. var _a;
  4861. if (attr.name === 'class') {
  4862. return b;
  4863. } else {
  4864. return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a));
  4865. }
  4866. }, {});
  4867. };
  4868. var getClasses = function (elem) {
  4869. return Array.prototype.slice.call(elem.dom.classList, 0);
  4870. };
  4871. var fromHtml = function (html) {
  4872. var elem = SugarElement.fromHtml(html);
  4873. var children$1 = children(elem);
  4874. var attrs = getAttrs$1(elem);
  4875. var classes = getClasses(elem);
  4876. var contents = children$1.length === 0 ? {} : { innerHtml: get$9(elem) };
  4877. return __assign({
  4878. tag: name$1(elem),
  4879. classes: classes,
  4880. attributes: attrs
  4881. }, contents);
  4882. };
  4883. var dom$1 = function (rawHtml) {
  4884. var html = supplant(rawHtml, { prefix: prefix$2 });
  4885. return fromHtml(html);
  4886. };
  4887. var spec = function (rawHtml) {
  4888. return { dom: dom$1(rawHtml) };
  4889. };
  4890. var forToolbarCommand = function (editor, command) {
  4891. return forToolbar(command, function () {
  4892. editor.execCommand(command);
  4893. }, {}, editor);
  4894. };
  4895. var getToggleBehaviours = function (command) {
  4896. return derive$2([
  4897. Toggling.config({
  4898. toggleClass: resolve('toolbar-button-selected'),
  4899. toggleOnExecute: false,
  4900. aria: { mode: 'pressed' }
  4901. }),
  4902. format(command, function (button, status) {
  4903. var toggle = status ? Toggling.on : Toggling.off;
  4904. toggle(button);
  4905. })
  4906. ]);
  4907. };
  4908. var forToolbarStateCommand = function (editor, command) {
  4909. var extraBehaviours = getToggleBehaviours(command);
  4910. return forToolbar(command, function () {
  4911. editor.execCommand(command);
  4912. }, extraBehaviours, editor);
  4913. };
  4914. var forToolbarStateAction = function (editor, clazz, command, action) {
  4915. var extraBehaviours = getToggleBehaviours(command);
  4916. return forToolbar(clazz, action, extraBehaviours, editor);
  4917. };
  4918. var getToolbarIconButton = function (clazz, editor) {
  4919. var icons = editor.ui.registry.getAll().icons;
  4920. var optOxideIcon = Optional.from(icons[clazz]);
  4921. return optOxideIcon.fold(function () {
  4922. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>');
  4923. }, function (icon) {
  4924. return dom$1('<span class="${prefix}-toolbar-button ${prefix}-toolbar-group-item">' + icon + '</span>');
  4925. });
  4926. };
  4927. var forToolbar = function (clazz, action, extraBehaviours, editor) {
  4928. return Button.sketch({
  4929. dom: getToolbarIconButton(clazz, editor),
  4930. action: action,
  4931. buttonBehaviours: deepMerge(derive$2([Unselecting.config({})]), extraBehaviours)
  4932. });
  4933. };
  4934. var labelPart = optional({
  4935. schema: [required$1('dom')],
  4936. name: 'label'
  4937. });
  4938. var edgePart = function (name) {
  4939. return optional({
  4940. name: '' + name + '-edge',
  4941. overrides: function (detail) {
  4942. var action = detail.model.manager.edgeActions[name];
  4943. return action.fold(function () {
  4944. return {};
  4945. }, function (a) {
  4946. return {
  4947. events: derive$3([
  4948. runActionExtra(touchstart(), function (comp, se, d) {
  4949. return a(comp, d);
  4950. }, [detail]),
  4951. runActionExtra(mousedown(), function (comp, se, d) {
  4952. return a(comp, d);
  4953. }, [detail]),
  4954. runActionExtra(mousemove(), function (comp, se, det) {
  4955. if (det.mouseIsDown.get()) {
  4956. a(comp, det);
  4957. }
  4958. }, [detail])
  4959. ])
  4960. };
  4961. });
  4962. }
  4963. });
  4964. };
  4965. var tlEdgePart = edgePart('top-left');
  4966. var tedgePart = edgePart('top');
  4967. var trEdgePart = edgePart('top-right');
  4968. var redgePart = edgePart('right');
  4969. var brEdgePart = edgePart('bottom-right');
  4970. var bedgePart = edgePart('bottom');
  4971. var blEdgePart = edgePart('bottom-left');
  4972. var ledgePart = edgePart('left');
  4973. var thumbPart = required({
  4974. name: 'thumb',
  4975. defaults: constant$1({ dom: { styles: { position: 'absolute' } } }),
  4976. overrides: function (detail) {
  4977. return {
  4978. events: derive$3([
  4979. redirectToPart(touchstart(), detail, 'spectrum'),
  4980. redirectToPart(touchmove(), detail, 'spectrum'),
  4981. redirectToPart(touchend(), detail, 'spectrum'),
  4982. redirectToPart(mousedown(), detail, 'spectrum'),
  4983. redirectToPart(mousemove(), detail, 'spectrum'),
  4984. redirectToPart(mouseup(), detail, 'spectrum')
  4985. ])
  4986. };
  4987. }
  4988. });
  4989. var spectrumPart = required({
  4990. schema: [customField('mouseIsDown', function () {
  4991. return Cell(false);
  4992. })],
  4993. name: 'spectrum',
  4994. overrides: function (detail) {
  4995. var modelDetail = detail.model;
  4996. var model = modelDetail.manager;
  4997. var setValueFrom = function (component, simulatedEvent) {
  4998. return model.getValueFromEvent(simulatedEvent).map(function (value) {
  4999. return model.setValueFrom(component, detail, value);
  5000. });
  5001. };
  5002. return {
  5003. behaviours: derive$2([
  5004. Keying.config({
  5005. mode: 'special',
  5006. onLeft: function (spectrum) {
  5007. return model.onLeft(spectrum, detail);
  5008. },
  5009. onRight: function (spectrum) {
  5010. return model.onRight(spectrum, detail);
  5011. },
  5012. onUp: function (spectrum) {
  5013. return model.onUp(spectrum, detail);
  5014. },
  5015. onDown: function (spectrum) {
  5016. return model.onDown(spectrum, detail);
  5017. }
  5018. }),
  5019. Focusing.config({})
  5020. ]),
  5021. events: derive$3([
  5022. run(touchstart(), setValueFrom),
  5023. run(touchmove(), setValueFrom),
  5024. run(mousedown(), setValueFrom),
  5025. run(mousemove(), function (spectrum, se) {
  5026. if (detail.mouseIsDown.get()) {
  5027. setValueFrom(spectrum, se);
  5028. }
  5029. })
  5030. ])
  5031. };
  5032. }
  5033. });
  5034. var SliderParts = [
  5035. labelPart,
  5036. ledgePart,
  5037. redgePart,
  5038. tedgePart,
  5039. bedgePart,
  5040. tlEdgePart,
  5041. trEdgePart,
  5042. blEdgePart,
  5043. brEdgePart,
  5044. thumbPart,
  5045. spectrumPart
  5046. ];
  5047. var onLoad$4 = function (component, repConfig, repState) {
  5048. repConfig.store.manager.onLoad(component, repConfig, repState);
  5049. };
  5050. var onUnload$2 = function (component, repConfig, repState) {
  5051. repConfig.store.manager.onUnload(component, repConfig, repState);
  5052. };
  5053. var setValue$3 = function (component, repConfig, repState, data) {
  5054. repConfig.store.manager.setValue(component, repConfig, repState, data);
  5055. };
  5056. var getValue$4 = function (component, repConfig, repState) {
  5057. return repConfig.store.manager.getValue(component, repConfig, repState);
  5058. };
  5059. var getState$1 = function (component, repConfig, repState) {
  5060. return repState;
  5061. };
  5062. var RepresentApis = /*#__PURE__*/Object.freeze({
  5063. __proto__: null,
  5064. onLoad: onLoad$4,
  5065. onUnload: onUnload$2,
  5066. setValue: setValue$3,
  5067. getValue: getValue$4,
  5068. getState: getState$1
  5069. });
  5070. var events$5 = function (repConfig, repState) {
  5071. var es = repConfig.resetOnDom ? [
  5072. runOnAttached(function (comp, _se) {
  5073. onLoad$4(comp, repConfig, repState);
  5074. }),
  5075. runOnDetached(function (comp, _se) {
  5076. onUnload$2(comp, repConfig, repState);
  5077. })
  5078. ] : [loadEvent(repConfig, repState, onLoad$4)];
  5079. return derive$3(es);
  5080. };
  5081. var ActiveRepresenting = /*#__PURE__*/Object.freeze({
  5082. __proto__: null,
  5083. events: events$5
  5084. });
  5085. var memory = function () {
  5086. var data = Cell(null);
  5087. var readState = function () {
  5088. return {
  5089. mode: 'memory',
  5090. value: data.get()
  5091. };
  5092. };
  5093. var isNotSet = function () {
  5094. return data.get() === null;
  5095. };
  5096. var clear = function () {
  5097. data.set(null);
  5098. };
  5099. return nu$2({
  5100. set: data.set,
  5101. get: data.get,
  5102. isNotSet: isNotSet,
  5103. clear: clear,
  5104. readState: readState
  5105. });
  5106. };
  5107. var manual = function () {
  5108. var readState = noop;
  5109. return nu$2({ readState: readState });
  5110. };
  5111. var dataset = function () {
  5112. var dataByValue = Cell({});
  5113. var dataByText = Cell({});
  5114. var readState = function () {
  5115. return {
  5116. mode: 'dataset',
  5117. dataByValue: dataByValue.get(),
  5118. dataByText: dataByText.get()
  5119. };
  5120. };
  5121. var clear = function () {
  5122. dataByValue.set({});
  5123. dataByText.set({});
  5124. };
  5125. var lookup = function (itemString) {
  5126. return get$c(dataByValue.get(), itemString).orThunk(function () {
  5127. return get$c(dataByText.get(), itemString);
  5128. });
  5129. };
  5130. var update = function (items) {
  5131. var currentDataByValue = dataByValue.get();
  5132. var currentDataByText = dataByText.get();
  5133. var newDataByValue = {};
  5134. var newDataByText = {};
  5135. each$1(items, function (item) {
  5136. newDataByValue[item.value] = item;
  5137. get$c(item, 'meta').each(function (meta) {
  5138. get$c(meta, 'text').each(function (text) {
  5139. newDataByText[text] = item;
  5140. });
  5141. });
  5142. });
  5143. dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue));
  5144. dataByText.set(__assign(__assign({}, currentDataByText), newDataByText));
  5145. };
  5146. return nu$2({
  5147. readState: readState,
  5148. lookup: lookup,
  5149. update: update,
  5150. clear: clear
  5151. });
  5152. };
  5153. var init$4 = function (spec) {
  5154. return spec.store.manager.state(spec);
  5155. };
  5156. var RepresentState = /*#__PURE__*/Object.freeze({
  5157. __proto__: null,
  5158. memory: memory,
  5159. dataset: dataset,
  5160. manual: manual,
  5161. init: init$4
  5162. });
  5163. var setValue$2 = function (component, repConfig, repState, data) {
  5164. var store = repConfig.store;
  5165. repState.update([data]);
  5166. store.setValue(component, data);
  5167. repConfig.onSetValue(component, data);
  5168. };
  5169. var getValue$3 = function (component, repConfig, repState) {
  5170. var store = repConfig.store;
  5171. var key = store.getDataKey(component);
  5172. return repState.lookup(key).getOrThunk(function () {
  5173. return store.getFallbackEntry(key);
  5174. });
  5175. };
  5176. var onLoad$3 = function (component, repConfig, repState) {
  5177. var store = repConfig.store;
  5178. store.initialValue.each(function (data) {
  5179. setValue$2(component, repConfig, repState, data);
  5180. });
  5181. };
  5182. var onUnload$1 = function (component, repConfig, repState) {
  5183. repState.clear();
  5184. };
  5185. var DatasetStore = [
  5186. option('initialValue'),
  5187. required$1('getFallbackEntry'),
  5188. required$1('getDataKey'),
  5189. required$1('setValue'),
  5190. output('manager', {
  5191. setValue: setValue$2,
  5192. getValue: getValue$3,
  5193. onLoad: onLoad$3,
  5194. onUnload: onUnload$1,
  5195. state: dataset
  5196. })
  5197. ];
  5198. var getValue$2 = function (component, repConfig, _repState) {
  5199. return repConfig.store.getValue(component);
  5200. };
  5201. var setValue$1 = function (component, repConfig, _repState, data) {
  5202. repConfig.store.setValue(component, data);
  5203. repConfig.onSetValue(component, data);
  5204. };
  5205. var onLoad$2 = function (component, repConfig, _repState) {
  5206. repConfig.store.initialValue.each(function (data) {
  5207. repConfig.store.setValue(component, data);
  5208. });
  5209. };
  5210. var ManualStore = [
  5211. required$1('getValue'),
  5212. defaulted('setValue', noop),
  5213. option('initialValue'),
  5214. output('manager', {
  5215. setValue: setValue$1,
  5216. getValue: getValue$2,
  5217. onLoad: onLoad$2,
  5218. onUnload: noop,
  5219. state: NoState.init
  5220. })
  5221. ];
  5222. var setValue = function (component, repConfig, repState, data) {
  5223. repState.set(data);
  5224. repConfig.onSetValue(component, data);
  5225. };
  5226. var getValue$1 = function (component, repConfig, repState) {
  5227. return repState.get();
  5228. };
  5229. var onLoad$1 = function (component, repConfig, repState) {
  5230. repConfig.store.initialValue.each(function (initVal) {
  5231. if (repState.isNotSet()) {
  5232. repState.set(initVal);
  5233. }
  5234. });
  5235. };
  5236. var onUnload = function (component, repConfig, repState) {
  5237. repState.clear();
  5238. };
  5239. var MemoryStore = [
  5240. option('initialValue'),
  5241. output('manager', {
  5242. setValue: setValue,
  5243. getValue: getValue$1,
  5244. onLoad: onLoad$1,
  5245. onUnload: onUnload,
  5246. state: memory
  5247. })
  5248. ];
  5249. var RepresentSchema = [
  5250. defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
  5251. memory: MemoryStore,
  5252. manual: ManualStore,
  5253. dataset: DatasetStore
  5254. })),
  5255. onHandler('onSetValue'),
  5256. defaulted('resetOnDom', false)
  5257. ];
  5258. var Representing = create$5({
  5259. fields: RepresentSchema,
  5260. name: 'representing',
  5261. active: ActiveRepresenting,
  5262. apis: RepresentApis,
  5263. extra: {
  5264. setValueFrom: function (component, source) {
  5265. var value = Representing.getValue(source);
  5266. Representing.setValue(component, value);
  5267. }
  5268. },
  5269. state: RepresentState
  5270. });
  5271. var api$1 = Dimension('width', function (element) {
  5272. return element.dom.offsetWidth;
  5273. });
  5274. var set$4 = function (element, h) {
  5275. return api$1.set(element, h);
  5276. };
  5277. var get$5 = function (element) {
  5278. return api$1.get(element);
  5279. };
  5280. var r$1 = function (left, top) {
  5281. var translate = function (x, y) {
  5282. return r$1(left + x, top + y);
  5283. };
  5284. return {
  5285. left: left,
  5286. top: top,
  5287. translate: translate
  5288. };
  5289. };
  5290. var SugarPosition = r$1;
  5291. var _sliderChangeEvent = 'slider.change.value';
  5292. var sliderChangeEvent = constant$1(_sliderChangeEvent);
  5293. var isTouchEvent = function (evt) {
  5294. return evt.type.indexOf('touch') !== -1;
  5295. };
  5296. var getEventSource = function (simulatedEvent) {
  5297. var evt = simulatedEvent.event.raw;
  5298. if (isTouchEvent(evt)) {
  5299. var touchEvent = evt;
  5300. return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) {
  5301. return SugarPosition(t.clientX, t.clientY);
  5302. }) : Optional.none();
  5303. } else {
  5304. var mouseEvent = evt;
  5305. return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) {
  5306. return SugarPosition(me.clientX, me.clientY);
  5307. }) : Optional.none();
  5308. }
  5309. };
  5310. var t = 'top', r = 'right', b = 'bottom', l = 'left';
  5311. var minX = function (detail) {
  5312. return detail.model.minX;
  5313. };
  5314. var minY = function (detail) {
  5315. return detail.model.minY;
  5316. };
  5317. var min1X = function (detail) {
  5318. return detail.model.minX - 1;
  5319. };
  5320. var min1Y = function (detail) {
  5321. return detail.model.minY - 1;
  5322. };
  5323. var maxX = function (detail) {
  5324. return detail.model.maxX;
  5325. };
  5326. var maxY = function (detail) {
  5327. return detail.model.maxY;
  5328. };
  5329. var max1X = function (detail) {
  5330. return detail.model.maxX + 1;
  5331. };
  5332. var max1Y = function (detail) {
  5333. return detail.model.maxY + 1;
  5334. };
  5335. var range$1 = function (detail, max, min) {
  5336. return max(detail) - min(detail);
  5337. };
  5338. var xRange = function (detail) {
  5339. return range$1(detail, maxX, minX);
  5340. };
  5341. var yRange = function (detail) {
  5342. return range$1(detail, maxY, minY);
  5343. };
  5344. var halfX = function (detail) {
  5345. return xRange(detail) / 2;
  5346. };
  5347. var halfY = function (detail) {
  5348. return yRange(detail) / 2;
  5349. };
  5350. var step = function (detail) {
  5351. return detail.stepSize;
  5352. };
  5353. var snap = function (detail) {
  5354. return detail.snapToGrid;
  5355. };
  5356. var snapStart = function (detail) {
  5357. return detail.snapStart;
  5358. };
  5359. var rounded = function (detail) {
  5360. return detail.rounded;
  5361. };
  5362. var hasEdge = function (detail, edgeName) {
  5363. return detail[edgeName + '-edge'] !== undefined;
  5364. };
  5365. var hasLEdge = function (detail) {
  5366. return hasEdge(detail, l);
  5367. };
  5368. var hasREdge = function (detail) {
  5369. return hasEdge(detail, r);
  5370. };
  5371. var hasTEdge = function (detail) {
  5372. return hasEdge(detail, t);
  5373. };
  5374. var hasBEdge = function (detail) {
  5375. return hasEdge(detail, b);
  5376. };
  5377. var currentValue = function (detail) {
  5378. return detail.model.value.get();
  5379. };
  5380. var xValue = function (x) {
  5381. return { x: x };
  5382. };
  5383. var yValue = function (y) {
  5384. return { y: y };
  5385. };
  5386. var xyValue = function (x, y) {
  5387. return {
  5388. x: x,
  5389. y: y
  5390. };
  5391. };
  5392. var fireSliderChange$3 = function (component, value) {
  5393. emitWith(component, sliderChangeEvent(), { value: value });
  5394. };
  5395. var setToTLEdgeXY = function (edge, detail) {
  5396. fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail)));
  5397. };
  5398. var setToTEdge = function (edge, detail) {
  5399. fireSliderChange$3(edge, yValue(min1Y(detail)));
  5400. };
  5401. var setToTEdgeXY = function (edge, detail) {
  5402. fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail)));
  5403. };
  5404. var setToTREdgeXY = function (edge, detail) {
  5405. fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail)));
  5406. };
  5407. var setToREdge = function (edge, detail) {
  5408. fireSliderChange$3(edge, xValue(max1X(detail)));
  5409. };
  5410. var setToREdgeXY = function (edge, detail) {
  5411. fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail)));
  5412. };
  5413. var setToBREdgeXY = function (edge, detail) {
  5414. fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail)));
  5415. };
  5416. var setToBEdge = function (edge, detail) {
  5417. fireSliderChange$3(edge, yValue(max1Y(detail)));
  5418. };
  5419. var setToBEdgeXY = function (edge, detail) {
  5420. fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail)));
  5421. };
  5422. var setToBLEdgeXY = function (edge, detail) {
  5423. fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail)));
  5424. };
  5425. var setToLEdge = function (edge, detail) {
  5426. fireSliderChange$3(edge, xValue(min1X(detail)));
  5427. };
  5428. var setToLEdgeXY = function (edge, detail) {
  5429. fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail)));
  5430. };
  5431. var reduceBy = function (value, min, max, step) {
  5432. if (value < min) {
  5433. return value;
  5434. } else if (value > max) {
  5435. return max;
  5436. } else if (value === min) {
  5437. return min - 1;
  5438. } else {
  5439. return Math.max(min, value - step);
  5440. }
  5441. };
  5442. var increaseBy = function (value, min, max, step) {
  5443. if (value > max) {
  5444. return value;
  5445. } else if (value < min) {
  5446. return min;
  5447. } else if (value === max) {
  5448. return max + 1;
  5449. } else {
  5450. return Math.min(max, value + step);
  5451. }
  5452. };
  5453. var capValue = function (value, min, max) {
  5454. return Math.max(min, Math.min(max, value));
  5455. };
  5456. var snapValueOf = function (value, min, max, step, snapStart) {
  5457. return snapStart.fold(function () {
  5458. var initValue = value - min;
  5459. var extraValue = Math.round(initValue / step) * step;
  5460. return capValue(min + extraValue, min - 1, max + 1);
  5461. }, function (start) {
  5462. var remainder = (value - start) % step;
  5463. var adjustment = Math.round(remainder / step);
  5464. var rawSteps = Math.floor((value - start) / step);
  5465. var maxSteps = Math.floor((max - start) / step);
  5466. var numSteps = Math.min(maxSteps, rawSteps + adjustment);
  5467. var r = start + numSteps * step;
  5468. return Math.max(start, r);
  5469. });
  5470. };
  5471. var findOffsetOf = function (value, min, max) {
  5472. return Math.min(max, Math.max(value, min)) - min;
  5473. };
  5474. var findValueOf = function (args) {
  5475. var min = args.min, max = args.max, range = args.range, value = args.value, step = args.step, snap = args.snap, snapStart = args.snapStart, rounded = args.rounded, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, minBound = args.minBound, maxBound = args.maxBound, screenRange = args.screenRange;
  5476. var capMin = hasMinEdge ? min - 1 : min;
  5477. var capMax = hasMaxEdge ? max + 1 : max;
  5478. if (value < minBound) {
  5479. return capMin;
  5480. } else if (value > maxBound) {
  5481. return capMax;
  5482. } else {
  5483. var offset = findOffsetOf(value, minBound, maxBound);
  5484. var newValue = capValue(offset / screenRange * range + min, capMin, capMax);
  5485. if (snap && newValue >= min && newValue <= max) {
  5486. return snapValueOf(newValue, min, max, step, snapStart);
  5487. } else if (rounded) {
  5488. return Math.round(newValue);
  5489. } else {
  5490. return newValue;
  5491. }
  5492. }
  5493. };
  5494. var findOffsetOfValue$2 = function (args) {
  5495. var min = args.min, max = args.max, range = args.range, value = args.value, hasMinEdge = args.hasMinEdge, hasMaxEdge = args.hasMaxEdge, maxBound = args.maxBound, maxOffset = args.maxOffset, centerMinEdge = args.centerMinEdge, centerMaxEdge = args.centerMaxEdge;
  5496. if (value < min) {
  5497. return hasMinEdge ? 0 : centerMinEdge;
  5498. } else if (value > max) {
  5499. return hasMaxEdge ? maxBound : centerMaxEdge;
  5500. } else {
  5501. return (value - min) / range * maxOffset;
  5502. }
  5503. };
  5504. var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height';
  5505. var getBounds$1 = function (component) {
  5506. return component.element.dom.getBoundingClientRect();
  5507. };
  5508. var getBoundsProperty = function (bounds, property) {
  5509. return bounds[property];
  5510. };
  5511. var getMinXBounds = function (component) {
  5512. var bounds = getBounds$1(component);
  5513. return getBoundsProperty(bounds, left);
  5514. };
  5515. var getMaxXBounds = function (component) {
  5516. var bounds = getBounds$1(component);
  5517. return getBoundsProperty(bounds, right);
  5518. };
  5519. var getMinYBounds = function (component) {
  5520. var bounds = getBounds$1(component);
  5521. return getBoundsProperty(bounds, top);
  5522. };
  5523. var getMaxYBounds = function (component) {
  5524. var bounds = getBounds$1(component);
  5525. return getBoundsProperty(bounds, bottom);
  5526. };
  5527. var getXScreenRange = function (component) {
  5528. var bounds = getBounds$1(component);
  5529. return getBoundsProperty(bounds, width);
  5530. };
  5531. var getYScreenRange = function (component) {
  5532. var bounds = getBounds$1(component);
  5533. return getBoundsProperty(bounds, height);
  5534. };
  5535. var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) {
  5536. return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge;
  5537. };
  5538. var getXCenterOffSetOf = function (component, spectrum) {
  5539. var componentBounds = getBounds$1(component);
  5540. var spectrumBounds = getBounds$1(spectrum);
  5541. var componentMinEdge = getBoundsProperty(componentBounds, left);
  5542. var componentMaxEdge = getBoundsProperty(componentBounds, right);
  5543. var spectrumMinEdge = getBoundsProperty(spectrumBounds, left);
  5544. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5545. };
  5546. var getYCenterOffSetOf = function (component, spectrum) {
  5547. var componentBounds = getBounds$1(component);
  5548. var spectrumBounds = getBounds$1(spectrum);
  5549. var componentMinEdge = getBoundsProperty(componentBounds, top);
  5550. var componentMaxEdge = getBoundsProperty(componentBounds, bottom);
  5551. var spectrumMinEdge = getBoundsProperty(spectrumBounds, top);
  5552. return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge);
  5553. };
  5554. var fireSliderChange$2 = function (spectrum, value) {
  5555. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5556. };
  5557. var sliderValue$2 = function (x) {
  5558. return { x: x };
  5559. };
  5560. var findValueOfOffset$1 = function (spectrum, detail, left) {
  5561. var args = {
  5562. min: minX(detail),
  5563. max: maxX(detail),
  5564. range: xRange(detail),
  5565. value: left,
  5566. step: step(detail),
  5567. snap: snap(detail),
  5568. snapStart: snapStart(detail),
  5569. rounded: rounded(detail),
  5570. hasMinEdge: hasLEdge(detail),
  5571. hasMaxEdge: hasREdge(detail),
  5572. minBound: getMinXBounds(spectrum),
  5573. maxBound: getMaxXBounds(spectrum),
  5574. screenRange: getXScreenRange(spectrum)
  5575. };
  5576. return findValueOf(args);
  5577. };
  5578. var setValueFrom$2 = function (spectrum, detail, value) {
  5579. var xValue = findValueOfOffset$1(spectrum, detail, value);
  5580. var sliderVal = sliderValue$2(xValue);
  5581. fireSliderChange$2(spectrum, sliderVal);
  5582. return xValue;
  5583. };
  5584. var setToMin$2 = function (spectrum, detail) {
  5585. var min = minX(detail);
  5586. fireSliderChange$2(spectrum, sliderValue$2(min));
  5587. };
  5588. var setToMax$2 = function (spectrum, detail) {
  5589. var max = maxX(detail);
  5590. fireSliderChange$2(spectrum, sliderValue$2(max));
  5591. };
  5592. var moveBy$2 = function (direction, spectrum, detail) {
  5593. var f = direction > 0 ? increaseBy : reduceBy;
  5594. var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5595. fireSliderChange$2(spectrum, sliderValue$2(xValue));
  5596. return Optional.some(xValue);
  5597. };
  5598. var handleMovement$2 = function (direction) {
  5599. return function (spectrum, detail) {
  5600. return moveBy$2(direction, spectrum, detail).map(always);
  5601. };
  5602. };
  5603. var getValueFromEvent$2 = function (simulatedEvent) {
  5604. var pos = getEventSource(simulatedEvent);
  5605. return pos.map(function (p) {
  5606. return p.left;
  5607. });
  5608. };
  5609. var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) {
  5610. var minOffset = 0;
  5611. var maxOffset = getXScreenRange(spectrum);
  5612. var centerMinEdge = minEdge.bind(function (edge) {
  5613. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5614. }).getOr(minOffset);
  5615. var centerMaxEdge = maxEdge.bind(function (edge) {
  5616. return Optional.some(getXCenterOffSetOf(edge, spectrum));
  5617. }).getOr(maxOffset);
  5618. var args = {
  5619. min: minX(detail),
  5620. max: maxX(detail),
  5621. range: xRange(detail),
  5622. value: value,
  5623. hasMinEdge: hasLEdge(detail),
  5624. hasMaxEdge: hasREdge(detail),
  5625. minBound: getMinXBounds(spectrum),
  5626. minOffset: minOffset,
  5627. maxBound: getMaxXBounds(spectrum),
  5628. maxOffset: maxOffset,
  5629. centerMinEdge: centerMinEdge,
  5630. centerMaxEdge: centerMaxEdge
  5631. };
  5632. return findOffsetOfValue$2(args);
  5633. };
  5634. var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5635. var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge);
  5636. return getMinXBounds(spectrum) - getMinXBounds(slider) + offset;
  5637. };
  5638. var setPositionFromValue$2 = function (slider, thumb, detail, edges) {
  5639. var value = currentValue(detail);
  5640. var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5641. var thumbRadius = get$5(thumb.element) / 2;
  5642. set$5(thumb.element, 'left', pos - thumbRadius + 'px');
  5643. };
  5644. var onLeft$2 = handleMovement$2(-1);
  5645. var onRight$2 = handleMovement$2(1);
  5646. var onUp$2 = Optional.none;
  5647. var onDown$2 = Optional.none;
  5648. var edgeActions$2 = {
  5649. 'top-left': Optional.none(),
  5650. 'top': Optional.none(),
  5651. 'top-right': Optional.none(),
  5652. 'right': Optional.some(setToREdge),
  5653. 'bottom-right': Optional.none(),
  5654. 'bottom': Optional.none(),
  5655. 'bottom-left': Optional.none(),
  5656. 'left': Optional.some(setToLEdge)
  5657. };
  5658. var HorizontalModel = /*#__PURE__*/Object.freeze({
  5659. __proto__: null,
  5660. setValueFrom: setValueFrom$2,
  5661. setToMin: setToMin$2,
  5662. setToMax: setToMax$2,
  5663. findValueOfOffset: findValueOfOffset$1,
  5664. getValueFromEvent: getValueFromEvent$2,
  5665. findPositionOfValue: findPositionOfValue$1,
  5666. setPositionFromValue: setPositionFromValue$2,
  5667. onLeft: onLeft$2,
  5668. onRight: onRight$2,
  5669. onUp: onUp$2,
  5670. onDown: onDown$2,
  5671. edgeActions: edgeActions$2
  5672. });
  5673. var fireSliderChange$1 = function (spectrum, value) {
  5674. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5675. };
  5676. var sliderValue$1 = function (y) {
  5677. return { y: y };
  5678. };
  5679. var findValueOfOffset = function (spectrum, detail, top) {
  5680. var args = {
  5681. min: minY(detail),
  5682. max: maxY(detail),
  5683. range: yRange(detail),
  5684. value: top,
  5685. step: step(detail),
  5686. snap: snap(detail),
  5687. snapStart: snapStart(detail),
  5688. rounded: rounded(detail),
  5689. hasMinEdge: hasTEdge(detail),
  5690. hasMaxEdge: hasBEdge(detail),
  5691. minBound: getMinYBounds(spectrum),
  5692. maxBound: getMaxYBounds(spectrum),
  5693. screenRange: getYScreenRange(spectrum)
  5694. };
  5695. return findValueOf(args);
  5696. };
  5697. var setValueFrom$1 = function (spectrum, detail, value) {
  5698. var yValue = findValueOfOffset(spectrum, detail, value);
  5699. var sliderVal = sliderValue$1(yValue);
  5700. fireSliderChange$1(spectrum, sliderVal);
  5701. return yValue;
  5702. };
  5703. var setToMin$1 = function (spectrum, detail) {
  5704. var min = minY(detail);
  5705. fireSliderChange$1(spectrum, sliderValue$1(min));
  5706. };
  5707. var setToMax$1 = function (spectrum, detail) {
  5708. var max = maxY(detail);
  5709. fireSliderChange$1(spectrum, sliderValue$1(max));
  5710. };
  5711. var moveBy$1 = function (direction, spectrum, detail) {
  5712. var f = direction > 0 ? increaseBy : reduceBy;
  5713. var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5714. fireSliderChange$1(spectrum, sliderValue$1(yValue));
  5715. return Optional.some(yValue);
  5716. };
  5717. var handleMovement$1 = function (direction) {
  5718. return function (spectrum, detail) {
  5719. return moveBy$1(direction, spectrum, detail).map(always);
  5720. };
  5721. };
  5722. var getValueFromEvent$1 = function (simulatedEvent) {
  5723. var pos = getEventSource(simulatedEvent);
  5724. return pos.map(function (p) {
  5725. return p.top;
  5726. });
  5727. };
  5728. var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) {
  5729. var minOffset = 0;
  5730. var maxOffset = getYScreenRange(spectrum);
  5731. var centerMinEdge = minEdge.bind(function (edge) {
  5732. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5733. }).getOr(minOffset);
  5734. var centerMaxEdge = maxEdge.bind(function (edge) {
  5735. return Optional.some(getYCenterOffSetOf(edge, spectrum));
  5736. }).getOr(maxOffset);
  5737. var args = {
  5738. min: minY(detail),
  5739. max: maxY(detail),
  5740. range: yRange(detail),
  5741. value: value,
  5742. hasMinEdge: hasTEdge(detail),
  5743. hasMaxEdge: hasBEdge(detail),
  5744. minBound: getMinYBounds(spectrum),
  5745. minOffset: minOffset,
  5746. maxBound: getMaxYBounds(spectrum),
  5747. maxOffset: maxOffset,
  5748. centerMinEdge: centerMinEdge,
  5749. centerMaxEdge: centerMaxEdge
  5750. };
  5751. return findOffsetOfValue$2(args);
  5752. };
  5753. var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) {
  5754. var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge);
  5755. return getMinYBounds(spectrum) - getMinYBounds(slider) + offset;
  5756. };
  5757. var setPositionFromValue$1 = function (slider, thumb, detail, edges) {
  5758. var value = currentValue(detail);
  5759. var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5760. var thumbRadius = get$7(thumb.element) / 2;
  5761. set$5(thumb.element, 'top', pos - thumbRadius + 'px');
  5762. };
  5763. var onLeft$1 = Optional.none;
  5764. var onRight$1 = Optional.none;
  5765. var onUp$1 = handleMovement$1(-1);
  5766. var onDown$1 = handleMovement$1(1);
  5767. var edgeActions$1 = {
  5768. 'top-left': Optional.none(),
  5769. 'top': Optional.some(setToTEdge),
  5770. 'top-right': Optional.none(),
  5771. 'right': Optional.none(),
  5772. 'bottom-right': Optional.none(),
  5773. 'bottom': Optional.some(setToBEdge),
  5774. 'bottom-left': Optional.none(),
  5775. 'left': Optional.none()
  5776. };
  5777. var VerticalModel = /*#__PURE__*/Object.freeze({
  5778. __proto__: null,
  5779. setValueFrom: setValueFrom$1,
  5780. setToMin: setToMin$1,
  5781. setToMax: setToMax$1,
  5782. findValueOfOffset: findValueOfOffset,
  5783. getValueFromEvent: getValueFromEvent$1,
  5784. findPositionOfValue: findPositionOfValue,
  5785. setPositionFromValue: setPositionFromValue$1,
  5786. onLeft: onLeft$1,
  5787. onRight: onRight$1,
  5788. onUp: onUp$1,
  5789. onDown: onDown$1,
  5790. edgeActions: edgeActions$1
  5791. });
  5792. var fireSliderChange = function (spectrum, value) {
  5793. emitWith(spectrum, sliderChangeEvent(), { value: value });
  5794. };
  5795. var sliderValue = function (x, y) {
  5796. return {
  5797. x: x,
  5798. y: y
  5799. };
  5800. };
  5801. var setValueFrom = function (spectrum, detail, value) {
  5802. var xValue = findValueOfOffset$1(spectrum, detail, value.left);
  5803. var yValue = findValueOfOffset(spectrum, detail, value.top);
  5804. var val = sliderValue(xValue, yValue);
  5805. fireSliderChange(spectrum, val);
  5806. return val;
  5807. };
  5808. var moveBy = function (direction, isVerticalMovement, spectrum, detail) {
  5809. var f = direction > 0 ? increaseBy : reduceBy;
  5810. var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail));
  5811. var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail));
  5812. fireSliderChange(spectrum, sliderValue(xValue, yValue));
  5813. return Optional.some(xValue);
  5814. };
  5815. var handleMovement = function (direction, isVerticalMovement) {
  5816. return function (spectrum, detail) {
  5817. return moveBy(direction, isVerticalMovement, spectrum, detail).map(always);
  5818. };
  5819. };
  5820. var setToMin = function (spectrum, detail) {
  5821. var mX = minX(detail);
  5822. var mY = minY(detail);
  5823. fireSliderChange(spectrum, sliderValue(mX, mY));
  5824. };
  5825. var setToMax = function (spectrum, detail) {
  5826. var mX = maxX(detail);
  5827. var mY = maxY(detail);
  5828. fireSliderChange(spectrum, sliderValue(mX, mY));
  5829. };
  5830. var getValueFromEvent = function (simulatedEvent) {
  5831. return getEventSource(simulatedEvent);
  5832. };
  5833. var setPositionFromValue = function (slider, thumb, detail, edges) {
  5834. var value = currentValue(detail);
  5835. var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail);
  5836. var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail);
  5837. var thumbXRadius = get$5(thumb.element) / 2;
  5838. var thumbYRadius = get$7(thumb.element) / 2;
  5839. set$5(thumb.element, 'left', xPos - thumbXRadius + 'px');
  5840. set$5(thumb.element, 'top', yPos - thumbYRadius + 'px');
  5841. };
  5842. var onLeft = handleMovement(-1, false);
  5843. var onRight = handleMovement(1, false);
  5844. var onUp = handleMovement(-1, true);
  5845. var onDown = handleMovement(1, true);
  5846. var edgeActions = {
  5847. 'top-left': Optional.some(setToTLEdgeXY),
  5848. 'top': Optional.some(setToTEdgeXY),
  5849. 'top-right': Optional.some(setToTREdgeXY),
  5850. 'right': Optional.some(setToREdgeXY),
  5851. 'bottom-right': Optional.some(setToBREdgeXY),
  5852. 'bottom': Optional.some(setToBEdgeXY),
  5853. 'bottom-left': Optional.some(setToBLEdgeXY),
  5854. 'left': Optional.some(setToLEdgeXY)
  5855. };
  5856. var TwoDModel = /*#__PURE__*/Object.freeze({
  5857. __proto__: null,
  5858. setValueFrom: setValueFrom,
  5859. setToMin: setToMin,
  5860. setToMax: setToMax,
  5861. getValueFromEvent: getValueFromEvent,
  5862. setPositionFromValue: setPositionFromValue,
  5863. onLeft: onLeft,
  5864. onRight: onRight,
  5865. onUp: onUp,
  5866. onDown: onDown,
  5867. edgeActions: edgeActions
  5868. });
  5869. var SliderSchema = [
  5870. defaulted('stepSize', 1),
  5871. defaulted('onChange', noop),
  5872. defaulted('onChoose', noop),
  5873. defaulted('onInit', noop),
  5874. defaulted('onDragStart', noop),
  5875. defaulted('onDragEnd', noop),
  5876. defaulted('snapToGrid', false),
  5877. defaulted('rounded', true),
  5878. option('snapStart'),
  5879. requiredOf('model', choose$1('mode', {
  5880. x: [
  5881. defaulted('minX', 0),
  5882. defaulted('maxX', 100),
  5883. customField('value', function (spec) {
  5884. return Cell(spec.mode.minX);
  5885. }),
  5886. required$1('getInitialValue'),
  5887. output('manager', HorizontalModel)
  5888. ],
  5889. y: [
  5890. defaulted('minY', 0),
  5891. defaulted('maxY', 100),
  5892. customField('value', function (spec) {
  5893. return Cell(spec.mode.minY);
  5894. }),
  5895. required$1('getInitialValue'),
  5896. output('manager', VerticalModel)
  5897. ],
  5898. xy: [
  5899. defaulted('minX', 0),
  5900. defaulted('maxX', 100),
  5901. defaulted('minY', 0),
  5902. defaulted('maxY', 100),
  5903. customField('value', function (spec) {
  5904. return Cell({
  5905. x: spec.mode.minX,
  5906. y: spec.mode.minY
  5907. });
  5908. }),
  5909. required$1('getInitialValue'),
  5910. output('manager', TwoDModel)
  5911. ]
  5912. })),
  5913. field$1('sliderBehaviours', [
  5914. Keying,
  5915. Representing
  5916. ]),
  5917. customField('mouseIsDown', function () {
  5918. return Cell(false);
  5919. })
  5920. ];
  5921. var mouseReleased = constant$1('mouse.released');
  5922. var sketch$9 = function (detail, components, _spec, _externals) {
  5923. var _a;
  5924. var getThumb = function (component) {
  5925. return getPartOrDie(component, detail, 'thumb');
  5926. };
  5927. var getSpectrum = function (component) {
  5928. return getPartOrDie(component, detail, 'spectrum');
  5929. };
  5930. var getLeftEdge = function (component) {
  5931. return getPart(component, detail, 'left-edge');
  5932. };
  5933. var getRightEdge = function (component) {
  5934. return getPart(component, detail, 'right-edge');
  5935. };
  5936. var getTopEdge = function (component) {
  5937. return getPart(component, detail, 'top-edge');
  5938. };
  5939. var getBottomEdge = function (component) {
  5940. return getPart(component, detail, 'bottom-edge');
  5941. };
  5942. var modelDetail = detail.model;
  5943. var model = modelDetail.manager;
  5944. var refresh = function (slider, thumb) {
  5945. model.setPositionFromValue(slider, thumb, detail, {
  5946. getLeftEdge: getLeftEdge,
  5947. getRightEdge: getRightEdge,
  5948. getTopEdge: getTopEdge,
  5949. getBottomEdge: getBottomEdge,
  5950. getSpectrum: getSpectrum
  5951. });
  5952. };
  5953. var setValue = function (slider, newValue) {
  5954. modelDetail.value.set(newValue);
  5955. var thumb = getThumb(slider);
  5956. refresh(slider, thumb);
  5957. };
  5958. var changeValue = function (slider, newValue) {
  5959. setValue(slider, newValue);
  5960. var thumb = getThumb(slider);
  5961. detail.onChange(slider, thumb, newValue);
  5962. return Optional.some(true);
  5963. };
  5964. var resetToMin = function (slider) {
  5965. model.setToMin(slider, detail);
  5966. };
  5967. var resetToMax = function (slider) {
  5968. model.setToMax(slider, detail);
  5969. };
  5970. var choose = function (slider) {
  5971. var fireOnChoose = function () {
  5972. getPart(slider, detail, 'thumb').each(function (thumb) {
  5973. var value = modelDetail.value.get();
  5974. detail.onChoose(slider, thumb, value);
  5975. });
  5976. };
  5977. var wasDown = detail.mouseIsDown.get();
  5978. detail.mouseIsDown.set(false);
  5979. if (wasDown) {
  5980. fireOnChoose();
  5981. }
  5982. };
  5983. var onDragStart = function (slider, simulatedEvent) {
  5984. simulatedEvent.stop();
  5985. detail.mouseIsDown.set(true);
  5986. detail.onDragStart(slider, getThumb(slider));
  5987. };
  5988. var onDragEnd = function (slider, simulatedEvent) {
  5989. simulatedEvent.stop();
  5990. detail.onDragEnd(slider, getThumb(slider));
  5991. choose(slider);
  5992. };
  5993. return {
  5994. uid: detail.uid,
  5995. dom: detail.dom,
  5996. components: components,
  5997. behaviours: augment(detail.sliderBehaviours, [
  5998. Keying.config({
  5999. mode: 'special',
  6000. focusIn: function (slider) {
  6001. return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always);
  6002. }
  6003. }),
  6004. Representing.config({
  6005. store: {
  6006. mode: 'manual',
  6007. getValue: function (_) {
  6008. return modelDetail.value.get();
  6009. }
  6010. }
  6011. }),
  6012. Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) })
  6013. ]),
  6014. events: derive$3([
  6015. run(sliderChangeEvent(), function (slider, simulatedEvent) {
  6016. changeValue(slider, simulatedEvent.event.value);
  6017. }),
  6018. runOnAttached(function (slider, _simulatedEvent) {
  6019. var getInitial = modelDetail.getInitialValue();
  6020. modelDetail.value.set(getInitial);
  6021. var thumb = getThumb(slider);
  6022. refresh(slider, thumb);
  6023. var spectrum = getSpectrum(slider);
  6024. detail.onInit(slider, thumb, spectrum, modelDetail.value.get());
  6025. }),
  6026. run(touchstart(), onDragStart),
  6027. run(touchend(), onDragEnd),
  6028. run(mousedown(), onDragStart),
  6029. run(mouseup(), onDragEnd)
  6030. ]),
  6031. apis: {
  6032. resetToMin: resetToMin,
  6033. resetToMax: resetToMax,
  6034. setValue: setValue,
  6035. refresh: refresh
  6036. },
  6037. domModification: { styles: { position: 'relative' } }
  6038. };
  6039. };
  6040. var Slider = composite({
  6041. name: 'Slider',
  6042. configFields: SliderSchema,
  6043. partFields: SliderParts,
  6044. factory: sketch$9,
  6045. apis: {
  6046. setValue: function (apis, slider, value) {
  6047. apis.setValue(slider, value);
  6048. },
  6049. resetToMin: function (apis, slider) {
  6050. apis.resetToMin(slider);
  6051. },
  6052. resetToMax: function (apis, slider) {
  6053. apis.resetToMax(slider);
  6054. },
  6055. refresh: function (apis, slider) {
  6056. apis.refresh(slider);
  6057. }
  6058. }
  6059. });
  6060. var button = function (realm, clazz, makeItems, editor) {
  6061. return forToolbar(clazz, function () {
  6062. var items = makeItems();
  6063. realm.setContextToolbar([{
  6064. label: clazz + ' group',
  6065. items: items
  6066. }]);
  6067. }, {}, editor);
  6068. };
  6069. var BLACK = -1;
  6070. var makeSlider$1 = function (spec$1) {
  6071. var getColor = function (hue) {
  6072. if (hue < 0) {
  6073. return 'black';
  6074. } else if (hue > 360) {
  6075. return 'white';
  6076. } else {
  6077. return 'hsl(' + hue + ', 100%, 50%)';
  6078. }
  6079. };
  6080. var onInit = function (slider, thumb, spectrum, value) {
  6081. var color = getColor(value.x());
  6082. set$5(thumb.element, 'background-color', color);
  6083. };
  6084. var onChange = function (slider, thumb, value) {
  6085. var color = getColor(value.x());
  6086. set$5(thumb.element, 'background-color', color);
  6087. spec$1.onChange(slider, thumb, color);
  6088. };
  6089. return Slider.sketch({
  6090. dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
  6091. components: [
  6092. Slider.parts['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
  6093. Slider.parts.spectrum({
  6094. dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
  6095. components: [spec('<div class="${prefix}-slider-gradient"></div>')],
  6096. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6097. }),
  6098. Slider.parts['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
  6099. Slider.parts.thumb({
  6100. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6101. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6102. })
  6103. ],
  6104. onChange: onChange,
  6105. onDragStart: function (slider, thumb) {
  6106. Toggling.on(thumb);
  6107. },
  6108. onDragEnd: function (slider, thumb) {
  6109. Toggling.off(thumb);
  6110. },
  6111. onInit: onInit,
  6112. stepSize: 10,
  6113. model: {
  6114. mode: 'x',
  6115. minX: 0,
  6116. maxX: 360,
  6117. getInitialValue: function () {
  6118. return { x: spec$1.getInitialValue() };
  6119. }
  6120. },
  6121. sliderBehaviours: derive$2([orientation(Slider.refresh)])
  6122. });
  6123. };
  6124. var makeItems$1 = function (spec) {
  6125. return [makeSlider$1(spec)];
  6126. };
  6127. var sketch$8 = function (realm, editor) {
  6128. var spec = {
  6129. onChange: function (slider, thumb, color) {
  6130. editor.undoManager.transact(function () {
  6131. editor.formatter.apply('forecolor', { value: color });
  6132. editor.nodeChanged();
  6133. });
  6134. },
  6135. getInitialValue: constant$1(BLACK)
  6136. };
  6137. return button(realm, 'color-levels', function () {
  6138. return makeItems$1(spec);
  6139. }, editor);
  6140. };
  6141. var candidatesArray = [
  6142. '9px',
  6143. '10px',
  6144. '11px',
  6145. '12px',
  6146. '14px',
  6147. '16px',
  6148. '18px',
  6149. '20px',
  6150. '24px',
  6151. '32px',
  6152. '36px'
  6153. ];
  6154. var defaultSize = 'medium';
  6155. var defaultIndex = 2;
  6156. var indexToSize = function (index) {
  6157. return Optional.from(candidatesArray[index]);
  6158. };
  6159. var sizeToIndex = function (size) {
  6160. return findIndex$1(candidatesArray, function (v) {
  6161. return v === size;
  6162. });
  6163. };
  6164. var getRawOrComputed = function (isRoot, rawStart) {
  6165. var optStart = isElement(rawStart) ? Optional.some(rawStart) : parent(rawStart).filter(isElement);
  6166. return optStart.map(function (start) {
  6167. var inline = closest$2(start, function (elem) {
  6168. return getRaw(elem, 'font-size').isSome();
  6169. }, isRoot).bind(function (elem) {
  6170. return getRaw(elem, 'font-size');
  6171. });
  6172. return inline.getOrThunk(function () {
  6173. return get$8(start, 'font-size');
  6174. });
  6175. }).getOr('');
  6176. };
  6177. var getSize = function (editor) {
  6178. var node = editor.selection.getStart();
  6179. var elem = SugarElement.fromDom(node);
  6180. var root = SugarElement.fromDom(editor.getBody());
  6181. var isRoot = function (e) {
  6182. return eq(root, e);
  6183. };
  6184. var elemSize = getRawOrComputed(isRoot, elem);
  6185. return find$2(candidatesArray, function (size) {
  6186. return elemSize === size;
  6187. }).getOr(defaultSize);
  6188. };
  6189. var applySize = function (editor, value) {
  6190. var currentValue = getSize(editor);
  6191. if (currentValue !== value) {
  6192. editor.execCommand('fontSize', false, value);
  6193. }
  6194. };
  6195. var get$4 = function (editor) {
  6196. var size = getSize(editor);
  6197. return sizeToIndex(size).getOr(defaultIndex);
  6198. };
  6199. var apply = function (editor, index) {
  6200. indexToSize(index).each(function (size) {
  6201. applySize(editor, size);
  6202. });
  6203. };
  6204. var candidates = constant$1(candidatesArray);
  6205. var schema$9 = objOfOnly([
  6206. required$1('getInitialValue'),
  6207. required$1('onChange'),
  6208. required$1('category'),
  6209. required$1('sizes')
  6210. ]);
  6211. var sketch$7 = function (rawSpec) {
  6212. var spec$1 = asRawOrDie$1('SizeSlider', schema$9, rawSpec);
  6213. var isValidValue = function (valueIndex) {
  6214. return valueIndex >= 0 && valueIndex < spec$1.sizes.length;
  6215. };
  6216. var onChange = function (slider, thumb, valueIndex) {
  6217. var index = valueIndex.x();
  6218. if (isValidValue(index)) {
  6219. spec$1.onChange(index);
  6220. }
  6221. };
  6222. return Slider.sketch({
  6223. dom: {
  6224. tag: 'div',
  6225. classes: [
  6226. resolve('slider-' + spec$1.category + '-size-container'),
  6227. resolve('slider'),
  6228. resolve('slider-size-container')
  6229. ]
  6230. },
  6231. onChange: onChange,
  6232. onDragStart: function (slider, thumb) {
  6233. Toggling.on(thumb);
  6234. },
  6235. onDragEnd: function (slider, thumb) {
  6236. Toggling.off(thumb);
  6237. },
  6238. model: {
  6239. mode: 'x',
  6240. minX: 0,
  6241. maxX: spec$1.sizes.length - 1,
  6242. getInitialValue: function () {
  6243. return { x: spec$1.getInitialValue() };
  6244. }
  6245. },
  6246. stepSize: 1,
  6247. snapToGrid: true,
  6248. sliderBehaviours: derive$2([orientation(Slider.refresh)]),
  6249. components: [
  6250. Slider.parts.spectrum({
  6251. dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
  6252. components: [spec('<div class="${prefix}-slider-size-line"></div>')]
  6253. }),
  6254. Slider.parts.thumb({
  6255. dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
  6256. behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })])
  6257. })
  6258. ]
  6259. });
  6260. };
  6261. var sizes = candidates();
  6262. var makeSlider = function (spec) {
  6263. return sketch$7({
  6264. onChange: spec.onChange,
  6265. sizes: sizes,
  6266. category: 'font',
  6267. getInitialValue: spec.getInitialValue
  6268. });
  6269. };
  6270. var makeItems = function (spec$1) {
  6271. return [
  6272. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
  6273. makeSlider(spec$1),
  6274. spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
  6275. ];
  6276. };
  6277. var sketch$6 = function (realm, editor) {
  6278. var spec = {
  6279. onChange: function (value) {
  6280. apply(editor, value);
  6281. },
  6282. getInitialValue: function () {
  6283. return get$4(editor);
  6284. }
  6285. };
  6286. return button(realm, 'font-size', function () {
  6287. return makeItems(spec);
  6288. }, editor);
  6289. };
  6290. var record = function (spec) {
  6291. var uid = isSketchSpec$1(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento');
  6292. var get = function (anyInSystem) {
  6293. return anyInSystem.getSystem().getByUid(uid).getOrDie();
  6294. };
  6295. var getOpt = function (anyInSystem) {
  6296. return anyInSystem.getSystem().getByUid(uid).toOptional();
  6297. };
  6298. var asSpec = function () {
  6299. return __assign(__assign({}, spec), { uid: uid });
  6300. };
  6301. return {
  6302. get: get,
  6303. getOpt: getOpt,
  6304. asSpec: asSpec
  6305. };
  6306. };
  6307. var exports$1 = {}, module = { exports: exports$1 };
  6308. (function (define, exports, module, require) {
  6309. (function (global, factory) {
  6310. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.EphoxContactWrapper = factory());
  6311. }(this, function () {
  6312. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  6313. var promise = { exports: {} };
  6314. (function (module) {
  6315. (function (root) {
  6316. var setTimeoutFunc = setTimeout;
  6317. function noop() {
  6318. }
  6319. function bind(fn, thisArg) {
  6320. return function () {
  6321. fn.apply(thisArg, arguments);
  6322. };
  6323. }
  6324. function Promise(fn) {
  6325. if (typeof this !== 'object')
  6326. throw new TypeError('Promises must be constructed via new');
  6327. if (typeof fn !== 'function')
  6328. throw new TypeError('not a function');
  6329. this._state = 0;
  6330. this._handled = false;
  6331. this._value = undefined;
  6332. this._deferreds = [];
  6333. doResolve(fn, this);
  6334. }
  6335. function handle(self, deferred) {
  6336. while (self._state === 3) {
  6337. self = self._value;
  6338. }
  6339. if (self._state === 0) {
  6340. self._deferreds.push(deferred);
  6341. return;
  6342. }
  6343. self._handled = true;
  6344. Promise._immediateFn(function () {
  6345. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  6346. if (cb === null) {
  6347. (self._state === 1 ? resolve : reject)(deferred.promise, self._value);
  6348. return;
  6349. }
  6350. var ret;
  6351. try {
  6352. ret = cb(self._value);
  6353. } catch (e) {
  6354. reject(deferred.promise, e);
  6355. return;
  6356. }
  6357. resolve(deferred.promise, ret);
  6358. });
  6359. }
  6360. function resolve(self, newValue) {
  6361. try {
  6362. if (newValue === self)
  6363. throw new TypeError('A promise cannot be resolved with itself.');
  6364. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  6365. var then = newValue.then;
  6366. if (newValue instanceof Promise) {
  6367. self._state = 3;
  6368. self._value = newValue;
  6369. finale(self);
  6370. return;
  6371. } else if (typeof then === 'function') {
  6372. doResolve(bind(then, newValue), self);
  6373. return;
  6374. }
  6375. }
  6376. self._state = 1;
  6377. self._value = newValue;
  6378. finale(self);
  6379. } catch (e) {
  6380. reject(self, e);
  6381. }
  6382. }
  6383. function reject(self, newValue) {
  6384. self._state = 2;
  6385. self._value = newValue;
  6386. finale(self);
  6387. }
  6388. function finale(self) {
  6389. if (self._state === 2 && self._deferreds.length === 0) {
  6390. Promise._immediateFn(function () {
  6391. if (!self._handled) {
  6392. Promise._unhandledRejectionFn(self._value);
  6393. }
  6394. });
  6395. }
  6396. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  6397. handle(self, self._deferreds[i]);
  6398. }
  6399. self._deferreds = null;
  6400. }
  6401. function Handler(onFulfilled, onRejected, promise) {
  6402. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  6403. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  6404. this.promise = promise;
  6405. }
  6406. function doResolve(fn, self) {
  6407. var done = false;
  6408. try {
  6409. fn(function (value) {
  6410. if (done)
  6411. return;
  6412. done = true;
  6413. resolve(self, value);
  6414. }, function (reason) {
  6415. if (done)
  6416. return;
  6417. done = true;
  6418. reject(self, reason);
  6419. });
  6420. } catch (ex) {
  6421. if (done)
  6422. return;
  6423. done = true;
  6424. reject(self, ex);
  6425. }
  6426. }
  6427. Promise.prototype['catch'] = function (onRejected) {
  6428. return this.then(null, onRejected);
  6429. };
  6430. Promise.prototype.then = function (onFulfilled, onRejected) {
  6431. var prom = new this.constructor(noop);
  6432. handle(this, new Handler(onFulfilled, onRejected, prom));
  6433. return prom;
  6434. };
  6435. Promise.all = function (arr) {
  6436. var args = Array.prototype.slice.call(arr);
  6437. return new Promise(function (resolve, reject) {
  6438. if (args.length === 0)
  6439. return resolve([]);
  6440. var remaining = args.length;
  6441. function res(i, val) {
  6442. try {
  6443. if (val && (typeof val === 'object' || typeof val === 'function')) {
  6444. var then = val.then;
  6445. if (typeof then === 'function') {
  6446. then.call(val, function (val) {
  6447. res(i, val);
  6448. }, reject);
  6449. return;
  6450. }
  6451. }
  6452. args[i] = val;
  6453. if (--remaining === 0) {
  6454. resolve(args);
  6455. }
  6456. } catch (ex) {
  6457. reject(ex);
  6458. }
  6459. }
  6460. for (var i = 0; i < args.length; i++) {
  6461. res(i, args[i]);
  6462. }
  6463. });
  6464. };
  6465. Promise.resolve = function (value) {
  6466. if (value && typeof value === 'object' && value.constructor === Promise) {
  6467. return value;
  6468. }
  6469. return new Promise(function (resolve) {
  6470. resolve(value);
  6471. });
  6472. };
  6473. Promise.reject = function (value) {
  6474. return new Promise(function (resolve, reject) {
  6475. reject(value);
  6476. });
  6477. };
  6478. Promise.race = function (values) {
  6479. return new Promise(function (resolve, reject) {
  6480. for (var i = 0, len = values.length; i < len; i++) {
  6481. values[i].then(resolve, reject);
  6482. }
  6483. });
  6484. };
  6485. Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) {
  6486. setImmediate(fn);
  6487. } : function (fn) {
  6488. setTimeoutFunc(fn, 0);
  6489. };
  6490. Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  6491. if (typeof console !== 'undefined' && console) {
  6492. console.warn('Possible Unhandled Promise Rejection:', err);
  6493. }
  6494. };
  6495. Promise._setImmediateFn = function _setImmediateFn(fn) {
  6496. Promise._immediateFn = fn;
  6497. };
  6498. Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
  6499. Promise._unhandledRejectionFn = fn;
  6500. };
  6501. if (module.exports) {
  6502. module.exports = Promise;
  6503. } else if (!root.Promise) {
  6504. root.Promise = Promise;
  6505. }
  6506. }(commonjsGlobal));
  6507. }(promise));
  6508. var promisePolyfill = promise.exports;
  6509. var Global = function () {
  6510. if (typeof window !== 'undefined') {
  6511. return window;
  6512. } else {
  6513. return Function('return this;')();
  6514. }
  6515. }();
  6516. var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill };
  6517. return promisePolyfill_1;
  6518. }));
  6519. }(undefined, exports$1, module));
  6520. var Promise$1 = module.exports.boltExport;
  6521. var blobToDataUri = function (blob) {
  6522. return new Promise$1(function (resolve) {
  6523. var reader = new FileReader();
  6524. reader.onloadend = function () {
  6525. resolve(reader.result);
  6526. };
  6527. reader.readAsDataURL(blob);
  6528. });
  6529. };
  6530. var blobToBase64$1 = function (blob) {
  6531. return blobToDataUri(blob).then(function (dataUri) {
  6532. return dataUri.split(',')[1];
  6533. });
  6534. };
  6535. var blobToBase64 = function (blob) {
  6536. return blobToBase64$1(blob);
  6537. };
  6538. var addImage = function (editor, blob) {
  6539. blobToBase64(blob).then(function (base64) {
  6540. editor.undoManager.transact(function () {
  6541. var cache = editor.editorUpload.blobCache;
  6542. var info = cache.create(generate$4('mceu'), blob, base64);
  6543. cache.add(info);
  6544. var img = editor.dom.createHTML('img', { src: info.blobUri() });
  6545. editor.insertContent(img);
  6546. });
  6547. });
  6548. };
  6549. var extractBlob = function (simulatedEvent) {
  6550. var event = simulatedEvent.event.raw;
  6551. var files = event.target.files || event.dataTransfer.files;
  6552. return Optional.from(files[0]);
  6553. };
  6554. var sketch$5 = function (editor) {
  6555. var pickerDom = {
  6556. tag: 'input',
  6557. attributes: {
  6558. accept: 'image/*',
  6559. type: 'file',
  6560. title: ''
  6561. },
  6562. styles: {
  6563. visibility: 'hidden',
  6564. position: 'absolute'
  6565. }
  6566. };
  6567. var memPicker = record({
  6568. dom: pickerDom,
  6569. events: derive$3([
  6570. cutter(click()),
  6571. run(change(), function (picker, simulatedEvent) {
  6572. extractBlob(simulatedEvent).each(function (blob) {
  6573. addImage(editor, blob);
  6574. });
  6575. })
  6576. ])
  6577. });
  6578. return Button.sketch({
  6579. dom: getToolbarIconButton('image', editor),
  6580. components: [memPicker.asSpec()],
  6581. action: function (button) {
  6582. var picker = memPicker.get(button);
  6583. picker.element.dom.click();
  6584. }
  6585. });
  6586. };
  6587. var get$3 = function (element) {
  6588. return element.dom.textContent;
  6589. };
  6590. var set$3 = function (element, value) {
  6591. element.dom.textContent = value;
  6592. };
  6593. var isNotEmpty = function (val) {
  6594. return val.length > 0;
  6595. };
  6596. var defaultToEmpty = function (str) {
  6597. return str === undefined || str === null ? '' : str;
  6598. };
  6599. var noLink = function (editor) {
  6600. var text = editor.selection.getContent({ format: 'text' });
  6601. return {
  6602. url: '',
  6603. text: text,
  6604. title: '',
  6605. target: '',
  6606. link: Optional.none()
  6607. };
  6608. };
  6609. var fromLink = function (link) {
  6610. var text = get$3(link);
  6611. var url = get$b(link, 'href');
  6612. var title = get$b(link, 'title');
  6613. var target = get$b(link, 'target');
  6614. return {
  6615. url: defaultToEmpty(url),
  6616. text: text !== url ? defaultToEmpty(text) : '',
  6617. title: defaultToEmpty(title),
  6618. target: defaultToEmpty(target),
  6619. link: Optional.some(link)
  6620. };
  6621. };
  6622. var getInfo = function (editor) {
  6623. return query(editor).fold(function () {
  6624. return noLink(editor);
  6625. }, function (link) {
  6626. return fromLink(link);
  6627. });
  6628. };
  6629. var wasSimple = function (link) {
  6630. var prevHref = get$b(link, 'href');
  6631. var prevText = get$3(link);
  6632. return prevHref === prevText;
  6633. };
  6634. var getTextToApply = function (link, url, info) {
  6635. return info.text.toOptional().filter(isNotEmpty).fold(function () {
  6636. return wasSimple(link) ? Optional.some(url) : Optional.none();
  6637. }, Optional.some);
  6638. };
  6639. var unlinkIfRequired = function (editor, info) {
  6640. var activeLink = info.link.bind(identity);
  6641. activeLink.each(function (_link) {
  6642. editor.execCommand('unlink');
  6643. });
  6644. };
  6645. var getAttrs = function (url, info) {
  6646. var attrs = {};
  6647. attrs.href = url;
  6648. info.title.toOptional().filter(isNotEmpty).each(function (title) {
  6649. attrs.title = title;
  6650. });
  6651. info.target.toOptional().filter(isNotEmpty).each(function (target) {
  6652. attrs.target = target;
  6653. });
  6654. return attrs;
  6655. };
  6656. var applyInfo = function (editor, info) {
  6657. info.url.toOptional().filter(isNotEmpty).fold(function () {
  6658. unlinkIfRequired(editor, info);
  6659. }, function (url) {
  6660. var attrs = getAttrs(url, info);
  6661. var activeLink = info.link.bind(identity);
  6662. activeLink.fold(function () {
  6663. var text = info.text.toOptional().filter(isNotEmpty).getOr(url);
  6664. editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
  6665. }, function (link) {
  6666. var text = getTextToApply(link, url, info);
  6667. setAll$1(link, attrs);
  6668. text.each(function (newText) {
  6669. set$3(link, newText);
  6670. });
  6671. });
  6672. });
  6673. };
  6674. var query = function (editor) {
  6675. var start = SugarElement.fromDom(editor.selection.getStart());
  6676. return closest$1(start, 'a');
  6677. };
  6678. var platform = detect$1();
  6679. var preserve$1 = function (f, editor) {
  6680. var rng = editor.selection.getRng();
  6681. f();
  6682. editor.selection.setRng(rng);
  6683. };
  6684. var forAndroid = function (editor, f) {
  6685. var wrapper = platform.os.isAndroid() ? preserve$1 : apply$1;
  6686. wrapper(f, editor);
  6687. };
  6688. var events$4 = function (name, eventHandlers) {
  6689. var events = derive$3(eventHandlers);
  6690. return create$5({
  6691. fields: [required$1('enabled')],
  6692. name: name,
  6693. active: { events: constant$1(events) }
  6694. });
  6695. };
  6696. var config = function (name, eventHandlers) {
  6697. var me = events$4(name, eventHandlers);
  6698. return {
  6699. key: name,
  6700. value: {
  6701. config: {},
  6702. me: me,
  6703. configAsRaw: constant$1({}),
  6704. initialConfig: {},
  6705. state: NoState
  6706. }
  6707. };
  6708. };
  6709. var getCurrent = function (component, composeConfig, _composeState) {
  6710. return composeConfig.find(component);
  6711. };
  6712. var ComposeApis = /*#__PURE__*/Object.freeze({
  6713. __proto__: null,
  6714. getCurrent: getCurrent
  6715. });
  6716. var ComposeSchema = [required$1('find')];
  6717. var Composing = create$5({
  6718. fields: ComposeSchema,
  6719. name: 'composing',
  6720. apis: ComposeApis
  6721. });
  6722. var factory$4 = function (detail) {
  6723. var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']);
  6724. return {
  6725. uid: detail.uid,
  6726. dom: __assign({
  6727. tag: 'div',
  6728. attributes: __assign({ role: 'presentation' }, attributes)
  6729. }, domWithoutAttributes),
  6730. components: detail.components,
  6731. behaviours: get$6(detail.containerBehaviours),
  6732. events: detail.events,
  6733. domModification: detail.domModification,
  6734. eventOrder: detail.eventOrder
  6735. };
  6736. };
  6737. var Container = single({
  6738. name: 'Container',
  6739. factory: factory$4,
  6740. configFields: [
  6741. defaulted('components', []),
  6742. field$1('containerBehaviours', []),
  6743. defaulted('events', {}),
  6744. defaulted('domModification', {}),
  6745. defaulted('eventOrder', {})
  6746. ]
  6747. });
  6748. var factory$3 = function (detail) {
  6749. return {
  6750. uid: detail.uid,
  6751. dom: detail.dom,
  6752. behaviours: SketchBehaviours.augment(detail.dataBehaviours, [
  6753. Representing.config({
  6754. store: {
  6755. mode: 'memory',
  6756. initialValue: detail.getInitialValue()
  6757. }
  6758. }),
  6759. Composing.config({ find: Optional.some })
  6760. ]),
  6761. events: derive$3([runOnAttached(function (component, _simulatedEvent) {
  6762. Representing.setValue(component, detail.getInitialValue());
  6763. })])
  6764. };
  6765. };
  6766. var DataField = single({
  6767. name: 'DataField',
  6768. factory: factory$3,
  6769. configFields: [
  6770. required$1('uid'),
  6771. required$1('dom'),
  6772. required$1('getInitialValue'),
  6773. SketchBehaviours.field('dataBehaviours', [
  6774. Representing,
  6775. Composing
  6776. ])
  6777. ]
  6778. });
  6779. var get$2 = function (element) {
  6780. return element.dom.value;
  6781. };
  6782. var set$2 = function (element, value) {
  6783. if (value === undefined) {
  6784. throw new Error('Value.set was undefined');
  6785. }
  6786. element.dom.value = value;
  6787. };
  6788. var schema$8 = constant$1([
  6789. option('data'),
  6790. defaulted('inputAttributes', {}),
  6791. defaulted('inputStyles', {}),
  6792. defaulted('tag', 'input'),
  6793. defaulted('inputClasses', []),
  6794. onHandler('onSetValue'),
  6795. defaulted('styles', {}),
  6796. defaulted('eventOrder', {}),
  6797. field$1('inputBehaviours', [
  6798. Representing,
  6799. Focusing
  6800. ]),
  6801. defaulted('selectOnFocus', true)
  6802. ]);
  6803. var focusBehaviours = function (detail) {
  6804. return derive$2([Focusing.config({
  6805. onFocus: !detail.selectOnFocus ? noop : function (component) {
  6806. var input = component.element;
  6807. var value = get$2(input);
  6808. input.dom.setSelectionRange(0, value.length);
  6809. }
  6810. })]);
  6811. };
  6812. var behaviours = function (detail) {
  6813. return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({
  6814. store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) {
  6815. return { initialValue: data };
  6816. }).getOr({})), {
  6817. getValue: function (input) {
  6818. return get$2(input.element);
  6819. },
  6820. setValue: function (input, data) {
  6821. var current = get$2(input.element);
  6822. if (current !== data) {
  6823. set$2(input.element, data);
  6824. }
  6825. }
  6826. }),
  6827. onSetValue: detail.onSetValue
  6828. })]));
  6829. };
  6830. var dom = function (detail) {
  6831. return {
  6832. tag: detail.tag,
  6833. attributes: __assign({ type: 'text' }, detail.inputAttributes),
  6834. styles: detail.inputStyles,
  6835. classes: detail.inputClasses
  6836. };
  6837. };
  6838. var factory$2 = function (detail, _spec) {
  6839. return {
  6840. uid: detail.uid,
  6841. dom: dom(detail),
  6842. components: [],
  6843. behaviours: behaviours(detail),
  6844. eventOrder: detail.eventOrder
  6845. };
  6846. };
  6847. var Input = single({
  6848. name: 'Input',
  6849. configFields: schema$8(),
  6850. factory: factory$2
  6851. });
  6852. var exhibit$2 = function (base, tabConfig) {
  6853. return nu$3({
  6854. attributes: wrapAll([{
  6855. key: tabConfig.tabAttr,
  6856. value: 'true'
  6857. }])
  6858. });
  6859. };
  6860. var ActiveTabstopping = /*#__PURE__*/Object.freeze({
  6861. __proto__: null,
  6862. exhibit: exhibit$2
  6863. });
  6864. var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')];
  6865. var Tabstopping = create$5({
  6866. fields: TabstopSchema,
  6867. name: 'tabstopping',
  6868. active: ActiveTabstopping
  6869. });
  6870. var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n');
  6871. var clearInputBehaviour = 'input-clearing';
  6872. var field = function (name, placeholder) {
  6873. var inputSpec = record(Input.sketch({
  6874. inputAttributes: { placeholder: global$3.translate(placeholder) },
  6875. onSetValue: function (input, _data) {
  6876. emit(input, input$1());
  6877. },
  6878. inputBehaviours: derive$2([
  6879. Composing.config({ find: Optional.some }),
  6880. Tabstopping.config({}),
  6881. Keying.config({ mode: 'execution' })
  6882. ]),
  6883. selectOnFocus: false
  6884. }));
  6885. var buttonSpec = record(Button.sketch({
  6886. dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
  6887. action: function (button) {
  6888. var input = inputSpec.get(button);
  6889. Representing.setValue(input, '');
  6890. }
  6891. }));
  6892. return {
  6893. name: name,
  6894. spec: Container.sketch({
  6895. dom: dom$1('<div class="${prefix}-input-container"></div>'),
  6896. components: [
  6897. inputSpec.asSpec(),
  6898. buttonSpec.asSpec()
  6899. ],
  6900. containerBehaviours: derive$2([
  6901. Toggling.config({ toggleClass: resolve('input-container-empty') }),
  6902. Composing.config({
  6903. find: function (comp) {
  6904. return Optional.some(inputSpec.get(comp));
  6905. }
  6906. }),
  6907. config(clearInputBehaviour, [run(input$1(), function (iContainer) {
  6908. var input = inputSpec.get(iContainer);
  6909. var val = Representing.getValue(input);
  6910. var f = val.length > 0 ? Toggling.off : Toggling.on;
  6911. f(iContainer);
  6912. })])
  6913. ])
  6914. })
  6915. };
  6916. };
  6917. var hidden = function (name) {
  6918. return {
  6919. name: name,
  6920. spec: DataField.sketch({
  6921. dom: {
  6922. tag: 'span',
  6923. styles: { display: 'none' }
  6924. },
  6925. getInitialValue: function () {
  6926. return Optional.none();
  6927. }
  6928. })
  6929. };
  6930. };
  6931. var nativeDisabled = [
  6932. 'input',
  6933. 'button',
  6934. 'textarea',
  6935. 'select'
  6936. ];
  6937. var onLoad = function (component, disableConfig, disableState) {
  6938. var f = disableConfig.disabled() ? disable : enable;
  6939. f(component, disableConfig);
  6940. };
  6941. var hasNative = function (component, config) {
  6942. return config.useNative === true && contains$1(nativeDisabled, name$1(component.element));
  6943. };
  6944. var nativeIsDisabled = function (component) {
  6945. return has$1(component.element, 'disabled');
  6946. };
  6947. var nativeDisable = function (component) {
  6948. set$8(component.element, 'disabled', 'disabled');
  6949. };
  6950. var nativeEnable = function (component) {
  6951. remove$6(component.element, 'disabled');
  6952. };
  6953. var ariaIsDisabled = function (component) {
  6954. return get$b(component.element, 'aria-disabled') === 'true';
  6955. };
  6956. var ariaDisable = function (component) {
  6957. set$8(component.element, 'aria-disabled', 'true');
  6958. };
  6959. var ariaEnable = function (component) {
  6960. set$8(component.element, 'aria-disabled', 'false');
  6961. };
  6962. var disable = function (component, disableConfig, _disableState) {
  6963. disableConfig.disableClass.each(function (disableClass) {
  6964. add$1(component.element, disableClass);
  6965. });
  6966. var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable;
  6967. f(component);
  6968. disableConfig.onDisabled(component);
  6969. };
  6970. var enable = function (component, disableConfig, _disableState) {
  6971. disableConfig.disableClass.each(function (disableClass) {
  6972. remove$3(component.element, disableClass);
  6973. });
  6974. var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable;
  6975. f(component);
  6976. disableConfig.onEnabled(component);
  6977. };
  6978. var isDisabled = function (component, disableConfig) {
  6979. return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component);
  6980. };
  6981. var set$1 = function (component, disableConfig, disableState, disabled) {
  6982. var f = disabled ? disable : enable;
  6983. f(component, disableConfig);
  6984. };
  6985. var DisableApis = /*#__PURE__*/Object.freeze({
  6986. __proto__: null,
  6987. enable: enable,
  6988. disable: disable,
  6989. isDisabled: isDisabled,
  6990. onLoad: onLoad,
  6991. set: set$1
  6992. });
  6993. var exhibit$1 = function (base, disableConfig) {
  6994. return nu$3({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] });
  6995. };
  6996. var events$3 = function (disableConfig, disableState) {
  6997. return derive$3([
  6998. abort(execute$5(), function (component, _simulatedEvent) {
  6999. return isDisabled(component, disableConfig);
  7000. }),
  7001. loadEvent(disableConfig, disableState, onLoad)
  7002. ]);
  7003. };
  7004. var ActiveDisable = /*#__PURE__*/Object.freeze({
  7005. __proto__: null,
  7006. exhibit: exhibit$1,
  7007. events: events$3
  7008. });
  7009. var DisableSchema = [
  7010. defaultedFunction('disabled', never),
  7011. defaulted('useNative', true),
  7012. option('disableClass'),
  7013. onHandler('onDisabled'),
  7014. onHandler('onEnabled')
  7015. ];
  7016. var Disabling = create$5({
  7017. fields: DisableSchema,
  7018. name: 'disabling',
  7019. active: ActiveDisable,
  7020. apis: DisableApis
  7021. });
  7022. var owner$1 = 'form';
  7023. var schema$7 = [field$1('formBehaviours', [Representing])];
  7024. var getPartName = function (name) {
  7025. return '<alloy.field.' + name + '>';
  7026. };
  7027. var sketch$4 = function (fSpec) {
  7028. var parts = function () {
  7029. var record = [];
  7030. var field = function (name, config) {
  7031. record.push(name);
  7032. return generateOne(owner$1, getPartName(name), config);
  7033. };
  7034. return {
  7035. field: field,
  7036. record: constant$1(record)
  7037. };
  7038. }();
  7039. var spec = fSpec(parts);
  7040. var partNames = parts.record();
  7041. var fieldParts = map$2(partNames, function (n) {
  7042. return required({
  7043. name: n,
  7044. pname: getPartName(n)
  7045. });
  7046. });
  7047. return composite$1(owner$1, schema$7, fieldParts, make$4, spec);
  7048. };
  7049. var toResult = function (o, e) {
  7050. return o.fold(function () {
  7051. return Result.error(e);
  7052. }, Result.value);
  7053. };
  7054. var make$4 = function (detail, components) {
  7055. return {
  7056. uid: detail.uid,
  7057. dom: detail.dom,
  7058. components: components,
  7059. behaviours: augment(detail.formBehaviours, [Representing.config({
  7060. store: {
  7061. mode: 'manual',
  7062. getValue: function (form) {
  7063. var resPs = getAllParts(form, detail);
  7064. return map$1(resPs, function (resPThunk, pName) {
  7065. return resPThunk().bind(function (v) {
  7066. var opt = Composing.getCurrent(v);
  7067. return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element)));
  7068. }).map(Representing.getValue);
  7069. });
  7070. },
  7071. setValue: function (form, values) {
  7072. each(values, function (newValue, key) {
  7073. getPart(form, detail, key).each(function (wrapper) {
  7074. Composing.getCurrent(wrapper).each(function (field) {
  7075. Representing.setValue(field, newValue);
  7076. });
  7077. });
  7078. });
  7079. }
  7080. }
  7081. })]),
  7082. apis: {
  7083. getField: function (form, key) {
  7084. return getPart(form, detail, key).bind(Composing.getCurrent);
  7085. }
  7086. }
  7087. };
  7088. };
  7089. var Form = {
  7090. getField: makeApi(function (apis, component, key) {
  7091. return apis.getField(component, key);
  7092. }),
  7093. sketch: sketch$4
  7094. };
  7095. var SWIPING_LEFT = 1;
  7096. var SWIPING_RIGHT = -1;
  7097. var SWIPING_NONE = 0;
  7098. var init$3 = function (xValue) {
  7099. return {
  7100. xValue: xValue,
  7101. points: []
  7102. };
  7103. };
  7104. var move = function (model, xValue) {
  7105. if (xValue === model.xValue) {
  7106. return model;
  7107. }
  7108. var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
  7109. var newPoint = {
  7110. direction: currentDirection,
  7111. xValue: xValue
  7112. };
  7113. var priorPoints = function () {
  7114. if (model.points.length === 0) {
  7115. return [];
  7116. } else {
  7117. var prev = model.points[model.points.length - 1];
  7118. return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
  7119. }
  7120. }();
  7121. return {
  7122. xValue: xValue,
  7123. points: priorPoints.concat([newPoint])
  7124. };
  7125. };
  7126. var complete = function (model) {
  7127. if (model.points.length === 0) {
  7128. return SWIPING_NONE;
  7129. } else {
  7130. var firstDirection = model.points[0].direction;
  7131. var lastDirection = model.points[model.points.length - 1].direction;
  7132. return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
  7133. }
  7134. };
  7135. var sketch$3 = function (rawSpec) {
  7136. var navigateEvent = 'navigateEvent';
  7137. var wrapperAdhocEvents = 'serializer-wrapper-events';
  7138. var formAdhocEvents = 'form-events';
  7139. var schema = objOf([
  7140. required$1('fields'),
  7141. defaulted('maxFieldIndex', rawSpec.fields.length - 1),
  7142. required$1('onExecute'),
  7143. required$1('getInitialValue'),
  7144. customField('state', function () {
  7145. return {
  7146. dialogSwipeState: value(),
  7147. currentScreen: Cell(0)
  7148. };
  7149. })
  7150. ]);
  7151. var spec$1 = asRawOrDie$1('SerialisedDialog', schema, rawSpec);
  7152. var navigationButton = function (direction, directionName, enabled) {
  7153. return Button.sketch({
  7154. dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
  7155. action: function (button) {
  7156. emitWith(button, navigateEvent, { direction: direction });
  7157. },
  7158. buttonBehaviours: derive$2([Disabling.config({
  7159. disableClass: resolve('toolbar-navigation-disabled'),
  7160. disabled: function () {
  7161. return !enabled;
  7162. }
  7163. })])
  7164. });
  7165. };
  7166. var reposition = function (dialog, message) {
  7167. descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7168. set$5(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px');
  7169. });
  7170. };
  7171. var navigate = function (dialog, direction) {
  7172. var screens = descendants(dialog.element, '.' + resolve('serialised-dialog-screen'));
  7173. descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) {
  7174. if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) {
  7175. getRaw(parent, 'left').each(function (left) {
  7176. var currentLeft = parseInt(left, 10);
  7177. var w = get$5(screens[0]);
  7178. set$5(parent, 'left', currentLeft - direction * w + 'px');
  7179. });
  7180. spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction);
  7181. }
  7182. });
  7183. };
  7184. var focusInput = function (dialog) {
  7185. var inputs = descendants(dialog.element, 'input');
  7186. var optInput = Optional.from(inputs[spec$1.state.currentScreen.get()]);
  7187. optInput.each(function (input) {
  7188. dialog.getSystem().getByDom(input).each(function (inputComp) {
  7189. dispatchFocus(dialog, inputComp.element);
  7190. });
  7191. });
  7192. var dotitems = memDots.get(dialog);
  7193. Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get());
  7194. };
  7195. var resetState = function () {
  7196. spec$1.state.currentScreen.set(0);
  7197. spec$1.state.dialogSwipeState.clear();
  7198. };
  7199. var memForm = record(Form.sketch(function (parts) {
  7200. return {
  7201. dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
  7202. components: [Container.sketch({
  7203. dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
  7204. components: map$2(spec$1.fields, function (field, i) {
  7205. return i <= spec$1.maxFieldIndex ? Container.sketch({
  7206. dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
  7207. components: [
  7208. navigationButton(-1, 'previous', i > 0),
  7209. parts.field(field.name, field.spec),
  7210. navigationButton(+1, 'next', i < spec$1.maxFieldIndex)
  7211. ]
  7212. }) : parts.field(field.name, field.spec);
  7213. })
  7214. })],
  7215. formBehaviours: derive$2([
  7216. orientation(function (dialog, message) {
  7217. reposition(dialog, message);
  7218. }),
  7219. Keying.config({
  7220. mode: 'special',
  7221. focusIn: function (dialog, _specialInfo) {
  7222. focusInput(dialog);
  7223. },
  7224. onTab: function (dialog, _specialInfo) {
  7225. navigate(dialog, +1);
  7226. return Optional.some(true);
  7227. },
  7228. onShiftTab: function (dialog, _specialInfo) {
  7229. navigate(dialog, -1);
  7230. return Optional.some(true);
  7231. }
  7232. }),
  7233. config(formAdhocEvents, [
  7234. runOnAttached(function (dialog, _simulatedEvent) {
  7235. resetState();
  7236. var dotitems = memDots.get(dialog);
  7237. Highlighting.highlightFirst(dotitems);
  7238. spec$1.getInitialValue(dialog).each(function (v) {
  7239. Representing.setValue(dialog, v);
  7240. });
  7241. }),
  7242. runOnExecute(spec$1.onExecute),
  7243. run(transitionend(), function (dialog, simulatedEvent) {
  7244. var event = simulatedEvent.event;
  7245. if (event.raw.propertyName === 'left') {
  7246. focusInput(dialog);
  7247. }
  7248. }),
  7249. run(navigateEvent, function (dialog, simulatedEvent) {
  7250. var event = simulatedEvent.event;
  7251. var direction = event.direction;
  7252. navigate(dialog, direction);
  7253. })
  7254. ])
  7255. ])
  7256. };
  7257. }));
  7258. var memDots = record({
  7259. dom: dom$1('<div class="${prefix}-dot-container"></div>'),
  7260. behaviours: derive$2([Highlighting.config({
  7261. highlightClass: resolve('dot-active'),
  7262. itemClass: resolve('dot-item')
  7263. })]),
  7264. components: bind$3(spec$1.fields, function (_f, i) {
  7265. return i <= spec$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
  7266. })
  7267. });
  7268. return {
  7269. dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
  7270. components: [
  7271. memForm.asSpec(),
  7272. memDots.asSpec()
  7273. ],
  7274. behaviours: derive$2([
  7275. Keying.config({
  7276. mode: 'special',
  7277. focusIn: function (wrapper) {
  7278. var form = memForm.get(wrapper);
  7279. Keying.focusIn(form);
  7280. }
  7281. }),
  7282. config(wrapperAdhocEvents, [
  7283. run(touchstart(), function (_wrapper, simulatedEvent) {
  7284. var event = simulatedEvent.event;
  7285. spec$1.state.dialogSwipeState.set(init$3(event.raw.touches[0].clientX));
  7286. }),
  7287. run(touchmove(), function (_wrapper, simulatedEvent) {
  7288. var event = simulatedEvent.event;
  7289. spec$1.state.dialogSwipeState.on(function (state) {
  7290. simulatedEvent.event.prevent();
  7291. spec$1.state.dialogSwipeState.set(move(state, event.raw.touches[0].clientX));
  7292. });
  7293. }),
  7294. run(touchend(), function (wrapper, _simulatedEvent) {
  7295. spec$1.state.dialogSwipeState.on(function (state) {
  7296. var dialog = memForm.get(wrapper);
  7297. var direction = -1 * complete(state);
  7298. navigate(dialog, direction);
  7299. });
  7300. })
  7301. ])
  7302. ])
  7303. };
  7304. };
  7305. var getGroups = cached(function (realm, editor) {
  7306. return [{
  7307. label: 'the link group',
  7308. items: [sketch$3({
  7309. fields: [
  7310. field('url', 'Type or paste URL'),
  7311. field('text', 'Link text'),
  7312. field('title', 'Link title'),
  7313. field('target', 'Link target'),
  7314. hidden('link')
  7315. ],
  7316. maxFieldIndex: [
  7317. 'url',
  7318. 'text',
  7319. 'title',
  7320. 'target'
  7321. ].length - 1,
  7322. getInitialValue: function () {
  7323. return Optional.some(getInfo(editor));
  7324. },
  7325. onExecute: function (dialog, _simulatedEvent) {
  7326. var info = Representing.getValue(dialog);
  7327. applyInfo(editor, info);
  7328. realm.restoreToolbar();
  7329. editor.focus();
  7330. }
  7331. })]
  7332. }];
  7333. });
  7334. var sketch$2 = function (realm, editor) {
  7335. return forToolbarStateAction(editor, 'link', 'link', function () {
  7336. var groups = getGroups(realm, editor);
  7337. realm.setContextToolbar(groups);
  7338. forAndroid(editor, function () {
  7339. realm.focusToolbar();
  7340. });
  7341. query(editor).each(function (link) {
  7342. editor.selection.select(link.dom);
  7343. });
  7344. });
  7345. };
  7346. var isRecursive = function (component, originator, target) {
  7347. return eq(originator, component.element) && !eq(originator, target);
  7348. };
  7349. var events$2 = derive$3([can(focus$4(), function (component, simulatedEvent) {
  7350. var event = simulatedEvent.event;
  7351. var originator = event.originator;
  7352. var target = event.target;
  7353. if (isRecursive(component, originator, target)) {
  7354. console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers');
  7355. return false;
  7356. } else {
  7357. return true;
  7358. }
  7359. })]);
  7360. var DefaultEvents = /*#__PURE__*/Object.freeze({
  7361. __proto__: null,
  7362. events: events$2
  7363. });
  7364. var make$3 = identity;
  7365. var NoContextApi = function (getComp) {
  7366. var getMessage = function (event) {
  7367. return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : '');
  7368. };
  7369. var fail = function (event) {
  7370. return function () {
  7371. throw new Error(getMessage(event));
  7372. };
  7373. };
  7374. var warn = function (event) {
  7375. return function () {
  7376. console.warn(getMessage(event));
  7377. };
  7378. };
  7379. return {
  7380. debugInfo: constant$1('fake'),
  7381. triggerEvent: warn('triggerEvent'),
  7382. triggerFocus: warn('triggerFocus'),
  7383. triggerEscape: warn('triggerEscape'),
  7384. broadcast: warn('broadcast'),
  7385. broadcastOn: warn('broadcastOn'),
  7386. broadcastEvent: warn('broadcastEvent'),
  7387. build: fail('build'),
  7388. addToWorld: fail('addToWorld'),
  7389. removeFromWorld: fail('removeFromWorld'),
  7390. addToGui: fail('addToGui'),
  7391. removeFromGui: fail('removeFromGui'),
  7392. getByUid: fail('getByUid'),
  7393. getByDom: fail('getByDom'),
  7394. isConnected: never
  7395. };
  7396. };
  7397. var singleton = NoContextApi();
  7398. var generateFrom$1 = function (spec, all) {
  7399. var schema = map$2(all, function (a) {
  7400. return optionObjOf(a.name(), [
  7401. required$1('config'),
  7402. defaulted('state', NoState)
  7403. ]);
  7404. });
  7405. var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
  7406. throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2));
  7407. }, identity);
  7408. return {
  7409. list: all,
  7410. data: map$1(validated, function (optBlobThunk) {
  7411. var output = optBlobThunk.map(function (blob) {
  7412. return {
  7413. config: blob.config,
  7414. state: blob.state.init(blob.config)
  7415. };
  7416. });
  7417. return constant$1(output);
  7418. })
  7419. };
  7420. };
  7421. var getBehaviours$1 = function (bData) {
  7422. return bData.list;
  7423. };
  7424. var getData = function (bData) {
  7425. return bData.data;
  7426. };
  7427. var byInnerKey = function (data, tuple) {
  7428. var r = {};
  7429. each(data, function (detail, key) {
  7430. each(detail, function (value, indexKey) {
  7431. var chain = get$c(r, indexKey).getOr([]);
  7432. r[indexKey] = chain.concat([tuple(key, value)]);
  7433. });
  7434. });
  7435. return r;
  7436. };
  7437. var combine$1 = function (info, baseMod, behaviours, base) {
  7438. var modsByBehaviour = __assign({}, baseMod);
  7439. each$1(behaviours, function (behaviour) {
  7440. modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
  7441. });
  7442. var byAspect = byInnerKey(modsByBehaviour, function (name, modification) {
  7443. return {
  7444. name: name,
  7445. modification: modification
  7446. };
  7447. });
  7448. var combineObjects = function (objects) {
  7449. return foldr(objects, function (b, a) {
  7450. return __assign(__assign({}, a.modification), b);
  7451. }, {});
  7452. };
  7453. var combinedClasses = foldr(byAspect.classes, function (b, a) {
  7454. return a.modification.concat(b);
  7455. }, []);
  7456. var combinedAttributes = combineObjects(byAspect.attributes);
  7457. var combinedStyles = combineObjects(byAspect.styles);
  7458. return nu$3({
  7459. classes: combinedClasses,
  7460. attributes: combinedAttributes,
  7461. styles: combinedStyles
  7462. });
  7463. };
  7464. var sortKeys = function (label, keyName, array, order) {
  7465. try {
  7466. var sorted = sort(array, function (a, b) {
  7467. var aKey = a[keyName];
  7468. var bKey = b[keyName];
  7469. var aIndex = order.indexOf(aKey);
  7470. var bIndex = order.indexOf(bKey);
  7471. if (aIndex === -1) {
  7472. throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7473. }
  7474. if (bIndex === -1) {
  7475. throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2));
  7476. }
  7477. if (aIndex < bIndex) {
  7478. return -1;
  7479. } else if (bIndex < aIndex) {
  7480. return 1;
  7481. } else {
  7482. return 0;
  7483. }
  7484. });
  7485. return Result.value(sorted);
  7486. } catch (err) {
  7487. return Result.error([err]);
  7488. }
  7489. };
  7490. var uncurried = function (handler, purpose) {
  7491. return {
  7492. handler: handler,
  7493. purpose: purpose
  7494. };
  7495. };
  7496. var curried = function (handler, purpose) {
  7497. return {
  7498. cHandler: handler,
  7499. purpose: purpose
  7500. };
  7501. };
  7502. var curryArgs = function (descHandler, extraArgs) {
  7503. return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose);
  7504. };
  7505. var getCurried = function (descHandler) {
  7506. return descHandler.cHandler;
  7507. };
  7508. var behaviourTuple = function (name, handler) {
  7509. return {
  7510. name: name,
  7511. handler: handler
  7512. };
  7513. };
  7514. var nameToHandlers = function (behaviours, info) {
  7515. var r = {};
  7516. each$1(behaviours, function (behaviour) {
  7517. r[behaviour.name()] = behaviour.handlers(info);
  7518. });
  7519. return r;
  7520. };
  7521. var groupByEvents = function (info, behaviours, base) {
  7522. var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info));
  7523. return byInnerKey(behaviourEvents, behaviourTuple);
  7524. };
  7525. var combine = function (info, eventOrder, behaviours, base) {
  7526. var byEventName = groupByEvents(info, behaviours, base);
  7527. return combineGroups(byEventName, eventOrder);
  7528. };
  7529. var assemble = function (rawHandler) {
  7530. var handler = read$1(rawHandler);
  7531. return function (component, simulatedEvent) {
  7532. var rest = [];
  7533. for (var _i = 2; _i < arguments.length; _i++) {
  7534. rest[_i - 2] = arguments[_i];
  7535. }
  7536. var args = [
  7537. component,
  7538. simulatedEvent
  7539. ].concat(rest);
  7540. if (handler.abort.apply(undefined, args)) {
  7541. simulatedEvent.stop();
  7542. } else if (handler.can.apply(undefined, args)) {
  7543. handler.run.apply(undefined, args);
  7544. }
  7545. };
  7546. };
  7547. var missingOrderError = function (eventName, tuples) {
  7548. return Result.error(['The event (' + eventName + ') has more than one behaviour that listens to it.\nWhen this occurs, you must ' + 'specify an event ordering for the behaviours in your spec (e.g. [ "listing", "toggling" ]).\nThe behaviours that ' + 'can trigger it are: ' + JSON.stringify(map$2(tuples, function (c) {
  7549. return c.name;
  7550. }), null, 2)]);
  7551. };
  7552. var fuse = function (tuples, eventOrder, eventName) {
  7553. var order = eventOrder[eventName];
  7554. if (!order) {
  7555. return missingOrderError(eventName, tuples);
  7556. } else {
  7557. return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
  7558. var handlers = map$2(sortedTuples, function (tuple) {
  7559. return tuple.handler;
  7560. });
  7561. return fuse$1(handlers);
  7562. });
  7563. }
  7564. };
  7565. var combineGroups = function (byEventName, eventOrder) {
  7566. var r = mapToArray(byEventName, function (tuples, eventName) {
  7567. var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName);
  7568. return combined.map(function (handler) {
  7569. var assembled = assemble(handler);
  7570. var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) {
  7571. return exists(tuples, function (t) {
  7572. return t.name === o;
  7573. });
  7574. }).join(' > ') : tuples[0].name;
  7575. return wrap(eventName, uncurried(assembled, purpose));
  7576. });
  7577. });
  7578. return consolidate(r, {});
  7579. };
  7580. var _a;
  7581. var baseBehaviour = 'alloy.base.behaviour';
  7582. var schema$6 = objOf([
  7583. field$2('dom', 'dom', required$2(), objOf([
  7584. required$1('tag'),
  7585. defaulted('styles', {}),
  7586. defaulted('classes', []),
  7587. defaulted('attributes', {}),
  7588. option('value'),
  7589. option('innerHtml')
  7590. ])),
  7591. required$1('components'),
  7592. required$1('uid'),
  7593. defaulted('events', {}),
  7594. defaulted('apis', {}),
  7595. field$2('eventOrder', 'eventOrder', mergeWith((_a = {}, _a[execute$5()] = [
  7596. 'disabling',
  7597. baseBehaviour,
  7598. 'toggling',
  7599. 'typeaheadevents'
  7600. ], _a[focus$4()] = [
  7601. baseBehaviour,
  7602. 'focusing',
  7603. 'keying'
  7604. ], _a[systemInit()] = [
  7605. baseBehaviour,
  7606. 'disabling',
  7607. 'toggling',
  7608. 'representing'
  7609. ], _a[input$1()] = [
  7610. baseBehaviour,
  7611. 'representing',
  7612. 'streaming',
  7613. 'invalidating'
  7614. ], _a[detachedFromDom()] = [
  7615. baseBehaviour,
  7616. 'representing',
  7617. 'item-events',
  7618. 'tooltipping'
  7619. ], _a[mousedown()] = [
  7620. 'focusing',
  7621. baseBehaviour,
  7622. 'item-type-events'
  7623. ], _a[touchstart()] = [
  7624. 'focusing',
  7625. baseBehaviour,
  7626. 'item-type-events'
  7627. ], _a[mouseover()] = [
  7628. 'item-type-events',
  7629. 'tooltipping'
  7630. ], _a[receive$1()] = [
  7631. 'receiving',
  7632. 'reflecting',
  7633. 'tooltipping'
  7634. ], _a)), anyValue()),
  7635. option('domModification')
  7636. ]);
  7637. var toInfo = function (spec) {
  7638. return asRaw('custom.definition', schema$6, spec);
  7639. };
  7640. var toDefinition = function (detail) {
  7641. return __assign(__assign({}, detail.dom), {
  7642. uid: detail.uid,
  7643. domChildren: map$2(detail.components, function (comp) {
  7644. return comp.element;
  7645. })
  7646. });
  7647. };
  7648. var toModification = function (detail) {
  7649. return detail.domModification.fold(function () {
  7650. return nu$3({});
  7651. }, nu$3);
  7652. };
  7653. var toEvents = function (info) {
  7654. return info.events;
  7655. };
  7656. var add = function (element, classes) {
  7657. each$1(classes, function (x) {
  7658. add$1(element, x);
  7659. });
  7660. };
  7661. var remove$1 = function (element, classes) {
  7662. each$1(classes, function (x) {
  7663. remove$3(element, x);
  7664. });
  7665. };
  7666. var renderToDom = function (definition) {
  7667. var subject = SugarElement.fromTag(definition.tag);
  7668. setAll$1(subject, definition.attributes);
  7669. add(subject, definition.classes);
  7670. setAll(subject, definition.styles);
  7671. definition.innerHtml.each(function (html) {
  7672. return set$7(subject, html);
  7673. });
  7674. var children = definition.domChildren;
  7675. append$1(subject, children);
  7676. definition.value.each(function (value) {
  7677. set$2(subject, value);
  7678. });
  7679. if (!definition.uid) {
  7680. }
  7681. writeOnly(subject, definition.uid);
  7682. return subject;
  7683. };
  7684. var getBehaviours = function (spec) {
  7685. var behaviours = get$c(spec, 'behaviours').getOr({});
  7686. return bind$3(keys(behaviours), function (name) {
  7687. var behaviour = behaviours[name];
  7688. return isNonNullable(behaviour) ? [behaviour.me] : [];
  7689. });
  7690. };
  7691. var generateFrom = function (spec, all) {
  7692. return generateFrom$1(spec, all);
  7693. };
  7694. var generate$1 = function (spec) {
  7695. var all = getBehaviours(spec);
  7696. return generateFrom(spec, all);
  7697. };
  7698. var getDomDefinition = function (info, bList, bData) {
  7699. var definition = toDefinition(info);
  7700. var infoModification = toModification(info);
  7701. var baseModification = { 'alloy.base.modification': infoModification };
  7702. var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification;
  7703. return merge(definition, modification);
  7704. };
  7705. var getEvents = function (info, bList, bData) {
  7706. var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
  7707. return combine(bData, info.eventOrder, bList, baseEvents).getOrDie();
  7708. };
  7709. var build$2 = function (spec) {
  7710. var getMe = function () {
  7711. return me;
  7712. };
  7713. var systemApi = Cell(singleton);
  7714. var info = getOrDie(toInfo(spec));
  7715. var bBlob = generate$1(spec);
  7716. var bList = getBehaviours$1(bBlob);
  7717. var bData = getData(bBlob);
  7718. var modDefinition = getDomDefinition(info, bList, bData);
  7719. var item = renderToDom(modDefinition);
  7720. var events = getEvents(info, bList, bData);
  7721. var subcomponents = Cell(info.components);
  7722. var connect = function (newApi) {
  7723. systemApi.set(newApi);
  7724. };
  7725. var disconnect = function () {
  7726. systemApi.set(NoContextApi(getMe));
  7727. };
  7728. var syncComponents = function () {
  7729. var children$1 = children(item);
  7730. var subs = bind$3(children$1, function (child) {
  7731. return systemApi.get().getByDom(child).fold(function () {
  7732. return [];
  7733. }, pure$2);
  7734. });
  7735. subcomponents.set(subs);
  7736. };
  7737. var config = function (behaviour) {
  7738. var b = bData;
  7739. var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
  7740. throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2));
  7741. };
  7742. return f();
  7743. };
  7744. var hasConfigured = function (behaviour) {
  7745. return isFunction(bData[behaviour.name()]);
  7746. };
  7747. var getApis = function () {
  7748. return info.apis;
  7749. };
  7750. var readState = function (behaviourName) {
  7751. return bData[behaviourName]().map(function (b) {
  7752. return b.state.readState();
  7753. }).getOr('not enabled');
  7754. };
  7755. var me = {
  7756. uid: spec.uid,
  7757. getSystem: systemApi.get,
  7758. config: config,
  7759. hasConfigured: hasConfigured,
  7760. spec: spec,
  7761. readState: readState,
  7762. getApis: getApis,
  7763. connect: connect,
  7764. disconnect: disconnect,
  7765. element: item,
  7766. syncComponents: syncComponents,
  7767. components: subcomponents.get,
  7768. events: events
  7769. };
  7770. return me;
  7771. };
  7772. var buildSubcomponents = function (spec) {
  7773. var components = get$c(spec, 'components').getOr([]);
  7774. return map$2(components, build$1);
  7775. };
  7776. var buildFromSpec = function (userSpec) {
  7777. var _a = make$3(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']);
  7778. var components = buildSubcomponents(spec);
  7779. var completeSpec = __assign(__assign({}, spec), {
  7780. events: __assign(__assign({}, DefaultEvents), specEvents),
  7781. components: components
  7782. });
  7783. return Result.value(build$2(completeSpec));
  7784. };
  7785. var text = function (textContent) {
  7786. var element = SugarElement.fromText(textContent);
  7787. return external({ element: element });
  7788. };
  7789. var external = function (spec) {
  7790. var extSpec = asRawOrDie$1('external.component', objOfOnly([
  7791. required$1('element'),
  7792. option('uid')
  7793. ]), spec);
  7794. var systemApi = Cell(NoContextApi());
  7795. var connect = function (newApi) {
  7796. systemApi.set(newApi);
  7797. };
  7798. var disconnect = function () {
  7799. systemApi.set(NoContextApi(function () {
  7800. return me;
  7801. }));
  7802. };
  7803. var uid = extSpec.uid.getOrThunk(function () {
  7804. return generate$2('external');
  7805. });
  7806. writeOnly(extSpec.element, uid);
  7807. var me = {
  7808. uid: uid,
  7809. getSystem: systemApi.get,
  7810. config: Optional.none,
  7811. hasConfigured: never,
  7812. connect: connect,
  7813. disconnect: disconnect,
  7814. getApis: function () {
  7815. return {};
  7816. },
  7817. element: extSpec.element,
  7818. spec: spec,
  7819. readState: constant$1('No state'),
  7820. syncComponents: noop,
  7821. components: constant$1([]),
  7822. events: {}
  7823. };
  7824. return premade$1(me);
  7825. };
  7826. var uids = generate$2;
  7827. var isSketchSpec = function (spec) {
  7828. return has$2(spec, 'uid');
  7829. };
  7830. var build$1 = function (spec) {
  7831. return getPremade(spec).getOrThunk(function () {
  7832. var userSpecWithUid = isSketchSpec(spec) ? spec : __assign({ uid: uids('') }, spec);
  7833. return buildFromSpec(userSpecWithUid).getOrDie();
  7834. });
  7835. };
  7836. var premade = premade$1;
  7837. var hoverEvent = 'alloy.item-hover';
  7838. var focusEvent = 'alloy.item-focus';
  7839. var onHover = function (item) {
  7840. if (search(item.element).isNone() || Focusing.isFocused(item)) {
  7841. if (!Focusing.isFocused(item)) {
  7842. Focusing.focus(item);
  7843. }
  7844. emitWith(item, hoverEvent, { item: item });
  7845. }
  7846. };
  7847. var onFocus = function (item) {
  7848. emitWith(item, focusEvent, { item: item });
  7849. };
  7850. var hover = constant$1(hoverEvent);
  7851. var focus$1 = constant$1(focusEvent);
  7852. var builder$2 = function (detail) {
  7853. return {
  7854. dom: detail.dom,
  7855. domModification: __assign(__assign({}, detail.domModification), { attributes: __assign(__assign(__assign({ 'role': detail.toggling.isSome() ? 'menuitemcheckbox' : 'menuitem' }, detail.domModification.attributes), { 'aria-haspopup': detail.hasSubmenu }), detail.hasSubmenu ? { 'aria-expanded': false } : {}) }),
  7856. behaviours: SketchBehaviours.augment(detail.itemBehaviours, [
  7857. detail.toggling.fold(Toggling.revoke, function (tConfig) {
  7858. return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig));
  7859. }),
  7860. Focusing.config({
  7861. ignore: detail.ignoreFocus,
  7862. stopMousedown: detail.ignoreFocus,
  7863. onFocus: function (component) {
  7864. onFocus(component);
  7865. }
  7866. }),
  7867. Keying.config({ mode: 'execution' }),
  7868. Representing.config({
  7869. store: {
  7870. mode: 'memory',
  7871. initialValue: detail.data
  7872. }
  7873. }),
  7874. config('item-type-events', __spreadArray(__spreadArray([], pointerEvents(), true), [
  7875. run(mouseover(), onHover),
  7876. run(focusItem(), Focusing.focus)
  7877. ], false))
  7878. ]),
  7879. components: detail.components,
  7880. eventOrder: detail.eventOrder
  7881. };
  7882. };
  7883. var schema$5 = [
  7884. required$1('data'),
  7885. required$1('components'),
  7886. required$1('dom'),
  7887. defaulted('hasSubmenu', false),
  7888. option('toggling'),
  7889. SketchBehaviours.field('itemBehaviours', [
  7890. Toggling,
  7891. Focusing,
  7892. Keying,
  7893. Representing
  7894. ]),
  7895. defaulted('ignoreFocus', false),
  7896. defaulted('domModification', {}),
  7897. output('builder', builder$2),
  7898. defaulted('eventOrder', {})
  7899. ];
  7900. var builder$1 = function (detail) {
  7901. return {
  7902. dom: detail.dom,
  7903. components: detail.components,
  7904. events: derive$3([stopper(focusItem())])
  7905. };
  7906. };
  7907. var schema$4 = [
  7908. required$1('dom'),
  7909. required$1('components'),
  7910. output('builder', builder$1)
  7911. ];
  7912. var owner = constant$1('item-widget');
  7913. var parts$3 = constant$1([required({
  7914. name: 'widget',
  7915. overrides: function (detail) {
  7916. return {
  7917. behaviours: derive$2([Representing.config({
  7918. store: {
  7919. mode: 'manual',
  7920. getValue: function (_component) {
  7921. return detail.data;
  7922. },
  7923. setValue: noop
  7924. }
  7925. })])
  7926. };
  7927. }
  7928. })]);
  7929. var builder = function (detail) {
  7930. var subs = substitutes(owner(), detail, parts$3());
  7931. var components$1 = components(owner(), detail, subs.internals());
  7932. var focusWidget = function (component) {
  7933. return getPart(component, detail, 'widget').map(function (widget) {
  7934. Keying.focusIn(widget);
  7935. return widget;
  7936. });
  7937. };
  7938. var onHorizontalArrow = function (component, simulatedEvent) {
  7939. return inside(simulatedEvent.event.target) ? Optional.none() : function () {
  7940. if (detail.autofocus) {
  7941. simulatedEvent.setSource(component.element);
  7942. return Optional.none();
  7943. } else {
  7944. return Optional.none();
  7945. }
  7946. }();
  7947. };
  7948. return {
  7949. dom: detail.dom,
  7950. components: components$1,
  7951. domModification: detail.domModification,
  7952. events: derive$3([
  7953. runOnExecute(function (component, simulatedEvent) {
  7954. focusWidget(component).each(function (_widget) {
  7955. simulatedEvent.stop();
  7956. });
  7957. }),
  7958. run(mouseover(), onHover),
  7959. run(focusItem(), function (component, _simulatedEvent) {
  7960. if (detail.autofocus) {
  7961. focusWidget(component);
  7962. } else {
  7963. Focusing.focus(component);
  7964. }
  7965. })
  7966. ]),
  7967. behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [
  7968. Representing.config({
  7969. store: {
  7970. mode: 'memory',
  7971. initialValue: detail.data
  7972. }
  7973. }),
  7974. Focusing.config({
  7975. ignore: detail.ignoreFocus,
  7976. onFocus: function (component) {
  7977. onFocus(component);
  7978. }
  7979. }),
  7980. Keying.config({
  7981. mode: 'special',
  7982. focusIn: detail.autofocus ? function (component) {
  7983. focusWidget(component);
  7984. } : revoke(),
  7985. onLeft: onHorizontalArrow,
  7986. onRight: onHorizontalArrow,
  7987. onEscape: function (component, simulatedEvent) {
  7988. if (!Focusing.isFocused(component) && !detail.autofocus) {
  7989. Focusing.focus(component);
  7990. return Optional.some(true);
  7991. } else if (detail.autofocus) {
  7992. simulatedEvent.setSource(component.element);
  7993. return Optional.none();
  7994. } else {
  7995. return Optional.none();
  7996. }
  7997. }
  7998. })
  7999. ])
  8000. };
  8001. };
  8002. var schema$3 = [
  8003. required$1('uid'),
  8004. required$1('data'),
  8005. required$1('components'),
  8006. required$1('dom'),
  8007. defaulted('autofocus', false),
  8008. defaulted('ignoreFocus', false),
  8009. SketchBehaviours.field('widgetBehaviours', [
  8010. Representing,
  8011. Focusing,
  8012. Keying
  8013. ]),
  8014. defaulted('domModification', {}),
  8015. defaultUidsSchema(parts$3()),
  8016. output('builder', builder)
  8017. ];
  8018. var itemSchema = choose$1('type', {
  8019. widget: schema$3,
  8020. item: schema$5,
  8021. separator: schema$4
  8022. });
  8023. var configureGrid = function (detail, movementInfo) {
  8024. return {
  8025. mode: 'flatgrid',
  8026. selector: '.' + detail.markers.item,
  8027. initSize: {
  8028. numColumns: movementInfo.initSize.numColumns,
  8029. numRows: movementInfo.initSize.numRows
  8030. },
  8031. focusManager: detail.focusManager
  8032. };
  8033. };
  8034. var configureMatrix = function (detail, movementInfo) {
  8035. return {
  8036. mode: 'matrix',
  8037. selectors: {
  8038. row: movementInfo.rowSelector,
  8039. cell: '.' + detail.markers.item
  8040. },
  8041. focusManager: detail.focusManager
  8042. };
  8043. };
  8044. var configureMenu = function (detail, movementInfo) {
  8045. return {
  8046. mode: 'menu',
  8047. selector: '.' + detail.markers.item,
  8048. moveOnTab: movementInfo.moveOnTab,
  8049. focusManager: detail.focusManager
  8050. };
  8051. };
  8052. var parts$2 = constant$1([group({
  8053. factory: {
  8054. sketch: function (spec) {
  8055. var itemInfo = asRawOrDie$1('menu.spec item', itemSchema, spec);
  8056. return itemInfo.builder(itemInfo);
  8057. }
  8058. },
  8059. name: 'items',
  8060. unit: 'item',
  8061. defaults: function (detail, u) {
  8062. return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') });
  8063. },
  8064. overrides: function (detail, u) {
  8065. return {
  8066. type: u.type,
  8067. ignoreFocus: detail.fakeFocus,
  8068. domModification: { classes: [detail.markers.item] }
  8069. };
  8070. }
  8071. })]);
  8072. var schema$2 = constant$1([
  8073. required$1('value'),
  8074. required$1('items'),
  8075. required$1('dom'),
  8076. required$1('components'),
  8077. defaulted('eventOrder', {}),
  8078. field$1('menuBehaviours', [
  8079. Highlighting,
  8080. Representing,
  8081. Composing,
  8082. Keying
  8083. ]),
  8084. defaultedOf('movement', {
  8085. mode: 'menu',
  8086. moveOnTab: true
  8087. }, choose$1('mode', {
  8088. grid: [
  8089. initSize(),
  8090. output('config', configureGrid)
  8091. ],
  8092. matrix: [
  8093. output('config', configureMatrix),
  8094. required$1('rowSelector')
  8095. ],
  8096. menu: [
  8097. defaulted('moveOnTab', true),
  8098. output('config', configureMenu)
  8099. ]
  8100. })),
  8101. itemMarkers(),
  8102. defaulted('fakeFocus', false),
  8103. defaulted('focusManager', dom$2()),
  8104. onHandler('onHighlight')
  8105. ]);
  8106. var focus = constant$1('alloy.menu-focus');
  8107. var make$2 = function (detail, components, _spec, _externals) {
  8108. return {
  8109. uid: detail.uid,
  8110. dom: detail.dom,
  8111. markers: detail.markers,
  8112. behaviours: augment(detail.menuBehaviours, [
  8113. Highlighting.config({
  8114. highlightClass: detail.markers.selectedItem,
  8115. itemClass: detail.markers.item,
  8116. onHighlight: detail.onHighlight
  8117. }),
  8118. Representing.config({
  8119. store: {
  8120. mode: 'memory',
  8121. initialValue: detail.value
  8122. }
  8123. }),
  8124. Composing.config({ find: Optional.some }),
  8125. Keying.config(detail.movement.config(detail, detail.movement))
  8126. ]),
  8127. events: derive$3([
  8128. run(focus$1(), function (menu, simulatedEvent) {
  8129. var event = simulatedEvent.event;
  8130. menu.getSystem().getByDom(event.target).each(function (item) {
  8131. Highlighting.highlight(menu, item);
  8132. simulatedEvent.stop();
  8133. emitWith(menu, focus(), {
  8134. menu: menu,
  8135. item: item
  8136. });
  8137. });
  8138. }),
  8139. run(hover(), function (menu, simulatedEvent) {
  8140. var item = simulatedEvent.event.item;
  8141. Highlighting.highlight(menu, item);
  8142. })
  8143. ]),
  8144. components: components,
  8145. eventOrder: detail.eventOrder,
  8146. domModification: { attributes: { role: 'menu' } }
  8147. };
  8148. };
  8149. var Menu = composite({
  8150. name: 'Menu',
  8151. configFields: schema$2(),
  8152. partFields: parts$2(),
  8153. factory: make$2
  8154. });
  8155. var preserve = function (f, container) {
  8156. var dos = getRootNode(container);
  8157. var refocus = active(dos).bind(function (focused) {
  8158. var hasFocus = function (elem) {
  8159. return eq(focused, elem);
  8160. };
  8161. return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus);
  8162. });
  8163. var result = f(container);
  8164. refocus.each(function (oldFocus) {
  8165. active(dos).filter(function (newFocus) {
  8166. return eq(newFocus, oldFocus);
  8167. }).fold(function () {
  8168. focus$3(oldFocus);
  8169. }, noop);
  8170. });
  8171. return result;
  8172. };
  8173. var set = function (component, replaceConfig, replaceState, data) {
  8174. preserve(function () {
  8175. var newChildren = map$2(data, component.getSystem().build);
  8176. replaceChildren(component, newChildren);
  8177. }, component.element);
  8178. };
  8179. var insert = function (component, replaceConfig, insertion, childSpec) {
  8180. var child = component.getSystem().build(childSpec);
  8181. attachWith(component, child, insertion);
  8182. };
  8183. var append = function (component, replaceConfig, replaceState, appendee) {
  8184. insert(component, replaceConfig, append$2, appendee);
  8185. };
  8186. var prepend = function (component, replaceConfig, replaceState, prependee) {
  8187. insert(component, replaceConfig, prepend$1, prependee);
  8188. };
  8189. var remove = function (component, replaceConfig, replaceState, removee) {
  8190. var children = contents(component);
  8191. var foundChild = find$2(children, function (child) {
  8192. return eq(removee.element, child.element);
  8193. });
  8194. foundChild.each(detach);
  8195. };
  8196. var contents = function (component, _replaceConfig) {
  8197. return component.components();
  8198. };
  8199. var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) {
  8200. var children = contents(component);
  8201. return Optional.from(children[replaceeIndex]).map(function (replacee) {
  8202. remove(component, replaceConfig, replaceState, replacee);
  8203. replacer.each(function (r) {
  8204. insert(component, replaceConfig, function (p, c) {
  8205. appendAt(p, c, replaceeIndex);
  8206. }, r);
  8207. });
  8208. return replacee;
  8209. });
  8210. };
  8211. var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) {
  8212. var children = contents(component);
  8213. return findIndex$1(children, replaceePred).bind(function (replaceeIndex) {
  8214. return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer);
  8215. });
  8216. };
  8217. var ReplaceApis = /*#__PURE__*/Object.freeze({
  8218. __proto__: null,
  8219. append: append,
  8220. prepend: prepend,
  8221. remove: remove,
  8222. replaceAt: replaceAt,
  8223. replaceBy: replaceBy,
  8224. set: set,
  8225. contents: contents
  8226. });
  8227. var Replacing = create$5({
  8228. fields: [],
  8229. name: 'replacing',
  8230. apis: ReplaceApis
  8231. });
  8232. var transpose = function (obj) {
  8233. return tupleMap(obj, function (v, k) {
  8234. return {
  8235. k: v,
  8236. v: k
  8237. };
  8238. });
  8239. };
  8240. var trace = function (items, byItem, byMenu, finish) {
  8241. return get$c(byMenu, finish).bind(function (triggerItem) {
  8242. return get$c(items, triggerItem).bind(function (triggerMenu) {
  8243. var rest = trace(items, byItem, byMenu, triggerMenu);
  8244. return Optional.some([triggerMenu].concat(rest));
  8245. });
  8246. }).getOr([]);
  8247. };
  8248. var generate = function (menus, expansions) {
  8249. var items = {};
  8250. each(menus, function (menuItems, menu) {
  8251. each$1(menuItems, function (item) {
  8252. items[item] = menu;
  8253. });
  8254. });
  8255. var byItem = expansions;
  8256. var byMenu = transpose(expansions);
  8257. var menuPaths = map$1(byMenu, function (_triggerItem, submenu) {
  8258. return [submenu].concat(trace(items, byItem, byMenu, submenu));
  8259. });
  8260. return map$1(items, function (menu) {
  8261. return get$c(menuPaths, menu).getOr([menu]);
  8262. });
  8263. };
  8264. var init$2 = function () {
  8265. var expansions = Cell({});
  8266. var menus = Cell({});
  8267. var paths = Cell({});
  8268. var primary = value();
  8269. var directory = Cell({});
  8270. var clear = function () {
  8271. expansions.set({});
  8272. menus.set({});
  8273. paths.set({});
  8274. primary.clear();
  8275. };
  8276. var isClear = function () {
  8277. return primary.get().isNone();
  8278. };
  8279. var setMenuBuilt = function (menuName, built) {
  8280. var _a;
  8281. menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = {
  8282. type: 'prepared',
  8283. menu: built
  8284. }, _a)));
  8285. };
  8286. var setContents = function (sPrimary, sMenus, sExpansions, dir) {
  8287. primary.set(sPrimary);
  8288. expansions.set(sExpansions);
  8289. menus.set(sMenus);
  8290. directory.set(dir);
  8291. var sPaths = generate(dir, sExpansions);
  8292. paths.set(sPaths);
  8293. };
  8294. var getTriggeringItem = function (menuValue) {
  8295. return find(expansions.get(), function (v, _k) {
  8296. return v === menuValue;
  8297. });
  8298. };
  8299. var getTriggerData = function (menuValue, getItemByValue, path) {
  8300. return getPreparedMenu(menuValue).bind(function (menu) {
  8301. return getTriggeringItem(menuValue).bind(function (triggeringItemValue) {
  8302. return getItemByValue(triggeringItemValue).map(function (triggeredItem) {
  8303. return {
  8304. triggeredMenu: menu,
  8305. triggeringItem: triggeredItem,
  8306. triggeringPath: path
  8307. };
  8308. });
  8309. });
  8310. });
  8311. };
  8312. var getTriggeringPath = function (itemValue, getItemByValue) {
  8313. var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) {
  8314. return getPreparedMenu(menuValue).isSome();
  8315. });
  8316. return get$c(paths.get(), itemValue).bind(function (path) {
  8317. var revPath = reverse(extraPath.concat(path));
  8318. var triggers = bind$3(revPath, function (menuValue, menuIndex) {
  8319. return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () {
  8320. return is(primary.get(), menuValue) ? [] : [Optional.none()];
  8321. }, function (data) {
  8322. return [Optional.some(data)];
  8323. });
  8324. });
  8325. return sequence(triggers);
  8326. });
  8327. };
  8328. var expand = function (itemValue) {
  8329. return get$c(expansions.get(), itemValue).map(function (menu) {
  8330. var current = get$c(paths.get(), itemValue).getOr([]);
  8331. return [menu].concat(current);
  8332. });
  8333. };
  8334. var collapse = function (itemValue) {
  8335. return get$c(paths.get(), itemValue).bind(function (path) {
  8336. return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none();
  8337. });
  8338. };
  8339. var refresh = function (itemValue) {
  8340. return get$c(paths.get(), itemValue);
  8341. };
  8342. var getPreparedMenu = function (menuValue) {
  8343. return lookupMenu(menuValue).bind(extractPreparedMenu);
  8344. };
  8345. var lookupMenu = function (menuValue) {
  8346. return get$c(menus.get(), menuValue);
  8347. };
  8348. var lookupItem = function (itemValue) {
  8349. return get$c(expansions.get(), itemValue);
  8350. };
  8351. var otherMenus = function (path) {
  8352. var menuValues = directory.get();
  8353. return difference(keys(menuValues), path);
  8354. };
  8355. var getPrimary = function () {
  8356. return primary.get().bind(getPreparedMenu);
  8357. };
  8358. var getMenus = function () {
  8359. return menus.get();
  8360. };
  8361. return {
  8362. setMenuBuilt: setMenuBuilt,
  8363. setContents: setContents,
  8364. expand: expand,
  8365. refresh: refresh,
  8366. collapse: collapse,
  8367. lookupMenu: lookupMenu,
  8368. lookupItem: lookupItem,
  8369. otherMenus: otherMenus,
  8370. getPrimary: getPrimary,
  8371. getMenus: getMenus,
  8372. clear: clear,
  8373. isClear: isClear,
  8374. getTriggeringPath: getTriggeringPath
  8375. };
  8376. };
  8377. var extractPreparedMenu = function (prep) {
  8378. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8379. };
  8380. var LayeredState = {
  8381. init: init$2,
  8382. extractPreparedMenu: extractPreparedMenu
  8383. };
  8384. var make$1 = function (detail, _rawUiSpec) {
  8385. var submenuParentItems = value();
  8386. var buildMenus = function (container, primaryName, menus) {
  8387. return map$1(menus, function (spec, name) {
  8388. var makeSketch = function () {
  8389. return Menu.sketch(__assign(__assign({}, spec), {
  8390. value: name,
  8391. markers: detail.markers,
  8392. fakeFocus: detail.fakeFocus,
  8393. onHighlight: detail.onHighlight,
  8394. focusManager: detail.fakeFocus ? highlights() : dom$2()
  8395. }));
  8396. };
  8397. return name === primaryName ? {
  8398. type: 'prepared',
  8399. menu: container.getSystem().build(makeSketch())
  8400. } : {
  8401. type: 'notbuilt',
  8402. nbMenu: makeSketch
  8403. };
  8404. });
  8405. };
  8406. var layeredState = LayeredState.init();
  8407. var setup = function (container) {
  8408. var componentMap = buildMenus(container, detail.data.primary, detail.data.menus);
  8409. var directory = toDirectory();
  8410. layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory);
  8411. return layeredState.getPrimary();
  8412. };
  8413. var getItemValue = function (item) {
  8414. return Representing.getValue(item).value;
  8415. };
  8416. var getItemByValue = function (_container, menus, itemValue) {
  8417. return findMap(menus, function (menu) {
  8418. if (!menu.getSystem().isConnected()) {
  8419. return Optional.none();
  8420. }
  8421. var candidates = Highlighting.getCandidates(menu);
  8422. return find$2(candidates, function (c) {
  8423. return getItemValue(c) === itemValue;
  8424. });
  8425. });
  8426. };
  8427. var toDirectory = function (_container) {
  8428. return map$1(detail.data.menus, function (data, _menuName) {
  8429. return bind$3(data.items, function (item) {
  8430. return item.type === 'separator' ? [] : [item.data.value];
  8431. });
  8432. });
  8433. };
  8434. var setActiveMenu = function (container, menu) {
  8435. Highlighting.highlight(container, menu);
  8436. Highlighting.getHighlighted(menu).orThunk(function () {
  8437. return Highlighting.getFirst(menu);
  8438. }).each(function (item) {
  8439. dispatch(container, item.element, focusItem());
  8440. });
  8441. };
  8442. var getMenus = function (state, menuValues) {
  8443. return cat(map$2(menuValues, function (mv) {
  8444. return state.lookupMenu(mv).bind(function (prep) {
  8445. return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none();
  8446. });
  8447. }));
  8448. };
  8449. var closeOthers = function (container, state, path) {
  8450. var others = getMenus(state, state.otherMenus(path));
  8451. each$1(others, function (o) {
  8452. remove$1(o.element, [detail.markers.backgroundMenu]);
  8453. if (!detail.stayInDom) {
  8454. Replacing.remove(container, o);
  8455. }
  8456. });
  8457. };
  8458. var getSubmenuParents = function (container) {
  8459. return submenuParentItems.get().getOrThunk(function () {
  8460. var r = {};
  8461. var items = descendants(container.element, '.' + detail.markers.item);
  8462. var parentItems = filter$2(items, function (i) {
  8463. return get$b(i, 'aria-haspopup') === 'true';
  8464. });
  8465. each$1(parentItems, function (i) {
  8466. container.getSystem().getByDom(i).each(function (itemComp) {
  8467. var key = getItemValue(itemComp);
  8468. r[key] = itemComp;
  8469. });
  8470. });
  8471. submenuParentItems.set(r);
  8472. return r;
  8473. });
  8474. };
  8475. var updateAriaExpansions = function (container, path) {
  8476. var parentItems = getSubmenuParents(container);
  8477. each(parentItems, function (v, k) {
  8478. var expanded = contains$1(path, k);
  8479. set$8(v.element, 'aria-expanded', expanded);
  8480. });
  8481. };
  8482. var updateMenuPath = function (container, state, path) {
  8483. return Optional.from(path[0]).bind(function (latestMenuName) {
  8484. return state.lookupMenu(latestMenuName).bind(function (menuPrep) {
  8485. if (menuPrep.type === 'notbuilt') {
  8486. return Optional.none();
  8487. } else {
  8488. var activeMenu = menuPrep.menu;
  8489. var rest = getMenus(state, path.slice(1));
  8490. each$1(rest, function (r) {
  8491. add$1(r.element, detail.markers.backgroundMenu);
  8492. });
  8493. if (!inBody(activeMenu.element)) {
  8494. Replacing.append(container, premade(activeMenu));
  8495. }
  8496. remove$1(activeMenu.element, [detail.markers.backgroundMenu]);
  8497. setActiveMenu(container, activeMenu);
  8498. closeOthers(container, state, path);
  8499. return Optional.some(activeMenu);
  8500. }
  8501. });
  8502. });
  8503. };
  8504. var ExpandHighlightDecision;
  8505. (function (ExpandHighlightDecision) {
  8506. ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu';
  8507. ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent';
  8508. }(ExpandHighlightDecision || (ExpandHighlightDecision = {})));
  8509. var buildIfRequired = function (container, menuName, menuPrep) {
  8510. if (menuPrep.type === 'notbuilt') {
  8511. var menu = container.getSystem().build(menuPrep.nbMenu());
  8512. layeredState.setMenuBuilt(menuName, menu);
  8513. return menu;
  8514. } else {
  8515. return menuPrep.menu;
  8516. }
  8517. };
  8518. var expandRight = function (container, item, decision) {
  8519. if (decision === void 0) {
  8520. decision = ExpandHighlightDecision.HighlightSubmenu;
  8521. }
  8522. if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) {
  8523. return Optional.some(item);
  8524. } else {
  8525. var value = getItemValue(item);
  8526. return layeredState.expand(value).bind(function (path) {
  8527. updateAriaExpansions(container, path);
  8528. return Optional.from(path[0]).bind(function (menuName) {
  8529. return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) {
  8530. var activeMenu = buildIfRequired(container, menuName, activeMenuPrep);
  8531. if (!inBody(activeMenu.element)) {
  8532. Replacing.append(container, premade(activeMenu));
  8533. }
  8534. detail.onOpenSubmenu(container, item, activeMenu, reverse(path));
  8535. if (decision === ExpandHighlightDecision.HighlightSubmenu) {
  8536. Highlighting.highlightFirst(activeMenu);
  8537. return updateMenuPath(container, layeredState, path);
  8538. } else {
  8539. Highlighting.dehighlightAll(activeMenu);
  8540. return Optional.some(item);
  8541. }
  8542. });
  8543. });
  8544. });
  8545. }
  8546. };
  8547. var collapseLeft = function (container, item) {
  8548. var value = getItemValue(item);
  8549. return layeredState.collapse(value).bind(function (path) {
  8550. updateAriaExpansions(container, path);
  8551. return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
  8552. detail.onCollapseMenu(container, item, activeMenu);
  8553. return activeMenu;
  8554. });
  8555. });
  8556. };
  8557. var updateView = function (container, item) {
  8558. var value = getItemValue(item);
  8559. return layeredState.refresh(value).bind(function (path) {
  8560. updateAriaExpansions(container, path);
  8561. return updateMenuPath(container, layeredState, path);
  8562. });
  8563. };
  8564. var onRight = function (container, item) {
  8565. return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu);
  8566. };
  8567. var onLeft = function (container, item) {
  8568. return inside(item.element) ? Optional.none() : collapseLeft(container, item);
  8569. };
  8570. var onEscape = function (container, item) {
  8571. return collapseLeft(container, item).orThunk(function () {
  8572. return detail.onEscape(container, item).map(function () {
  8573. return container;
  8574. });
  8575. });
  8576. };
  8577. var keyOnItem = function (f) {
  8578. return function (container, simulatedEvent) {
  8579. return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) {
  8580. return container.getSystem().getByDom(target).toOptional().bind(function (item) {
  8581. return f(container, item).map(always);
  8582. });
  8583. });
  8584. };
  8585. };
  8586. var events = derive$3([
  8587. run(focus(), function (sandbox, simulatedEvent) {
  8588. var item = simulatedEvent.event.item;
  8589. layeredState.lookupItem(getItemValue(item)).each(function () {
  8590. var menu = simulatedEvent.event.menu;
  8591. Highlighting.highlight(sandbox, menu);
  8592. var value = getItemValue(simulatedEvent.event.item);
  8593. layeredState.refresh(value).each(function (path) {
  8594. return closeOthers(sandbox, layeredState, path);
  8595. });
  8596. });
  8597. }),
  8598. runOnExecute(function (component, simulatedEvent) {
  8599. var target = simulatedEvent.event.target;
  8600. component.getSystem().getByDom(target).each(function (item) {
  8601. var itemValue = getItemValue(item);
  8602. if (itemValue.indexOf('collapse-item') === 0) {
  8603. collapseLeft(component, item);
  8604. }
  8605. expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () {
  8606. detail.onExecute(component, item);
  8607. }, noop);
  8608. });
  8609. }),
  8610. runOnAttached(function (container, _simulatedEvent) {
  8611. setup(container).each(function (primary) {
  8612. Replacing.append(container, premade(primary));
  8613. detail.onOpenMenu(container, primary);
  8614. if (detail.highlightImmediately) {
  8615. setActiveMenu(container, primary);
  8616. }
  8617. });
  8618. })
  8619. ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) {
  8620. var item = simulatedEvent.event.item;
  8621. updateView(sandbox, item);
  8622. expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent);
  8623. detail.onHover(sandbox, item);
  8624. })] : []));
  8625. var getActiveItem = function (container) {
  8626. return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted);
  8627. };
  8628. var collapseMenuApi = function (container) {
  8629. getActiveItem(container).each(function (currentItem) {
  8630. collapseLeft(container, currentItem);
  8631. });
  8632. };
  8633. var highlightPrimary = function (container) {
  8634. layeredState.getPrimary().each(function (primary) {
  8635. setActiveMenu(container, primary);
  8636. });
  8637. };
  8638. var extractMenuFromContainer = function (container) {
  8639. return Optional.from(container.components()[0]).filter(function (comp) {
  8640. return get$b(comp.element, 'role') === 'menu';
  8641. });
  8642. };
  8643. var repositionMenus = function (container) {
  8644. var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) {
  8645. return getActiveItem(container).bind(function (currentItem) {
  8646. var itemValue = getItemValue(currentItem);
  8647. var allMenus = values(layeredState.getMenus());
  8648. var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu));
  8649. return layeredState.getTriggeringPath(itemValue, function (v) {
  8650. return getItemByValue(container, preparedMenus, v);
  8651. });
  8652. }).map(function (triggeringPath) {
  8653. return {
  8654. primary: primary,
  8655. triggeringPath: triggeringPath
  8656. };
  8657. });
  8658. });
  8659. maybeActivePrimary.fold(function () {
  8660. extractMenuFromContainer(container).each(function (primaryMenu) {
  8661. detail.onRepositionMenu(container, primaryMenu, []);
  8662. });
  8663. }, function (_a) {
  8664. var primary = _a.primary, triggeringPath = _a.triggeringPath;
  8665. detail.onRepositionMenu(container, primary, triggeringPath);
  8666. });
  8667. };
  8668. var apis = {
  8669. collapseMenu: collapseMenuApi,
  8670. highlightPrimary: highlightPrimary,
  8671. repositionMenus: repositionMenus
  8672. };
  8673. return {
  8674. uid: detail.uid,
  8675. dom: detail.dom,
  8676. markers: detail.markers,
  8677. behaviours: augment(detail.tmenuBehaviours, [
  8678. Keying.config({
  8679. mode: 'special',
  8680. onRight: keyOnItem(onRight),
  8681. onLeft: keyOnItem(onLeft),
  8682. onEscape: keyOnItem(onEscape),
  8683. focusIn: function (container, _keyInfo) {
  8684. layeredState.getPrimary().each(function (primary) {
  8685. dispatch(container, primary.element, focusItem());
  8686. });
  8687. }
  8688. }),
  8689. Highlighting.config({
  8690. highlightClass: detail.markers.selectedMenu,
  8691. itemClass: detail.markers.menu
  8692. }),
  8693. Composing.config({
  8694. find: function (container) {
  8695. return Highlighting.getHighlighted(container);
  8696. }
  8697. }),
  8698. Replacing.config({})
  8699. ]),
  8700. eventOrder: detail.eventOrder,
  8701. apis: apis,
  8702. events: events
  8703. };
  8704. };
  8705. var collapseItem$1 = constant$1('collapse-item');
  8706. var tieredData = function (primary, menus, expansions) {
  8707. return {
  8708. primary: primary,
  8709. menus: menus,
  8710. expansions: expansions
  8711. };
  8712. };
  8713. var singleData = function (name, menu) {
  8714. return {
  8715. primary: name,
  8716. menus: wrap(name, menu),
  8717. expansions: {}
  8718. };
  8719. };
  8720. var collapseItem = function (text) {
  8721. return {
  8722. value: generate$4(collapseItem$1()),
  8723. meta: { text: text }
  8724. };
  8725. };
  8726. var tieredMenu = single({
  8727. name: 'TieredMenu',
  8728. configFields: [
  8729. onStrictKeyboardHandler('onExecute'),
  8730. onStrictKeyboardHandler('onEscape'),
  8731. onStrictHandler('onOpenMenu'),
  8732. onStrictHandler('onOpenSubmenu'),
  8733. onHandler('onRepositionMenu'),
  8734. onHandler('onCollapseMenu'),
  8735. defaulted('highlightImmediately', true),
  8736. requiredObjOf('data', [
  8737. required$1('primary'),
  8738. required$1('menus'),
  8739. required$1('expansions')
  8740. ]),
  8741. defaulted('fakeFocus', false),
  8742. onHandler('onHighlight'),
  8743. onHandler('onHover'),
  8744. tieredMenuMarkers(),
  8745. required$1('dom'),
  8746. defaulted('navigateOnHover', true),
  8747. defaulted('stayInDom', false),
  8748. field$1('tmenuBehaviours', [
  8749. Keying,
  8750. Highlighting,
  8751. Composing,
  8752. Replacing
  8753. ]),
  8754. defaulted('eventOrder', {})
  8755. ],
  8756. apis: {
  8757. collapseMenu: function (apis, tmenu) {
  8758. apis.collapseMenu(tmenu);
  8759. },
  8760. highlightPrimary: function (apis, tmenu) {
  8761. apis.highlightPrimary(tmenu);
  8762. },
  8763. repositionMenus: function (apis, tmenu) {
  8764. apis.repositionMenus(tmenu);
  8765. }
  8766. },
  8767. factory: make$1,
  8768. extraApis: {
  8769. tieredData: tieredData,
  8770. singleData: singleData,
  8771. collapseItem: collapseItem
  8772. }
  8773. });
  8774. var findRoute = function (component, transConfig, transState, route) {
  8775. return get$c(transConfig.routes, route.start).bind(function (sConfig) {
  8776. return get$c(sConfig, route.destination);
  8777. });
  8778. };
  8779. var getTransition = function (comp, transConfig, transState) {
  8780. var route = getCurrentRoute(comp, transConfig);
  8781. return route.bind(function (r) {
  8782. return getTransitionOf(comp, transConfig, transState, r);
  8783. });
  8784. };
  8785. var getTransitionOf = function (comp, transConfig, transState, route) {
  8786. return findRoute(comp, transConfig, transState, route).bind(function (r) {
  8787. return r.transition.map(function (t) {
  8788. return {
  8789. transition: t,
  8790. route: r
  8791. };
  8792. });
  8793. });
  8794. };
  8795. var disableTransition = function (comp, transConfig, transState) {
  8796. getTransition(comp, transConfig, transState).each(function (routeTransition) {
  8797. var t = routeTransition.transition;
  8798. remove$3(comp.element, t.transitionClass);
  8799. remove$6(comp.element, transConfig.destinationAttr);
  8800. });
  8801. };
  8802. var getNewRoute = function (comp, transConfig, transState, destination) {
  8803. return {
  8804. start: get$b(comp.element, transConfig.stateAttr),
  8805. destination: destination
  8806. };
  8807. };
  8808. var getCurrentRoute = function (comp, transConfig, _transState) {
  8809. var el = comp.element;
  8810. return getOpt(el, transConfig.destinationAttr).map(function (destination) {
  8811. return {
  8812. start: get$b(comp.element, transConfig.stateAttr),
  8813. destination: destination
  8814. };
  8815. });
  8816. };
  8817. var jumpTo = function (comp, transConfig, transState, destination) {
  8818. disableTransition(comp, transConfig, transState);
  8819. if (has$1(comp.element, transConfig.stateAttr) && get$b(comp.element, transConfig.stateAttr) !== destination) {
  8820. transConfig.onFinish(comp, destination);
  8821. }
  8822. set$8(comp.element, transConfig.stateAttr, destination);
  8823. };
  8824. var fasttrack = function (comp, transConfig, _transState, _destination) {
  8825. if (has$1(comp.element, transConfig.destinationAttr)) {
  8826. getOpt(comp.element, transConfig.destinationAttr).each(function (destination) {
  8827. set$8(comp.element, transConfig.stateAttr, destination);
  8828. });
  8829. remove$6(comp.element, transConfig.destinationAttr);
  8830. }
  8831. };
  8832. var progressTo = function (comp, transConfig, transState, destination) {
  8833. fasttrack(comp, transConfig);
  8834. var route = getNewRoute(comp, transConfig, transState, destination);
  8835. getTransitionOf(comp, transConfig, transState, route).fold(function () {
  8836. jumpTo(comp, transConfig, transState, destination);
  8837. }, function (routeTransition) {
  8838. disableTransition(comp, transConfig, transState);
  8839. var t = routeTransition.transition;
  8840. add$1(comp.element, t.transitionClass);
  8841. set$8(comp.element, transConfig.destinationAttr, destination);
  8842. });
  8843. };
  8844. var getState = function (comp, transConfig, _transState) {
  8845. return getOpt(comp.element, transConfig.stateAttr);
  8846. };
  8847. var TransitionApis = /*#__PURE__*/Object.freeze({
  8848. __proto__: null,
  8849. findRoute: findRoute,
  8850. disableTransition: disableTransition,
  8851. getCurrentRoute: getCurrentRoute,
  8852. jumpTo: jumpTo,
  8853. progressTo: progressTo,
  8854. getState: getState
  8855. });
  8856. var events$1 = function (transConfig, transState) {
  8857. return derive$3([
  8858. run(transitionend(), function (component, simulatedEvent) {
  8859. var raw = simulatedEvent.event.raw;
  8860. getCurrentRoute(component, transConfig).each(function (route) {
  8861. findRoute(component, transConfig, transState, route).each(function (rInfo) {
  8862. rInfo.transition.each(function (rTransition) {
  8863. if (raw.propertyName === rTransition.property) {
  8864. jumpTo(component, transConfig, transState, route.destination);
  8865. transConfig.onTransition(component, route);
  8866. }
  8867. });
  8868. });
  8869. });
  8870. }),
  8871. runOnAttached(function (comp, _se) {
  8872. jumpTo(comp, transConfig, transState, transConfig.initialState);
  8873. })
  8874. ]);
  8875. };
  8876. var ActiveTransitioning = /*#__PURE__*/Object.freeze({
  8877. __proto__: null,
  8878. events: events$1
  8879. });
  8880. var TransitionSchema = [
  8881. defaulted('destinationAttr', 'data-transitioning-destination'),
  8882. defaulted('stateAttr', 'data-transitioning-state'),
  8883. required$1('initialState'),
  8884. onHandler('onTransition'),
  8885. onHandler('onFinish'),
  8886. requiredOf('routes', setOf(Result.value, setOf(Result.value, objOfOnly([optionObjOfOnly('transition', [
  8887. required$1('property'),
  8888. required$1('transitionClass')
  8889. ])]))))
  8890. ];
  8891. var createRoutes = function (routes) {
  8892. var r = {};
  8893. each(routes, function (v, k) {
  8894. var waypoints = k.split('<->');
  8895. r[waypoints[0]] = wrap(waypoints[1], v);
  8896. r[waypoints[1]] = wrap(waypoints[0], v);
  8897. });
  8898. return r;
  8899. };
  8900. var createBistate = function (first, second, transitions) {
  8901. return wrapAll([
  8902. {
  8903. key: first,
  8904. value: wrap(second, transitions)
  8905. },
  8906. {
  8907. key: second,
  8908. value: wrap(first, transitions)
  8909. }
  8910. ]);
  8911. };
  8912. var createTristate = function (first, second, third, transitions) {
  8913. return wrapAll([
  8914. {
  8915. key: first,
  8916. value: wrapAll([
  8917. {
  8918. key: second,
  8919. value: transitions
  8920. },
  8921. {
  8922. key: third,
  8923. value: transitions
  8924. }
  8925. ])
  8926. },
  8927. {
  8928. key: second,
  8929. value: wrapAll([
  8930. {
  8931. key: first,
  8932. value: transitions
  8933. },
  8934. {
  8935. key: third,
  8936. value: transitions
  8937. }
  8938. ])
  8939. },
  8940. {
  8941. key: third,
  8942. value: wrapAll([
  8943. {
  8944. key: first,
  8945. value: transitions
  8946. },
  8947. {
  8948. key: second,
  8949. value: transitions
  8950. }
  8951. ])
  8952. }
  8953. ]);
  8954. };
  8955. var Transitioning = create$5({
  8956. fields: TransitionSchema,
  8957. name: 'transitioning',
  8958. active: ActiveTransitioning,
  8959. apis: TransitionApis,
  8960. extra: {
  8961. createRoutes: createRoutes,
  8962. createBistate: createBistate,
  8963. createTristate: createTristate
  8964. }
  8965. });
  8966. var scrollableStyle = resolve('scrollable');
  8967. var register$2 = function (element) {
  8968. add$1(element, scrollableStyle);
  8969. };
  8970. var deregister = function (element) {
  8971. remove$3(element, scrollableStyle);
  8972. };
  8973. var scrollable = scrollableStyle;
  8974. var getValue = function (item) {
  8975. return get$c(item, 'format').getOr(item.title);
  8976. };
  8977. var convert = function (formats, memMenuThunk) {
  8978. var mainMenu = makeMenu('Styles', [].concat(map$2(formats.items, function (k) {
  8979. return makeItem(getValue(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue(k)));
  8980. })), memMenuThunk, false);
  8981. var submenus = map$1(formats.menus, function (menuItems, menuName) {
  8982. var items = map$2(menuItems, function (item) {
  8983. return makeItem(getValue(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue(item)));
  8984. });
  8985. return makeMenu(menuName, items, memMenuThunk, true);
  8986. });
  8987. var menus = deepMerge(submenus, wrap('styles', mainMenu));
  8988. var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
  8989. return { tmenu: tmenu };
  8990. };
  8991. var makeItem = function (value, text, selected, preview, isMenu) {
  8992. return {
  8993. data: {
  8994. value: value,
  8995. text: text
  8996. },
  8997. type: 'item',
  8998. dom: {
  8999. tag: 'div',
  9000. classes: isMenu ? [resolve('styles-item-is-menu')] : []
  9001. },
  9002. toggling: {
  9003. toggleOnExecute: false,
  9004. toggleClass: resolve('format-matches'),
  9005. selected: selected
  9006. },
  9007. itemBehaviours: derive$2(isMenu ? [] : [format(value, function (comp, status) {
  9008. var toggle = status ? Toggling.on : Toggling.off;
  9009. toggle(comp);
  9010. })]),
  9011. components: [{
  9012. dom: {
  9013. tag: 'div',
  9014. attributes: { style: preview },
  9015. innerHtml: text
  9016. }
  9017. }]
  9018. };
  9019. };
  9020. var makeMenu = function (value, items, memMenuThunk, collapsable) {
  9021. return {
  9022. value: value,
  9023. dom: { tag: 'div' },
  9024. components: [
  9025. Button.sketch({
  9026. dom: {
  9027. tag: 'div',
  9028. classes: [resolve('styles-collapser')]
  9029. },
  9030. components: collapsable ? [
  9031. {
  9032. dom: {
  9033. tag: 'span',
  9034. classes: [resolve('styles-collapse-icon')]
  9035. }
  9036. },
  9037. text(value)
  9038. ] : [text(value)],
  9039. action: function (item) {
  9040. if (collapsable) {
  9041. var comp = memMenuThunk().get(item);
  9042. tieredMenu.collapseMenu(comp);
  9043. }
  9044. }
  9045. }),
  9046. {
  9047. dom: {
  9048. tag: 'div',
  9049. classes: [resolve('styles-menu-items-container')]
  9050. },
  9051. components: [Menu.parts.items({})],
  9052. behaviours: derive$2([config('adhoc-scrollable-menu', [
  9053. runOnAttached(function (component, _simulatedEvent) {
  9054. set$5(component.element, 'overflow-y', 'auto');
  9055. set$5(component.element, '-webkit-overflow-scrolling', 'touch');
  9056. register$2(component.element);
  9057. }),
  9058. runOnDetached(function (component) {
  9059. remove$2(component.element, 'overflow-y');
  9060. remove$2(component.element, '-webkit-overflow-scrolling');
  9061. deregister(component.element);
  9062. })
  9063. ])])
  9064. }
  9065. ],
  9066. items: items,
  9067. menuBehaviours: derive$2([Transitioning.config({
  9068. initialState: 'after',
  9069. routes: Transitioning.createTristate('before', 'current', 'after', {
  9070. transition: {
  9071. property: 'transform',
  9072. transitionClass: 'transitioning'
  9073. }
  9074. })
  9075. })])
  9076. };
  9077. };
  9078. var sketch$1 = function (settings) {
  9079. var dataset = convert(settings.formats, function () {
  9080. return memMenu;
  9081. });
  9082. var memMenu = record(tieredMenu.sketch({
  9083. dom: {
  9084. tag: 'div',
  9085. classes: [resolve('styles-menu')]
  9086. },
  9087. components: [],
  9088. fakeFocus: true,
  9089. stayInDom: true,
  9090. onExecute: function (_tmenu, item) {
  9091. var v = Representing.getValue(item);
  9092. settings.handle(item, v.value);
  9093. return Optional.none();
  9094. },
  9095. onEscape: function () {
  9096. return Optional.none();
  9097. },
  9098. onOpenMenu: function (container, menu) {
  9099. var w = get$5(container.element);
  9100. set$4(menu.element, w);
  9101. Transitioning.jumpTo(menu, 'current');
  9102. },
  9103. onOpenSubmenu: function (container, item, submenu) {
  9104. var w = get$5(container.element);
  9105. var menu = ancestor(item.element, '[role="menu"]').getOrDie('hacky');
  9106. var menuComp = container.getSystem().getByDom(menu).getOrDie();
  9107. set$4(submenu.element, w);
  9108. Transitioning.progressTo(menuComp, 'before');
  9109. Transitioning.jumpTo(submenu, 'after');
  9110. Transitioning.progressTo(submenu, 'current');
  9111. },
  9112. onCollapseMenu: function (container, item, menu) {
  9113. var submenu = ancestor(item.element, '[role="menu"]').getOrDie('hacky');
  9114. var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
  9115. Transitioning.progressTo(submenuComp, 'after');
  9116. Transitioning.progressTo(menu, 'current');
  9117. },
  9118. navigateOnHover: false,
  9119. highlightImmediately: true,
  9120. data: dataset.tmenu,
  9121. markers: {
  9122. backgroundMenu: resolve('styles-background-menu'),
  9123. menu: resolve('styles-menu'),
  9124. selectedMenu: resolve('styles-selected-menu'),
  9125. item: resolve('styles-item'),
  9126. selectedItem: resolve('styles-selected-item')
  9127. }
  9128. }));
  9129. return memMenu.asSpec();
  9130. };
  9131. var getFromExpandingItem = function (item) {
  9132. var newItem = deepMerge(exclude(item, ['items']), { menu: true });
  9133. var rest = expand(item.items);
  9134. var newMenus = deepMerge(rest.menus, wrap(item.title, rest.items));
  9135. var newExpansions = deepMerge(rest.expansions, wrap(item.title, item.title));
  9136. return {
  9137. item: newItem,
  9138. menus: newMenus,
  9139. expansions: newExpansions
  9140. };
  9141. };
  9142. var getFromItem = function (item) {
  9143. return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : {
  9144. item: item,
  9145. menus: {},
  9146. expansions: {}
  9147. };
  9148. };
  9149. var expand = function (items) {
  9150. return foldr(items, function (acc, item) {
  9151. var newData = getFromItem(item);
  9152. return {
  9153. menus: deepMerge(acc.menus, newData.menus),
  9154. items: [newData.item].concat(acc.items),
  9155. expansions: deepMerge(acc.expansions, newData.expansions)
  9156. };
  9157. }, {
  9158. menus: {},
  9159. expansions: {},
  9160. items: []
  9161. });
  9162. };
  9163. var register$1 = function (editor) {
  9164. var isSelectedFor = function (format) {
  9165. return function () {
  9166. return editor.formatter.match(format);
  9167. };
  9168. };
  9169. var getPreview = function (format) {
  9170. return function () {
  9171. return editor.formatter.getCssText(format);
  9172. };
  9173. };
  9174. var enrichSupported = function (item) {
  9175. return deepMerge(item, {
  9176. isSelected: isSelectedFor(item.format),
  9177. getPreview: getPreview(item.format)
  9178. });
  9179. };
  9180. var enrichMenu = function (item) {
  9181. return deepMerge(item, {
  9182. isSelected: never,
  9183. getPreview: constant$1('')
  9184. });
  9185. };
  9186. var enrichCustom = function (item) {
  9187. var formatName = generate$4(item.title);
  9188. var newItem = deepMerge(item, {
  9189. format: formatName,
  9190. isSelected: isSelectedFor(formatName),
  9191. getPreview: getPreview(formatName)
  9192. });
  9193. editor.formatter.register(formatName, newItem);
  9194. return newItem;
  9195. };
  9196. var doEnrich = function (items) {
  9197. return map$2(items, function (item) {
  9198. if (hasNonNullableKey(item, 'items')) {
  9199. var newItems = doEnrich(item.items);
  9200. return deepMerge(enrichMenu(item), { items: newItems });
  9201. } else if (hasNonNullableKey(item, 'format')) {
  9202. return enrichSupported(item);
  9203. } else {
  9204. return enrichCustom(item);
  9205. }
  9206. });
  9207. };
  9208. return doEnrich(getStyleFormats(editor));
  9209. };
  9210. var prune = function (editor, formats) {
  9211. var doPrune = function (items) {
  9212. return bind$3(items, function (item) {
  9213. if (item.items !== undefined) {
  9214. var newItems = doPrune(item.items);
  9215. return newItems.length > 0 ? [item] : [];
  9216. } else {
  9217. var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true;
  9218. return keep ? [item] : [];
  9219. }
  9220. });
  9221. };
  9222. var prunedItems = doPrune(formats);
  9223. return expand(prunedItems);
  9224. };
  9225. var ui = function (editor, formats, onDone) {
  9226. var pruned = prune(editor, formats);
  9227. return sketch$1({
  9228. formats: pruned,
  9229. handle: function (item, value) {
  9230. editor.undoManager.transact(function () {
  9231. if (Toggling.isOn(item)) {
  9232. editor.formatter.remove(value);
  9233. } else {
  9234. editor.formatter.apply(value);
  9235. }
  9236. });
  9237. onDone();
  9238. }
  9239. });
  9240. };
  9241. var extract = function (rawToolbar) {
  9242. var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
  9243. return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
  9244. };
  9245. var identifyFromArray = function (toolbar) {
  9246. return bind$3(toolbar, function (item) {
  9247. return isArray(item) ? identifyFromArray(item) : extract(item);
  9248. });
  9249. };
  9250. var identify = function (editor) {
  9251. var toolbar = getToolbar(editor);
  9252. return isArray(toolbar) ? identifyFromArray(toolbar) : extract(toolbar);
  9253. };
  9254. var setup$3 = function (realm, editor) {
  9255. var commandSketch = function (name) {
  9256. return function () {
  9257. return forToolbarCommand(editor, name);
  9258. };
  9259. };
  9260. var stateCommandSketch = function (name) {
  9261. return function () {
  9262. return forToolbarStateCommand(editor, name);
  9263. };
  9264. };
  9265. var actionSketch = function (name, query, action) {
  9266. return function () {
  9267. return forToolbarStateAction(editor, name, query, action);
  9268. };
  9269. };
  9270. var undo = commandSketch('undo');
  9271. var redo = commandSketch('redo');
  9272. var bold = stateCommandSketch('bold');
  9273. var italic = stateCommandSketch('italic');
  9274. var underline = stateCommandSketch('underline');
  9275. var removeformat = commandSketch('removeformat');
  9276. var link = function () {
  9277. return sketch$2(realm, editor);
  9278. };
  9279. var unlink = actionSketch('unlink', 'link', function () {
  9280. editor.execCommand('unlink', null, false);
  9281. });
  9282. var image = function () {
  9283. return sketch$5(editor);
  9284. };
  9285. var bullist = actionSketch('unordered-list', 'ul', function () {
  9286. editor.execCommand('InsertUnorderedList', null, false);
  9287. });
  9288. var numlist = actionSketch('ordered-list', 'ol', function () {
  9289. editor.execCommand('InsertOrderedList', null, false);
  9290. });
  9291. var fontsizeselect = function () {
  9292. return sketch$6(realm, editor);
  9293. };
  9294. var forecolor = function () {
  9295. return sketch$8(realm, editor);
  9296. };
  9297. var styleFormats = register$1(editor);
  9298. var styleFormatsMenu = function () {
  9299. return ui(editor, styleFormats, function () {
  9300. editor.fire('scrollIntoView');
  9301. });
  9302. };
  9303. var styleselect = function () {
  9304. return forToolbar('style-formats', function (button) {
  9305. editor.fire('toReading');
  9306. realm.dropup.appear(styleFormatsMenu, Toggling.on, button);
  9307. }, derive$2([
  9308. Toggling.config({
  9309. toggleClass: resolve('toolbar-button-selected'),
  9310. toggleOnExecute: false,
  9311. aria: { mode: 'pressed' }
  9312. }),
  9313. Receiving.config({
  9314. channels: wrapAll([
  9315. receive(orientationChanged, Toggling.off),
  9316. receive(dropupDismissed, Toggling.off)
  9317. ])
  9318. })
  9319. ]), editor);
  9320. };
  9321. var feature = function (prereq, sketch) {
  9322. return {
  9323. isSupported: function () {
  9324. var buttons = editor.ui.registry.getAll().buttons;
  9325. return prereq.forall(function (p) {
  9326. return hasNonNullableKey(buttons, p);
  9327. });
  9328. },
  9329. sketch: sketch
  9330. };
  9331. };
  9332. return {
  9333. undo: feature(Optional.none(), undo),
  9334. redo: feature(Optional.none(), redo),
  9335. bold: feature(Optional.none(), bold),
  9336. italic: feature(Optional.none(), italic),
  9337. underline: feature(Optional.none(), underline),
  9338. removeformat: feature(Optional.none(), removeformat),
  9339. link: feature(Optional.none(), link),
  9340. unlink: feature(Optional.none(), unlink),
  9341. image: feature(Optional.none(), image),
  9342. bullist: feature(Optional.some('bullist'), bullist),
  9343. numlist: feature(Optional.some('numlist'), numlist),
  9344. fontsizeselect: feature(Optional.none(), fontsizeselect),
  9345. forecolor: feature(Optional.none(), forecolor),
  9346. styleselect: feature(Optional.none(), styleselect)
  9347. };
  9348. };
  9349. var detect = function (editor, features) {
  9350. var itemNames = identify(editor);
  9351. var present = {};
  9352. return bind$3(itemNames, function (iName) {
  9353. var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
  9354. present[iName] = true;
  9355. return r;
  9356. });
  9357. };
  9358. var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
  9359. return {
  9360. target: target,
  9361. x: x,
  9362. y: y,
  9363. stop: stop,
  9364. prevent: prevent,
  9365. kill: kill,
  9366. raw: raw
  9367. };
  9368. };
  9369. var fromRawEvent = function (rawEvent) {
  9370. var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target));
  9371. var stop = function () {
  9372. return rawEvent.stopPropagation();
  9373. };
  9374. var prevent = function () {
  9375. return rawEvent.preventDefault();
  9376. };
  9377. var kill = compose(prevent, stop);
  9378. return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
  9379. };
  9380. var handle = function (filter, handler) {
  9381. return function (rawEvent) {
  9382. if (filter(rawEvent)) {
  9383. handler(fromRawEvent(rawEvent));
  9384. }
  9385. };
  9386. };
  9387. var binder = function (element, event, filter, handler, useCapture) {
  9388. var wrapped = handle(filter, handler);
  9389. element.dom.addEventListener(event, wrapped, useCapture);
  9390. return { unbind: curry(unbind, element, event, wrapped, useCapture) };
  9391. };
  9392. var bind$1 = function (element, event, filter, handler) {
  9393. return binder(element, event, filter, handler, false);
  9394. };
  9395. var capture$1 = function (element, event, filter, handler) {
  9396. return binder(element, event, filter, handler, true);
  9397. };
  9398. var unbind = function (element, event, handler, useCapture) {
  9399. element.dom.removeEventListener(event, handler, useCapture);
  9400. };
  9401. var filter = always;
  9402. var bind = function (element, event, handler) {
  9403. return bind$1(element, event, filter, handler);
  9404. };
  9405. var capture = function (element, event, handler) {
  9406. return capture$1(element, event, filter, handler);
  9407. };
  9408. var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
  9409. var INTERVAL = 50;
  9410. var INSURANCE = 1000 / INTERVAL;
  9411. var get$1 = function (outerWindow) {
  9412. var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
  9413. return { isPortrait: constant$1(isPortrait) };
  9414. };
  9415. var getActualWidth = function (outerWindow) {
  9416. var isIos = detect$1().os.isiOS();
  9417. var isPortrait = get$1(outerWindow).isPortrait();
  9418. return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
  9419. };
  9420. var onChange = function (outerWindow, listeners) {
  9421. var win = SugarElement.fromDom(outerWindow);
  9422. var poller = null;
  9423. var change = function () {
  9424. global$2.clearInterval(poller);
  9425. var orientation = get$1(outerWindow);
  9426. listeners.onChange(orientation);
  9427. onAdjustment(function () {
  9428. listeners.onReady(orientation);
  9429. });
  9430. };
  9431. var orientationHandle = bind(win, 'orientationchange', change);
  9432. var onAdjustment = function (f) {
  9433. global$2.clearInterval(poller);
  9434. var flag = outerWindow.innerHeight;
  9435. var insurance = 0;
  9436. poller = global$2.setInterval(function () {
  9437. if (flag !== outerWindow.innerHeight) {
  9438. global$2.clearInterval(poller);
  9439. f(Optional.some(outerWindow.innerHeight));
  9440. } else if (insurance > INSURANCE) {
  9441. global$2.clearInterval(poller);
  9442. f(Optional.none());
  9443. }
  9444. insurance++;
  9445. }, INTERVAL);
  9446. };
  9447. var destroy = function () {
  9448. orientationHandle.unbind();
  9449. };
  9450. return {
  9451. onAdjustment: onAdjustment,
  9452. destroy: destroy
  9453. };
  9454. };
  9455. var setStart = function (rng, situ) {
  9456. situ.fold(function (e) {
  9457. rng.setStartBefore(e.dom);
  9458. }, function (e, o) {
  9459. rng.setStart(e.dom, o);
  9460. }, function (e) {
  9461. rng.setStartAfter(e.dom);
  9462. });
  9463. };
  9464. var setFinish = function (rng, situ) {
  9465. situ.fold(function (e) {
  9466. rng.setEndBefore(e.dom);
  9467. }, function (e, o) {
  9468. rng.setEnd(e.dom, o);
  9469. }, function (e) {
  9470. rng.setEndAfter(e.dom);
  9471. });
  9472. };
  9473. var relativeToNative = function (win, startSitu, finishSitu) {
  9474. var range = win.document.createRange();
  9475. setStart(range, startSitu);
  9476. setFinish(range, finishSitu);
  9477. return range;
  9478. };
  9479. var exactToNative = function (win, start, soffset, finish, foffset) {
  9480. var rng = win.document.createRange();
  9481. rng.setStart(start.dom, soffset);
  9482. rng.setEnd(finish.dom, foffset);
  9483. return rng;
  9484. };
  9485. var toRect$1 = function (rect) {
  9486. return {
  9487. left: rect.left,
  9488. top: rect.top,
  9489. right: rect.right,
  9490. bottom: rect.bottom,
  9491. width: rect.width,
  9492. height: rect.height
  9493. };
  9494. };
  9495. var getFirstRect$1 = function (rng) {
  9496. var rects = rng.getClientRects();
  9497. var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
  9498. return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect$1) : Optional.none();
  9499. };
  9500. var adt$3 = Adt.generate([
  9501. {
  9502. ltr: [
  9503. 'start',
  9504. 'soffset',
  9505. 'finish',
  9506. 'foffset'
  9507. ]
  9508. },
  9509. {
  9510. rtl: [
  9511. 'start',
  9512. 'soffset',
  9513. 'finish',
  9514. 'foffset'
  9515. ]
  9516. }
  9517. ]);
  9518. var fromRange = function (win, type, range) {
  9519. return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset);
  9520. };
  9521. var getRanges = function (win, selection) {
  9522. return selection.match({
  9523. domRange: function (rng) {
  9524. return {
  9525. ltr: constant$1(rng),
  9526. rtl: Optional.none
  9527. };
  9528. },
  9529. relative: function (startSitu, finishSitu) {
  9530. return {
  9531. ltr: cached(function () {
  9532. return relativeToNative(win, startSitu, finishSitu);
  9533. }),
  9534. rtl: cached(function () {
  9535. return Optional.some(relativeToNative(win, finishSitu, startSitu));
  9536. })
  9537. };
  9538. },
  9539. exact: function (start, soffset, finish, foffset) {
  9540. return {
  9541. ltr: cached(function () {
  9542. return exactToNative(win, start, soffset, finish, foffset);
  9543. }),
  9544. rtl: cached(function () {
  9545. return Optional.some(exactToNative(win, finish, foffset, start, soffset));
  9546. })
  9547. };
  9548. }
  9549. });
  9550. };
  9551. var doDiagnose = function (win, ranges) {
  9552. var rng = ranges.ltr();
  9553. if (rng.collapsed) {
  9554. var reversed = ranges.rtl().filter(function (rev) {
  9555. return rev.collapsed === false;
  9556. });
  9557. return reversed.map(function (rev) {
  9558. return adt$3.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset);
  9559. }).getOrThunk(function () {
  9560. return fromRange(win, adt$3.ltr, rng);
  9561. });
  9562. } else {
  9563. return fromRange(win, adt$3.ltr, rng);
  9564. }
  9565. };
  9566. var diagnose = function (win, selection) {
  9567. var ranges = getRanges(win, selection);
  9568. return doDiagnose(win, ranges);
  9569. };
  9570. var asLtrRange = function (win, selection) {
  9571. var diagnosis = diagnose(win, selection);
  9572. return diagnosis.match({
  9573. ltr: function (start, soffset, finish, foffset) {
  9574. var rng = win.document.createRange();
  9575. rng.setStart(start.dom, soffset);
  9576. rng.setEnd(finish.dom, foffset);
  9577. return rng;
  9578. },
  9579. rtl: function (start, soffset, finish, foffset) {
  9580. var rng = win.document.createRange();
  9581. rng.setStart(finish.dom, foffset);
  9582. rng.setEnd(start.dom, soffset);
  9583. return rng;
  9584. }
  9585. });
  9586. };
  9587. adt$3.ltr;
  9588. adt$3.rtl;
  9589. var create$3 = function (start, soffset, finish, foffset) {
  9590. return {
  9591. start: start,
  9592. soffset: soffset,
  9593. finish: finish,
  9594. foffset: foffset
  9595. };
  9596. };
  9597. var SimRange = { create: create$3 };
  9598. var NodeValue = function (is, name) {
  9599. var get = function (element) {
  9600. if (!is(element)) {
  9601. throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
  9602. }
  9603. return getOption(element).getOr('');
  9604. };
  9605. var getOption = function (element) {
  9606. return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none();
  9607. };
  9608. var set = function (element, value) {
  9609. if (!is(element)) {
  9610. throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
  9611. }
  9612. element.dom.nodeValue = value;
  9613. };
  9614. return {
  9615. get: get,
  9616. getOption: getOption,
  9617. set: set
  9618. };
  9619. };
  9620. var api = NodeValue(isText, 'text');
  9621. var getOption = function (element) {
  9622. return api.getOption(element);
  9623. };
  9624. var getEnd = function (element) {
  9625. return name$1(element) === 'img' ? 1 : getOption(element).fold(function () {
  9626. return children(element).length;
  9627. }, function (v) {
  9628. return v.length;
  9629. });
  9630. };
  9631. var adt$2 = Adt.generate([
  9632. { before: ['element'] },
  9633. {
  9634. on: [
  9635. 'element',
  9636. 'offset'
  9637. ]
  9638. },
  9639. { after: ['element'] }
  9640. ]);
  9641. var cata = function (subject, onBefore, onOn, onAfter) {
  9642. return subject.fold(onBefore, onOn, onAfter);
  9643. };
  9644. var getStart$1 = function (situ) {
  9645. return situ.fold(identity, identity, identity);
  9646. };
  9647. var before = adt$2.before;
  9648. var on = adt$2.on;
  9649. var after$1 = adt$2.after;
  9650. var Situ = {
  9651. before: before,
  9652. on: on,
  9653. after: after$1,
  9654. cata: cata,
  9655. getStart: getStart$1
  9656. };
  9657. var adt$1 = Adt.generate([
  9658. { domRange: ['rng'] },
  9659. {
  9660. relative: [
  9661. 'startSitu',
  9662. 'finishSitu'
  9663. ]
  9664. },
  9665. {
  9666. exact: [
  9667. 'start',
  9668. 'soffset',
  9669. 'finish',
  9670. 'foffset'
  9671. ]
  9672. }
  9673. ]);
  9674. var exactFromRange = function (simRange) {
  9675. return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset);
  9676. };
  9677. var getStart = function (selection) {
  9678. return selection.match({
  9679. domRange: function (rng) {
  9680. return SugarElement.fromDom(rng.startContainer);
  9681. },
  9682. relative: function (startSitu, _finishSitu) {
  9683. return Situ.getStart(startSitu);
  9684. },
  9685. exact: function (start, _soffset, _finish, _foffset) {
  9686. return start;
  9687. }
  9688. });
  9689. };
  9690. var domRange = adt$1.domRange;
  9691. var relative = adt$1.relative;
  9692. var exact = adt$1.exact;
  9693. var getWin$1 = function (selection) {
  9694. var start = getStart(selection);
  9695. return defaultView(start);
  9696. };
  9697. var range = SimRange.create;
  9698. var SimSelection = {
  9699. domRange: domRange,
  9700. relative: relative,
  9701. exact: exact,
  9702. exactFromRange: exactFromRange,
  9703. getWin: getWin$1,
  9704. range: range
  9705. };
  9706. var beforeSpecial = function (element, offset) {
  9707. var name = name$1(element);
  9708. if ('input' === name) {
  9709. return Situ.after(element);
  9710. } else if (!contains$1([
  9711. 'br',
  9712. 'img'
  9713. ], name)) {
  9714. return Situ.on(element, offset);
  9715. } else {
  9716. return offset === 0 ? Situ.before(element) : Situ.after(element);
  9717. }
  9718. };
  9719. var preprocessExact = function (start, soffset, finish, foffset) {
  9720. var startSitu = beforeSpecial(start, soffset);
  9721. var finishSitu = beforeSpecial(finish, foffset);
  9722. return SimSelection.relative(startSitu, finishSitu);
  9723. };
  9724. var makeRange = function (start, soffset, finish, foffset) {
  9725. var doc = owner$2(start);
  9726. var rng = doc.dom.createRange();
  9727. rng.setStart(start.dom, soffset);
  9728. rng.setEnd(finish.dom, foffset);
  9729. return rng;
  9730. };
  9731. var after = function (start, soffset, finish, foffset) {
  9732. var r = makeRange(start, soffset, finish, foffset);
  9733. var same = eq(start, finish) && soffset === foffset;
  9734. return r.collapsed && !same;
  9735. };
  9736. var getNativeSelection = function (win) {
  9737. return Optional.from(win.getSelection());
  9738. };
  9739. var doSetNativeRange = function (win, rng) {
  9740. getNativeSelection(win).each(function (selection) {
  9741. selection.removeAllRanges();
  9742. selection.addRange(rng);
  9743. });
  9744. };
  9745. var doSetRange = function (win, start, soffset, finish, foffset) {
  9746. var rng = exactToNative(win, start, soffset, finish, foffset);
  9747. doSetNativeRange(win, rng);
  9748. };
  9749. var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
  9750. selection.collapse(start.dom, soffset);
  9751. selection.extend(finish.dom, foffset);
  9752. };
  9753. var setRangeFromRelative = function (win, relative) {
  9754. return diagnose(win, relative).match({
  9755. ltr: function (start, soffset, finish, foffset) {
  9756. doSetRange(win, start, soffset, finish, foffset);
  9757. },
  9758. rtl: function (start, soffset, finish, foffset) {
  9759. getNativeSelection(win).each(function (selection) {
  9760. if (selection.setBaseAndExtent) {
  9761. selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset);
  9762. } else if (selection.extend) {
  9763. try {
  9764. setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
  9765. } catch (e) {
  9766. doSetRange(win, finish, foffset, start, soffset);
  9767. }
  9768. } else {
  9769. doSetRange(win, finish, foffset, start, soffset);
  9770. }
  9771. });
  9772. }
  9773. });
  9774. };
  9775. var setExact = function (win, start, soffset, finish, foffset) {
  9776. var relative = preprocessExact(start, soffset, finish, foffset);
  9777. setRangeFromRelative(win, relative);
  9778. };
  9779. var readRange = function (selection) {
  9780. if (selection.rangeCount > 0) {
  9781. var firstRng = selection.getRangeAt(0);
  9782. var lastRng = selection.getRangeAt(selection.rangeCount - 1);
  9783. return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset));
  9784. } else {
  9785. return Optional.none();
  9786. }
  9787. };
  9788. var doGetExact = function (selection) {
  9789. if (selection.anchorNode === null || selection.focusNode === null) {
  9790. return readRange(selection);
  9791. } else {
  9792. var anchor = SugarElement.fromDom(selection.anchorNode);
  9793. var focus_1 = SugarElement.fromDom(selection.focusNode);
  9794. return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection);
  9795. }
  9796. };
  9797. var getExact = function (win) {
  9798. return getNativeSelection(win).filter(function (sel) {
  9799. return sel.rangeCount > 0;
  9800. }).bind(doGetExact);
  9801. };
  9802. var get = function (win) {
  9803. return getExact(win).map(function (range) {
  9804. return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset);
  9805. });
  9806. };
  9807. var getFirstRect = function (win, selection) {
  9808. var rng = asLtrRange(win, selection);
  9809. return getFirstRect$1(rng);
  9810. };
  9811. var clear = function (win) {
  9812. getNativeSelection(win).each(function (selection) {
  9813. return selection.removeAllRanges();
  9814. });
  9815. };
  9816. var getBodyFromFrame = function (frame) {
  9817. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document.body));
  9818. };
  9819. var getDocFromFrame = function (frame) {
  9820. return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document));
  9821. };
  9822. var getWinFromFrame = function (frame) {
  9823. return Optional.from(frame.dom.contentWindow);
  9824. };
  9825. var getSelectionFromFrame = function (frame) {
  9826. var optWin = getWinFromFrame(frame);
  9827. return optWin.bind(getExact);
  9828. };
  9829. var getFrame = function (editor) {
  9830. return editor.getFrame();
  9831. };
  9832. var getOrDerive = function (name, f) {
  9833. return function (editor) {
  9834. var g = editor[name].getOrThunk(function () {
  9835. var frame = getFrame(editor);
  9836. return function () {
  9837. return f(frame);
  9838. };
  9839. });
  9840. return g();
  9841. };
  9842. };
  9843. var getOrListen = function (editor, doc, name, type) {
  9844. return editor[name].getOrThunk(function () {
  9845. return function (handler) {
  9846. return bind(doc, type, handler);
  9847. };
  9848. });
  9849. };
  9850. var getActiveApi = function (editor) {
  9851. var frame = getFrame(editor);
  9852. var tryFallbackBox = function (win) {
  9853. var isCollapsed = function (sel) {
  9854. return eq(sel.start, sel.finish) && sel.soffset === sel.foffset;
  9855. };
  9856. var toStartRect = function (sel) {
  9857. var rect = sel.start.dom.getBoundingClientRect();
  9858. return rect.width > 0 || rect.height > 0 ? Optional.some(rect) : Optional.none();
  9859. };
  9860. return getExact(win).filter(isCollapsed).bind(toStartRect);
  9861. };
  9862. return getBodyFromFrame(frame).bind(function (body) {
  9863. return getDocFromFrame(frame).bind(function (doc) {
  9864. return getWinFromFrame(frame).map(function (win) {
  9865. var html = SugarElement.fromDom(doc.dom.documentElement);
  9866. var getCursorBox = editor.getCursorBox.getOrThunk(function () {
  9867. return function () {
  9868. return get(win).bind(function (sel) {
  9869. return getFirstRect(win, sel).orThunk(function () {
  9870. return tryFallbackBox(win);
  9871. });
  9872. });
  9873. };
  9874. });
  9875. var setSelection = editor.setSelection.getOrThunk(function () {
  9876. return function (start, soffset, finish, foffset) {
  9877. setExact(win, start, soffset, finish, foffset);
  9878. };
  9879. });
  9880. var clearSelection = editor.clearSelection.getOrThunk(function () {
  9881. return function () {
  9882. clear(win);
  9883. };
  9884. });
  9885. return {
  9886. body: body,
  9887. doc: doc,
  9888. win: win,
  9889. html: html,
  9890. getSelection: curry(getSelectionFromFrame, frame),
  9891. setSelection: setSelection,
  9892. clearSelection: clearSelection,
  9893. frame: frame,
  9894. onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
  9895. onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'),
  9896. onDomChanged: editor.onDomChanged,
  9897. onScrollToCursor: editor.onScrollToCursor,
  9898. onScrollToElement: editor.onScrollToElement,
  9899. onToReading: editor.onToReading,
  9900. onToEditing: editor.onToEditing,
  9901. onToolbarScrollStart: editor.onToolbarScrollStart,
  9902. onTouchContent: editor.onTouchContent,
  9903. onTapContent: editor.onTapContent,
  9904. onTouchToolstrip: editor.onTouchToolstrip,
  9905. getCursorBox: getCursorBox
  9906. };
  9907. });
  9908. });
  9909. });
  9910. };
  9911. var getWin = getOrDerive('getWin', getWinFromFrame);
  9912. var tag = function () {
  9913. var head = first$1('head').getOrDie();
  9914. var nu = function () {
  9915. var meta = SugarElement.fromTag('meta');
  9916. set$8(meta, 'name', 'viewport');
  9917. append$2(head, meta);
  9918. return meta;
  9919. };
  9920. var element = first$1('meta[name="viewport"]').getOrThunk(nu);
  9921. var backup = get$b(element, 'content');
  9922. var maximize = function () {
  9923. set$8(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
  9924. };
  9925. var restore = function () {
  9926. if (backup !== undefined && backup !== null && backup.length > 0) {
  9927. set$8(element, 'content', backup);
  9928. } else {
  9929. set$8(element, 'content', 'user-scalable=yes');
  9930. }
  9931. };
  9932. return {
  9933. maximize: maximize,
  9934. restore: restore
  9935. };
  9936. };
  9937. var attr = 'data-ephox-mobile-fullscreen-style';
  9938. var siblingStyles = 'display:none!important;';
  9939. var ancestorPosition = 'position:absolute!important;';
  9940. var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;';
  9941. var bgFallback = 'background-color:rgb(255,255,255)!important;';
  9942. var isAndroid = detect$1().os.isAndroid();
  9943. var matchColor = function (editorBody) {
  9944. var color = get$8(editorBody, 'background-color');
  9945. return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
  9946. };
  9947. var clobberStyles = function (container, editorBody) {
  9948. var gatherSiblings = function (element) {
  9949. return siblings(element, '*');
  9950. };
  9951. var clobber = function (clobberStyle) {
  9952. return function (element) {
  9953. var styles = get$b(element, 'style');
  9954. var backup = styles === undefined ? 'no-styles' : styles.trim();
  9955. if (backup === clobberStyle) {
  9956. return;
  9957. } else {
  9958. set$8(element, attr, backup);
  9959. set$8(element, 'style', clobberStyle);
  9960. }
  9961. };
  9962. };
  9963. var ancestors$1 = ancestors(container, '*');
  9964. var siblings$1 = bind$3(ancestors$1, gatherSiblings);
  9965. var bgColor = matchColor(editorBody);
  9966. each$1(siblings$1, clobber(siblingStyles));
  9967. each$1(ancestors$1, clobber(ancestorPosition + ancestorStyles + bgColor));
  9968. var containerStyles = isAndroid === true ? '' : ancestorPosition;
  9969. clobber(containerStyles + ancestorStyles + bgColor)(container);
  9970. };
  9971. var restoreStyles = function () {
  9972. var clobberedEls = all('[' + attr + ']');
  9973. each$1(clobberedEls, function (element) {
  9974. var restore = get$b(element, attr);
  9975. if (restore !== 'no-styles') {
  9976. set$8(element, 'style', restore);
  9977. } else {
  9978. remove$6(element, 'style');
  9979. }
  9980. remove$6(element, attr);
  9981. });
  9982. };
  9983. var DelayedFunction = function (fun, delay) {
  9984. var ref = null;
  9985. var schedule = function () {
  9986. var args = [];
  9987. for (var _i = 0; _i < arguments.length; _i++) {
  9988. args[_i] = arguments[_i];
  9989. }
  9990. ref = setTimeout(function () {
  9991. fun.apply(null, args);
  9992. ref = null;
  9993. }, delay);
  9994. };
  9995. var cancel = function () {
  9996. if (ref !== null) {
  9997. clearTimeout(ref);
  9998. ref = null;
  9999. }
  10000. };
  10001. return {
  10002. cancel: cancel,
  10003. schedule: schedule
  10004. };
  10005. };
  10006. var SIGNIFICANT_MOVE = 5;
  10007. var LONGPRESS_DELAY = 400;
  10008. var getTouch = function (event) {
  10009. var raw = event.raw;
  10010. if (raw.touches === undefined || raw.touches.length !== 1) {
  10011. return Optional.none();
  10012. }
  10013. return Optional.some(raw.touches[0]);
  10014. };
  10015. var isFarEnough = function (touch, data) {
  10016. var distX = Math.abs(touch.clientX - data.x);
  10017. var distY = Math.abs(touch.clientY - data.y);
  10018. return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
  10019. };
  10020. var monitor$1 = function (settings) {
  10021. var startData = value();
  10022. var longpressFired = Cell(false);
  10023. var longpress$1 = DelayedFunction(function (event) {
  10024. settings.triggerEvent(longpress(), event);
  10025. longpressFired.set(true);
  10026. }, LONGPRESS_DELAY);
  10027. var handleTouchstart = function (event) {
  10028. getTouch(event).each(function (touch) {
  10029. longpress$1.cancel();
  10030. var data = {
  10031. x: touch.clientX,
  10032. y: touch.clientY,
  10033. target: event.target
  10034. };
  10035. longpress$1.schedule(event);
  10036. longpressFired.set(false);
  10037. startData.set(data);
  10038. });
  10039. return Optional.none();
  10040. };
  10041. var handleTouchmove = function (event) {
  10042. longpress$1.cancel();
  10043. getTouch(event).each(function (touch) {
  10044. startData.on(function (data) {
  10045. if (isFarEnough(touch, data)) {
  10046. startData.clear();
  10047. }
  10048. });
  10049. });
  10050. return Optional.none();
  10051. };
  10052. var handleTouchend = function (event) {
  10053. longpress$1.cancel();
  10054. var isSame = function (data) {
  10055. return eq(data.target, event.target);
  10056. };
  10057. return startData.get().filter(isSame).map(function (_data) {
  10058. if (longpressFired.get()) {
  10059. event.prevent();
  10060. return false;
  10061. } else {
  10062. return settings.triggerEvent(tap(), event);
  10063. }
  10064. });
  10065. };
  10066. var handlers = wrapAll([
  10067. {
  10068. key: touchstart(),
  10069. value: handleTouchstart
  10070. },
  10071. {
  10072. key: touchmove(),
  10073. value: handleTouchmove
  10074. },
  10075. {
  10076. key: touchend(),
  10077. value: handleTouchend
  10078. }
  10079. ]);
  10080. var fireIfReady = function (event, type) {
  10081. return get$c(handlers, type).bind(function (handler) {
  10082. return handler(event);
  10083. });
  10084. };
  10085. return { fireIfReady: fireIfReady };
  10086. };
  10087. var monitor = function (editorApi) {
  10088. var tapEvent = monitor$1({
  10089. triggerEvent: function (type, evt) {
  10090. editorApi.onTapContent(evt);
  10091. }
  10092. });
  10093. var onTouchend = function () {
  10094. return bind(editorApi.body, 'touchend', function (evt) {
  10095. tapEvent.fireIfReady(evt, 'touchend');
  10096. });
  10097. };
  10098. var onTouchmove = function () {
  10099. return bind(editorApi.body, 'touchmove', function (evt) {
  10100. tapEvent.fireIfReady(evt, 'touchmove');
  10101. });
  10102. };
  10103. var fireTouchstart = function (evt) {
  10104. tapEvent.fireIfReady(evt, 'touchstart');
  10105. };
  10106. return {
  10107. fireTouchstart: fireTouchstart,
  10108. onTouchend: onTouchend,
  10109. onTouchmove: onTouchmove
  10110. };
  10111. };
  10112. var isAndroid6 = detect$1().os.version.major >= 6;
  10113. var initEvents$1 = function (editorApi, toolstrip, alloy) {
  10114. var tapping = monitor(editorApi);
  10115. var outerDoc = owner$2(toolstrip);
  10116. var isRanged = function (sel) {
  10117. return !eq(sel.start, sel.finish) || sel.soffset !== sel.foffset;
  10118. };
  10119. var hasRangeInUi = function () {
  10120. return active(outerDoc).filter(function (input) {
  10121. return name$1(input) === 'input';
  10122. }).exists(function (input) {
  10123. return input.dom.selectionStart !== input.dom.selectionEnd;
  10124. });
  10125. };
  10126. var updateMargin = function () {
  10127. var rangeInContent = editorApi.doc.dom.hasFocus() && editorApi.getSelection().exists(isRanged);
  10128. alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
  10129. };
  10130. var listeners = [
  10131. bind(editorApi.body, 'touchstart', function (evt) {
  10132. editorApi.onTouchContent();
  10133. tapping.fireTouchstart(evt);
  10134. }),
  10135. tapping.onTouchmove(),
  10136. tapping.onTouchend(),
  10137. bind(toolstrip, 'touchstart', function (_evt) {
  10138. editorApi.onTouchToolstrip();
  10139. }),
  10140. editorApi.onToReading(function () {
  10141. blur$1(editorApi.body);
  10142. }),
  10143. editorApi.onToEditing(noop),
  10144. editorApi.onScrollToCursor(function (tinyEvent) {
  10145. tinyEvent.preventDefault();
  10146. editorApi.getCursorBox().each(function (bounds) {
  10147. var cWin = editorApi.win;
  10148. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10149. var cScrollBy = isOutside ? bounds.bottom - cWin.innerHeight + 50 : 0;
  10150. if (cScrollBy !== 0) {
  10151. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10152. }
  10153. });
  10154. })
  10155. ].concat(isAndroid6 === true ? [] : [
  10156. bind(SugarElement.fromDom(editorApi.win), 'blur', function () {
  10157. alloy.getByDom(toolstrip).each(Toggling.off);
  10158. }),
  10159. bind(outerDoc, 'select', updateMargin),
  10160. bind(editorApi.doc, 'selectionchange', updateMargin)
  10161. ]);
  10162. var destroy = function () {
  10163. each$1(listeners, function (l) {
  10164. l.unbind();
  10165. });
  10166. };
  10167. return { destroy: destroy };
  10168. };
  10169. var safeParse = function (element, attribute) {
  10170. var parsed = parseInt(get$b(element, attribute), 10);
  10171. return isNaN(parsed) ? 0 : parsed;
  10172. };
  10173. var COLLAPSED_WIDTH = 2;
  10174. var collapsedRect = function (rect) {
  10175. return __assign(__assign({}, rect), { width: COLLAPSED_WIDTH });
  10176. };
  10177. var toRect = function (rawRect) {
  10178. return {
  10179. left: rawRect.left,
  10180. top: rawRect.top,
  10181. right: rawRect.right,
  10182. bottom: rawRect.bottom,
  10183. width: rawRect.width,
  10184. height: rawRect.height
  10185. };
  10186. };
  10187. var getRectsFromRange = function (range) {
  10188. if (!range.collapsed) {
  10189. return map$2(range.getClientRects(), toRect);
  10190. } else {
  10191. var start_1 = SugarElement.fromDom(range.startContainer);
  10192. return parent(start_1).bind(function (parent) {
  10193. var selection = SimSelection.exact(start_1, range.startOffset, parent, getEnd(parent));
  10194. var optRect = getFirstRect(range.startContainer.ownerDocument.defaultView, selection);
  10195. return optRect.map(collapsedRect).map(pure$2);
  10196. }).getOr([]);
  10197. }
  10198. };
  10199. var getRectangles = function (cWin) {
  10200. var sel = cWin.getSelection();
  10201. return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
  10202. };
  10203. var autocompleteHack = function () {
  10204. return function (f) {
  10205. global$2.setTimeout(function () {
  10206. f();
  10207. }, 0);
  10208. };
  10209. };
  10210. var resume$1 = function (cWin) {
  10211. cWin.focus();
  10212. var iBody = SugarElement.fromDom(cWin.document.body);
  10213. var inInput = active().exists(function (elem) {
  10214. return contains$1([
  10215. 'input',
  10216. 'textarea'
  10217. ], name$1(elem));
  10218. });
  10219. var transaction = inInput ? autocompleteHack() : apply$1;
  10220. transaction(function () {
  10221. active().each(blur$1);
  10222. focus$3(iBody);
  10223. });
  10224. };
  10225. var EXTRA_SPACING = 50;
  10226. var data = 'data-' + resolve('last-outer-height');
  10227. var setLastHeight = function (cBody, value) {
  10228. set$8(cBody, data, value);
  10229. };
  10230. var getLastHeight = function (cBody) {
  10231. return safeParse(cBody, data);
  10232. };
  10233. var getBoundsFrom = function (rect) {
  10234. return {
  10235. top: rect.top,
  10236. bottom: rect.top + rect.height
  10237. };
  10238. };
  10239. var getBounds = function (cWin) {
  10240. var rects = getRectangles(cWin);
  10241. return rects.length > 0 ? Optional.some(rects[0]).map(getBoundsFrom) : Optional.none();
  10242. };
  10243. var findDelta = function (outerWindow, cBody) {
  10244. var last = getLastHeight(cBody);
  10245. var current = outerWindow.innerHeight;
  10246. return last > current ? Optional.some(last - current) : Optional.none();
  10247. };
  10248. var calculate = function (cWin, bounds, delta) {
  10249. var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight;
  10250. return isOutside ? Math.min(delta, bounds.bottom - cWin.innerHeight + EXTRA_SPACING) : 0;
  10251. };
  10252. var setup$2 = function (outerWindow, cWin) {
  10253. var cBody = SugarElement.fromDom(cWin.document.body);
  10254. var toEditing = function () {
  10255. resume$1(cWin);
  10256. };
  10257. var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () {
  10258. findDelta(outerWindow, cBody).each(function (delta) {
  10259. getBounds(cWin).each(function (bounds) {
  10260. var cScrollBy = calculate(cWin, bounds, delta);
  10261. if (cScrollBy !== 0) {
  10262. cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
  10263. }
  10264. });
  10265. });
  10266. setLastHeight(cBody, outerWindow.innerHeight);
  10267. });
  10268. setLastHeight(cBody, outerWindow.innerHeight);
  10269. var destroy = function () {
  10270. onResize.unbind();
  10271. };
  10272. return {
  10273. toEditing: toEditing,
  10274. destroy: destroy
  10275. };
  10276. };
  10277. var create$2 = function (platform, mask) {
  10278. var meta = tag();
  10279. var androidApi = api$2();
  10280. var androidEvents = api$2();
  10281. var enter = function () {
  10282. mask.hide();
  10283. add$1(platform.container, resolve('fullscreen-maximized'));
  10284. add$1(platform.container, resolve('android-maximized'));
  10285. meta.maximize();
  10286. add$1(platform.body, resolve('android-scroll-reload'));
  10287. androidApi.set(setup$2(platform.win, getWin(platform.editor).getOrDie('no')));
  10288. getActiveApi(platform.editor).each(function (editorApi) {
  10289. clobberStyles(platform.container, editorApi.body);
  10290. androidEvents.set(initEvents$1(editorApi, platform.toolstrip, platform.alloy));
  10291. });
  10292. };
  10293. var exit = function () {
  10294. meta.restore();
  10295. mask.show();
  10296. remove$3(platform.container, resolve('fullscreen-maximized'));
  10297. remove$3(platform.container, resolve('android-maximized'));
  10298. restoreStyles();
  10299. remove$3(platform.body, resolve('android-scroll-reload'));
  10300. androidEvents.clear();
  10301. androidApi.clear();
  10302. };
  10303. return {
  10304. enter: enter,
  10305. exit: exit
  10306. };
  10307. };
  10308. var first = function (fn, rate) {
  10309. var timer = null;
  10310. var cancel = function () {
  10311. if (!isNull(timer)) {
  10312. clearTimeout(timer);
  10313. timer = null;
  10314. }
  10315. };
  10316. var throttle = function () {
  10317. var args = [];
  10318. for (var _i = 0; _i < arguments.length; _i++) {
  10319. args[_i] = arguments[_i];
  10320. }
  10321. if (isNull(timer)) {
  10322. timer = setTimeout(function () {
  10323. timer = null;
  10324. fn.apply(null, args);
  10325. }, rate);
  10326. }
  10327. };
  10328. return {
  10329. cancel: cancel,
  10330. throttle: throttle
  10331. };
  10332. };
  10333. var last = function (fn, rate) {
  10334. var timer = null;
  10335. var cancel = function () {
  10336. if (!isNull(timer)) {
  10337. clearTimeout(timer);
  10338. timer = null;
  10339. }
  10340. };
  10341. var throttle = function () {
  10342. var args = [];
  10343. for (var _i = 0; _i < arguments.length; _i++) {
  10344. args[_i] = arguments[_i];
  10345. }
  10346. cancel();
  10347. timer = setTimeout(function () {
  10348. timer = null;
  10349. fn.apply(null, args);
  10350. }, rate);
  10351. };
  10352. return {
  10353. cancel: cancel,
  10354. throttle: throttle
  10355. };
  10356. };
  10357. var sketch = function (onView, _translate) {
  10358. var memIcon = record(Container.sketch({
  10359. dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
  10360. containerBehaviours: derive$2([Toggling.config({
  10361. toggleClass: resolve('mask-tap-icon-selected'),
  10362. toggleOnExecute: false
  10363. })])
  10364. }));
  10365. var onViewThrottle = first(onView, 200);
  10366. return Container.sketch({
  10367. dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
  10368. components: [Container.sketch({
  10369. dom: dom$1('<div class="${prefix}-content-container"></div>'),
  10370. components: [Button.sketch({
  10371. dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
  10372. components: [memIcon.asSpec()],
  10373. action: function (_button) {
  10374. onViewThrottle.throttle();
  10375. },
  10376. buttonBehaviours: derive$2([Toggling.config({ toggleClass: resolve('mask-tap-icon-selected') })])
  10377. })]
  10378. })]
  10379. });
  10380. };
  10381. var unbindNoop = constant$1({ unbind: noop });
  10382. var MobileSchema = objOf([
  10383. requiredObjOf('editor', [
  10384. required$1('getFrame'),
  10385. option('getBody'),
  10386. option('getDoc'),
  10387. option('getWin'),
  10388. option('getSelection'),
  10389. option('setSelection'),
  10390. option('clearSelection'),
  10391. option('cursorSaver'),
  10392. option('onKeyup'),
  10393. option('onNodeChanged'),
  10394. option('getCursorBox'),
  10395. required$1('onDomChanged'),
  10396. defaulted('onTouchContent', noop),
  10397. defaulted('onTapContent', noop),
  10398. defaulted('onTouchToolstrip', noop),
  10399. defaulted('onScrollToCursor', unbindNoop),
  10400. defaulted('onScrollToElement', unbindNoop),
  10401. defaulted('onToEditing', unbindNoop),
  10402. defaulted('onToReading', unbindNoop),
  10403. defaulted('onToolbarScrollStart', identity)
  10404. ]),
  10405. required$1('socket'),
  10406. required$1('toolstrip'),
  10407. required$1('dropup'),
  10408. required$1('toolbar'),
  10409. required$1('container'),
  10410. required$1('alloy'),
  10411. customField('win', function (spec) {
  10412. return owner$2(spec.socket).dom.defaultView;
  10413. }),
  10414. customField('body', function (spec) {
  10415. return SugarElement.fromDom(spec.socket.dom.ownerDocument.body);
  10416. }),
  10417. defaulted('translate', identity),
  10418. defaulted('setReadOnly', noop),
  10419. defaulted('readOnlyOnInit', always)
  10420. ]);
  10421. var produce$1 = function (raw) {
  10422. var mobile = asRawOrDie$1('Getting AndroidWebapp schema', MobileSchema, raw);
  10423. set$5(mobile.toolstrip, 'width', '100%');
  10424. var onTap = function () {
  10425. mobile.setReadOnly(mobile.readOnlyOnInit());
  10426. mode.enter();
  10427. };
  10428. var mask = build$1(sketch(onTap, mobile.translate));
  10429. mobile.alloy.add(mask);
  10430. var maskApi = {
  10431. show: function () {
  10432. mobile.alloy.add(mask);
  10433. },
  10434. hide: function () {
  10435. mobile.alloy.remove(mask);
  10436. }
  10437. };
  10438. append$2(mobile.container, mask.element);
  10439. var mode = create$2(mobile, maskApi);
  10440. return {
  10441. setReadOnly: mobile.setReadOnly,
  10442. refreshStructure: noop,
  10443. enter: mode.enter,
  10444. exit: mode.exit,
  10445. destroy: noop
  10446. };
  10447. };
  10448. var schema$1 = constant$1([
  10449. required$1('dom'),
  10450. defaulted('shell', true),
  10451. field$1('toolbarBehaviours', [Replacing])
  10452. ]);
  10453. var enhanceGroups = function () {
  10454. return { behaviours: derive$2([Replacing.config({})]) };
  10455. };
  10456. var parts$1 = constant$1([optional({
  10457. name: 'groups',
  10458. overrides: enhanceGroups
  10459. })]);
  10460. var factory$1 = function (detail, components, _spec, _externals) {
  10461. var setGroups = function (toolbar, groups) {
  10462. getGroupContainer(toolbar).fold(function () {
  10463. console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10464. throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
  10465. }, function (container) {
  10466. Replacing.set(container, groups);
  10467. });
  10468. };
  10469. var getGroupContainer = function (component) {
  10470. return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups');
  10471. };
  10472. var extra = detail.shell ? {
  10473. behaviours: [Replacing.config({})],
  10474. components: []
  10475. } : {
  10476. behaviours: [],
  10477. components: components
  10478. };
  10479. return {
  10480. uid: detail.uid,
  10481. dom: detail.dom,
  10482. components: extra.components,
  10483. behaviours: augment(detail.toolbarBehaviours, extra.behaviours),
  10484. apis: { setGroups: setGroups },
  10485. domModification: { attributes: { role: 'group' } }
  10486. };
  10487. };
  10488. var Toolbar = composite({
  10489. name: 'Toolbar',
  10490. configFields: schema$1(),
  10491. partFields: parts$1(),
  10492. factory: factory$1,
  10493. apis: {
  10494. setGroups: function (apis, toolbar, groups) {
  10495. apis.setGroups(toolbar, groups);
  10496. }
  10497. }
  10498. });
  10499. var schema = constant$1([
  10500. required$1('items'),
  10501. markers(['itemSelector']),
  10502. field$1('tgroupBehaviours', [Keying])
  10503. ]);
  10504. var parts = constant$1([group({
  10505. name: 'items',
  10506. unit: 'item'
  10507. })]);
  10508. var factory = function (detail, components, _spec, _externals) {
  10509. return {
  10510. uid: detail.uid,
  10511. dom: detail.dom,
  10512. components: components,
  10513. behaviours: augment(detail.tgroupBehaviours, [Keying.config({
  10514. mode: 'flow',
  10515. selector: detail.markers.itemSelector
  10516. })]),
  10517. domModification: { attributes: { role: 'toolbar' } }
  10518. };
  10519. };
  10520. var ToolbarGroup = composite({
  10521. name: 'ToolbarGroup',
  10522. configFields: schema(),
  10523. partFields: parts(),
  10524. factory: factory
  10525. });
  10526. var dataHorizontal = 'data-' + resolve('horizontal-scroll');
  10527. var canScrollVertically = function (container) {
  10528. container.dom.scrollTop = 1;
  10529. var result = container.dom.scrollTop !== 0;
  10530. container.dom.scrollTop = 0;
  10531. return result;
  10532. };
  10533. var canScrollHorizontally = function (container) {
  10534. container.dom.scrollLeft = 1;
  10535. var result = container.dom.scrollLeft !== 0;
  10536. container.dom.scrollLeft = 0;
  10537. return result;
  10538. };
  10539. var hasVerticalScroll = function (container) {
  10540. return container.dom.scrollTop > 0 || canScrollVertically(container);
  10541. };
  10542. var hasHorizontalScroll = function (container) {
  10543. return container.dom.scrollLeft > 0 || canScrollHorizontally(container);
  10544. };
  10545. var markAsHorizontal = function (container) {
  10546. set$8(container, dataHorizontal, 'true');
  10547. };
  10548. var hasScroll = function (container) {
  10549. return get$b(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
  10550. };
  10551. var exclusive = function (scope, selector) {
  10552. return bind(scope, 'touchmove', function (event) {
  10553. closest$1(event.target, selector).filter(hasScroll).fold(function () {
  10554. event.prevent();
  10555. }, noop);
  10556. });
  10557. };
  10558. var ScrollingToolbar = function () {
  10559. var makeGroup = function (gSpec) {
  10560. var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
  10561. return {
  10562. dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
  10563. tgroupBehaviours: derive$2([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, _simulatedEvent) {
  10564. set$5(component.element, 'overflow-x', 'auto');
  10565. markAsHorizontal(component.element);
  10566. register$2(component.element);
  10567. })] : [])]),
  10568. components: [Container.sketch({ components: [ToolbarGroup.parts.items({})] })],
  10569. markers: { itemSelector: '.' + resolve('toolbar-group-item') },
  10570. items: gSpec.items
  10571. };
  10572. };
  10573. var toolbar = build$1(Toolbar.sketch({
  10574. dom: dom$1('<div class="${prefix}-toolbar"></div>'),
  10575. components: [Toolbar.parts.groups({})],
  10576. toolbarBehaviours: derive$2([
  10577. Toggling.config({
  10578. toggleClass: resolve('context-toolbar'),
  10579. toggleOnExecute: false,
  10580. aria: { mode: 'none' }
  10581. }),
  10582. Keying.config({ mode: 'cyclic' })
  10583. ]),
  10584. shell: true
  10585. }));
  10586. var wrapper = build$1(Container.sketch({
  10587. dom: { classes: [resolve('toolstrip')] },
  10588. components: [premade(toolbar)],
  10589. containerBehaviours: derive$2([Toggling.config({
  10590. toggleClass: resolve('android-selection-context-toolbar'),
  10591. toggleOnExecute: false
  10592. })])
  10593. }));
  10594. var resetGroups = function () {
  10595. Toolbar.setGroups(toolbar, initGroups.get());
  10596. Toggling.off(toolbar);
  10597. };
  10598. var initGroups = Cell([]);
  10599. var setGroups = function (gs) {
  10600. initGroups.set(gs);
  10601. resetGroups();
  10602. };
  10603. var createGroups = function (gs) {
  10604. return map$2(gs, compose(ToolbarGroup.sketch, makeGroup));
  10605. };
  10606. var refresh = function () {
  10607. };
  10608. var setContextToolbar = function (gs) {
  10609. Toggling.on(toolbar);
  10610. Toolbar.setGroups(toolbar, gs);
  10611. };
  10612. var restoreToolbar = function () {
  10613. if (Toggling.isOn(toolbar)) {
  10614. resetGroups();
  10615. }
  10616. };
  10617. var focus = function () {
  10618. Keying.focusIn(toolbar);
  10619. };
  10620. return {
  10621. wrapper: wrapper,
  10622. toolbar: toolbar,
  10623. createGroups: createGroups,
  10624. setGroups: setGroups,
  10625. setContextToolbar: setContextToolbar,
  10626. restoreToolbar: restoreToolbar,
  10627. refresh: refresh,
  10628. focus: focus
  10629. };
  10630. };
  10631. var makeEditSwitch = function (webapp) {
  10632. return build$1(Button.sketch({
  10633. dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
  10634. action: function () {
  10635. webapp.run(function (w) {
  10636. w.setReadOnly(false);
  10637. });
  10638. }
  10639. }));
  10640. };
  10641. var makeSocket = function () {
  10642. return build$1(Container.sketch({
  10643. dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
  10644. components: [],
  10645. containerBehaviours: derive$2([Replacing.config({})])
  10646. }));
  10647. };
  10648. var showEdit = function (socket, switchToEdit) {
  10649. Replacing.append(socket, premade(switchToEdit));
  10650. };
  10651. var hideEdit = function (socket, switchToEdit) {
  10652. Replacing.remove(socket, switchToEdit);
  10653. };
  10654. var updateMode = function (socket, switchToEdit, readOnly, root) {
  10655. var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
  10656. swap(root);
  10657. var f = readOnly ? showEdit : hideEdit;
  10658. f(socket, switchToEdit);
  10659. };
  10660. var getAnimationRoot = function (component, slideConfig) {
  10661. return slideConfig.getAnimationRoot.fold(function () {
  10662. return component.element;
  10663. }, function (get) {
  10664. return get(component);
  10665. });
  10666. };
  10667. var getDimensionProperty = function (slideConfig) {
  10668. return slideConfig.dimension.property;
  10669. };
  10670. var getDimension = function (slideConfig, elem) {
  10671. return slideConfig.dimension.getDimension(elem);
  10672. };
  10673. var disableTransitions = function (component, slideConfig) {
  10674. var root = getAnimationRoot(component, slideConfig);
  10675. remove$1(root, [
  10676. slideConfig.shrinkingClass,
  10677. slideConfig.growingClass
  10678. ]);
  10679. };
  10680. var setShrunk = function (component, slideConfig) {
  10681. remove$3(component.element, slideConfig.openClass);
  10682. add$1(component.element, slideConfig.closedClass);
  10683. set$5(component.element, getDimensionProperty(slideConfig), '0px');
  10684. reflow(component.element);
  10685. };
  10686. var setGrown = function (component, slideConfig) {
  10687. remove$3(component.element, slideConfig.closedClass);
  10688. add$1(component.element, slideConfig.openClass);
  10689. remove$2(component.element, getDimensionProperty(slideConfig));
  10690. };
  10691. var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) {
  10692. slideState.setCollapsed();
  10693. set$5(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element));
  10694. reflow(component.element);
  10695. disableTransitions(component, slideConfig);
  10696. setShrunk(component, slideConfig);
  10697. slideConfig.onStartShrink(component);
  10698. slideConfig.onShrunk(component);
  10699. };
  10700. var doStartShrink = function (component, slideConfig, slideState, calculatedSize) {
  10701. var size = calculatedSize.getOrThunk(function () {
  10702. return getDimension(slideConfig, component.element);
  10703. });
  10704. slideState.setCollapsed();
  10705. set$5(component.element, getDimensionProperty(slideConfig), size);
  10706. reflow(component.element);
  10707. var root = getAnimationRoot(component, slideConfig);
  10708. remove$3(root, slideConfig.growingClass);
  10709. add$1(root, slideConfig.shrinkingClass);
  10710. setShrunk(component, slideConfig);
  10711. slideConfig.onStartShrink(component);
  10712. };
  10713. var doStartSmartShrink = function (component, slideConfig, slideState) {
  10714. var size = getDimension(slideConfig, component.element);
  10715. var shrinker = size === '0px' ? doImmediateShrink : doStartShrink;
  10716. shrinker(component, slideConfig, slideState, Optional.some(size));
  10717. };
  10718. var doStartGrow = function (component, slideConfig, slideState) {
  10719. var root = getAnimationRoot(component, slideConfig);
  10720. var wasShrinking = has(root, slideConfig.shrinkingClass);
  10721. var beforeSize = getDimension(slideConfig, component.element);
  10722. setGrown(component, slideConfig);
  10723. var fullSize = getDimension(slideConfig, component.element);
  10724. var startPartialGrow = function () {
  10725. set$5(component.element, getDimensionProperty(slideConfig), beforeSize);
  10726. reflow(component.element);
  10727. };
  10728. var startCompleteGrow = function () {
  10729. setShrunk(component, slideConfig);
  10730. };
  10731. var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow;
  10732. setStartSize();
  10733. remove$3(root, slideConfig.shrinkingClass);
  10734. add$1(root, slideConfig.growingClass);
  10735. setGrown(component, slideConfig);
  10736. set$5(component.element, getDimensionProperty(slideConfig), fullSize);
  10737. slideState.setExpanded();
  10738. slideConfig.onStartGrow(component);
  10739. };
  10740. var refresh$1 = function (component, slideConfig, slideState) {
  10741. if (slideState.isExpanded()) {
  10742. remove$2(component.element, getDimensionProperty(slideConfig));
  10743. var fullSize = getDimension(slideConfig, component.element);
  10744. set$5(component.element, getDimensionProperty(slideConfig), fullSize);
  10745. }
  10746. };
  10747. var grow = function (component, slideConfig, slideState) {
  10748. if (!slideState.isExpanded()) {
  10749. doStartGrow(component, slideConfig, slideState);
  10750. }
  10751. };
  10752. var shrink = function (component, slideConfig, slideState) {
  10753. if (slideState.isExpanded()) {
  10754. doStartSmartShrink(component, slideConfig, slideState);
  10755. }
  10756. };
  10757. var immediateShrink = function (component, slideConfig, slideState) {
  10758. if (slideState.isExpanded()) {
  10759. doImmediateShrink(component, slideConfig, slideState);
  10760. }
  10761. };
  10762. var hasGrown = function (component, slideConfig, slideState) {
  10763. return slideState.isExpanded();
  10764. };
  10765. var hasShrunk = function (component, slideConfig, slideState) {
  10766. return slideState.isCollapsed();
  10767. };
  10768. var isGrowing = function (component, slideConfig, _slideState) {
  10769. var root = getAnimationRoot(component, slideConfig);
  10770. return has(root, slideConfig.growingClass) === true;
  10771. };
  10772. var isShrinking = function (component, slideConfig, _slideState) {
  10773. var root = getAnimationRoot(component, slideConfig);
  10774. return has(root, slideConfig.shrinkingClass) === true;
  10775. };
  10776. var isTransitioning = function (component, slideConfig, slideState) {
  10777. return isGrowing(component, slideConfig) || isShrinking(component, slideConfig);
  10778. };
  10779. var toggleGrow = function (component, slideConfig, slideState) {
  10780. var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow;
  10781. f(component, slideConfig, slideState);
  10782. };
  10783. var SlidingApis = /*#__PURE__*/Object.freeze({
  10784. __proto__: null,
  10785. refresh: refresh$1,
  10786. grow: grow,
  10787. shrink: shrink,
  10788. immediateShrink: immediateShrink,
  10789. hasGrown: hasGrown,
  10790. hasShrunk: hasShrunk,
  10791. isGrowing: isGrowing,
  10792. isShrinking: isShrinking,
  10793. isTransitioning: isTransitioning,
  10794. toggleGrow: toggleGrow,
  10795. disableTransitions: disableTransitions
  10796. });
  10797. var exhibit = function (base, slideConfig, _slideState) {
  10798. var expanded = slideConfig.expanded;
  10799. return expanded ? nu$3({
  10800. classes: [slideConfig.openClass],
  10801. styles: {}
  10802. }) : nu$3({
  10803. classes: [slideConfig.closedClass],
  10804. styles: wrap(slideConfig.dimension.property, '0px')
  10805. });
  10806. };
  10807. var events = function (slideConfig, slideState) {
  10808. return derive$3([runOnSource(transitionend(), function (component, simulatedEvent) {
  10809. var raw = simulatedEvent.event.raw;
  10810. if (raw.propertyName === slideConfig.dimension.property) {
  10811. disableTransitions(component, slideConfig);
  10812. if (slideState.isExpanded()) {
  10813. remove$2(component.element, slideConfig.dimension.property);
  10814. }
  10815. var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk;
  10816. notify(component);
  10817. }
  10818. })]);
  10819. };
  10820. var ActiveSliding = /*#__PURE__*/Object.freeze({
  10821. __proto__: null,
  10822. exhibit: exhibit,
  10823. events: events
  10824. });
  10825. var SlidingSchema = [
  10826. required$1('closedClass'),
  10827. required$1('openClass'),
  10828. required$1('shrinkingClass'),
  10829. required$1('growingClass'),
  10830. option('getAnimationRoot'),
  10831. onHandler('onShrunk'),
  10832. onHandler('onStartShrink'),
  10833. onHandler('onGrown'),
  10834. onHandler('onStartGrow'),
  10835. defaulted('expanded', false),
  10836. requiredOf('dimension', choose$1('property', {
  10837. width: [
  10838. output('property', 'width'),
  10839. output('getDimension', function (elem) {
  10840. return get$5(elem) + 'px';
  10841. })
  10842. ],
  10843. height: [
  10844. output('property', 'height'),
  10845. output('getDimension', function (elem) {
  10846. return get$7(elem) + 'px';
  10847. })
  10848. ]
  10849. }))
  10850. ];
  10851. var init$1 = function (spec) {
  10852. var state = Cell(spec.expanded);
  10853. var readState = function () {
  10854. return 'expanded: ' + state.get();
  10855. };
  10856. return nu$2({
  10857. isExpanded: function () {
  10858. return state.get() === true;
  10859. },
  10860. isCollapsed: function () {
  10861. return state.get() === false;
  10862. },
  10863. setCollapsed: curry(state.set, false),
  10864. setExpanded: curry(state.set, true),
  10865. readState: readState
  10866. });
  10867. };
  10868. var SlidingState = /*#__PURE__*/Object.freeze({
  10869. __proto__: null,
  10870. init: init$1
  10871. });
  10872. var Sliding = create$5({
  10873. fields: SlidingSchema,
  10874. name: 'sliding',
  10875. active: ActiveSliding,
  10876. apis: SlidingApis,
  10877. state: SlidingState
  10878. });
  10879. var build = function (refresh, scrollIntoView) {
  10880. var dropup = build$1(Container.sketch({
  10881. dom: {
  10882. tag: 'div',
  10883. classes: [resolve('dropup')]
  10884. },
  10885. components: [],
  10886. containerBehaviours: derive$2([
  10887. Replacing.config({}),
  10888. Sliding.config({
  10889. closedClass: resolve('dropup-closed'),
  10890. openClass: resolve('dropup-open'),
  10891. shrinkingClass: resolve('dropup-shrinking'),
  10892. growingClass: resolve('dropup-growing'),
  10893. dimension: { property: 'height' },
  10894. onShrunk: function (component) {
  10895. refresh();
  10896. scrollIntoView();
  10897. Replacing.set(component, []);
  10898. },
  10899. onGrown: function (_component) {
  10900. refresh();
  10901. scrollIntoView();
  10902. }
  10903. }),
  10904. orientation(function (_component, _data) {
  10905. disappear(noop);
  10906. })
  10907. ])
  10908. }));
  10909. var appear = function (menu, update, component) {
  10910. if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
  10911. window.requestAnimationFrame(function () {
  10912. update(component);
  10913. Replacing.set(dropup, [menu()]);
  10914. Sliding.grow(dropup);
  10915. });
  10916. }
  10917. };
  10918. var disappear = function (onReadyToShrink) {
  10919. window.requestAnimationFrame(function () {
  10920. onReadyToShrink();
  10921. Sliding.shrink(dropup);
  10922. });
  10923. };
  10924. return {
  10925. appear: appear,
  10926. disappear: disappear,
  10927. component: dropup,
  10928. element: dropup.element
  10929. };
  10930. };
  10931. var closest = function (scope, selector, isRoot) {
  10932. return closest$1(scope, selector, isRoot).isSome();
  10933. };
  10934. var isDangerous = function (event) {
  10935. var keyEv = event.raw;
  10936. return keyEv.which === BACKSPACE[0] && !contains$1([
  10937. 'input',
  10938. 'textarea'
  10939. ], name$1(event.target)) && !closest(event.target, '[contenteditable="true"]');
  10940. };
  10941. var isFirefox = function () {
  10942. return detect$1().browser.isFirefox();
  10943. };
  10944. var bindFocus = function (container, handler) {
  10945. if (isFirefox()) {
  10946. return capture(container, 'focus', handler);
  10947. } else {
  10948. return bind(container, 'focusin', handler);
  10949. }
  10950. };
  10951. var bindBlur = function (container, handler) {
  10952. if (isFirefox()) {
  10953. return capture(container, 'blur', handler);
  10954. } else {
  10955. return bind(container, 'focusout', handler);
  10956. }
  10957. };
  10958. var setup$1 = function (container, rawSettings) {
  10959. var settings = __assign({ stopBackspace: true }, rawSettings);
  10960. var pointerEvents = [
  10961. 'touchstart',
  10962. 'touchmove',
  10963. 'touchend',
  10964. 'touchcancel',
  10965. 'gesturestart',
  10966. 'mousedown',
  10967. 'mouseup',
  10968. 'mouseover',
  10969. 'mousemove',
  10970. 'mouseout',
  10971. 'click'
  10972. ];
  10973. var tapEvent = monitor$1(settings);
  10974. var simpleEvents = map$2(pointerEvents.concat([
  10975. 'selectstart',
  10976. 'input',
  10977. 'contextmenu',
  10978. 'change',
  10979. 'transitionend',
  10980. 'transitioncancel',
  10981. 'drag',
  10982. 'dragstart',
  10983. 'dragend',
  10984. 'dragenter',
  10985. 'dragleave',
  10986. 'dragover',
  10987. 'drop',
  10988. 'keyup'
  10989. ]), function (type) {
  10990. return bind(container, type, function (event) {
  10991. tapEvent.fireIfReady(event, type).each(function (tapStopped) {
  10992. if (tapStopped) {
  10993. event.kill();
  10994. }
  10995. });
  10996. var stopped = settings.triggerEvent(type, event);
  10997. if (stopped) {
  10998. event.kill();
  10999. }
  11000. });
  11001. });
  11002. var pasteTimeout = value();
  11003. var onPaste = bind(container, 'paste', function (event) {
  11004. tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) {
  11005. if (tapStopped) {
  11006. event.kill();
  11007. }
  11008. });
  11009. var stopped = settings.triggerEvent('paste', event);
  11010. if (stopped) {
  11011. event.kill();
  11012. }
  11013. pasteTimeout.set(setTimeout(function () {
  11014. settings.triggerEvent(postPaste(), event);
  11015. }, 0));
  11016. });
  11017. var onKeydown = bind(container, 'keydown', function (event) {
  11018. var stopped = settings.triggerEvent('keydown', event);
  11019. if (stopped) {
  11020. event.kill();
  11021. } else if (settings.stopBackspace && isDangerous(event)) {
  11022. event.prevent();
  11023. }
  11024. });
  11025. var onFocusIn = bindFocus(container, function (event) {
  11026. var stopped = settings.triggerEvent('focusin', event);
  11027. if (stopped) {
  11028. event.kill();
  11029. }
  11030. });
  11031. var focusoutTimeout = value();
  11032. var onFocusOut = bindBlur(container, function (event) {
  11033. var stopped = settings.triggerEvent('focusout', event);
  11034. if (stopped) {
  11035. event.kill();
  11036. }
  11037. focusoutTimeout.set(setTimeout(function () {
  11038. settings.triggerEvent(postBlur(), event);
  11039. }, 0));
  11040. });
  11041. var unbind = function () {
  11042. each$1(simpleEvents, function (e) {
  11043. e.unbind();
  11044. });
  11045. onKeydown.unbind();
  11046. onFocusIn.unbind();
  11047. onFocusOut.unbind();
  11048. onPaste.unbind();
  11049. pasteTimeout.on(clearTimeout);
  11050. focusoutTimeout.on(clearTimeout);
  11051. };
  11052. return { unbind: unbind };
  11053. };
  11054. var derive$1 = function (rawEvent, rawTarget) {
  11055. var source = get$c(rawEvent, 'target').getOr(rawTarget);
  11056. return Cell(source);
  11057. };
  11058. var fromSource = function (event, source) {
  11059. var stopper = Cell(false);
  11060. var cutter = Cell(false);
  11061. var stop = function () {
  11062. stopper.set(true);
  11063. };
  11064. var cut = function () {
  11065. cutter.set(true);
  11066. };
  11067. return {
  11068. stop: stop,
  11069. cut: cut,
  11070. isStopped: stopper.get,
  11071. isCut: cutter.get,
  11072. event: event,
  11073. setSource: source.set,
  11074. getSource: source.get
  11075. };
  11076. };
  11077. var fromExternal = function (event) {
  11078. var stopper = Cell(false);
  11079. var stop = function () {
  11080. stopper.set(true);
  11081. };
  11082. return {
  11083. stop: stop,
  11084. cut: noop,
  11085. isStopped: stopper.get,
  11086. isCut: never,
  11087. event: event,
  11088. setSource: die('Cannot set source of a broadcasted event'),
  11089. getSource: die('Cannot get source of a broadcasted event')
  11090. };
  11091. };
  11092. var adt = Adt.generate([
  11093. { stopped: [] },
  11094. { resume: ['element'] },
  11095. { complete: [] }
  11096. ]);
  11097. var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
  11098. var handler = lookup(eventType, target);
  11099. var simulatedEvent = fromSource(rawEvent, source);
  11100. return handler.fold(function () {
  11101. logger.logEventNoHandlers(eventType, target);
  11102. return adt.complete();
  11103. }, function (handlerInfo) {
  11104. var descHandler = handlerInfo.descHandler;
  11105. var eventHandler = getCurried(descHandler);
  11106. eventHandler(simulatedEvent);
  11107. if (simulatedEvent.isStopped()) {
  11108. logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose);
  11109. return adt.stopped();
  11110. } else if (simulatedEvent.isCut()) {
  11111. logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose);
  11112. return adt.complete();
  11113. } else {
  11114. return parent(handlerInfo.element).fold(function () {
  11115. logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose);
  11116. return adt.complete();
  11117. }, function (parent) {
  11118. logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose);
  11119. return adt.resume(parent);
  11120. });
  11121. }
  11122. });
  11123. };
  11124. var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
  11125. return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) {
  11126. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger);
  11127. }, never);
  11128. };
  11129. var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
  11130. var source = derive$1(rawEvent, target);
  11131. return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
  11132. };
  11133. var broadcast = function (listeners, rawEvent, _logger) {
  11134. var simulatedEvent = fromExternal(rawEvent);
  11135. each$1(listeners, function (listener) {
  11136. var descHandler = listener.descHandler;
  11137. var handler = getCurried(descHandler);
  11138. handler(simulatedEvent);
  11139. });
  11140. return simulatedEvent.isStopped();
  11141. };
  11142. var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
  11143. return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger);
  11144. };
  11145. var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
  11146. var source = derive$1(rawEvent, rawTarget);
  11147. return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
  11148. };
  11149. var eventHandler = function (element, descHandler) {
  11150. return {
  11151. element: element,
  11152. descHandler: descHandler
  11153. };
  11154. };
  11155. var broadcastHandler = function (id, handler) {
  11156. return {
  11157. id: id,
  11158. descHandler: handler
  11159. };
  11160. };
  11161. var EventRegistry = function () {
  11162. var registry = {};
  11163. var registerId = function (extraArgs, id, events) {
  11164. each(events, function (v, k) {
  11165. var handlers = registry[k] !== undefined ? registry[k] : {};
  11166. handlers[id] = curryArgs(v, extraArgs);
  11167. registry[k] = handlers;
  11168. });
  11169. };
  11170. var findHandler = function (handlers, elem) {
  11171. return read(elem).bind(function (id) {
  11172. return get$c(handlers, id);
  11173. }).map(function (descHandler) {
  11174. return eventHandler(elem, descHandler);
  11175. });
  11176. };
  11177. var filterByType = function (type) {
  11178. return get$c(registry, type).map(function (handlers) {
  11179. return mapToArray(handlers, function (f, id) {
  11180. return broadcastHandler(id, f);
  11181. });
  11182. }).getOr([]);
  11183. };
  11184. var find = function (isAboveRoot, type, target) {
  11185. return get$c(registry, type).bind(function (handlers) {
  11186. return closest$3(target, function (elem) {
  11187. return findHandler(handlers, elem);
  11188. }, isAboveRoot);
  11189. });
  11190. };
  11191. var unregisterId = function (id) {
  11192. each(registry, function (handlersById, _eventName) {
  11193. if (has$2(handlersById, id)) {
  11194. delete handlersById[id];
  11195. }
  11196. });
  11197. };
  11198. return {
  11199. registerId: registerId,
  11200. unregisterId: unregisterId,
  11201. filterByType: filterByType,
  11202. find: find
  11203. };
  11204. };
  11205. var Registry = function () {
  11206. var events = EventRegistry();
  11207. var components = {};
  11208. var readOrTag = function (component) {
  11209. var elem = component.element;
  11210. return read(elem).getOrThunk(function () {
  11211. return write('uid-', component.element);
  11212. });
  11213. };
  11214. var failOnDuplicate = function (component, tagId) {
  11215. var conflict = components[tagId];
  11216. if (conflict === component) {
  11217. unregister(component);
  11218. } else {
  11219. throw new Error('The tagId "' + tagId + '" is already used by: ' + element(conflict.element) + '\nCannot use it for: ' + element(component.element) + '\n' + 'The conflicting element is' + (inBody(conflict.element) ? ' ' : ' not ') + 'already in the DOM');
  11220. }
  11221. };
  11222. var register = function (component) {
  11223. var tagId = readOrTag(component);
  11224. if (hasNonNullableKey(components, tagId)) {
  11225. failOnDuplicate(component, tagId);
  11226. }
  11227. var extraArgs = [component];
  11228. events.registerId(extraArgs, tagId, component.events);
  11229. components[tagId] = component;
  11230. };
  11231. var unregister = function (component) {
  11232. read(component.element).each(function (tagId) {
  11233. delete components[tagId];
  11234. events.unregisterId(tagId);
  11235. });
  11236. };
  11237. var filter = function (type) {
  11238. return events.filterByType(type);
  11239. };
  11240. var find = function (isAboveRoot, type, target) {
  11241. return events.find(isAboveRoot, type, target);
  11242. };
  11243. var getById = function (id) {
  11244. return get$c(components, id);
  11245. };
  11246. return {
  11247. find: find,
  11248. filter: filter,
  11249. register: register,
  11250. unregister: unregister,
  11251. getById: getById
  11252. };
  11253. };
  11254. var takeover$1 = function (root) {
  11255. var isAboveRoot = function (el) {
  11256. return parent(root.element).fold(always, function (parent) {
  11257. return eq(el, parent);
  11258. });
  11259. };
  11260. var registry = Registry();
  11261. var lookup = function (eventName, target) {
  11262. return registry.find(isAboveRoot, eventName, target);
  11263. };
  11264. var domEvents = setup$1(root.element, {
  11265. triggerEvent: function (eventName, event) {
  11266. return monitorEvent(eventName, event.target, function (logger) {
  11267. return triggerUntilStopped(lookup, eventName, event, logger);
  11268. });
  11269. }
  11270. });
  11271. var systemApi = {
  11272. debugInfo: constant$1('real'),
  11273. triggerEvent: function (eventName, target, data) {
  11274. monitorEvent(eventName, target, function (logger) {
  11275. return triggerOnUntilStopped(lookup, eventName, data, target, logger);
  11276. });
  11277. },
  11278. triggerFocus: function (target, originator) {
  11279. read(target).fold(function () {
  11280. focus$3(target);
  11281. }, function (_alloyId) {
  11282. monitorEvent(focus$4(), target, function (logger) {
  11283. triggerHandler(lookup, focus$4(), {
  11284. originator: originator,
  11285. kill: noop,
  11286. prevent: noop,
  11287. target: target
  11288. }, target, logger);
  11289. return false;
  11290. });
  11291. });
  11292. },
  11293. triggerEscape: function (comp, simulatedEvent) {
  11294. systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event);
  11295. },
  11296. getByUid: function (uid) {
  11297. return getByUid(uid);
  11298. },
  11299. getByDom: function (elem) {
  11300. return getByDom(elem);
  11301. },
  11302. build: build$1,
  11303. addToGui: function (c) {
  11304. add(c);
  11305. },
  11306. removeFromGui: function (c) {
  11307. remove(c);
  11308. },
  11309. addToWorld: function (c) {
  11310. addToWorld(c);
  11311. },
  11312. removeFromWorld: function (c) {
  11313. removeFromWorld(c);
  11314. },
  11315. broadcast: function (message) {
  11316. broadcast$1(message);
  11317. },
  11318. broadcastOn: function (channels, message) {
  11319. broadcastOn(channels, message);
  11320. },
  11321. broadcastEvent: function (eventName, event) {
  11322. broadcastEvent(eventName, event);
  11323. },
  11324. isConnected: always
  11325. };
  11326. var addToWorld = function (component) {
  11327. component.connect(systemApi);
  11328. if (!isText(component.element)) {
  11329. registry.register(component);
  11330. each$1(component.components(), addToWorld);
  11331. systemApi.triggerEvent(systemInit(), component.element, { target: component.element });
  11332. }
  11333. };
  11334. var removeFromWorld = function (component) {
  11335. if (!isText(component.element)) {
  11336. each$1(component.components(), removeFromWorld);
  11337. registry.unregister(component);
  11338. }
  11339. component.disconnect();
  11340. };
  11341. var add = function (component) {
  11342. attach(root, component);
  11343. };
  11344. var remove = function (component) {
  11345. detach(component);
  11346. };
  11347. var destroy = function () {
  11348. domEvents.unbind();
  11349. remove$7(root.element);
  11350. };
  11351. var broadcastData = function (data) {
  11352. var receivers = registry.filter(receive$1());
  11353. each$1(receivers, function (receiver) {
  11354. var descHandler = receiver.descHandler;
  11355. var handler = getCurried(descHandler);
  11356. handler(data);
  11357. });
  11358. };
  11359. var broadcast$1 = function (message) {
  11360. broadcastData({
  11361. universal: true,
  11362. data: message
  11363. });
  11364. };
  11365. var broadcastOn = function (channels, message) {
  11366. broadcastData({
  11367. universal: false,
  11368. channels: channels,
  11369. data: message
  11370. });
  11371. };
  11372. var broadcastEvent = function (eventName, event) {
  11373. var listeners = registry.filter(eventName);
  11374. return broadcast(listeners, event);
  11375. };
  11376. var getByUid = function (uid) {
  11377. return registry.getById(uid).fold(function () {
  11378. return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
  11379. }, Result.value);
  11380. };
  11381. var getByDom = function (elem) {
  11382. var uid = read(elem).getOr('not found');
  11383. return getByUid(uid);
  11384. };
  11385. addToWorld(root);
  11386. return {
  11387. root: root,
  11388. element: root.element,
  11389. destroy: destroy,
  11390. add: add,
  11391. remove: remove,
  11392. getByUid: getByUid,
  11393. getByDom: getByDom,
  11394. addToWorld: addToWorld,
  11395. removeFromWorld: removeFromWorld,
  11396. broadcast: broadcast$1,
  11397. broadcastOn: broadcastOn,
  11398. broadcastEvent: broadcastEvent
  11399. };
  11400. };
  11401. var READ_ONLY_MODE_CLASS = resolve('readonly-mode');
  11402. var EDIT_MODE_CLASS = resolve('edit-mode');
  11403. function OuterContainer (spec) {
  11404. var root = build$1(Container.sketch({
  11405. dom: { classes: [resolve('outer-container')].concat(spec.classes) },
  11406. containerBehaviours: derive$2([Swapping.config({
  11407. alpha: READ_ONLY_MODE_CLASS,
  11408. omega: EDIT_MODE_CLASS
  11409. })])
  11410. }));
  11411. return takeover$1(root);
  11412. }
  11413. function AndroidRealm (scrollIntoView) {
  11414. var alloy = OuterContainer({ classes: [resolve('android-container')] });
  11415. var toolbar = ScrollingToolbar();
  11416. var webapp = api$2();
  11417. var switchToEdit = makeEditSwitch(webapp);
  11418. var socket = makeSocket();
  11419. var dropup = build(noop, scrollIntoView);
  11420. alloy.add(toolbar.wrapper);
  11421. alloy.add(socket);
  11422. alloy.add(dropup.component);
  11423. var setToolbarGroups = function (rawGroups) {
  11424. var groups = toolbar.createGroups(rawGroups);
  11425. toolbar.setGroups(groups);
  11426. };
  11427. var setContextToolbar = function (rawGroups) {
  11428. var groups = toolbar.createGroups(rawGroups);
  11429. toolbar.setContextToolbar(groups);
  11430. };
  11431. var focusToolbar = function () {
  11432. toolbar.focus();
  11433. };
  11434. var restoreToolbar = function () {
  11435. toolbar.restoreToolbar();
  11436. };
  11437. var init = function (spec) {
  11438. webapp.set(produce$1(spec));
  11439. };
  11440. var exit = function () {
  11441. webapp.run(function (w) {
  11442. w.exit();
  11443. Replacing.remove(socket, switchToEdit);
  11444. });
  11445. };
  11446. var updateMode$1 = function (readOnly) {
  11447. updateMode(socket, switchToEdit, readOnly, alloy.root);
  11448. };
  11449. return {
  11450. system: alloy,
  11451. element: alloy.element,
  11452. init: init,
  11453. exit: exit,
  11454. setToolbarGroups: setToolbarGroups,
  11455. setContextToolbar: setContextToolbar,
  11456. focusToolbar: focusToolbar,
  11457. restoreToolbar: restoreToolbar,
  11458. updateMode: updateMode$1,
  11459. socket: socket,
  11460. dropup: dropup
  11461. };
  11462. }
  11463. var input = function (parent, operation) {
  11464. var input = SugarElement.fromTag('input');
  11465. setAll(input, {
  11466. opacity: '0',
  11467. position: 'absolute',
  11468. top: '-1000px',
  11469. left: '-1000px'
  11470. });
  11471. append$2(parent, input);
  11472. focus$3(input);
  11473. operation(input);
  11474. remove$7(input);
  11475. };
  11476. var refresh = function (winScope) {
  11477. var sel = winScope.getSelection();
  11478. if (sel.rangeCount > 0) {
  11479. var br = sel.getRangeAt(0);
  11480. var r = winScope.document.createRange();
  11481. r.setStart(br.startContainer, br.startOffset);
  11482. r.setEnd(br.endContainer, br.endOffset);
  11483. sel.removeAllRanges();
  11484. sel.addRange(r);
  11485. }
  11486. };
  11487. var resume = function (cWin, frame) {
  11488. active().each(function (active) {
  11489. if (!eq(active, frame)) {
  11490. blur$1(active);
  11491. }
  11492. });
  11493. cWin.focus();
  11494. focus$3(SugarElement.fromDom(cWin.document.body));
  11495. refresh(cWin);
  11496. };
  11497. var stubborn = function (outerBody, cWin, page, frame) {
  11498. var toEditing = function () {
  11499. resume(cWin, frame);
  11500. };
  11501. var toReading = function () {
  11502. input(outerBody, blur$1);
  11503. };
  11504. var captureInput = bind(page, 'keydown', function (evt) {
  11505. if (!contains$1([
  11506. 'input',
  11507. 'textarea'
  11508. ], name$1(evt.target))) {
  11509. toEditing();
  11510. }
  11511. });
  11512. var onToolbarTouch = noop;
  11513. var destroy = function () {
  11514. captureInput.unbind();
  11515. };
  11516. return {
  11517. toReading: toReading,
  11518. toEditing: toEditing,
  11519. onToolbarTouch: onToolbarTouch,
  11520. destroy: destroy
  11521. };
  11522. };
  11523. var initEvents = function (editorApi, iosApi, toolstrip, socket, _dropup) {
  11524. var saveSelectionFirst = function () {
  11525. iosApi.run(function (api) {
  11526. api.highlightSelection();
  11527. });
  11528. };
  11529. var refreshIosSelection = function () {
  11530. iosApi.run(function (api) {
  11531. api.refreshSelection();
  11532. });
  11533. };
  11534. var scrollToY = function (yTop, height) {
  11535. var y = yTop - socket.dom.scrollTop;
  11536. iosApi.run(function (api) {
  11537. api.scrollIntoView(y, y + height);
  11538. });
  11539. };
  11540. var scrollToElement = function (_target) {
  11541. scrollToY(iosApi, socket);
  11542. };
  11543. var scrollToCursor = function () {
  11544. editorApi.getCursorBox().each(function (box) {
  11545. scrollToY(box.top, box.height);
  11546. });
  11547. };
  11548. var clearSelection = function () {
  11549. iosApi.run(function (api) {
  11550. api.clearSelection();
  11551. });
  11552. };
  11553. var clearAndRefresh = function () {
  11554. clearSelection();
  11555. refreshThrottle.throttle();
  11556. };
  11557. var refreshView = function () {
  11558. scrollToCursor();
  11559. iosApi.run(function (api) {
  11560. api.syncHeight();
  11561. });
  11562. };
  11563. var reposition = function () {
  11564. var toolbarHeight = get$7(toolstrip);
  11565. iosApi.run(function (api) {
  11566. api.setViewportOffset(toolbarHeight);
  11567. });
  11568. refreshIosSelection();
  11569. refreshView();
  11570. };
  11571. var toEditing = function () {
  11572. iosApi.run(function (api) {
  11573. api.toEditing();
  11574. });
  11575. };
  11576. var toReading = function () {
  11577. iosApi.run(function (api) {
  11578. api.toReading();
  11579. });
  11580. };
  11581. var onToolbarTouch = function (event) {
  11582. iosApi.run(function (api) {
  11583. api.onToolbarTouch(event);
  11584. });
  11585. };
  11586. var tapping = monitor(editorApi);
  11587. var refreshThrottle = last(refreshView, 300);
  11588. var listeners = [
  11589. editorApi.onKeyup(clearAndRefresh),
  11590. editorApi.onNodeChanged(refreshIosSelection),
  11591. editorApi.onDomChanged(refreshThrottle.throttle),
  11592. editorApi.onDomChanged(refreshIosSelection),
  11593. editorApi.onScrollToCursor(function (tinyEvent) {
  11594. tinyEvent.preventDefault();
  11595. refreshThrottle.throttle();
  11596. }),
  11597. editorApi.onScrollToElement(function (event) {
  11598. scrollToElement(event.element);
  11599. }),
  11600. editorApi.onToEditing(toEditing),
  11601. editorApi.onToReading(toReading),
  11602. bind(editorApi.doc, 'touchend', function (touchEvent) {
  11603. if (eq(editorApi.html, touchEvent.target) || eq(editorApi.body, touchEvent.target)) ;
  11604. }),
  11605. bind(toolstrip, 'transitionend', function (transitionEvent) {
  11606. if (transitionEvent.raw.propertyName === 'height') {
  11607. reposition();
  11608. }
  11609. }),
  11610. capture(toolstrip, 'touchstart', function (touchEvent) {
  11611. saveSelectionFirst();
  11612. onToolbarTouch(touchEvent);
  11613. editorApi.onTouchToolstrip();
  11614. }),
  11615. bind(editorApi.body, 'touchstart', function (evt) {
  11616. clearSelection();
  11617. editorApi.onTouchContent();
  11618. tapping.fireTouchstart(evt);
  11619. }),
  11620. tapping.onTouchmove(),
  11621. tapping.onTouchend(),
  11622. bind(editorApi.body, 'click', function (event) {
  11623. event.kill();
  11624. }),
  11625. bind(toolstrip, 'touchmove', function () {
  11626. editorApi.onToolbarScrollStart();
  11627. })
  11628. ];
  11629. var destroy = function () {
  11630. each$1(listeners, function (l) {
  11631. l.unbind();
  11632. });
  11633. };
  11634. return { destroy: destroy };
  11635. };
  11636. function FakeSelection (win, frame) {
  11637. var doc = win.document;
  11638. var container = SugarElement.fromTag('div');
  11639. add$1(container, resolve('unfocused-selections'));
  11640. append$2(SugarElement.fromDom(doc.documentElement), container);
  11641. var onTouch = bind(container, 'touchstart', function (event) {
  11642. event.prevent();
  11643. resume(win, frame);
  11644. clear();
  11645. });
  11646. var make = function (rectangle) {
  11647. var span = SugarElement.fromTag('span');
  11648. add(span, [
  11649. resolve('layer-editor'),
  11650. resolve('unfocused-selection')
  11651. ]);
  11652. setAll(span, {
  11653. left: rectangle.left + 'px',
  11654. top: rectangle.top + 'px',
  11655. width: rectangle.width + 'px',
  11656. height: rectangle.height + 'px'
  11657. });
  11658. return span;
  11659. };
  11660. var update = function () {
  11661. clear();
  11662. var rectangles = getRectangles(win);
  11663. var spans = map$2(rectangles, make);
  11664. append$1(container, spans);
  11665. };
  11666. var clear = function () {
  11667. empty(container);
  11668. };
  11669. var destroy = function () {
  11670. onTouch.unbind();
  11671. remove$7(container);
  11672. };
  11673. var isActive = function () {
  11674. return children(container).length > 0;
  11675. };
  11676. return {
  11677. update: update,
  11678. isActive: isActive,
  11679. destroy: destroy,
  11680. clear: clear
  11681. };
  11682. }
  11683. var nu$1 = function (baseFn) {
  11684. var data = Optional.none();
  11685. var callbacks = [];
  11686. var map = function (f) {
  11687. return nu$1(function (nCallback) {
  11688. get(function (data) {
  11689. nCallback(f(data));
  11690. });
  11691. });
  11692. };
  11693. var get = function (nCallback) {
  11694. if (isReady()) {
  11695. call(nCallback);
  11696. } else {
  11697. callbacks.push(nCallback);
  11698. }
  11699. };
  11700. var set = function (x) {
  11701. if (!isReady()) {
  11702. data = Optional.some(x);
  11703. run(callbacks);
  11704. callbacks = [];
  11705. }
  11706. };
  11707. var isReady = function () {
  11708. return data.isSome();
  11709. };
  11710. var run = function (cbs) {
  11711. each$1(cbs, call);
  11712. };
  11713. var call = function (cb) {
  11714. data.each(function (x) {
  11715. setTimeout(function () {
  11716. cb(x);
  11717. }, 0);
  11718. });
  11719. };
  11720. baseFn(set);
  11721. return {
  11722. get: get,
  11723. map: map,
  11724. isReady: isReady
  11725. };
  11726. };
  11727. var pure$1 = function (a) {
  11728. return nu$1(function (callback) {
  11729. callback(a);
  11730. });
  11731. };
  11732. var LazyValue = {
  11733. nu: nu$1,
  11734. pure: pure$1
  11735. };
  11736. var errorReporter = function (err) {
  11737. setTimeout(function () {
  11738. throw err;
  11739. }, 0);
  11740. };
  11741. var make = function (run) {
  11742. var get = function (callback) {
  11743. run().then(callback, errorReporter);
  11744. };
  11745. var map = function (fab) {
  11746. return make(function () {
  11747. return run().then(fab);
  11748. });
  11749. };
  11750. var bind = function (aFutureB) {
  11751. return make(function () {
  11752. return run().then(function (v) {
  11753. return aFutureB(v).toPromise();
  11754. });
  11755. });
  11756. };
  11757. var anonBind = function (futureB) {
  11758. return make(function () {
  11759. return run().then(function () {
  11760. return futureB.toPromise();
  11761. });
  11762. });
  11763. };
  11764. var toLazy = function () {
  11765. return LazyValue.nu(get);
  11766. };
  11767. var toCached = function () {
  11768. var cache = null;
  11769. return make(function () {
  11770. if (cache === null) {
  11771. cache = run();
  11772. }
  11773. return cache;
  11774. });
  11775. };
  11776. var toPromise = run;
  11777. return {
  11778. map: map,
  11779. bind: bind,
  11780. anonBind: anonBind,
  11781. toLazy: toLazy,
  11782. toCached: toCached,
  11783. toPromise: toPromise,
  11784. get: get
  11785. };
  11786. };
  11787. var nu = function (baseFn) {
  11788. return make(function () {
  11789. return new Promise$1(baseFn);
  11790. });
  11791. };
  11792. var pure = function (a) {
  11793. return make(function () {
  11794. return Promise$1.resolve(a);
  11795. });
  11796. };
  11797. var Future = {
  11798. nu: nu,
  11799. pure: pure
  11800. };
  11801. var adjust = function (value, destination, amount) {
  11802. if (Math.abs(value - destination) <= amount) {
  11803. return Optional.none();
  11804. } else if (value < destination) {
  11805. return Optional.some(value + amount);
  11806. } else {
  11807. return Optional.some(value - amount);
  11808. }
  11809. };
  11810. var create$1 = function () {
  11811. var interval = null;
  11812. var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
  11813. var finished = false;
  11814. var finish = function (v) {
  11815. finished = true;
  11816. doFinish(v);
  11817. };
  11818. global$2.clearInterval(interval);
  11819. var abort = function (v) {
  11820. global$2.clearInterval(interval);
  11821. finish(v);
  11822. };
  11823. interval = global$2.setInterval(function () {
  11824. var value = getCurrent();
  11825. adjust(value, destination, amount).fold(function () {
  11826. global$2.clearInterval(interval);
  11827. finish(destination);
  11828. }, function (s) {
  11829. increment(s, abort);
  11830. if (!finished) {
  11831. var newValue = getCurrent();
  11832. if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
  11833. global$2.clearInterval(interval);
  11834. finish(destination);
  11835. }
  11836. }
  11837. });
  11838. }, rate);
  11839. };
  11840. return { animate: animate };
  11841. };
  11842. var findDevice = function (deviceWidth, deviceHeight) {
  11843. var devices = [
  11844. {
  11845. width: 320,
  11846. height: 480,
  11847. keyboard: {
  11848. portrait: 300,
  11849. landscape: 240
  11850. }
  11851. },
  11852. {
  11853. width: 320,
  11854. height: 568,
  11855. keyboard: {
  11856. portrait: 300,
  11857. landscape: 240
  11858. }
  11859. },
  11860. {
  11861. width: 375,
  11862. height: 667,
  11863. keyboard: {
  11864. portrait: 305,
  11865. landscape: 240
  11866. }
  11867. },
  11868. {
  11869. width: 414,
  11870. height: 736,
  11871. keyboard: {
  11872. portrait: 320,
  11873. landscape: 240
  11874. }
  11875. },
  11876. {
  11877. width: 768,
  11878. height: 1024,
  11879. keyboard: {
  11880. portrait: 320,
  11881. landscape: 400
  11882. }
  11883. },
  11884. {
  11885. width: 1024,
  11886. height: 1366,
  11887. keyboard: {
  11888. portrait: 380,
  11889. landscape: 460
  11890. }
  11891. }
  11892. ];
  11893. return findMap(devices, function (device) {
  11894. return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard);
  11895. }).getOr({
  11896. portrait: deviceHeight / 5,
  11897. landscape: deviceWidth / 4
  11898. });
  11899. };
  11900. var softKeyboardLimits = function (outerWindow) {
  11901. return findDevice(outerWindow.screen.width, outerWindow.screen.height);
  11902. };
  11903. var accountableKeyboardHeight = function (outerWindow) {
  11904. var portrait = get$1(outerWindow).isPortrait();
  11905. var limits = softKeyboardLimits(outerWindow);
  11906. var keyboard = portrait ? limits.portrait : limits.landscape;
  11907. var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
  11908. return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
  11909. };
  11910. var getGreenzone = function (socket, dropup) {
  11911. var outerWindow = owner$2(socket).dom.defaultView;
  11912. var viewportHeight = get$7(socket) + get$7(dropup);
  11913. var acc = accountableKeyboardHeight(outerWindow);
  11914. return viewportHeight - acc;
  11915. };
  11916. var updatePadding = function (contentBody, socket, dropup) {
  11917. var greenzoneHeight = getGreenzone(socket, dropup);
  11918. var deltaHeight = get$7(socket) + get$7(dropup) - greenzoneHeight;
  11919. set$5(contentBody, 'padding-bottom', deltaHeight + 'px');
  11920. };
  11921. var fixture = Adt.generate([
  11922. {
  11923. fixed: [
  11924. 'element',
  11925. 'property',
  11926. 'offsetY'
  11927. ]
  11928. },
  11929. {
  11930. scroller: [
  11931. 'element',
  11932. 'offsetY'
  11933. ]
  11934. }
  11935. ]);
  11936. var yFixedData = 'data-' + resolve('position-y-fixed');
  11937. var yFixedProperty = 'data-' + resolve('y-property');
  11938. var yScrollingData = 'data-' + resolve('scrolling');
  11939. var windowSizeData = 'data-' + resolve('last-window-height');
  11940. var getYFixedData = function (element) {
  11941. return safeParse(element, yFixedData);
  11942. };
  11943. var getYFixedProperty = function (element) {
  11944. return get$b(element, yFixedProperty);
  11945. };
  11946. var getLastWindowSize = function (element) {
  11947. return safeParse(element, windowSizeData);
  11948. };
  11949. var classifyFixed = function (element, offsetY) {
  11950. var prop = getYFixedProperty(element);
  11951. return fixture.fixed(element, prop, offsetY);
  11952. };
  11953. var classifyScrolling = function (element, offsetY) {
  11954. return fixture.scroller(element, offsetY);
  11955. };
  11956. var classify = function (element) {
  11957. var offsetY = getYFixedData(element);
  11958. var classifier = get$b(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
  11959. return classifier(element, offsetY);
  11960. };
  11961. var findFixtures = function (container) {
  11962. var candidates = descendants(container, '[' + yFixedData + ']');
  11963. return map$2(candidates, classify);
  11964. };
  11965. var takeoverToolbar = function (toolbar) {
  11966. var oldToolbarStyle = get$b(toolbar, 'style');
  11967. setAll(toolbar, {
  11968. position: 'absolute',
  11969. top: '0px'
  11970. });
  11971. set$8(toolbar, yFixedData, '0px');
  11972. set$8(toolbar, yFixedProperty, 'top');
  11973. var restore = function () {
  11974. set$8(toolbar, 'style', oldToolbarStyle || '');
  11975. remove$6(toolbar, yFixedData);
  11976. remove$6(toolbar, yFixedProperty);
  11977. };
  11978. return { restore: restore };
  11979. };
  11980. var takeoverViewport = function (toolbarHeight, height, viewport) {
  11981. var oldViewportStyle = get$b(viewport, 'style');
  11982. register$2(viewport);
  11983. setAll(viewport, {
  11984. position: 'absolute',
  11985. height: height + 'px',
  11986. width: '100%',
  11987. top: toolbarHeight + 'px'
  11988. });
  11989. set$8(viewport, yFixedData, toolbarHeight + 'px');
  11990. set$8(viewport, yScrollingData, 'true');
  11991. set$8(viewport, yFixedProperty, 'top');
  11992. var restore = function () {
  11993. deregister(viewport);
  11994. set$8(viewport, 'style', oldViewportStyle || '');
  11995. remove$6(viewport, yFixedData);
  11996. remove$6(viewport, yScrollingData);
  11997. remove$6(viewport, yFixedProperty);
  11998. };
  11999. return { restore: restore };
  12000. };
  12001. var takeoverDropup = function (dropup) {
  12002. var oldDropupStyle = get$b(dropup, 'style');
  12003. setAll(dropup, {
  12004. position: 'absolute',
  12005. bottom: '0px'
  12006. });
  12007. set$8(dropup, yFixedData, '0px');
  12008. set$8(dropup, yFixedProperty, 'bottom');
  12009. var restore = function () {
  12010. set$8(dropup, 'style', oldDropupStyle || '');
  12011. remove$6(dropup, yFixedData);
  12012. remove$6(dropup, yFixedProperty);
  12013. };
  12014. return { restore: restore };
  12015. };
  12016. var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
  12017. var outerWindow = owner$2(viewport).dom.defaultView;
  12018. var winH = outerWindow.innerHeight;
  12019. set$8(viewport, windowSizeData, winH + 'px');
  12020. return winH - toolbarHeight - dropupHeight;
  12021. };
  12022. var takeover = function (viewport, contentBody, toolbar, dropup) {
  12023. var outerWindow = owner$2(viewport).dom.defaultView;
  12024. var toolbarSetup = takeoverToolbar(toolbar);
  12025. var toolbarHeight = get$7(toolbar);
  12026. var dropupHeight = get$7(dropup);
  12027. var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
  12028. var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
  12029. var dropupSetup = takeoverDropup(dropup);
  12030. var isActive = true;
  12031. var restore = function () {
  12032. isActive = false;
  12033. toolbarSetup.restore();
  12034. viewportSetup.restore();
  12035. dropupSetup.restore();
  12036. };
  12037. var isExpanding = function () {
  12038. var currentWinHeight = outerWindow.innerHeight;
  12039. var lastWinHeight = getLastWindowSize(viewport);
  12040. return currentWinHeight > lastWinHeight;
  12041. };
  12042. var refresh = function () {
  12043. if (isActive) {
  12044. var newToolbarHeight = get$7(toolbar);
  12045. var dropupHeight_1 = get$7(dropup);
  12046. var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
  12047. set$8(viewport, yFixedData, newToolbarHeight + 'px');
  12048. set$5(viewport, 'height', newHeight + 'px');
  12049. updatePadding(contentBody, viewport, dropup);
  12050. }
  12051. };
  12052. var setViewportOffset = function (newYOffset) {
  12053. var offsetPx = newYOffset + 'px';
  12054. set$8(viewport, yFixedData, offsetPx);
  12055. refresh();
  12056. };
  12057. updatePadding(contentBody, viewport, dropup);
  12058. return {
  12059. setViewportOffset: setViewportOffset,
  12060. isExpanding: isExpanding,
  12061. isShrinking: not(isExpanding),
  12062. refresh: refresh,
  12063. restore: restore
  12064. };
  12065. };
  12066. var animator = create$1();
  12067. var ANIMATION_STEP = 15;
  12068. var NUM_TOP_ANIMATION_FRAMES = 10;
  12069. var ANIMATION_RATE = 10;
  12070. var lastScroll = 'data-' + resolve('last-scroll-top');
  12071. var getTop = function (element) {
  12072. var raw = getRaw(element, 'top').getOr('0');
  12073. return parseInt(raw, 10);
  12074. };
  12075. var getScrollTop = function (element) {
  12076. return parseInt(element.dom.scrollTop, 10);
  12077. };
  12078. var moveScrollAndTop = function (element, destination, finalTop) {
  12079. return Future.nu(function (callback) {
  12080. var getCurrent = curry(getScrollTop, element);
  12081. var update = function (newScroll) {
  12082. element.dom.scrollTop = newScroll;
  12083. set$5(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
  12084. };
  12085. var finish = function () {
  12086. element.dom.scrollTop = destination;
  12087. set$5(element, 'top', finalTop + 'px');
  12088. callback(destination);
  12089. };
  12090. animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
  12091. });
  12092. };
  12093. var moveOnlyScroll = function (element, destination) {
  12094. return Future.nu(function (callback) {
  12095. var getCurrent = curry(getScrollTop, element);
  12096. set$8(element, lastScroll, getCurrent());
  12097. var update = function (newScroll, abort) {
  12098. var previous = safeParse(element, lastScroll);
  12099. if (previous !== element.dom.scrollTop) {
  12100. abort(element.dom.scrollTop);
  12101. } else {
  12102. element.dom.scrollTop = newScroll;
  12103. set$8(element, lastScroll, newScroll);
  12104. }
  12105. };
  12106. var finish = function () {
  12107. element.dom.scrollTop = destination;
  12108. set$8(element, lastScroll, destination);
  12109. callback(destination);
  12110. };
  12111. var distance = Math.abs(destination - getCurrent());
  12112. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12113. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12114. });
  12115. };
  12116. var moveOnlyTop = function (element, destination) {
  12117. return Future.nu(function (callback) {
  12118. var getCurrent = curry(getTop, element);
  12119. var update = function (newTop) {
  12120. set$5(element, 'top', newTop + 'px');
  12121. };
  12122. var finish = function () {
  12123. update(destination);
  12124. callback(destination);
  12125. };
  12126. var distance = Math.abs(destination - getCurrent());
  12127. var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
  12128. animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
  12129. });
  12130. };
  12131. var updateTop = function (element, amount) {
  12132. var newTop = amount + getYFixedData(element) + 'px';
  12133. set$5(element, 'top', newTop);
  12134. };
  12135. var moveWindowScroll = function (toolbar, viewport, destY) {
  12136. var outerWindow = owner$2(toolbar).dom.defaultView;
  12137. return Future.nu(function (callback) {
  12138. updateTop(toolbar, destY);
  12139. updateTop(viewport, destY);
  12140. outerWindow.scrollTo(0, destY);
  12141. callback(destY);
  12142. });
  12143. };
  12144. function BackgroundActivity (doAction) {
  12145. var action = Cell(LazyValue.pure({}));
  12146. var start = function (value) {
  12147. var future = LazyValue.nu(function (callback) {
  12148. return doAction(value).get(callback);
  12149. });
  12150. action.set(future);
  12151. };
  12152. var idle = function (g) {
  12153. action.get().get(function () {
  12154. g();
  12155. });
  12156. };
  12157. return {
  12158. start: start,
  12159. idle: idle
  12160. };
  12161. }
  12162. var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
  12163. var greenzone = getGreenzone(socket, dropup);
  12164. var refreshCursor = curry(refresh, cWin);
  12165. if (top > greenzone || bottom > greenzone) {
  12166. moveOnlyScroll(socket, socket.dom.scrollTop - greenzone + bottom).get(refreshCursor);
  12167. } else if (top < 0) {
  12168. moveOnlyScroll(socket, socket.dom.scrollTop + top).get(refreshCursor);
  12169. } else ;
  12170. };
  12171. var par$1 = function (asyncValues, nu) {
  12172. return nu(function (callback) {
  12173. var r = [];
  12174. var count = 0;
  12175. var cb = function (i) {
  12176. return function (value) {
  12177. r[i] = value;
  12178. count++;
  12179. if (count >= asyncValues.length) {
  12180. callback(r);
  12181. }
  12182. };
  12183. };
  12184. if (asyncValues.length === 0) {
  12185. callback([]);
  12186. } else {
  12187. each$1(asyncValues, function (asyncValue, i) {
  12188. asyncValue.get(cb(i));
  12189. });
  12190. }
  12191. });
  12192. };
  12193. var par = function (futures) {
  12194. return par$1(futures, Future.nu);
  12195. };
  12196. var updateFixed = function (element, property, winY, offsetY) {
  12197. var destination = winY + offsetY;
  12198. set$5(element, property, destination + 'px');
  12199. return Future.pure(offsetY);
  12200. };
  12201. var updateScrollingFixed = function (element, winY, offsetY) {
  12202. var destTop = winY + offsetY;
  12203. var oldProp = getRaw(element, 'top').getOr(offsetY);
  12204. var delta = destTop - parseInt(oldProp, 10);
  12205. var destScroll = element.dom.scrollTop + delta;
  12206. return moveScrollAndTop(element, destScroll, destTop);
  12207. };
  12208. var updateFixture = function (fixture, winY) {
  12209. return fixture.fold(function (element, property, offsetY) {
  12210. return updateFixed(element, property, winY, offsetY);
  12211. }, function (element, offsetY) {
  12212. return updateScrollingFixed(element, winY, offsetY);
  12213. });
  12214. };
  12215. var updatePositions = function (container, winY) {
  12216. var fixtures = findFixtures(container);
  12217. var updates = map$2(fixtures, function (fixture) {
  12218. return updateFixture(fixture, winY);
  12219. });
  12220. return par(updates);
  12221. };
  12222. var VIEW_MARGIN = 5;
  12223. var register = function (toolstrip, socket, container, outerWindow, structure, cWin) {
  12224. var scroller = BackgroundActivity(function (y) {
  12225. return moveWindowScroll(toolstrip, socket, y);
  12226. });
  12227. var scrollBounds = function () {
  12228. var rects = getRectangles(cWin);
  12229. return Optional.from(rects[0]).bind(function (rect) {
  12230. var viewTop = rect.top - socket.dom.scrollTop;
  12231. var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
  12232. return outside ? Optional.some({
  12233. top: viewTop,
  12234. bottom: viewTop + rect.height
  12235. }) : Optional.none();
  12236. });
  12237. };
  12238. var scrollThrottle = last(function () {
  12239. scroller.idle(function () {
  12240. updatePositions(container, outerWindow.pageYOffset).get(function () {
  12241. var extraScroll = scrollBounds();
  12242. extraScroll.each(function (extra) {
  12243. socket.dom.scrollTop = socket.dom.scrollTop + extra.top;
  12244. });
  12245. scroller.start(0);
  12246. structure.refresh();
  12247. });
  12248. });
  12249. }, 1000);
  12250. var onScroll = bind(SugarElement.fromDom(outerWindow), 'scroll', function () {
  12251. if (outerWindow.pageYOffset < 0) {
  12252. return;
  12253. }
  12254. scrollThrottle.throttle();
  12255. });
  12256. updatePositions(container, outerWindow.pageYOffset).get(identity);
  12257. return { unbind: onScroll.unbind };
  12258. };
  12259. var setup = function (bag) {
  12260. var cWin = bag.cWin;
  12261. var ceBody = bag.ceBody;
  12262. var socket = bag.socket;
  12263. var toolstrip = bag.toolstrip;
  12264. var contentElement = bag.contentElement;
  12265. var keyboardType = bag.keyboardType;
  12266. var outerWindow = bag.outerWindow;
  12267. var dropup = bag.dropup;
  12268. var outerBody = bag.outerBody;
  12269. var structure = takeover(socket, ceBody, toolstrip, dropup);
  12270. var keyboardModel = keyboardType(outerBody, cWin, body(), contentElement);
  12271. var toEditing = function () {
  12272. keyboardModel.toEditing();
  12273. clearSelection();
  12274. };
  12275. var toReading = function () {
  12276. keyboardModel.toReading();
  12277. };
  12278. var onToolbarTouch = function (_event) {
  12279. keyboardModel.onToolbarTouch();
  12280. };
  12281. var onOrientation = onChange(outerWindow, {
  12282. onChange: noop,
  12283. onReady: structure.refresh
  12284. });
  12285. onOrientation.onAdjustment(function () {
  12286. structure.refresh();
  12287. });
  12288. var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () {
  12289. if (structure.isExpanding()) {
  12290. structure.refresh();
  12291. }
  12292. });
  12293. var onScroll = register(toolstrip, socket, outerBody, outerWindow, structure, cWin);
  12294. var unfocusedSelection = FakeSelection(cWin, contentElement);
  12295. var refreshSelection = function () {
  12296. if (unfocusedSelection.isActive()) {
  12297. unfocusedSelection.update();
  12298. }
  12299. };
  12300. var highlightSelection = function () {
  12301. unfocusedSelection.update();
  12302. };
  12303. var clearSelection = function () {
  12304. unfocusedSelection.clear();
  12305. };
  12306. var scrollIntoView$1 = function (top, bottom) {
  12307. scrollIntoView(cWin, socket, dropup, top, bottom);
  12308. };
  12309. var syncHeight = function () {
  12310. set$5(contentElement, 'height', contentElement.dom.contentWindow.document.body.scrollHeight + 'px');
  12311. };
  12312. var setViewportOffset = function (newYOffset) {
  12313. structure.setViewportOffset(newYOffset);
  12314. moveOnlyTop(socket, newYOffset).get(identity);
  12315. };
  12316. var destroy = function () {
  12317. structure.restore();
  12318. onOrientation.destroy();
  12319. onScroll.unbind();
  12320. onResize.unbind();
  12321. keyboardModel.destroy();
  12322. unfocusedSelection.destroy();
  12323. input(body(), blur$1);
  12324. };
  12325. return {
  12326. toEditing: toEditing,
  12327. toReading: toReading,
  12328. onToolbarTouch: onToolbarTouch,
  12329. refreshSelection: refreshSelection,
  12330. clearSelection: clearSelection,
  12331. highlightSelection: highlightSelection,
  12332. scrollIntoView: scrollIntoView$1,
  12333. updateToolbarPadding: noop,
  12334. setViewportOffset: setViewportOffset,
  12335. syncHeight: syncHeight,
  12336. refreshStructure: structure.refresh,
  12337. destroy: destroy
  12338. };
  12339. };
  12340. var create = function (platform, mask) {
  12341. var meta = tag();
  12342. var priorState = value();
  12343. var scrollEvents = value();
  12344. var iosApi = api$2();
  12345. var iosEvents = api$2();
  12346. var enter = function () {
  12347. mask.hide();
  12348. var doc = SugarElement.fromDom(document);
  12349. getActiveApi(platform.editor).each(function (editorApi) {
  12350. priorState.set({
  12351. socketHeight: getRaw(platform.socket, 'height'),
  12352. iframeHeight: getRaw(editorApi.frame, 'height'),
  12353. outerScroll: document.body.scrollTop
  12354. });
  12355. scrollEvents.set({ exclusives: exclusive(doc, '.' + scrollable) });
  12356. add$1(platform.container, resolve('fullscreen-maximized'));
  12357. clobberStyles(platform.container, editorApi.body);
  12358. meta.maximize();
  12359. set$5(platform.socket, 'overflow', 'scroll');
  12360. set$5(platform.socket, '-webkit-overflow-scrolling', 'touch');
  12361. focus$3(editorApi.body);
  12362. iosApi.set(setup({
  12363. cWin: editorApi.win,
  12364. ceBody: editorApi.body,
  12365. socket: platform.socket,
  12366. toolstrip: platform.toolstrip,
  12367. dropup: platform.dropup.element,
  12368. contentElement: editorApi.frame,
  12369. outerBody: platform.body,
  12370. outerWindow: platform.win,
  12371. keyboardType: stubborn
  12372. }));
  12373. iosApi.run(function (api) {
  12374. api.syncHeight();
  12375. });
  12376. iosEvents.set(initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
  12377. });
  12378. };
  12379. var exit = function () {
  12380. meta.restore();
  12381. iosEvents.clear();
  12382. iosApi.clear();
  12383. mask.show();
  12384. priorState.on(function (s) {
  12385. s.socketHeight.each(function (h) {
  12386. set$5(platform.socket, 'height', h);
  12387. });
  12388. s.iframeHeight.each(function (h) {
  12389. set$5(platform.editor.getFrame(), 'height', h);
  12390. });
  12391. document.body.scrollTop = s.scrollTop;
  12392. });
  12393. priorState.clear();
  12394. scrollEvents.on(function (s) {
  12395. s.exclusives.unbind();
  12396. });
  12397. scrollEvents.clear();
  12398. remove$3(platform.container, resolve('fullscreen-maximized'));
  12399. restoreStyles();
  12400. deregister(platform.toolbar);
  12401. remove$2(platform.socket, 'overflow');
  12402. remove$2(platform.socket, '-webkit-overflow-scrolling');
  12403. blur$1(platform.editor.getFrame());
  12404. getActiveApi(platform.editor).each(function (editorApi) {
  12405. editorApi.clearSelection();
  12406. });
  12407. };
  12408. var refreshStructure = function () {
  12409. iosApi.run(function (api) {
  12410. api.refreshStructure();
  12411. });
  12412. };
  12413. return {
  12414. enter: enter,
  12415. refreshStructure: refreshStructure,
  12416. exit: exit
  12417. };
  12418. };
  12419. var produce = function (raw) {
  12420. var mobile = asRawOrDie$1('Getting IosWebapp schema', MobileSchema, raw);
  12421. set$5(mobile.toolstrip, 'width', '100%');
  12422. set$5(mobile.container, 'position', 'relative');
  12423. var onView = function () {
  12424. mobile.setReadOnly(mobile.readOnlyOnInit());
  12425. mode.enter();
  12426. };
  12427. var mask = build$1(sketch(onView, mobile.translate));
  12428. mobile.alloy.add(mask);
  12429. var maskApi = {
  12430. show: function () {
  12431. mobile.alloy.add(mask);
  12432. },
  12433. hide: function () {
  12434. mobile.alloy.remove(mask);
  12435. }
  12436. };
  12437. var mode = create(mobile, maskApi);
  12438. return {
  12439. setReadOnly: mobile.setReadOnly,
  12440. refreshStructure: mode.refreshStructure,
  12441. enter: mode.enter,
  12442. exit: mode.exit,
  12443. destroy: noop
  12444. };
  12445. };
  12446. function IosRealm (scrollIntoView) {
  12447. var alloy = OuterContainer({ classes: [resolve('ios-container')] });
  12448. var toolbar = ScrollingToolbar();
  12449. var webapp = api$2();
  12450. var switchToEdit = makeEditSwitch(webapp);
  12451. var socket = makeSocket();
  12452. var dropup = build(function () {
  12453. webapp.run(function (w) {
  12454. w.refreshStructure();
  12455. });
  12456. }, scrollIntoView);
  12457. alloy.add(toolbar.wrapper);
  12458. alloy.add(socket);
  12459. alloy.add(dropup.component);
  12460. var setToolbarGroups = function (rawGroups) {
  12461. var groups = toolbar.createGroups(rawGroups);
  12462. toolbar.setGroups(groups);
  12463. };
  12464. var setContextToolbar = function (rawGroups) {
  12465. var groups = toolbar.createGroups(rawGroups);
  12466. toolbar.setContextToolbar(groups);
  12467. };
  12468. var focusToolbar = function () {
  12469. toolbar.focus();
  12470. };
  12471. var restoreToolbar = function () {
  12472. toolbar.restoreToolbar();
  12473. };
  12474. var init = function (spec) {
  12475. webapp.set(produce(spec));
  12476. };
  12477. var exit = function () {
  12478. webapp.run(function (w) {
  12479. Replacing.remove(socket, switchToEdit);
  12480. w.exit();
  12481. });
  12482. };
  12483. var updateMode$1 = function (readOnly) {
  12484. updateMode(socket, switchToEdit, readOnly, alloy.root);
  12485. };
  12486. return {
  12487. system: alloy,
  12488. element: alloy.element,
  12489. init: init,
  12490. exit: exit,
  12491. setToolbarGroups: setToolbarGroups,
  12492. setContextToolbar: setContextToolbar,
  12493. focusToolbar: focusToolbar,
  12494. restoreToolbar: restoreToolbar,
  12495. updateMode: updateMode$1,
  12496. socket: socket,
  12497. dropup: dropup
  12498. };
  12499. }
  12500. var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager');
  12501. var derive = function (editor) {
  12502. var base = Optional.from(getSkinUrl(editor)).getOrThunk(function () {
  12503. return global$1.baseURL + '/skins/ui/oxide';
  12504. });
  12505. return {
  12506. content: base + '/content.mobile.min.css',
  12507. ui: base + '/skin.mobile.min.css'
  12508. };
  12509. };
  12510. var fireChange = function (realm, command, state) {
  12511. realm.system.broadcastOn([formatChanged], {
  12512. command: command,
  12513. state: state
  12514. });
  12515. };
  12516. var init = function (realm, editor) {
  12517. var allFormats = keys(editor.formatter.get());
  12518. each$1(allFormats, function (command) {
  12519. editor.formatter.formatChanged(command, function (state) {
  12520. fireChange(realm, command, state);
  12521. });
  12522. });
  12523. each$1([
  12524. 'ul',
  12525. 'ol'
  12526. ], function (command) {
  12527. editor.selection.selectorChanged(command, function (state, _data) {
  12528. fireChange(realm, command, state);
  12529. });
  12530. });
  12531. };
  12532. var fireSkinLoaded = function (editor) {
  12533. return function () {
  12534. var done = function () {
  12535. editor._skinLoaded = true;
  12536. editor.fire('SkinLoaded');
  12537. };
  12538. if (editor.initialized) {
  12539. done();
  12540. } else {
  12541. editor.on('init', done);
  12542. }
  12543. };
  12544. };
  12545. var READING = 'toReading';
  12546. var EDITING = 'toEditing';
  12547. var renderMobileTheme = function (editor) {
  12548. var renderUI = function () {
  12549. var targetNode = editor.getElement();
  12550. var cssUrls = derive(editor);
  12551. if (isSkinDisabled(editor) === false) {
  12552. var styleSheetLoader_1 = global$5.DOM.styleSheetLoader;
  12553. editor.contentCSS.push(cssUrls.content);
  12554. styleSheetLoader_1.load(cssUrls.ui, fireSkinLoaded(editor));
  12555. editor.on('remove', function () {
  12556. return styleSheetLoader_1.unload(cssUrls.ui);
  12557. });
  12558. } else {
  12559. fireSkinLoaded(editor)();
  12560. }
  12561. var doScrollIntoView = function () {
  12562. editor.fire('ScrollIntoView');
  12563. };
  12564. var realm = detect$1().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
  12565. var original = SugarElement.fromDom(targetNode);
  12566. attachSystemAfter(original, realm.system);
  12567. var findFocusIn = function (elem) {
  12568. return search(elem).bind(function (focused) {
  12569. return realm.system.getByDom(focused).toOptional();
  12570. });
  12571. };
  12572. var outerWindow = targetNode.ownerDocument.defaultView;
  12573. var orientation = onChange(outerWindow, {
  12574. onChange: function () {
  12575. var alloy = realm.system;
  12576. alloy.broadcastOn([orientationChanged], { width: getActualWidth(outerWindow) });
  12577. },
  12578. onReady: noop
  12579. });
  12580. var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
  12581. if (ro === false) {
  12582. editor.selection.collapse();
  12583. }
  12584. var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
  12585. realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
  12586. editor.setMode(ro === true ? 'readonly' : 'design');
  12587. editor.fire(ro === true ? READING : EDITING);
  12588. realm.updateMode(ro);
  12589. };
  12590. var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
  12591. var dynamic = dynamicGroup.get();
  12592. var toolbars = {
  12593. readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
  12594. main: dynamic.backToMask.concat(mainGroups.get())
  12595. };
  12596. return toolbars;
  12597. };
  12598. var bindHandler = function (label, handler) {
  12599. editor.on(label, handler);
  12600. return {
  12601. unbind: function () {
  12602. editor.off(label);
  12603. }
  12604. };
  12605. };
  12606. editor.on('init', function () {
  12607. realm.init({
  12608. editor: {
  12609. getFrame: function () {
  12610. return SugarElement.fromDom(editor.contentAreaContainer.querySelector('iframe'));
  12611. },
  12612. onDomChanged: function () {
  12613. return { unbind: noop };
  12614. },
  12615. onToReading: function (handler) {
  12616. return bindHandler(READING, handler);
  12617. },
  12618. onToEditing: function (handler) {
  12619. return bindHandler(EDITING, handler);
  12620. },
  12621. onScrollToCursor: function (handler) {
  12622. editor.on('ScrollIntoView', function (tinyEvent) {
  12623. handler(tinyEvent);
  12624. });
  12625. var unbind = function () {
  12626. editor.off('ScrollIntoView');
  12627. orientation.destroy();
  12628. };
  12629. return { unbind: unbind };
  12630. },
  12631. onTouchToolstrip: function () {
  12632. hideDropup();
  12633. },
  12634. onTouchContent: function () {
  12635. var toolbar = SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar')));
  12636. findFocusIn(toolbar).each(emitExecute);
  12637. realm.restoreToolbar();
  12638. hideDropup();
  12639. },
  12640. onTapContent: function (evt) {
  12641. var target = evt.target;
  12642. if (name$1(target) === 'img') {
  12643. editor.selection.select(target.dom);
  12644. evt.kill();
  12645. } else if (name$1(target) === 'a') {
  12646. var component = realm.system.getByDom(SugarElement.fromDom(editor.editorContainer));
  12647. component.each(function (container) {
  12648. if (Swapping.isAlpha(container)) {
  12649. openLink(target.dom);
  12650. }
  12651. });
  12652. }
  12653. }
  12654. },
  12655. container: SugarElement.fromDom(editor.editorContainer),
  12656. socket: SugarElement.fromDom(editor.contentAreaContainer),
  12657. toolstrip: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolstrip'))),
  12658. toolbar: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))),
  12659. dropup: realm.dropup,
  12660. alloy: realm.system,
  12661. translate: noop,
  12662. setReadOnly: function (ro) {
  12663. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
  12664. },
  12665. readOnlyOnInit: function () {
  12666. return readOnlyOnInit();
  12667. }
  12668. });
  12669. var hideDropup = function () {
  12670. realm.dropup.disappear(function () {
  12671. realm.system.broadcastOn([dropupDismissed], {});
  12672. });
  12673. };
  12674. var backToMaskGroup = {
  12675. label: 'The first group',
  12676. scrollable: false,
  12677. items: [forToolbar('back', function () {
  12678. editor.selection.collapse();
  12679. realm.exit();
  12680. }, {}, editor)]
  12681. };
  12682. var backToReadOnlyGroup = {
  12683. label: 'Back to read only',
  12684. scrollable: false,
  12685. items: [forToolbar('readonly-back', function () {
  12686. setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
  12687. }, {}, editor)]
  12688. };
  12689. var readOnlyGroup = {
  12690. label: 'The read only mode group',
  12691. scrollable: true,
  12692. items: []
  12693. };
  12694. var features = setup$3(realm, editor);
  12695. var items = detect(editor, features);
  12696. var actionGroup = {
  12697. label: 'the action group',
  12698. scrollable: true,
  12699. items: items
  12700. };
  12701. var extraGroup = {
  12702. label: 'The extra group',
  12703. scrollable: false,
  12704. items: []
  12705. };
  12706. var mainGroups = Cell([
  12707. actionGroup,
  12708. extraGroup
  12709. ]);
  12710. var readOnlyGroups = Cell([
  12711. readOnlyGroup,
  12712. extraGroup
  12713. ]);
  12714. var dynamicGroup = Cell({
  12715. backToMask: [backToMaskGroup],
  12716. backToReadOnly: [backToReadOnlyGroup]
  12717. });
  12718. init(realm, editor);
  12719. });
  12720. editor.on('remove', function () {
  12721. realm.exit();
  12722. });
  12723. editor.on('detach', function () {
  12724. detachSystem(realm.system);
  12725. realm.system.destroy();
  12726. });
  12727. return {
  12728. iframeContainer: realm.socket.element.dom,
  12729. editorContainer: realm.element.dom
  12730. };
  12731. };
  12732. return {
  12733. getNotificationManagerImpl: function () {
  12734. return {
  12735. open: constant$1({
  12736. progressBar: { value: noop },
  12737. close: noop,
  12738. text: noop,
  12739. getEl: constant$1(null),
  12740. moveTo: noop,
  12741. moveRel: noop,
  12742. settings: {}
  12743. }),
  12744. close: noop,
  12745. reposition: noop,
  12746. getArgs: constant$1({})
  12747. };
  12748. },
  12749. renderUI: renderUI
  12750. };
  12751. };
  12752. function Theme () {
  12753. global$4.add('mobile', renderMobileTheme);
  12754. }
  12755. Theme();
  12756. }());