[ Index ] |
PHP Cross Reference of Joomla 4.2.2 documentation |
[Summary view] [Print] [Text view]
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.5 (2022-05-25) 8 */ 9 (function () { 10 'use strict'; 11 12 var __assign = function () { 13 __assign = Object.assign || function __assign(t) { 14 for (var s, i = 1, n = arguments.length; i < n; i++) { 15 s = arguments[i]; 16 for (var p in s) 17 if (Object.prototype.hasOwnProperty.call(s, p)) 18 t[p] = s[p]; 19 } 20 return t; 21 }; 22 return __assign.apply(this, arguments); 23 }; 24 function __rest(s, e) { 25 var t = {}; 26 for (var p in s) 27 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) 28 t[p] = s[p]; 29 if (s != null && typeof Object.getOwnPropertySymbols === 'function') 30 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { 31 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) 32 t[p[i]] = s[p[i]]; 33 } 34 return t; 35 } 36 function __spreadArray(to, from, pack) { 37 if (pack || arguments.length === 2) 38 for (var i = 0, l = from.length, ar; i < l; i++) { 39 if (ar || !(i in from)) { 40 if (!ar) 41 ar = Array.prototype.slice.call(from, 0, i); 42 ar[i] = from[i]; 43 } 44 } 45 return to.concat(ar || Array.prototype.slice.call(from)); 46 } 47 48 var typeOf = function (x) { 49 var t = typeof x; 50 if (x === null) { 51 return 'null'; 52 } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { 53 return 'array'; 54 } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { 55 return 'string'; 56 } else { 57 return t; 58 } 59 }; 60 var isType$1 = function (type) { 61 return function (value) { 62 return typeOf(value) === type; 63 }; 64 }; 65 var isSimpleType = function (type) { 66 return function (value) { 67 return typeof value === type; 68 }; 69 }; 70 var eq$1 = function (t) { 71 return function (a) { 72 return t === a; 73 }; 74 }; 75 var isString = isType$1('string'); 76 var isObject = isType$1('object'); 77 var isArray = isType$1('array'); 78 var isNull = eq$1(null); 79 var isBoolean = isSimpleType('boolean'); 80 var isUndefined = eq$1(undefined); 81 var isNullable = function (a) { 82 return a === null || a === undefined; 83 }; 84 var isNonNullable = function (a) { 85 return !isNullable(a); 86 }; 87 var isFunction = isSimpleType('function'); 88 var isNumber = isSimpleType('number'); 89 90 var noop = function () { 91 }; 92 var compose = function (fa, fb) { 93 return function () { 94 var args = []; 95 for (var _i = 0; _i < arguments.length; _i++) { 96 args[_i] = arguments[_i]; 97 } 98 return fa(fb.apply(null, args)); 99 }; 100 }; 101 var compose1 = function (fbc, fab) { 102 return function (a) { 103 return fbc(fab(a)); 104 }; 105 }; 106 var constant$1 = function (value) { 107 return function () { 108 return value; 109 }; 110 }; 111 var identity = function (x) { 112 return x; 113 }; 114 var tripleEquals = function (a, b) { 115 return a === b; 116 }; 117 function curry(fn) { 118 var initialArgs = []; 119 for (var _i = 1; _i < arguments.length; _i++) { 120 initialArgs[_i - 1] = arguments[_i]; 121 } 122 return function () { 123 var restArgs = []; 124 for (var _i = 0; _i < arguments.length; _i++) { 125 restArgs[_i] = arguments[_i]; 126 } 127 var all = initialArgs.concat(restArgs); 128 return fn.apply(null, all); 129 }; 130 } 131 var not = function (f) { 132 return function (t) { 133 return !f(t); 134 }; 135 }; 136 var die = function (msg) { 137 return function () { 138 throw new Error(msg); 139 }; 140 }; 141 var apply$1 = function (f) { 142 return f(); 143 }; 144 var never = constant$1(false); 145 var always = constant$1(true); 146 147 var none = function () { 148 return NONE; 149 }; 150 var NONE = function () { 151 var call = function (thunk) { 152 return thunk(); 153 }; 154 var id = identity; 155 var me = { 156 fold: function (n, _s) { 157 return n(); 158 }, 159 isSome: never, 160 isNone: always, 161 getOr: id, 162 getOrThunk: call, 163 getOrDie: function (msg) { 164 throw new Error(msg || 'error: getOrDie called on none.'); 165 }, 166 getOrNull: constant$1(null), 167 getOrUndefined: constant$1(undefined), 168 or: id, 169 orThunk: call, 170 map: none, 171 each: noop, 172 bind: none, 173 exists: never, 174 forall: always, 175 filter: function () { 176 return none(); 177 }, 178 toArray: function () { 179 return []; 180 }, 181 toString: constant$1('none()') 182 }; 183 return me; 184 }(); 185 var some = function (a) { 186 var constant_a = constant$1(a); 187 var self = function () { 188 return me; 189 }; 190 var bind = function (f) { 191 return f(a); 192 }; 193 var me = { 194 fold: function (n, s) { 195 return s(a); 196 }, 197 isSome: always, 198 isNone: never, 199 getOr: constant_a, 200 getOrThunk: constant_a, 201 getOrDie: constant_a, 202 getOrNull: constant_a, 203 getOrUndefined: constant_a, 204 or: self, 205 orThunk: self, 206 map: function (f) { 207 return some(f(a)); 208 }, 209 each: function (f) { 210 f(a); 211 }, 212 bind: bind, 213 exists: bind, 214 forall: bind, 215 filter: function (f) { 216 return f(a) ? me : NONE; 217 }, 218 toArray: function () { 219 return [a]; 220 }, 221 toString: function () { 222 return 'some(' + a + ')'; 223 } 224 }; 225 return me; 226 }; 227 var from = function (value) { 228 return value === null || value === undefined ? NONE : some(value); 229 }; 230 var Optional = { 231 some: some, 232 none: none, 233 from: from 234 }; 235 236 var cached = function (f) { 237 var called = false; 238 var r; 239 return function () { 240 var args = []; 241 for (var _i = 0; _i < arguments.length; _i++) { 242 args[_i] = arguments[_i]; 243 } 244 if (!called) { 245 called = true; 246 r = f.apply(null, args); 247 } 248 return r; 249 }; 250 }; 251 252 var DeviceType = function (os, browser, userAgent, mediaMatch) { 253 var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; 254 var isiPhone = os.isiOS() && !isiPad; 255 var isMobile = os.isiOS() || os.isAndroid(); 256 var isTouch = isMobile || mediaMatch('(pointer:coarse)'); 257 var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)'); 258 var isPhone = isiPhone || isMobile && !isTablet; 259 var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; 260 var isDesktop = !isPhone && !isTablet && !iOSwebview; 261 return { 262 isiPad: constant$1(isiPad), 263 isiPhone: constant$1(isiPhone), 264 isTablet: constant$1(isTablet), 265 isPhone: constant$1(isPhone), 266 isTouch: constant$1(isTouch), 267 isAndroid: os.isAndroid, 268 isiOS: os.isiOS, 269 isWebView: constant$1(iOSwebview), 270 isDesktop: constant$1(isDesktop) 271 }; 272 }; 273 274 var nativeSlice = Array.prototype.slice; 275 var nativeIndexOf = Array.prototype.indexOf; 276 var nativePush = Array.prototype.push; 277 var rawIndexOf = function (ts, t) { 278 return nativeIndexOf.call(ts, t); 279 }; 280 var contains$1 = function (xs, x) { 281 return rawIndexOf(xs, x) > -1; 282 }; 283 var exists = function (xs, pred) { 284 for (var i = 0, len = xs.length; i < len; i++) { 285 var x = xs[i]; 286 if (pred(x, i)) { 287 return true; 288 } 289 } 290 return false; 291 }; 292 var map$2 = function (xs, f) { 293 var len = xs.length; 294 var r = new Array(len); 295 for (var i = 0; i < len; i++) { 296 var x = xs[i]; 297 r[i] = f(x, i); 298 } 299 return r; 300 }; 301 var each$1 = function (xs, f) { 302 for (var i = 0, len = xs.length; i < len; i++) { 303 var x = xs[i]; 304 f(x, i); 305 } 306 }; 307 var eachr = function (xs, f) { 308 for (var i = xs.length - 1; i >= 0; i--) { 309 var x = xs[i]; 310 f(x, i); 311 } 312 }; 313 var filter$2 = function (xs, pred) { 314 var r = []; 315 for (var i = 0, len = xs.length; i < len; i++) { 316 var x = xs[i]; 317 if (pred(x, i)) { 318 r.push(x); 319 } 320 } 321 return r; 322 }; 323 var foldr = function (xs, f, acc) { 324 eachr(xs, function (x, i) { 325 acc = f(acc, x, i); 326 }); 327 return acc; 328 }; 329 var foldl = function (xs, f, acc) { 330 each$1(xs, function (x, i) { 331 acc = f(acc, x, i); 332 }); 333 return acc; 334 }; 335 var findUntil = function (xs, pred, until) { 336 for (var i = 0, len = xs.length; i < len; i++) { 337 var x = xs[i]; 338 if (pred(x, i)) { 339 return Optional.some(x); 340 } else if (until(x, i)) { 341 break; 342 } 343 } 344 return Optional.none(); 345 }; 346 var find$2 = function (xs, pred) { 347 return findUntil(xs, pred, never); 348 }; 349 var findIndex$1 = function (xs, pred) { 350 for (var i = 0, len = xs.length; i < len; i++) { 351 var x = xs[i]; 352 if (pred(x, i)) { 353 return Optional.some(i); 354 } 355 } 356 return Optional.none(); 357 }; 358 var flatten = function (xs) { 359 var r = []; 360 for (var i = 0, len = xs.length; i < len; ++i) { 361 if (!isArray(xs[i])) { 362 throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); 363 } 364 nativePush.apply(r, xs[i]); 365 } 366 return r; 367 }; 368 var bind$3 = function (xs, f) { 369 return flatten(map$2(xs, f)); 370 }; 371 var forall = function (xs, pred) { 372 for (var i = 0, len = xs.length; i < len; ++i) { 373 var x = xs[i]; 374 if (pred(x, i) !== true) { 375 return false; 376 } 377 } 378 return true; 379 }; 380 var reverse = function (xs) { 381 var r = nativeSlice.call(xs, 0); 382 r.reverse(); 383 return r; 384 }; 385 var difference = function (a1, a2) { 386 return filter$2(a1, function (x) { 387 return !contains$1(a2, x); 388 }); 389 }; 390 var pure$2 = function (x) { 391 return [x]; 392 }; 393 var sort = function (xs, comparator) { 394 var copy = nativeSlice.call(xs, 0); 395 copy.sort(comparator); 396 return copy; 397 }; 398 var get$d = function (xs, i) { 399 return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none(); 400 }; 401 var head = function (xs) { 402 return get$d(xs, 0); 403 }; 404 var findMap = function (arr, f) { 405 for (var i = 0; i < arr.length; i++) { 406 var r = f(arr[i], i); 407 if (r.isSome()) { 408 return r; 409 } 410 } 411 return Optional.none(); 412 }; 413 414 var firstMatch = function (regexes, s) { 415 for (var i = 0; i < regexes.length; i++) { 416 var x = regexes[i]; 417 if (x.test(s)) { 418 return x; 419 } 420 } 421 return undefined; 422 }; 423 var find$1 = function (regexes, agent) { 424 var r = firstMatch(regexes, agent); 425 if (!r) { 426 return { 427 major: 0, 428 minor: 0 429 }; 430 } 431 var group = function (i) { 432 return Number(agent.replace(r, '$' + i)); 433 }; 434 return nu$8(group(1), group(2)); 435 }; 436 var detect$4 = function (versionRegexes, agent) { 437 var cleanedAgent = String(agent).toLowerCase(); 438 if (versionRegexes.length === 0) { 439 return unknown$3(); 440 } 441 return find$1(versionRegexes, cleanedAgent); 442 }; 443 var unknown$3 = function () { 444 return nu$8(0, 0); 445 }; 446 var nu$8 = function (major, minor) { 447 return { 448 major: major, 449 minor: minor 450 }; 451 }; 452 var Version = { 453 nu: nu$8, 454 detect: detect$4, 455 unknown: unknown$3 456 }; 457 458 var detectBrowser$1 = function (browsers, userAgentData) { 459 return findMap(userAgentData.brands, function (uaBrand) { 460 var lcBrand = uaBrand.brand.toLowerCase(); 461 return find$2(browsers, function (browser) { 462 var _a; 463 return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase()); 464 }).map(function (info) { 465 return { 466 current: info.name, 467 version: Version.nu(parseInt(uaBrand.version, 10), 0) 468 }; 469 }); 470 }); 471 }; 472 473 var detect$3 = function (candidates, userAgent) { 474 var agent = String(userAgent).toLowerCase(); 475 return find$2(candidates, function (candidate) { 476 return candidate.search(agent); 477 }); 478 }; 479 var detectBrowser = function (browsers, userAgent) { 480 return detect$3(browsers, userAgent).map(function (browser) { 481 var version = Version.detect(browser.versionRegexes, userAgent); 482 return { 483 current: browser.name, 484 version: version 485 }; 486 }); 487 }; 488 var detectOs = function (oses, userAgent) { 489 return detect$3(oses, userAgent).map(function (os) { 490 var version = Version.detect(os.versionRegexes, userAgent); 491 return { 492 current: os.name, 493 version: version 494 }; 495 }); 496 }; 497 498 var checkRange = function (str, substr, start) { 499 return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr; 500 }; 501 var supplant = function (str, obj) { 502 var isStringOrNumber = function (a) { 503 var t = typeof a; 504 return t === 'string' || t === 'number'; 505 }; 506 return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) { 507 var value = obj[key]; 508 return isStringOrNumber(value) ? value.toString() : fullMatch; 509 }); 510 }; 511 var contains = function (str, substr) { 512 return str.indexOf(substr) !== -1; 513 }; 514 var endsWith = function (str, suffix) { 515 return checkRange(str, suffix, str.length - suffix.length); 516 }; 517 var blank = function (r) { 518 return function (s) { 519 return s.replace(r, ''); 520 }; 521 }; 522 var trim = blank(/^\s+|\s+$/g); 523 524 var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; 525 var checkContains = function (target) { 526 return function (uastring) { 527 return contains(uastring, target); 528 }; 529 }; 530 var browsers = [ 531 { 532 name: 'Edge', 533 versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], 534 search: function (uastring) { 535 return contains(uastring, 'edge/') && contains(uastring, 'chrome') && contains(uastring, 'safari') && contains(uastring, 'applewebkit'); 536 } 537 }, 538 { 539 name: 'Chrome', 540 brand: 'Chromium', 541 versionRegexes: [ 542 /.*?chrome\/([0-9]+)\.([0-9]+).*/, 543 normalVersionRegex 544 ], 545 search: function (uastring) { 546 return contains(uastring, 'chrome') && !contains(uastring, 'chromeframe'); 547 } 548 }, 549 { 550 name: 'IE', 551 versionRegexes: [ 552 /.*?msie\ ?([0-9]+)\.([0-9]+).*/, 553 /.*?rv:([0-9]+)\.([0-9]+).*/ 554 ], 555 search: function (uastring) { 556 return contains(uastring, 'msie') || contains(uastring, 'trident'); 557 } 558 }, 559 { 560 name: 'Opera', 561 versionRegexes: [ 562 normalVersionRegex, 563 /.*?opera\/([0-9]+)\.([0-9]+).*/ 564 ], 565 search: checkContains('opera') 566 }, 567 { 568 name: 'Firefox', 569 versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/], 570 search: checkContains('firefox') 571 }, 572 { 573 name: 'Safari', 574 versionRegexes: [ 575 normalVersionRegex, 576 /.*?cpu os ([0-9]+)_([0-9]+).*/ 577 ], 578 search: function (uastring) { 579 return (contains(uastring, 'safari') || contains(uastring, 'mobile/')) && contains(uastring, 'applewebkit'); 580 } 581 } 582 ]; 583 var oses = [ 584 { 585 name: 'Windows', 586 search: checkContains('win'), 587 versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/] 588 }, 589 { 590 name: 'iOS', 591 search: function (uastring) { 592 return contains(uastring, 'iphone') || contains(uastring, 'ipad'); 593 }, 594 versionRegexes: [ 595 /.*?version\/\ ?([0-9]+)\.([0-9]+).*/, 596 /.*cpu os ([0-9]+)_([0-9]+).*/, 597 /.*cpu iphone os ([0-9]+)_([0-9]+).*/ 598 ] 599 }, 600 { 601 name: 'Android', 602 search: checkContains('android'), 603 versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/] 604 }, 605 { 606 name: 'OSX', 607 search: checkContains('mac os x'), 608 versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/] 609 }, 610 { 611 name: 'Linux', 612 search: checkContains('linux'), 613 versionRegexes: [] 614 }, 615 { 616 name: 'Solaris', 617 search: checkContains('sunos'), 618 versionRegexes: [] 619 }, 620 { 621 name: 'FreeBSD', 622 search: checkContains('freebsd'), 623 versionRegexes: [] 624 }, 625 { 626 name: 'ChromeOS', 627 search: checkContains('cros'), 628 versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/] 629 } 630 ]; 631 var PlatformInfo = { 632 browsers: constant$1(browsers), 633 oses: constant$1(oses) 634 }; 635 636 var edge = 'Edge'; 637 var chrome = 'Chrome'; 638 var ie = 'IE'; 639 var opera = 'Opera'; 640 var firefox = 'Firefox'; 641 var safari = 'Safari'; 642 var unknown$2 = function () { 643 return nu$7({ 644 current: undefined, 645 version: Version.unknown() 646 }); 647 }; 648 var nu$7 = function (info) { 649 var current = info.current; 650 var version = info.version; 651 var isBrowser = function (name) { 652 return function () { 653 return current === name; 654 }; 655 }; 656 return { 657 current: current, 658 version: version, 659 isEdge: isBrowser(edge), 660 isChrome: isBrowser(chrome), 661 isIE: isBrowser(ie), 662 isOpera: isBrowser(opera), 663 isFirefox: isBrowser(firefox), 664 isSafari: isBrowser(safari) 665 }; 666 }; 667 var Browser = { 668 unknown: unknown$2, 669 nu: nu$7, 670 edge: constant$1(edge), 671 chrome: constant$1(chrome), 672 ie: constant$1(ie), 673 opera: constant$1(opera), 674 firefox: constant$1(firefox), 675 safari: constant$1(safari) 676 }; 677 678 var windows = 'Windows'; 679 var ios = 'iOS'; 680 var android = 'Android'; 681 var linux = 'Linux'; 682 var osx = 'OSX'; 683 var solaris = 'Solaris'; 684 var freebsd = 'FreeBSD'; 685 var chromeos = 'ChromeOS'; 686 var unknown$1 = function () { 687 return nu$6({ 688 current: undefined, 689 version: Version.unknown() 690 }); 691 }; 692 var nu$6 = function (info) { 693 var current = info.current; 694 var version = info.version; 695 var isOS = function (name) { 696 return function () { 697 return current === name; 698 }; 699 }; 700 return { 701 current: current, 702 version: version, 703 isWindows: isOS(windows), 704 isiOS: isOS(ios), 705 isAndroid: isOS(android), 706 isOSX: isOS(osx), 707 isLinux: isOS(linux), 708 isSolaris: isOS(solaris), 709 isFreeBSD: isOS(freebsd), 710 isChromeOS: isOS(chromeos) 711 }; 712 }; 713 var OperatingSystem = { 714 unknown: unknown$1, 715 nu: nu$6, 716 windows: constant$1(windows), 717 ios: constant$1(ios), 718 android: constant$1(android), 719 linux: constant$1(linux), 720 osx: constant$1(osx), 721 solaris: constant$1(solaris), 722 freebsd: constant$1(freebsd), 723 chromeos: constant$1(chromeos) 724 }; 725 726 var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) { 727 var browsers = PlatformInfo.browsers(); 728 var oses = PlatformInfo.oses(); 729 var browser = userAgentDataOpt.bind(function (userAgentData) { 730 return detectBrowser$1(browsers, userAgentData); 731 }).orThunk(function () { 732 return detectBrowser(browsers, userAgent); 733 }).fold(Browser.unknown, Browser.nu); 734 var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu); 735 var deviceType = DeviceType(os, browser, userAgent, mediaMatch); 736 return { 737 browser: browser, 738 os: os, 739 deviceType: deviceType 740 }; 741 }; 742 var PlatformDetection = { detect: detect$2 }; 743 744 var mediaMatch = function (query) { 745 return window.matchMedia(query).matches; 746 }; 747 var platform$1 = cached(function () { 748 return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch); 749 }); 750 var detect$1 = function () { 751 return platform$1(); 752 }; 753 754 var constant = constant$1; 755 var touchstart = constant('touchstart'); 756 var touchmove = constant('touchmove'); 757 var touchend = constant('touchend'); 758 var mousedown = constant('mousedown'); 759 var mousemove = constant('mousemove'); 760 var mouseup = constant('mouseup'); 761 var mouseover = constant('mouseover'); 762 var keydown = constant('keydown'); 763 var keyup = constant('keyup'); 764 var input$1 = constant('input'); 765 var change = constant('change'); 766 var click = constant('click'); 767 var transitionend = constant('transitionend'); 768 var selectstart = constant('selectstart'); 769 770 var prefixName = function (name) { 771 return constant$1('alloy.' + name); 772 }; 773 var alloy = { tap: prefixName('tap') }; 774 var focus$4 = prefixName('focus'); 775 var postBlur = prefixName('blur.post'); 776 var postPaste = prefixName('paste.post'); 777 var receive$1 = prefixName('receive'); 778 var execute$5 = prefixName('execute'); 779 var focusItem = prefixName('focus.item'); 780 var tap = alloy.tap; 781 var longpress = prefixName('longpress'); 782 var systemInit = prefixName('system.init'); 783 var attachedToDom = prefixName('system.attached'); 784 var detachedFromDom = prefixName('system.detached'); 785 var focusShifted = prefixName('focusmanager.shifted'); 786 var highlight$1 = prefixName('highlight'); 787 var dehighlight$1 = prefixName('dehighlight'); 788 789 var emit = function (component, event) { 790 dispatchWith(component, component.element, event, {}); 791 }; 792 var emitWith = function (component, event, properties) { 793 dispatchWith(component, component.element, event, properties); 794 }; 795 var emitExecute = function (component) { 796 emit(component, execute$5()); 797 }; 798 var dispatch = function (component, target, event) { 799 dispatchWith(component, target, event, {}); 800 }; 801 var dispatchWith = function (component, target, event, properties) { 802 var data = __assign({ target: target }, properties); 803 component.getSystem().triggerEvent(event, target, data); 804 }; 805 var dispatchEvent = function (component, target, event, simulatedEvent) { 806 component.getSystem().triggerEvent(event, target, simulatedEvent.event); 807 }; 808 var dispatchFocus = function (component, target) { 809 component.getSystem().triggerFocus(target, component.element); 810 }; 811 812 var DOCUMENT = 9; 813 var DOCUMENT_FRAGMENT = 11; 814 var ELEMENT = 1; 815 var TEXT = 3; 816 817 var fromHtml$2 = function (html, scope) { 818 var doc = scope || document; 819 var div = doc.createElement('div'); 820 div.innerHTML = html; 821 if (!div.hasChildNodes() || div.childNodes.length > 1) { 822 console.error('HTML does not have a single root node', html); 823 throw new Error('HTML must have a single root node'); 824 } 825 return fromDom(div.childNodes[0]); 826 }; 827 var fromTag = function (tag, scope) { 828 var doc = scope || document; 829 var node = doc.createElement(tag); 830 return fromDom(node); 831 }; 832 var fromText = function (text, scope) { 833 var doc = scope || document; 834 var node = doc.createTextNode(text); 835 return fromDom(node); 836 }; 837 var fromDom = function (node) { 838 if (node === null || node === undefined) { 839 throw new Error('Node cannot be null or undefined'); 840 } 841 return { dom: node }; 842 }; 843 var fromPoint = function (docElm, x, y) { 844 return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); 845 }; 846 var SugarElement = { 847 fromHtml: fromHtml$2, 848 fromTag: fromTag, 849 fromText: fromText, 850 fromDom: fromDom, 851 fromPoint: fromPoint 852 }; 853 854 var is$1 = function (element, selector) { 855 var dom = element.dom; 856 if (dom.nodeType !== ELEMENT) { 857 return false; 858 } else { 859 var elem = dom; 860 if (elem.matches !== undefined) { 861 return elem.matches(selector); 862 } else if (elem.msMatchesSelector !== undefined) { 863 return elem.msMatchesSelector(selector); 864 } else if (elem.webkitMatchesSelector !== undefined) { 865 return elem.webkitMatchesSelector(selector); 866 } else if (elem.mozMatchesSelector !== undefined) { 867 return elem.mozMatchesSelector(selector); 868 } else { 869 throw new Error('Browser lacks native selectors'); 870 } 871 } 872 }; 873 var bypassSelector = function (dom) { 874 return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0; 875 }; 876 var all$2 = function (selector, scope) { 877 var base = scope === undefined ? document : scope.dom; 878 return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom); 879 }; 880 var one = function (selector, scope) { 881 var base = scope === undefined ? document : scope.dom; 882 return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom); 883 }; 884 885 var eq = function (e1, e2) { 886 return e1.dom === e2.dom; 887 }; 888 889 typeof window !== 'undefined' ? window : Function('return this;')(); 890 891 var name$1 = function (element) { 892 var r = element.dom.nodeName; 893 return r.toLowerCase(); 894 }; 895 var type = function (element) { 896 return element.dom.nodeType; 897 }; 898 var isType = function (t) { 899 return function (element) { 900 return type(element) === t; 901 }; 902 }; 903 var isElement = isType(ELEMENT); 904 var isText = isType(TEXT); 905 var isDocument = isType(DOCUMENT); 906 var isDocumentFragment = isType(DOCUMENT_FRAGMENT); 907 908 var owner$2 = function (element) { 909 return SugarElement.fromDom(element.dom.ownerDocument); 910 }; 911 var documentOrOwner = function (dos) { 912 return isDocument(dos) ? dos : owner$2(dos); 913 }; 914 var defaultView = function (element) { 915 return SugarElement.fromDom(documentOrOwner(element).dom.defaultView); 916 }; 917 var parent = function (element) { 918 return Optional.from(element.dom.parentNode).map(SugarElement.fromDom); 919 }; 920 var parents = function (element, isRoot) { 921 var stop = isFunction(isRoot) ? isRoot : never; 922 var dom = element.dom; 923 var ret = []; 924 while (dom.parentNode !== null && dom.parentNode !== undefined) { 925 var rawParent = dom.parentNode; 926 var p = SugarElement.fromDom(rawParent); 927 ret.push(p); 928 if (stop(p) === true) { 929 break; 930 } else { 931 dom = rawParent; 932 } 933 } 934 return ret; 935 }; 936 var siblings$2 = function (element) { 937 var filterSelf = function (elements) { 938 return filter$2(elements, function (x) { 939 return !eq(element, x); 940 }); 941 }; 942 return parent(element).map(children).map(filterSelf).getOr([]); 943 }; 944 var nextSibling = function (element) { 945 return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom); 946 }; 947 var children = function (element) { 948 return map$2(element.dom.childNodes, SugarElement.fromDom); 949 }; 950 var child = function (element, index) { 951 var cs = element.dom.childNodes; 952 return Optional.from(cs[index]).map(SugarElement.fromDom); 953 }; 954 var firstChild = function (element) { 955 return child(element, 0); 956 }; 957 958 var before$1 = function (marker, element) { 959 var parent$1 = parent(marker); 960 parent$1.each(function (v) { 961 v.dom.insertBefore(element.dom, marker.dom); 962 }); 963 }; 964 var after$2 = function (marker, element) { 965 var sibling = nextSibling(marker); 966 sibling.fold(function () { 967 var parent$1 = parent(marker); 968 parent$1.each(function (v) { 969 append$2(v, element); 970 }); 971 }, function (v) { 972 before$1(v, element); 973 }); 974 }; 975 var prepend$1 = function (parent, element) { 976 var firstChild$1 = firstChild(parent); 977 firstChild$1.fold(function () { 978 append$2(parent, element); 979 }, function (v) { 980 parent.dom.insertBefore(element.dom, v.dom); 981 }); 982 }; 983 var append$2 = function (parent, element) { 984 parent.dom.appendChild(element.dom); 985 }; 986 var appendAt = function (parent, element, index) { 987 child(parent, index).fold(function () { 988 append$2(parent, element); 989 }, function (v) { 990 before$1(v, element); 991 }); 992 }; 993 994 var append$1 = function (parent, elements) { 995 each$1(elements, function (x) { 996 append$2(parent, x); 997 }); 998 }; 999 1000 var empty = function (element) { 1001 element.dom.textContent = ''; 1002 each$1(children(element), function (rogue) { 1003 remove$7(rogue); 1004 }); 1005 }; 1006 var remove$7 = function (element) { 1007 var dom = element.dom; 1008 if (dom.parentNode !== null) { 1009 dom.parentNode.removeChild(dom); 1010 } 1011 }; 1012 1013 var isShadowRoot = function (dos) { 1014 return isDocumentFragment(dos) && isNonNullable(dos.dom.host); 1015 }; 1016 var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode); 1017 var isSupported$1 = constant$1(supported); 1018 var getRootNode = supported ? function (e) { 1019 return SugarElement.fromDom(e.dom.getRootNode()); 1020 } : documentOrOwner; 1021 var getShadowRoot = function (e) { 1022 var r = getRootNode(e); 1023 return isShadowRoot(r) ? Optional.some(r) : Optional.none(); 1024 }; 1025 var getShadowHost = function (e) { 1026 return SugarElement.fromDom(e.dom.host); 1027 }; 1028 var getOriginalEventTarget = function (event) { 1029 if (isSupported$1() && isNonNullable(event.target)) { 1030 var el = SugarElement.fromDom(event.target); 1031 if (isElement(el) && isOpenShadowHost(el)) { 1032 if (event.composed && event.composedPath) { 1033 var composedPath = event.composedPath(); 1034 if (composedPath) { 1035 return head(composedPath); 1036 } 1037 } 1038 } 1039 } 1040 return Optional.from(event.target); 1041 }; 1042 var isOpenShadowHost = function (element) { 1043 return isNonNullable(element.dom.shadowRoot); 1044 }; 1045 1046 var inBody = function (element) { 1047 var dom = isText(element) ? element.dom.parentNode : element.dom; 1048 if (dom === undefined || dom === null || dom.ownerDocument === null) { 1049 return false; 1050 } 1051 var doc = dom.ownerDocument; 1052 return getShadowRoot(SugarElement.fromDom(dom)).fold(function () { 1053 return doc.body.contains(dom); 1054 }, compose1(inBody, getShadowHost)); 1055 }; 1056 var body = function () { 1057 return getBody(SugarElement.fromDom(document)); 1058 }; 1059 var getBody = function (doc) { 1060 var b = doc.dom.body; 1061 if (b === null || b === undefined) { 1062 throw new Error('Body is not available yet'); 1063 } 1064 return SugarElement.fromDom(b); 1065 }; 1066 1067 var fireDetaching = function (component) { 1068 emit(component, detachedFromDom()); 1069 var children = component.components(); 1070 each$1(children, fireDetaching); 1071 }; 1072 var fireAttaching = function (component) { 1073 var children = component.components(); 1074 each$1(children, fireAttaching); 1075 emit(component, attachedToDom()); 1076 }; 1077 var attach$1 = function (parent, child) { 1078 append$2(parent.element, child.element); 1079 }; 1080 var detachChildren = function (component) { 1081 each$1(component.components(), function (childComp) { 1082 return remove$7(childComp.element); 1083 }); 1084 empty(component.element); 1085 component.syncComponents(); 1086 }; 1087 var replaceChildren = function (component, newChildren) { 1088 var subs = component.components(); 1089 detachChildren(component); 1090 var deleted = difference(subs, newChildren); 1091 each$1(deleted, function (comp) { 1092 fireDetaching(comp); 1093 component.getSystem().removeFromWorld(comp); 1094 }); 1095 each$1(newChildren, function (childComp) { 1096 if (!childComp.getSystem().isConnected()) { 1097 component.getSystem().addToWorld(childComp); 1098 attach$1(component, childComp); 1099 if (inBody(component.element)) { 1100 fireAttaching(childComp); 1101 } 1102 } else { 1103 attach$1(component, childComp); 1104 } 1105 component.syncComponents(); 1106 }); 1107 }; 1108 1109 var attach = function (parent, child) { 1110 attachWith(parent, child, append$2); 1111 }; 1112 var attachWith = function (parent, child, insertion) { 1113 parent.getSystem().addToWorld(child); 1114 insertion(parent.element, child.element); 1115 if (inBody(parent.element)) { 1116 fireAttaching(child); 1117 } 1118 parent.syncComponents(); 1119 }; 1120 var doDetach = function (component) { 1121 fireDetaching(component); 1122 remove$7(component.element); 1123 component.getSystem().removeFromWorld(component); 1124 }; 1125 var detach = function (component) { 1126 var parent$1 = parent(component.element).bind(function (p) { 1127 return component.getSystem().getByDom(p).toOptional(); 1128 }); 1129 doDetach(component); 1130 parent$1.each(function (p) { 1131 p.syncComponents(); 1132 }); 1133 }; 1134 var attachSystemAfter = function (element, guiSystem) { 1135 attachSystemWith(element, guiSystem, after$2); 1136 }; 1137 var attachSystemWith = function (element, guiSystem, inserter) { 1138 inserter(element, guiSystem.element); 1139 var children$1 = children(guiSystem.element); 1140 each$1(children$1, function (child) { 1141 guiSystem.getByDom(child).each(fireAttaching); 1142 }); 1143 }; 1144 var detachSystem = function (guiSystem) { 1145 var children$1 = children(guiSystem.element); 1146 each$1(children$1, function (child) { 1147 guiSystem.getByDom(child).each(fireDetaching); 1148 }); 1149 remove$7(guiSystem.element); 1150 }; 1151 1152 var keys = Object.keys; 1153 var hasOwnProperty = Object.hasOwnProperty; 1154 var each = function (obj, f) { 1155 var props = keys(obj); 1156 for (var k = 0, len = props.length; k < len; k++) { 1157 var i = props[k]; 1158 var x = obj[i]; 1159 f(x, i); 1160 } 1161 }; 1162 var map$1 = function (obj, f) { 1163 return tupleMap(obj, function (x, i) { 1164 return { 1165 k: i, 1166 v: f(x, i) 1167 }; 1168 }); 1169 }; 1170 var tupleMap = function (obj, f) { 1171 var r = {}; 1172 each(obj, function (x, i) { 1173 var tuple = f(x, i); 1174 r[tuple.k] = tuple.v; 1175 }); 1176 return r; 1177 }; 1178 var objAcc = function (r) { 1179 return function (x, i) { 1180 r[i] = x; 1181 }; 1182 }; 1183 var internalFilter = function (obj, pred, onTrue, onFalse) { 1184 var r = {}; 1185 each(obj, function (x, i) { 1186 (pred(x, i) ? onTrue : onFalse)(x, i); 1187 }); 1188 return r; 1189 }; 1190 var filter$1 = function (obj, pred) { 1191 var t = {}; 1192 internalFilter(obj, pred, objAcc(t), noop); 1193 return t; 1194 }; 1195 var mapToArray = function (obj, f) { 1196 var r = []; 1197 each(obj, function (value, name) { 1198 r.push(f(value, name)); 1199 }); 1200 return r; 1201 }; 1202 var find = function (obj, pred) { 1203 var props = keys(obj); 1204 for (var k = 0, len = props.length; k < len; k++) { 1205 var i = props[k]; 1206 var x = obj[i]; 1207 if (pred(x, i, obj)) { 1208 return Optional.some(x); 1209 } 1210 } 1211 return Optional.none(); 1212 }; 1213 var values = function (obj) { 1214 return mapToArray(obj, identity); 1215 }; 1216 var get$c = function (obj, key) { 1217 return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none(); 1218 }; 1219 var has$2 = function (obj, key) { 1220 return hasOwnProperty.call(obj, key); 1221 }; 1222 var hasNonNullableKey = function (obj, key) { 1223 return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null; 1224 }; 1225 1226 var rawSet = function (dom, key, value) { 1227 if (isString(value) || isBoolean(value) || isNumber(value)) { 1228 dom.setAttribute(key, value + ''); 1229 } else { 1230 console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom); 1231 throw new Error('Attribute value was not simple'); 1232 } 1233 }; 1234 var set$8 = function (element, key, value) { 1235 rawSet(element.dom, key, value); 1236 }; 1237 var setAll$1 = function (element, attrs) { 1238 var dom = element.dom; 1239 each(attrs, function (v, k) { 1240 rawSet(dom, k, v); 1241 }); 1242 }; 1243 var get$b = function (element, key) { 1244 var v = element.dom.getAttribute(key); 1245 return v === null ? undefined : v; 1246 }; 1247 var getOpt = function (element, key) { 1248 return Optional.from(get$b(element, key)); 1249 }; 1250 var has$1 = function (element, key) { 1251 var dom = element.dom; 1252 return dom && dom.hasAttribute ? dom.hasAttribute(key) : false; 1253 }; 1254 var remove$6 = function (element, key) { 1255 element.dom.removeAttribute(key); 1256 }; 1257 1258 var read$2 = function (element, attr) { 1259 var value = get$b(element, attr); 1260 return value === undefined || value === '' ? [] : value.split(' '); 1261 }; 1262 var add$3 = function (element, attr, id) { 1263 var old = read$2(element, attr); 1264 var nu = old.concat([id]); 1265 set$8(element, attr, nu.join(' ')); 1266 return true; 1267 }; 1268 var remove$5 = function (element, attr, id) { 1269 var nu = filter$2(read$2(element, attr), function (v) { 1270 return v !== id; 1271 }); 1272 if (nu.length > 0) { 1273 set$8(element, attr, nu.join(' ')); 1274 } else { 1275 remove$6(element, attr); 1276 } 1277 return false; 1278 }; 1279 1280 var supports = function (element) { 1281 return element.dom.classList !== undefined; 1282 }; 1283 var get$a = function (element) { 1284 return read$2(element, 'class'); 1285 }; 1286 var add$2 = function (element, clazz) { 1287 return add$3(element, 'class', clazz); 1288 }; 1289 var remove$4 = function (element, clazz) { 1290 return remove$5(element, 'class', clazz); 1291 }; 1292 1293 var add$1 = function (element, clazz) { 1294 if (supports(element)) { 1295 element.dom.classList.add(clazz); 1296 } else { 1297 add$2(element, clazz); 1298 } 1299 }; 1300 var cleanClass = function (element) { 1301 var classList = supports(element) ? element.dom.classList : get$a(element); 1302 if (classList.length === 0) { 1303 remove$6(element, 'class'); 1304 } 1305 }; 1306 var remove$3 = function (element, clazz) { 1307 if (supports(element)) { 1308 var classList = element.dom.classList; 1309 classList.remove(clazz); 1310 } else { 1311 remove$4(element, clazz); 1312 } 1313 cleanClass(element); 1314 }; 1315 var has = function (element, clazz) { 1316 return supports(element) && element.dom.classList.contains(clazz); 1317 }; 1318 1319 var swap = function (element, addCls, removeCls) { 1320 remove$3(element, removeCls); 1321 add$1(element, addCls); 1322 }; 1323 var toAlpha = function (component, swapConfig, _swapState) { 1324 swap(component.element, swapConfig.alpha, swapConfig.omega); 1325 }; 1326 var toOmega = function (component, swapConfig, _swapState) { 1327 swap(component.element, swapConfig.omega, swapConfig.alpha); 1328 }; 1329 var clear$1 = function (component, swapConfig, _swapState) { 1330 remove$3(component.element, swapConfig.alpha); 1331 remove$3(component.element, swapConfig.omega); 1332 }; 1333 var isAlpha = function (component, swapConfig, _swapState) { 1334 return has(component.element, swapConfig.alpha); 1335 }; 1336 var isOmega = function (component, swapConfig, _swapState) { 1337 return has(component.element, swapConfig.omega); 1338 }; 1339 1340 var SwapApis = /*#__PURE__*/Object.freeze({ 1341 __proto__: null, 1342 toAlpha: toAlpha, 1343 toOmega: toOmega, 1344 isAlpha: isAlpha, 1345 isOmega: isOmega, 1346 clear: clear$1 1347 }); 1348 1349 var value$2 = function (o) { 1350 var or = function (_opt) { 1351 return value$2(o); 1352 }; 1353 var orThunk = function (_f) { 1354 return value$2(o); 1355 }; 1356 var map = function (f) { 1357 return value$2(f(o)); 1358 }; 1359 var mapError = function (_f) { 1360 return value$2(o); 1361 }; 1362 var each = function (f) { 1363 f(o); 1364 }; 1365 var bind = function (f) { 1366 return f(o); 1367 }; 1368 var fold = function (_, onValue) { 1369 return onValue(o); 1370 }; 1371 var exists = function (f) { 1372 return f(o); 1373 }; 1374 var forall = function (f) { 1375 return f(o); 1376 }; 1377 var toOptional = function () { 1378 return Optional.some(o); 1379 }; 1380 return { 1381 isValue: always, 1382 isError: never, 1383 getOr: constant$1(o), 1384 getOrThunk: constant$1(o), 1385 getOrDie: constant$1(o), 1386 or: or, 1387 orThunk: orThunk, 1388 fold: fold, 1389 map: map, 1390 mapError: mapError, 1391 each: each, 1392 bind: bind, 1393 exists: exists, 1394 forall: forall, 1395 toOptional: toOptional 1396 }; 1397 }; 1398 var error = function (message) { 1399 var getOrThunk = function (f) { 1400 return f(); 1401 }; 1402 var getOrDie = function () { 1403 return die(String(message))(); 1404 }; 1405 var or = identity; 1406 var orThunk = function (f) { 1407 return f(); 1408 }; 1409 var map = function (_f) { 1410 return error(message); 1411 }; 1412 var mapError = function (f) { 1413 return error(f(message)); 1414 }; 1415 var bind = function (_f) { 1416 return error(message); 1417 }; 1418 var fold = function (onError, _) { 1419 return onError(message); 1420 }; 1421 return { 1422 isValue: never, 1423 isError: always, 1424 getOr: identity, 1425 getOrThunk: getOrThunk, 1426 getOrDie: getOrDie, 1427 or: or, 1428 orThunk: orThunk, 1429 fold: fold, 1430 map: map, 1431 mapError: mapError, 1432 each: noop, 1433 bind: bind, 1434 exists: never, 1435 forall: always, 1436 toOptional: Optional.none 1437 }; 1438 }; 1439 var fromOption = function (opt, err) { 1440 return opt.fold(function () { 1441 return error(err); 1442 }, value$2); 1443 }; 1444 var Result = { 1445 value: value$2, 1446 error: error, 1447 fromOption: fromOption 1448 }; 1449 1450 var SimpleResultType; 1451 (function (SimpleResultType) { 1452 SimpleResultType[SimpleResultType['Error'] = 0] = 'Error'; 1453 SimpleResultType[SimpleResultType['Value'] = 1] = 'Value'; 1454 }(SimpleResultType || (SimpleResultType = {}))); 1455 var fold$1 = function (res, onError, onValue) { 1456 return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue); 1457 }; 1458 var partition$1 = function (results) { 1459 var values = []; 1460 var errors = []; 1461 each$1(results, function (obj) { 1462 fold$1(obj, function (err) { 1463 return errors.push(err); 1464 }, function (val) { 1465 return values.push(val); 1466 }); 1467 }); 1468 return { 1469 values: values, 1470 errors: errors 1471 }; 1472 }; 1473 var mapError = function (res, f) { 1474 if (res.stype === SimpleResultType.Error) { 1475 return { 1476 stype: SimpleResultType.Error, 1477 serror: f(res.serror) 1478 }; 1479 } else { 1480 return res; 1481 } 1482 }; 1483 var map = function (res, f) { 1484 if (res.stype === SimpleResultType.Value) { 1485 return { 1486 stype: SimpleResultType.Value, 1487 svalue: f(res.svalue) 1488 }; 1489 } else { 1490 return res; 1491 } 1492 }; 1493 var bind$2 = function (res, f) { 1494 if (res.stype === SimpleResultType.Value) { 1495 return f(res.svalue); 1496 } else { 1497 return res; 1498 } 1499 }; 1500 var bindError = function (res, f) { 1501 if (res.stype === SimpleResultType.Error) { 1502 return f(res.serror); 1503 } else { 1504 return res; 1505 } 1506 }; 1507 var svalue = function (v) { 1508 return { 1509 stype: SimpleResultType.Value, 1510 svalue: v 1511 }; 1512 }; 1513 var serror = function (e) { 1514 return { 1515 stype: SimpleResultType.Error, 1516 serror: e 1517 }; 1518 }; 1519 var toResult$1 = function (res) { 1520 return fold$1(res, Result.error, Result.value); 1521 }; 1522 var fromResult = function (res) { 1523 return res.fold(serror, svalue); 1524 }; 1525 var SimpleResult = { 1526 fromResult: fromResult, 1527 toResult: toResult$1, 1528 svalue: svalue, 1529 partition: partition$1, 1530 serror: serror, 1531 bind: bind$2, 1532 bindError: bindError, 1533 map: map, 1534 mapError: mapError, 1535 fold: fold$1 1536 }; 1537 1538 var field$3 = function (key, newKey, presence, prop) { 1539 return { 1540 tag: 'field', 1541 key: key, 1542 newKey: newKey, 1543 presence: presence, 1544 prop: prop 1545 }; 1546 }; 1547 var customField$1 = function (newKey, instantiator) { 1548 return { 1549 tag: 'custom', 1550 newKey: newKey, 1551 instantiator: instantiator 1552 }; 1553 }; 1554 var fold = function (value, ifField, ifCustom) { 1555 switch (value.tag) { 1556 case 'field': 1557 return ifField(value.key, value.newKey, value.presence, value.prop); 1558 case 'custom': 1559 return ifCustom(value.newKey, value.instantiator); 1560 } 1561 }; 1562 1563 var shallow$1 = function (old, nu) { 1564 return nu; 1565 }; 1566 var deep = function (old, nu) { 1567 var bothObjects = isObject(old) && isObject(nu); 1568 return bothObjects ? deepMerge(old, nu) : nu; 1569 }; 1570 var baseMerge = function (merger) { 1571 return function () { 1572 var objects = []; 1573 for (var _i = 0; _i < arguments.length; _i++) { 1574 objects[_i] = arguments[_i]; 1575 } 1576 if (objects.length === 0) { 1577 throw new Error('Can\'t merge zero objects'); 1578 } 1579 var ret = {}; 1580 for (var j = 0; j < objects.length; j++) { 1581 var curObject = objects[j]; 1582 for (var key in curObject) { 1583 if (has$2(curObject, key)) { 1584 ret[key] = merger(ret[key], curObject[key]); 1585 } 1586 } 1587 } 1588 return ret; 1589 }; 1590 }; 1591 var deepMerge = baseMerge(deep); 1592 var merge$1 = baseMerge(shallow$1); 1593 1594 var required$2 = function () { 1595 return { 1596 tag: 'required', 1597 process: {} 1598 }; 1599 }; 1600 var defaultedThunk = function (fallbackThunk) { 1601 return { 1602 tag: 'defaultedThunk', 1603 process: fallbackThunk 1604 }; 1605 }; 1606 var defaulted$1 = function (fallback) { 1607 return defaultedThunk(constant$1(fallback)); 1608 }; 1609 var asOption = function () { 1610 return { 1611 tag: 'option', 1612 process: {} 1613 }; 1614 }; 1615 var mergeWithThunk = function (baseThunk) { 1616 return { 1617 tag: 'mergeWithThunk', 1618 process: baseThunk 1619 }; 1620 }; 1621 var mergeWith = function (base) { 1622 return mergeWithThunk(constant$1(base)); 1623 }; 1624 1625 var mergeValues$1 = function (values, base) { 1626 return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base); 1627 }; 1628 var mergeErrors$1 = function (errors) { 1629 return compose(SimpleResult.serror, flatten)(errors); 1630 }; 1631 var consolidateObj = function (objects, base) { 1632 var partition = SimpleResult.partition(objects); 1633 return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base); 1634 }; 1635 var consolidateArr = function (objects) { 1636 var partitions = SimpleResult.partition(objects); 1637 return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values); 1638 }; 1639 var ResultCombine = { 1640 consolidateObj: consolidateObj, 1641 consolidateArr: consolidateArr 1642 }; 1643 1644 var formatObj = function (input) { 1645 return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2); 1646 }; 1647 var formatErrors = function (errors) { 1648 var es = errors.length > 10 ? errors.slice(0, 10).concat([{ 1649 path: [], 1650 getErrorInfo: constant$1('... (only showing first ten failures)') 1651 }]) : errors; 1652 return map$2(es, function (e) { 1653 return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo(); 1654 }); 1655 }; 1656 1657 var nu$5 = function (path, getErrorInfo) { 1658 return SimpleResult.serror([{ 1659 path: path, 1660 getErrorInfo: getErrorInfo 1661 }]); 1662 }; 1663 var missingRequired = function (path, key, obj) { 1664 return nu$5(path, function () { 1665 return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj); 1666 }); 1667 }; 1668 var missingKey = function (path, key) { 1669 return nu$5(path, function () { 1670 return 'Choice schema did not contain choice key: "' + key + '"'; 1671 }); 1672 }; 1673 var missingBranch = function (path, branches, branch) { 1674 return nu$5(path, function () { 1675 return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches); 1676 }); 1677 }; 1678 var unsupportedFields = function (path, unsupported) { 1679 return nu$5(path, function () { 1680 return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified'; 1681 }); 1682 }; 1683 var custom = function (path, err) { 1684 return nu$5(path, constant$1(err)); 1685 }; 1686 1687 var value$1 = function (validator) { 1688 var extract = function (path, val) { 1689 return SimpleResult.bindError(validator(val), function (err) { 1690 return custom(path, err); 1691 }); 1692 }; 1693 var toString = constant$1('val'); 1694 return { 1695 extract: extract, 1696 toString: toString 1697 }; 1698 }; 1699 var anyValue$1 = value$1(SimpleResult.svalue); 1700 1701 var requiredAccess = function (path, obj, key, bundle) { 1702 return get$c(obj, key).fold(function () { 1703 return missingRequired(path, key, obj); 1704 }, bundle); 1705 }; 1706 var fallbackAccess = function (obj, key, fallback, bundle) { 1707 var v = get$c(obj, key).getOrThunk(function () { 1708 return fallback(obj); 1709 }); 1710 return bundle(v); 1711 }; 1712 var optionAccess = function (obj, key, bundle) { 1713 return bundle(get$c(obj, key)); 1714 }; 1715 var optionDefaultedAccess = function (obj, key, fallback, bundle) { 1716 var opt = get$c(obj, key).map(function (val) { 1717 return val === true ? fallback(obj) : val; 1718 }); 1719 return bundle(opt); 1720 }; 1721 var extractField = function (field, path, obj, key, prop) { 1722 var bundle = function (av) { 1723 return prop.extract(path.concat([key]), av); 1724 }; 1725 var bundleAsOption = function (optValue) { 1726 return optValue.fold(function () { 1727 return SimpleResult.svalue(Optional.none()); 1728 }, function (ov) { 1729 var result = prop.extract(path.concat([key]), ov); 1730 return SimpleResult.map(result, Optional.some); 1731 }); 1732 }; 1733 switch (field.tag) { 1734 case 'required': 1735 return requiredAccess(path, obj, key, bundle); 1736 case 'defaultedThunk': 1737 return fallbackAccess(obj, key, field.process, bundle); 1738 case 'option': 1739 return optionAccess(obj, key, bundleAsOption); 1740 case 'defaultedOptionThunk': 1741 return optionDefaultedAccess(obj, key, field.process, bundleAsOption); 1742 case 'mergeWithThunk': { 1743 return fallbackAccess(obj, key, constant$1({}), function (v) { 1744 var result = deepMerge(field.process(obj), v); 1745 return bundle(result); 1746 }); 1747 } 1748 } 1749 }; 1750 var extractFields = function (path, obj, fields) { 1751 var success = {}; 1752 var errors = []; 1753 for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) { 1754 var field = fields_1[_i]; 1755 fold(field, function (key, newKey, presence, prop) { 1756 var result = extractField(presence, path, obj, key, prop); 1757 SimpleResult.fold(result, function (err) { 1758 errors.push.apply(errors, err); 1759 }, function (res) { 1760 success[newKey] = res; 1761 }); 1762 }, function (newKey, instantiator) { 1763 success[newKey] = instantiator(obj); 1764 }); 1765 } 1766 return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success); 1767 }; 1768 var getSetKeys = function (obj) { 1769 return keys(filter$1(obj, isNonNullable)); 1770 }; 1771 var objOfOnly = function (fields) { 1772 var delegate = objOf(fields); 1773 var fieldNames = foldr(fields, function (acc, value) { 1774 return fold(value, function (key) { 1775 var _a; 1776 return deepMerge(acc, (_a = {}, _a[key] = true, _a)); 1777 }, constant$1(acc)); 1778 }, {}); 1779 var extract = function (path, o) { 1780 var keys = isBoolean(o) ? [] : getSetKeys(o); 1781 var extra = filter$2(keys, function (k) { 1782 return !hasNonNullableKey(fieldNames, k); 1783 }); 1784 return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra); 1785 }; 1786 return { 1787 extract: extract, 1788 toString: delegate.toString 1789 }; 1790 }; 1791 var objOf = function (values) { 1792 var extract = function (path, o) { 1793 return extractFields(path, o, values); 1794 }; 1795 var toString = function () { 1796 var fieldStrings = map$2(values, function (value) { 1797 return fold(value, function (key, _okey, _presence, prop) { 1798 return key + ' -> ' + prop.toString(); 1799 }, function (newKey, _instantiator) { 1800 return 'state(' + newKey + ')'; 1801 }); 1802 }); 1803 return 'obj{\n' + fieldStrings.join('\n') + '}'; 1804 }; 1805 return { 1806 extract: extract, 1807 toString: toString 1808 }; 1809 }; 1810 var arrOf = function (prop) { 1811 var extract = function (path, array) { 1812 var results = map$2(array, function (a, i) { 1813 return prop.extract(path.concat(['[' + i + ']']), a); 1814 }); 1815 return ResultCombine.consolidateArr(results); 1816 }; 1817 var toString = function () { 1818 return 'array(' + prop.toString() + ')'; 1819 }; 1820 return { 1821 extract: extract, 1822 toString: toString 1823 }; 1824 }; 1825 var setOf$1 = function (validator, prop) { 1826 var validateKeys = function (path, keys) { 1827 return arrOf(value$1(validator)).extract(path, keys); 1828 }; 1829 var extract = function (path, o) { 1830 var keys$1 = keys(o); 1831 var validatedKeys = validateKeys(path, keys$1); 1832 return SimpleResult.bind(validatedKeys, function (validKeys) { 1833 var schema = map$2(validKeys, function (vk) { 1834 return field$3(vk, vk, required$2(), prop); 1835 }); 1836 return objOf(schema).extract(path, o); 1837 }); 1838 }; 1839 var toString = function () { 1840 return 'setOf(' + prop.toString() + ')'; 1841 }; 1842 return { 1843 extract: extract, 1844 toString: toString 1845 }; 1846 }; 1847 1848 var anyValue = constant$1(anyValue$1); 1849 var typedValue = function (validator, expectedType) { 1850 return value$1(function (a) { 1851 var actualType = typeof a; 1852 return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType); 1853 }); 1854 }; 1855 var functionProcessor = typedValue(isFunction, 'function'); 1856 1857 var chooseFrom = function (path, input, branches, ch) { 1858 var fields = get$c(branches, ch); 1859 return fields.fold(function () { 1860 return missingBranch(path, branches, ch); 1861 }, function (vp) { 1862 return vp.extract(path.concat(['branch: ' + ch]), input); 1863 }); 1864 }; 1865 var choose$2 = function (key, branches) { 1866 var extract = function (path, input) { 1867 var choice = get$c(input, key); 1868 return choice.fold(function () { 1869 return missingKey(path, key); 1870 }, function (chosen) { 1871 return chooseFrom(path, input, branches, chosen); 1872 }); 1873 }; 1874 var toString = function () { 1875 return 'chooseOn(' + key + '). Possible values: ' + keys(branches); 1876 }; 1877 return { 1878 extract: extract, 1879 toString: toString 1880 }; 1881 }; 1882 1883 var valueOf = function (validator) { 1884 return value$1(function (v) { 1885 return validator(v).fold(SimpleResult.serror, SimpleResult.svalue); 1886 }); 1887 }; 1888 var setOf = function (validator, prop) { 1889 return setOf$1(function (v) { 1890 return SimpleResult.fromResult(validator(v)); 1891 }, prop); 1892 }; 1893 var extractValue = function (label, prop, obj) { 1894 var res = prop.extract([label], obj); 1895 return SimpleResult.mapError(res, function (errs) { 1896 return { 1897 input: obj, 1898 errors: errs 1899 }; 1900 }); 1901 }; 1902 var asRaw = function (label, prop, obj) { 1903 return SimpleResult.toResult(extractValue(label, prop, obj)); 1904 }; 1905 var getOrDie = function (extraction) { 1906 return extraction.fold(function (errInfo) { 1907 throw new Error(formatError(errInfo)); 1908 }, identity); 1909 }; 1910 var asRawOrDie$1 = function (label, prop, obj) { 1911 return getOrDie(asRaw(label, prop, obj)); 1912 }; 1913 var formatError = function (errInfo) { 1914 return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input); 1915 }; 1916 var choose$1 = function (key, branches) { 1917 return choose$2(key, map$1(branches, objOf)); 1918 }; 1919 1920 var field$2 = field$3; 1921 var customField = customField$1; 1922 var required$1 = function (key) { 1923 return field$2(key, key, required$2(), anyValue()); 1924 }; 1925 var requiredOf = function (key, schema) { 1926 return field$2(key, key, required$2(), schema); 1927 }; 1928 var forbid = function (key, message) { 1929 return field$2(key, key, asOption(), value$1(function (_v) { 1930 return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message); 1931 })); 1932 }; 1933 var requiredObjOf = function (key, objSchema) { 1934 return field$2(key, key, required$2(), objOf(objSchema)); 1935 }; 1936 var option = function (key) { 1937 return field$2(key, key, asOption(), anyValue()); 1938 }; 1939 var optionOf = function (key, schema) { 1940 return field$2(key, key, asOption(), schema); 1941 }; 1942 var optionObjOf = function (key, objSchema) { 1943 return optionOf(key, objOf(objSchema)); 1944 }; 1945 var optionObjOfOnly = function (key, objSchema) { 1946 return optionOf(key, objOfOnly(objSchema)); 1947 }; 1948 var defaulted = function (key, fallback) { 1949 return field$2(key, key, defaulted$1(fallback), anyValue()); 1950 }; 1951 var defaultedOf = function (key, fallback, schema) { 1952 return field$2(key, key, defaulted$1(fallback), schema); 1953 }; 1954 var defaultedFunction = function (key, fallback) { 1955 return defaultedOf(key, fallback, functionProcessor); 1956 }; 1957 var defaultedObjOf = function (key, fallback, objSchema) { 1958 return defaultedOf(key, fallback, objOf(objSchema)); 1959 }; 1960 1961 var SwapSchema = [ 1962 required$1('alpha'), 1963 required$1('omega') 1964 ]; 1965 1966 var generate$5 = function (cases) { 1967 if (!isArray(cases)) { 1968 throw new Error('cases must be an array'); 1969 } 1970 if (cases.length === 0) { 1971 throw new Error('there must be at least one case'); 1972 } 1973 var constructors = []; 1974 var adt = {}; 1975 each$1(cases, function (acase, count) { 1976 var keys$1 = keys(acase); 1977 if (keys$1.length !== 1) { 1978 throw new Error('one and only one name per case'); 1979 } 1980 var key = keys$1[0]; 1981 var value = acase[key]; 1982 if (adt[key] !== undefined) { 1983 throw new Error('duplicate key detected:' + key); 1984 } else if (key === 'cata') { 1985 throw new Error('cannot have a case named cata (sorry)'); 1986 } else if (!isArray(value)) { 1987 throw new Error('case arguments must be an array'); 1988 } 1989 constructors.push(key); 1990 adt[key] = function () { 1991 var args = []; 1992 for (var _i = 0; _i < arguments.length; _i++) { 1993 args[_i] = arguments[_i]; 1994 } 1995 var argLength = args.length; 1996 if (argLength !== value.length) { 1997 throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength); 1998 } 1999 var match = function (branches) { 2000 var branchKeys = keys(branches); 2001 if (constructors.length !== branchKeys.length) { 2002 throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(',')); 2003 } 2004 var allReqd = forall(constructors, function (reqKey) { 2005 return contains$1(branchKeys, reqKey); 2006 }); 2007 if (!allReqd) { 2008 throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', ')); 2009 } 2010 return branches[key].apply(null, args); 2011 }; 2012 return { 2013 fold: function () { 2014 var foldArgs = []; 2015 for (var _i = 0; _i < arguments.length; _i++) { 2016 foldArgs[_i] = arguments[_i]; 2017 } 2018 if (foldArgs.length !== cases.length) { 2019 throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length); 2020 } 2021 var target = foldArgs[count]; 2022 return target.apply(null, args); 2023 }, 2024 match: match, 2025 log: function (label) { 2026 console.log(label, { 2027 constructors: constructors, 2028 constructor: key, 2029 params: args 2030 }); 2031 } 2032 }; 2033 }; 2034 }); 2035 return adt; 2036 }; 2037 var Adt = { generate: generate$5 }; 2038 2039 Adt.generate([ 2040 { 2041 bothErrors: [ 2042 'error1', 2043 'error2' 2044 ] 2045 }, 2046 { 2047 firstError: [ 2048 'error1', 2049 'value2' 2050 ] 2051 }, 2052 { 2053 secondError: [ 2054 'value1', 2055 'error2' 2056 ] 2057 }, 2058 { 2059 bothValues: [ 2060 'value1', 2061 'value2' 2062 ] 2063 } 2064 ]); 2065 var partition = function (results) { 2066 var errors = []; 2067 var values = []; 2068 each$1(results, function (result) { 2069 result.fold(function (err) { 2070 errors.push(err); 2071 }, function (value) { 2072 values.push(value); 2073 }); 2074 }); 2075 return { 2076 errors: errors, 2077 values: values 2078 }; 2079 }; 2080 2081 var exclude$1 = function (obj, fields) { 2082 var r = {}; 2083 each(obj, function (v, k) { 2084 if (!contains$1(fields, k)) { 2085 r[k] = v; 2086 } 2087 }); 2088 return r; 2089 }; 2090 2091 var wrap$1 = function (key, value) { 2092 var _a; 2093 return _a = {}, _a[key] = value, _a; 2094 }; 2095 var wrapAll$1 = function (keyvalues) { 2096 var r = {}; 2097 each$1(keyvalues, function (kv) { 2098 r[kv.key] = kv.value; 2099 }); 2100 return r; 2101 }; 2102 2103 var exclude = function (obj, fields) { 2104 return exclude$1(obj, fields); 2105 }; 2106 var wrap = function (key, value) { 2107 return wrap$1(key, value); 2108 }; 2109 var wrapAll = function (keyvalues) { 2110 return wrapAll$1(keyvalues); 2111 }; 2112 var mergeValues = function (values, base) { 2113 return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values))); 2114 }; 2115 var mergeErrors = function (errors) { 2116 return Result.error(flatten(errors)); 2117 }; 2118 var consolidate = function (objs, base) { 2119 var partitions = partition(objs); 2120 return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base); 2121 }; 2122 2123 var is = function (lhs, rhs, comparator) { 2124 if (comparator === void 0) { 2125 comparator = tripleEquals; 2126 } 2127 return lhs.exists(function (left) { 2128 return comparator(left, rhs); 2129 }); 2130 }; 2131 var cat = function (arr) { 2132 var r = []; 2133 var push = function (x) { 2134 r.push(x); 2135 }; 2136 for (var i = 0; i < arr.length; i++) { 2137 arr[i].each(push); 2138 } 2139 return r; 2140 }; 2141 var sequence = function (arr) { 2142 var r = []; 2143 for (var i = 0; i < arr.length; i++) { 2144 var x = arr[i]; 2145 if (x.isSome()) { 2146 r.push(x.getOrDie()); 2147 } else { 2148 return Optional.none(); 2149 } 2150 } 2151 return Optional.some(r); 2152 }; 2153 var lift2 = function (oa, ob, f) { 2154 return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none(); 2155 }; 2156 var someIf = function (b, a) { 2157 return b ? Optional.some(a) : Optional.none(); 2158 }; 2159 2160 var ensureIsRoot = function (isRoot) { 2161 return isFunction(isRoot) ? isRoot : never; 2162 }; 2163 var ancestor$2 = function (scope, transform, isRoot) { 2164 var element = scope.dom; 2165 var stop = ensureIsRoot(isRoot); 2166 while (element.parentNode) { 2167 element = element.parentNode; 2168 var el = SugarElement.fromDom(element); 2169 var transformed = transform(el); 2170 if (transformed.isSome()) { 2171 return transformed; 2172 } else if (stop(el)) { 2173 break; 2174 } 2175 } 2176 return Optional.none(); 2177 }; 2178 var closest$3 = function (scope, transform, isRoot) { 2179 var current = transform(scope); 2180 var stop = ensureIsRoot(isRoot); 2181 return current.orThunk(function () { 2182 return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop); 2183 }); 2184 }; 2185 2186 var isSource = function (component, simulatedEvent) { 2187 return eq(component.element, simulatedEvent.event.target); 2188 }; 2189 2190 var defaultEventHandler = { 2191 can: always, 2192 abort: never, 2193 run: noop 2194 }; 2195 var nu$4 = function (parts) { 2196 if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) { 2197 throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!'); 2198 } 2199 return __assign(__assign({}, defaultEventHandler), parts); 2200 }; 2201 var all$1 = function (handlers, f) { 2202 return function () { 2203 var args = []; 2204 for (var _i = 0; _i < arguments.length; _i++) { 2205 args[_i] = arguments[_i]; 2206 } 2207 return foldl(handlers, function (acc, handler) { 2208 return acc && f(handler).apply(undefined, args); 2209 }, true); 2210 }; 2211 }; 2212 var any = function (handlers, f) { 2213 return function () { 2214 var args = []; 2215 for (var _i = 0; _i < arguments.length; _i++) { 2216 args[_i] = arguments[_i]; 2217 } 2218 return foldl(handlers, function (acc, handler) { 2219 return acc || f(handler).apply(undefined, args); 2220 }, false); 2221 }; 2222 }; 2223 var read$1 = function (handler) { 2224 return isFunction(handler) ? { 2225 can: always, 2226 abort: never, 2227 run: handler 2228 } : handler; 2229 }; 2230 var fuse$1 = function (handlers) { 2231 var can = all$1(handlers, function (handler) { 2232 return handler.can; 2233 }); 2234 var abort = any(handlers, function (handler) { 2235 return handler.abort; 2236 }); 2237 var run = function () { 2238 var args = []; 2239 for (var _i = 0; _i < arguments.length; _i++) { 2240 args[_i] = arguments[_i]; 2241 } 2242 each$1(handlers, function (handler) { 2243 handler.run.apply(undefined, args); 2244 }); 2245 }; 2246 return { 2247 can: can, 2248 abort: abort, 2249 run: run 2250 }; 2251 }; 2252 2253 var derive$3 = function (configs) { 2254 return wrapAll(configs); 2255 }; 2256 var abort = function (name, predicate) { 2257 return { 2258 key: name, 2259 value: nu$4({ abort: predicate }) 2260 }; 2261 }; 2262 var can = function (name, predicate) { 2263 return { 2264 key: name, 2265 value: nu$4({ can: predicate }) 2266 }; 2267 }; 2268 var run = function (name, handler) { 2269 return { 2270 key: name, 2271 value: nu$4({ run: handler }) 2272 }; 2273 }; 2274 var runActionExtra = function (name, action, extra) { 2275 return { 2276 key: name, 2277 value: nu$4({ 2278 run: function (component, simulatedEvent) { 2279 action.apply(undefined, [ 2280 component, 2281 simulatedEvent 2282 ].concat(extra)); 2283 } 2284 }) 2285 }; 2286 }; 2287 var runOnName = function (name) { 2288 return function (handler) { 2289 return run(name, handler); 2290 }; 2291 }; 2292 var runOnSourceName = function (name) { 2293 return function (handler) { 2294 return { 2295 key: name, 2296 value: nu$4({ 2297 run: function (component, simulatedEvent) { 2298 if (isSource(component, simulatedEvent)) { 2299 handler(component, simulatedEvent); 2300 } 2301 } 2302 }) 2303 }; 2304 }; 2305 }; 2306 var redirectToUid = function (name, uid) { 2307 return run(name, function (component, simulatedEvent) { 2308 component.getSystem().getByUid(uid).each(function (redirectee) { 2309 dispatchEvent(redirectee, redirectee.element, name, simulatedEvent); 2310 }); 2311 }); 2312 }; 2313 var redirectToPart = function (name, detail, partName) { 2314 var uid = detail.partUids[partName]; 2315 return redirectToUid(name, uid); 2316 }; 2317 var cutter = function (name) { 2318 return run(name, function (component, simulatedEvent) { 2319 simulatedEvent.cut(); 2320 }); 2321 }; 2322 var stopper = function (name) { 2323 return run(name, function (component, simulatedEvent) { 2324 simulatedEvent.stop(); 2325 }); 2326 }; 2327 var runOnSource = function (name, f) { 2328 return runOnSourceName(name)(f); 2329 }; 2330 var runOnAttached = runOnSourceName(attachedToDom()); 2331 var runOnDetached = runOnSourceName(detachedFromDom()); 2332 var runOnInit = runOnSourceName(systemInit()); 2333 var runOnExecute = runOnName(execute$5()); 2334 2335 var markAsBehaviourApi = function (f, apiName, apiFunction) { 2336 var delegate = apiFunction.toString(); 2337 var endIndex = delegate.indexOf(')') + 1; 2338 var openBracketIndex = delegate.indexOf('('); 2339 var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); 2340 f.toFunctionAnnotation = function () { 2341 return { 2342 name: apiName, 2343 parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3))) 2344 }; 2345 }; 2346 return f; 2347 }; 2348 var cleanParameters = function (parameters) { 2349 return map$2(parameters, function (p) { 2350 return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p; 2351 }); 2352 }; 2353 var markAsExtraApi = function (f, extraName) { 2354 var delegate = f.toString(); 2355 var endIndex = delegate.indexOf(')') + 1; 2356 var openBracketIndex = delegate.indexOf('('); 2357 var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); 2358 f.toFunctionAnnotation = function () { 2359 return { 2360 name: extraName, 2361 parameters: cleanParameters(parameters) 2362 }; 2363 }; 2364 return f; 2365 }; 2366 var markAsSketchApi = function (f, apiFunction) { 2367 var delegate = apiFunction.toString(); 2368 var endIndex = delegate.indexOf(')') + 1; 2369 var openBracketIndex = delegate.indexOf('('); 2370 var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); 2371 f.toFunctionAnnotation = function () { 2372 return { 2373 name: 'OVERRIDE', 2374 parameters: cleanParameters(parameters.slice(1)) 2375 }; 2376 }; 2377 return f; 2378 }; 2379 2380 var nu$3 = function (s) { 2381 return { 2382 classes: isUndefined(s.classes) ? [] : s.classes, 2383 attributes: isUndefined(s.attributes) ? {} : s.attributes, 2384 styles: isUndefined(s.styles) ? {} : s.styles 2385 }; 2386 }; 2387 var merge = function (defnA, mod) { 2388 return __assign(__assign({}, defnA), { 2389 attributes: __assign(__assign({}, defnA.attributes), mod.attributes), 2390 styles: __assign(__assign({}, defnA.styles), mod.styles), 2391 classes: defnA.classes.concat(mod.classes) 2392 }); 2393 }; 2394 2395 var executeEvent = function (bConfig, bState, executor) { 2396 return runOnExecute(function (component) { 2397 executor(component, bConfig, bState); 2398 }); 2399 }; 2400 var loadEvent = function (bConfig, bState, f) { 2401 return runOnInit(function (component, _simulatedEvent) { 2402 f(component, bConfig, bState); 2403 }); 2404 }; 2405 var create$6 = function (schema, name, active, apis, extra, state) { 2406 var configSchema = objOfOnly(schema); 2407 var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]); 2408 return doCreate(configSchema, schemaSchema, name, active, apis, extra, state); 2409 }; 2410 var createModes$1 = function (modes, name, active, apis, extra, state) { 2411 var configSchema = modes; 2412 var schemaSchema = optionObjOf(name, [optionOf('config', modes)]); 2413 return doCreate(configSchema, schemaSchema, name, active, apis, extra, state); 2414 }; 2415 var wrapApi = function (bName, apiFunction, apiName) { 2416 var f = function (component) { 2417 var rest = []; 2418 for (var _i = 1; _i < arguments.length; _i++) { 2419 rest[_i - 1] = arguments[_i]; 2420 } 2421 var args = [component].concat(rest); 2422 return component.config({ name: constant$1(bName) }).fold(function () { 2423 throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName); 2424 }, function (info) { 2425 var rest = Array.prototype.slice.call(args, 1); 2426 return apiFunction.apply(undefined, [ 2427 component, 2428 info.config, 2429 info.state 2430 ].concat(rest)); 2431 }); 2432 }; 2433 return markAsBehaviourApi(f, apiName, apiFunction); 2434 }; 2435 var revokeBehaviour = function (name) { 2436 return { 2437 key: name, 2438 value: undefined 2439 }; 2440 }; 2441 var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) { 2442 var getConfig = function (info) { 2443 return hasNonNullableKey(info, name) ? info[name]() : Optional.none(); 2444 }; 2445 var wrappedApis = map$1(apis, function (apiF, apiName) { 2446 return wrapApi(name, apiF, apiName); 2447 }); 2448 var wrappedExtra = map$1(extra, function (extraF, extraName) { 2449 return markAsExtraApi(extraF, extraName); 2450 }); 2451 var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), { 2452 revoke: curry(revokeBehaviour, name), 2453 config: function (spec) { 2454 var prepared = asRawOrDie$1(name + '-config', configSchema, spec); 2455 return { 2456 key: name, 2457 value: { 2458 config: prepared, 2459 me: me, 2460 configAsRaw: cached(function () { 2461 return asRawOrDie$1(name + '-config', configSchema, spec); 2462 }), 2463 initialConfig: spec, 2464 state: state 2465 } 2466 }; 2467 }, 2468 schema: constant$1(schemaSchema), 2469 exhibit: function (info, base) { 2470 return lift2(getConfig(info), get$c(active, 'exhibit'), function (behaviourInfo, exhibitor) { 2471 return exhibitor(base, behaviourInfo.config, behaviourInfo.state); 2472 }).getOrThunk(function () { 2473 return nu$3({}); 2474 }); 2475 }, 2476 name: constant$1(name), 2477 handlers: function (info) { 2478 return getConfig(info).map(function (behaviourInfo) { 2479 var getEvents = get$c(active, 'events').getOr(function () { 2480 return {}; 2481 }); 2482 return getEvents(behaviourInfo.config, behaviourInfo.state); 2483 }).getOr({}); 2484 } 2485 }); 2486 return me; 2487 }; 2488 2489 var NoState = { 2490 init: function () { 2491 return nu$2({ readState: constant$1('No State required') }); 2492 } 2493 }; 2494 var nu$2 = function (spec) { 2495 return spec; 2496 }; 2497 2498 var derive$2 = function (capabilities) { 2499 return wrapAll(capabilities); 2500 }; 2501 var simpleSchema = objOfOnly([ 2502 required$1('fields'), 2503 required$1('name'), 2504 defaulted('active', {}), 2505 defaulted('apis', {}), 2506 defaulted('state', NoState), 2507 defaulted('extra', {}) 2508 ]); 2509 var create$5 = function (data) { 2510 var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data); 2511 return create$6(value.fields, value.name, value.active, value.apis, value.extra, value.state); 2512 }; 2513 var modeSchema = objOfOnly([ 2514 required$1('branchKey'), 2515 required$1('branches'), 2516 required$1('name'), 2517 defaulted('active', {}), 2518 defaulted('apis', {}), 2519 defaulted('state', NoState), 2520 defaulted('extra', {}) 2521 ]); 2522 var createModes = function (data) { 2523 var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data); 2524 return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state); 2525 }; 2526 var revoke = constant$1(undefined); 2527 2528 var Swapping = create$5({ 2529 fields: SwapSchema, 2530 name: 'swapping', 2531 apis: SwapApis 2532 }); 2533 2534 var Cell = function (initial) { 2535 var value = initial; 2536 var get = function () { 2537 return value; 2538 }; 2539 var set = function (v) { 2540 value = v; 2541 }; 2542 return { 2543 get: get, 2544 set: set 2545 }; 2546 }; 2547 2548 var getDocument = function () { 2549 return SugarElement.fromDom(document); 2550 }; 2551 2552 var focus$3 = function (element) { 2553 return element.dom.focus(); 2554 }; 2555 var blur$1 = function (element) { 2556 return element.dom.blur(); 2557 }; 2558 var hasFocus = function (element) { 2559 var root = getRootNode(element).dom; 2560 return element.dom === root.activeElement; 2561 }; 2562 var active = function (root) { 2563 if (root === void 0) { 2564 root = getDocument(); 2565 } 2566 return Optional.from(root.dom.activeElement).map(SugarElement.fromDom); 2567 }; 2568 var search = function (element) { 2569 return active(getRootNode(element)).filter(function (e) { 2570 return element.dom.contains(e.dom); 2571 }); 2572 }; 2573 2574 var global$5 = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); 2575 2576 var global$4 = tinymce.util.Tools.resolve('tinymce.ThemeManager'); 2577 2578 var openLink = function (target) { 2579 var link = document.createElement('a'); 2580 link.target = '_blank'; 2581 link.href = target.href; 2582 link.rel = 'noreferrer noopener'; 2583 var nuEvt = document.createEvent('MouseEvents'); 2584 nuEvt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 2585 document.body.appendChild(link); 2586 link.dispatchEvent(nuEvt); 2587 document.body.removeChild(link); 2588 }; 2589 2590 var DefaultStyleFormats = [ 2591 { 2592 title: 'Headings', 2593 items: [ 2594 { 2595 title: 'Heading 1', 2596 format: 'h1' 2597 }, 2598 { 2599 title: 'Heading 2', 2600 format: 'h2' 2601 }, 2602 { 2603 title: 'Heading 3', 2604 format: 'h3' 2605 }, 2606 { 2607 title: 'Heading 4', 2608 format: 'h4' 2609 }, 2610 { 2611 title: 'Heading 5', 2612 format: 'h5' 2613 }, 2614 { 2615 title: 'Heading 6', 2616 format: 'h6' 2617 } 2618 ] 2619 }, 2620 { 2621 title: 'Inline', 2622 items: [ 2623 { 2624 title: 'Bold', 2625 icon: 'bold', 2626 format: 'bold' 2627 }, 2628 { 2629 title: 'Italic', 2630 icon: 'italic', 2631 format: 'italic' 2632 }, 2633 { 2634 title: 'Underline', 2635 icon: 'underline', 2636 format: 'underline' 2637 }, 2638 { 2639 title: 'Strikethrough', 2640 icon: 'strikethrough', 2641 format: 'strikethrough' 2642 }, 2643 { 2644 title: 'Superscript', 2645 icon: 'superscript', 2646 format: 'superscript' 2647 }, 2648 { 2649 title: 'Subscript', 2650 icon: 'subscript', 2651 format: 'subscript' 2652 }, 2653 { 2654 title: 'Code', 2655 icon: 'code', 2656 format: 'code' 2657 } 2658 ] 2659 }, 2660 { 2661 title: 'Blocks', 2662 items: [ 2663 { 2664 title: 'Paragraph', 2665 format: 'p' 2666 }, 2667 { 2668 title: 'Blockquote', 2669 format: 'blockquote' 2670 }, 2671 { 2672 title: 'Div', 2673 format: 'div' 2674 }, 2675 { 2676 title: 'Pre', 2677 format: 'pre' 2678 } 2679 ] 2680 }, 2681 { 2682 title: 'Alignment', 2683 items: [ 2684 { 2685 title: 'Left', 2686 icon: 'alignleft', 2687 format: 'alignleft' 2688 }, 2689 { 2690 title: 'Center', 2691 icon: 'aligncenter', 2692 format: 'aligncenter' 2693 }, 2694 { 2695 title: 'Right', 2696 icon: 'alignright', 2697 format: 'alignright' 2698 }, 2699 { 2700 title: 'Justify', 2701 icon: 'alignjustify', 2702 format: 'alignjustify' 2703 } 2704 ] 2705 } 2706 ]; 2707 2708 var defaults = [ 2709 'undo', 2710 'bold', 2711 'italic', 2712 'link', 2713 'image', 2714 'bullist', 2715 'styleselect' 2716 ]; 2717 var isSkinDisabled = function (editor) { 2718 return editor.getParam('skin') === false; 2719 }; 2720 var readOnlyOnInit = function (_editor) { 2721 return false; 2722 }; 2723 var getToolbar = function (editor) { 2724 return editor.getParam('toolbar', defaults, 'array'); 2725 }; 2726 var getStyleFormats = function (editor) { 2727 return editor.getParam('style_formats', DefaultStyleFormats, 'array'); 2728 }; 2729 var getSkinUrl = function (editor) { 2730 return editor.getParam('skin_url'); 2731 }; 2732 2733 var formatChanged = 'formatChanged'; 2734 var orientationChanged = 'orientationChanged'; 2735 var dropupDismissed = 'dropupDismissed'; 2736 2737 var fromHtml$1 = function (html, scope) { 2738 var doc = scope || document; 2739 var div = doc.createElement('div'); 2740 div.innerHTML = html; 2741 return children(SugarElement.fromDom(div)); 2742 }; 2743 2744 var get$9 = function (element) { 2745 return element.dom.innerHTML; 2746 }; 2747 var set$7 = function (element, content) { 2748 var owner = owner$2(element); 2749 var docDom = owner.dom; 2750 var fragment = SugarElement.fromDom(docDom.createDocumentFragment()); 2751 var contentElements = fromHtml$1(content, docDom); 2752 append$1(fragment, contentElements); 2753 empty(element); 2754 append$2(element, fragment); 2755 }; 2756 var getOuter = function (element) { 2757 var container = SugarElement.fromTag('div'); 2758 var clone = SugarElement.fromDom(element.dom.cloneNode(true)); 2759 append$2(container, clone); 2760 return get$9(container); 2761 }; 2762 2763 var clone = function (original, isDeep) { 2764 return SugarElement.fromDom(original.dom.cloneNode(isDeep)); 2765 }; 2766 var shallow = function (original) { 2767 return clone(original, false); 2768 }; 2769 2770 var getHtml = function (element) { 2771 if (isShadowRoot(element)) { 2772 return '#shadow-root'; 2773 } else { 2774 var clone = shallow(element); 2775 return getOuter(clone); 2776 } 2777 }; 2778 2779 var element = function (elem) { 2780 return getHtml(elem); 2781 }; 2782 2783 var chooseChannels = function (channels, message) { 2784 return message.universal ? channels : filter$2(channels, function (ch) { 2785 return contains$1(message.channels, ch); 2786 }); 2787 }; 2788 var events$a = function (receiveConfig) { 2789 return derive$3([run(receive$1(), function (component, message) { 2790 var channelMap = receiveConfig.channels; 2791 var channels = keys(channelMap); 2792 var receivingData = message; 2793 var targetChannels = chooseChannels(channels, receivingData); 2794 each$1(targetChannels, function (ch) { 2795 var channelInfo = channelMap[ch]; 2796 var channelSchema = channelInfo.schema; 2797 var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data); 2798 channelInfo.onReceive(component, data); 2799 }); 2800 })]); 2801 }; 2802 2803 var ActiveReceiving = /*#__PURE__*/Object.freeze({ 2804 __proto__: null, 2805 events: events$a 2806 }); 2807 2808 var unknown = 'unknown'; 2809 var EventConfiguration; 2810 (function (EventConfiguration) { 2811 EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP'; 2812 EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL'; 2813 EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING'; 2814 }(EventConfiguration || (EventConfiguration = {}))); 2815 var eventConfig = Cell({}); 2816 var makeEventLogger = function (eventName, initialTarget) { 2817 var sequence = []; 2818 var startTime = new Date().getTime(); 2819 return { 2820 logEventCut: function (_name, target, purpose) { 2821 sequence.push({ 2822 outcome: 'cut', 2823 target: target, 2824 purpose: purpose 2825 }); 2826 }, 2827 logEventStopped: function (_name, target, purpose) { 2828 sequence.push({ 2829 outcome: 'stopped', 2830 target: target, 2831 purpose: purpose 2832 }); 2833 }, 2834 logNoParent: function (_name, target, purpose) { 2835 sequence.push({ 2836 outcome: 'no-parent', 2837 target: target, 2838 purpose: purpose 2839 }); 2840 }, 2841 logEventNoHandlers: function (_name, target) { 2842 sequence.push({ 2843 outcome: 'no-handlers-left', 2844 target: target 2845 }); 2846 }, 2847 logEventResponse: function (_name, target, purpose) { 2848 sequence.push({ 2849 outcome: 'response', 2850 purpose: purpose, 2851 target: target 2852 }); 2853 }, 2854 write: function () { 2855 var finishTime = new Date().getTime(); 2856 if (contains$1([ 2857 'mousemove', 2858 'mouseover', 2859 'mouseout', 2860 systemInit() 2861 ], eventName)) { 2862 return; 2863 } 2864 console.log(eventName, { 2865 event: eventName, 2866 time: finishTime - startTime, 2867 target: initialTarget.dom, 2868 sequence: map$2(sequence, function (s) { 2869 if (!contains$1([ 2870 'cut', 2871 'stopped', 2872 'response' 2873 ], s.outcome)) { 2874 return s.outcome; 2875 } else { 2876 return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')'; 2877 } 2878 }) 2879 }); 2880 } 2881 }; 2882 }; 2883 var processEvent = function (eventName, initialTarget, f) { 2884 var status = get$c(eventConfig.get(), eventName).orThunk(function () { 2885 var patterns = keys(eventConfig.get()); 2886 return findMap(patterns, function (p) { 2887 return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none(); 2888 }); 2889 }).getOr(EventConfiguration.NORMAL); 2890 switch (status) { 2891 case EventConfiguration.NORMAL: 2892 return f(noLogger()); 2893 case EventConfiguration.LOGGING: { 2894 var logger = makeEventLogger(eventName, initialTarget); 2895 var output = f(logger); 2896 logger.write(); 2897 return output; 2898 } 2899 case EventConfiguration.STOP: 2900 return true; 2901 } 2902 }; 2903 var path = [ 2904 'alloy/data/Fields', 2905 'alloy/debugging/Debugging' 2906 ]; 2907 var getTrace = function () { 2908 var err = new Error(); 2909 if (err.stack !== undefined) { 2910 var lines = err.stack.split('\n'); 2911 return find$2(lines, function (line) { 2912 return line.indexOf('alloy') > 0 && !exists(path, function (p) { 2913 return line.indexOf(p) > -1; 2914 }); 2915 }).getOr(unknown); 2916 } else { 2917 return unknown; 2918 } 2919 }; 2920 var ignoreEvent = { 2921 logEventCut: noop, 2922 logEventStopped: noop, 2923 logNoParent: noop, 2924 logEventNoHandlers: noop, 2925 logEventResponse: noop, 2926 write: noop 2927 }; 2928 var monitorEvent = function (eventName, initialTarget, f) { 2929 return processEvent(eventName, initialTarget, f); 2930 }; 2931 var noLogger = constant$1(ignoreEvent); 2932 2933 var menuFields = constant$1([ 2934 required$1('menu'), 2935 required$1('selectedMenu') 2936 ]); 2937 var itemFields = constant$1([ 2938 required$1('item'), 2939 required$1('selectedItem') 2940 ]); 2941 constant$1(objOf(itemFields().concat(menuFields()))); 2942 var itemSchema$1 = constant$1(objOf(itemFields())); 2943 2944 var _initSize = requiredObjOf('initSize', [ 2945 required$1('numColumns'), 2946 required$1('numRows') 2947 ]); 2948 var itemMarkers = function () { 2949 return requiredOf('markers', itemSchema$1()); 2950 }; 2951 var tieredMenuMarkers = function () { 2952 return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields())); 2953 }; 2954 var markers = function (required) { 2955 return requiredObjOf('markers', map$2(required, required$1)); 2956 }; 2957 var onPresenceHandler = function (label, fieldName, presence) { 2958 getTrace(); 2959 return field$2(fieldName, fieldName, presence, valueOf(function (f) { 2960 return Result.value(function () { 2961 var args = []; 2962 for (var _i = 0; _i < arguments.length; _i++) { 2963 args[_i] = arguments[_i]; 2964 } 2965 return f.apply(undefined, args); 2966 }); 2967 })); 2968 }; 2969 var onHandler = function (fieldName) { 2970 return onPresenceHandler('onHandler', fieldName, defaulted$1(noop)); 2971 }; 2972 var onKeyboardHandler = function (fieldName) { 2973 return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none)); 2974 }; 2975 var onStrictHandler = function (fieldName) { 2976 return onPresenceHandler('onHandler', fieldName, required$2()); 2977 }; 2978 var onStrictKeyboardHandler = function (fieldName) { 2979 return onPresenceHandler('onKeyboardHandler', fieldName, required$2()); 2980 }; 2981 var output = function (name, value) { 2982 return customField(name, constant$1(value)); 2983 }; 2984 var snapshot = function (name) { 2985 return customField(name, identity); 2986 }; 2987 var initSize = constant$1(_initSize); 2988 2989 var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([ 2990 onStrictHandler('onReceive'), 2991 defaulted('schema', anyValue()) 2992 ])))]; 2993 2994 var Receiving = create$5({ 2995 fields: ReceivingSchema, 2996 name: 'receiving', 2997 active: ActiveReceiving 2998 }); 2999 3000 var SetupBehaviourCellState = function (initialState) { 3001 var init = function () { 3002 var cell = Cell(initialState); 3003 var get = function () { 3004 return cell.get(); 3005 }; 3006 var set = function (newState) { 3007 return cell.set(newState); 3008 }; 3009 var clear = function () { 3010 return cell.set(initialState); 3011 }; 3012 var readState = function () { 3013 return cell.get(); 3014 }; 3015 return { 3016 get: get, 3017 set: set, 3018 clear: clear, 3019 readState: readState 3020 }; 3021 }; 3022 return { init: init }; 3023 }; 3024 3025 var updateAriaState = function (component, toggleConfig, toggleState) { 3026 var ariaInfo = toggleConfig.aria; 3027 ariaInfo.update(component, ariaInfo, toggleState.get()); 3028 }; 3029 var updateClass = function (component, toggleConfig, toggleState) { 3030 toggleConfig.toggleClass.each(function (toggleClass) { 3031 if (toggleState.get()) { 3032 add$1(component.element, toggleClass); 3033 } else { 3034 remove$3(component.element, toggleClass); 3035 } 3036 }); 3037 }; 3038 var toggle = function (component, toggleConfig, toggleState) { 3039 set$6(component, toggleConfig, toggleState, !toggleState.get()); 3040 }; 3041 var on$1 = function (component, toggleConfig, toggleState) { 3042 toggleState.set(true); 3043 updateClass(component, toggleConfig, toggleState); 3044 updateAriaState(component, toggleConfig, toggleState); 3045 }; 3046 var off = function (component, toggleConfig, toggleState) { 3047 toggleState.set(false); 3048 updateClass(component, toggleConfig, toggleState); 3049 updateAriaState(component, toggleConfig, toggleState); 3050 }; 3051 var set$6 = function (component, toggleConfig, toggleState, state) { 3052 var action = state ? on$1 : off; 3053 action(component, toggleConfig, toggleState); 3054 }; 3055 var isOn = function (component, toggleConfig, toggleState) { 3056 return toggleState.get(); 3057 }; 3058 var onLoad$5 = function (component, toggleConfig, toggleState) { 3059 set$6(component, toggleConfig, toggleState, toggleConfig.selected); 3060 }; 3061 3062 var ToggleApis = /*#__PURE__*/Object.freeze({ 3063 __proto__: null, 3064 onLoad: onLoad$5, 3065 toggle: toggle, 3066 isOn: isOn, 3067 on: on$1, 3068 off: off, 3069 set: set$6 3070 }); 3071 3072 var exhibit$5 = function () { 3073 return nu$3({}); 3074 }; 3075 var events$9 = function (toggleConfig, toggleState) { 3076 var execute = executeEvent(toggleConfig, toggleState, toggle); 3077 var load = loadEvent(toggleConfig, toggleState, onLoad$5); 3078 return derive$3(flatten([ 3079 toggleConfig.toggleOnExecute ? [execute] : [], 3080 [load] 3081 ])); 3082 }; 3083 3084 var ActiveToggle = /*#__PURE__*/Object.freeze({ 3085 __proto__: null, 3086 exhibit: exhibit$5, 3087 events: events$9 3088 }); 3089 3090 var updatePressed = function (component, ariaInfo, status) { 3091 set$8(component.element, 'aria-pressed', status); 3092 if (ariaInfo.syncWithExpanded) { 3093 updateExpanded(component, ariaInfo, status); 3094 } 3095 }; 3096 var updateSelected = function (component, ariaInfo, status) { 3097 set$8(component.element, 'aria-selected', status); 3098 }; 3099 var updateChecked = function (component, ariaInfo, status) { 3100 set$8(component.element, 'aria-checked', status); 3101 }; 3102 var updateExpanded = function (component, ariaInfo, status) { 3103 set$8(component.element, 'aria-expanded', status); 3104 }; 3105 3106 var ToggleSchema = [ 3107 defaulted('selected', false), 3108 option('toggleClass'), 3109 defaulted('toggleOnExecute', true), 3110 defaultedOf('aria', { mode: 'none' }, choose$1('mode', { 3111 pressed: [ 3112 defaulted('syncWithExpanded', false), 3113 output('update', updatePressed) 3114 ], 3115 checked: [output('update', updateChecked)], 3116 expanded: [output('update', updateExpanded)], 3117 selected: [output('update', updateSelected)], 3118 none: [output('update', noop)] 3119 })) 3120 ]; 3121 3122 var Toggling = create$5({ 3123 fields: ToggleSchema, 3124 name: 'toggling', 3125 active: ActiveToggle, 3126 apis: ToggleApis, 3127 state: SetupBehaviourCellState(false) 3128 }); 3129 3130 var format = function (command, update) { 3131 return Receiving.config({ 3132 channels: wrap(formatChanged, { 3133 onReceive: function (button, data) { 3134 if (data.command === command) { 3135 update(button, data.state); 3136 } 3137 } 3138 }) 3139 }); 3140 }; 3141 var orientation = function (onReceive) { 3142 return Receiving.config({ channels: wrap(orientationChanged, { onReceive: onReceive }) }); 3143 }; 3144 var receive = function (channel, onReceive) { 3145 return { 3146 key: channel, 3147 value: { onReceive: onReceive } 3148 }; 3149 }; 3150 3151 var prefix$2 = 'tinymce-mobile'; 3152 var resolve = function (p) { 3153 return prefix$2 + '-' + p; 3154 }; 3155 3156 var pointerEvents = function () { 3157 var onClick = function (component, simulatedEvent) { 3158 simulatedEvent.stop(); 3159 emitExecute(component); 3160 }; 3161 return [ 3162 run(click(), onClick), 3163 run(tap(), onClick), 3164 cutter(touchstart()), 3165 cutter(mousedown()) 3166 ]; 3167 }; 3168 var events$8 = function (optAction) { 3169 var executeHandler = function (action) { 3170 return runOnExecute(function (component, simulatedEvent) { 3171 action(component); 3172 simulatedEvent.stop(); 3173 }); 3174 }; 3175 return derive$3(flatten([ 3176 optAction.map(executeHandler).toArray(), 3177 pointerEvents() 3178 ])); 3179 }; 3180 3181 var focus$2 = function (component, focusConfig) { 3182 if (!focusConfig.ignore) { 3183 focus$3(component.element); 3184 focusConfig.onFocus(component); 3185 } 3186 }; 3187 var blur = function (component, focusConfig) { 3188 if (!focusConfig.ignore) { 3189 blur$1(component.element); 3190 } 3191 }; 3192 var isFocused = function (component) { 3193 return hasFocus(component.element); 3194 }; 3195 3196 var FocusApis = /*#__PURE__*/Object.freeze({ 3197 __proto__: null, 3198 focus: focus$2, 3199 blur: blur, 3200 isFocused: isFocused 3201 }); 3202 3203 var exhibit$4 = function (base, focusConfig) { 3204 var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } }; 3205 return nu$3(mod); 3206 }; 3207 var events$7 = function (focusConfig) { 3208 return derive$3([run(focus$4(), function (component, simulatedEvent) { 3209 focus$2(component, focusConfig); 3210 simulatedEvent.stop(); 3211 })].concat(focusConfig.stopMousedown ? [run(mousedown(), function (_, simulatedEvent) { 3212 simulatedEvent.event.prevent(); 3213 })] : [])); 3214 }; 3215 3216 var ActiveFocus = /*#__PURE__*/Object.freeze({ 3217 __proto__: null, 3218 exhibit: exhibit$4, 3219 events: events$7 3220 }); 3221 3222 var FocusSchema = [ 3223 onHandler('onFocus'), 3224 defaulted('stopMousedown', false), 3225 defaulted('ignore', false) 3226 ]; 3227 3228 var Focusing = create$5({ 3229 fields: FocusSchema, 3230 name: 'focusing', 3231 active: ActiveFocus, 3232 apis: FocusApis 3233 }); 3234 3235 var isSupported = function (dom) { 3236 return dom.style !== undefined && isFunction(dom.style.getPropertyValue); 3237 }; 3238 3239 var internalSet = function (dom, property, value) { 3240 if (!isString(value)) { 3241 console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom); 3242 throw new Error('CSS value must be a string: ' + value); 3243 } 3244 if (isSupported(dom)) { 3245 dom.style.setProperty(property, value); 3246 } 3247 }; 3248 var internalRemove = function (dom, property) { 3249 if (isSupported(dom)) { 3250 dom.style.removeProperty(property); 3251 } 3252 }; 3253 var set$5 = function (element, property, value) { 3254 var dom = element.dom; 3255 internalSet(dom, property, value); 3256 }; 3257 var setAll = function (element, css) { 3258 var dom = element.dom; 3259 each(css, function (v, k) { 3260 internalSet(dom, k, v); 3261 }); 3262 }; 3263 var get$8 = function (element, property) { 3264 var dom = element.dom; 3265 var styles = window.getComputedStyle(dom); 3266 var r = styles.getPropertyValue(property); 3267 return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r; 3268 }; 3269 var getUnsafeProperty = function (dom, property) { 3270 return isSupported(dom) ? dom.style.getPropertyValue(property) : ''; 3271 }; 3272 var getRaw = function (element, property) { 3273 var dom = element.dom; 3274 var raw = getUnsafeProperty(dom, property); 3275 return Optional.from(raw).filter(function (r) { 3276 return r.length > 0; 3277 }); 3278 }; 3279 var remove$2 = function (element, property) { 3280 var dom = element.dom; 3281 internalRemove(dom, property); 3282 if (is(getOpt(element, 'style').map(trim), '')) { 3283 remove$6(element, 'style'); 3284 } 3285 }; 3286 var reflow = function (e) { 3287 return e.dom.offsetWidth; 3288 }; 3289 3290 var Dimension = function (name, getOffset) { 3291 var set = function (element, h) { 3292 if (!isNumber(h) && !h.match(/^[0-9]+$/)) { 3293 throw new Error(name + '.set accepts only positive integer values. Value was ' + h); 3294 } 3295 var dom = element.dom; 3296 if (isSupported(dom)) { 3297 dom.style[name] = h + 'px'; 3298 } 3299 }; 3300 var get = function (element) { 3301 var r = getOffset(element); 3302 if (r <= 0 || r === null) { 3303 var css = get$8(element, name); 3304 return parseFloat(css) || 0; 3305 } 3306 return r; 3307 }; 3308 var getOuter = get; 3309 var aggregate = function (element, properties) { 3310 return foldl(properties, function (acc, property) { 3311 var val = get$8(element, property); 3312 var value = val === undefined ? 0 : parseInt(val, 10); 3313 return isNaN(value) ? acc : acc + value; 3314 }, 0); 3315 }; 3316 var max = function (element, value, properties) { 3317 var cumulativeInclusions = aggregate(element, properties); 3318 var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0; 3319 return absoluteMax; 3320 }; 3321 return { 3322 set: set, 3323 get: get, 3324 getOuter: getOuter, 3325 aggregate: aggregate, 3326 max: max 3327 }; 3328 }; 3329 3330 var api$3 = Dimension('height', function (element) { 3331 var dom = element.dom; 3332 return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight; 3333 }); 3334 var get$7 = function (element) { 3335 return api$3.get(element); 3336 }; 3337 3338 var ancestors$1 = function (scope, predicate, isRoot) { 3339 return filter$2(parents(scope, isRoot), predicate); 3340 }; 3341 var siblings$1 = function (scope, predicate) { 3342 return filter$2(siblings$2(scope), predicate); 3343 }; 3344 3345 var all = function (selector) { 3346 return all$2(selector); 3347 }; 3348 var ancestors = function (scope, selector, isRoot) { 3349 return ancestors$1(scope, function (e) { 3350 return is$1(e, selector); 3351 }, isRoot); 3352 }; 3353 var siblings = function (scope, selector) { 3354 return siblings$1(scope, function (e) { 3355 return is$1(e, selector); 3356 }); 3357 }; 3358 var descendants = function (scope, selector) { 3359 return all$2(selector, scope); 3360 }; 3361 3362 function ClosestOrAncestor (is, ancestor, scope, a, isRoot) { 3363 if (is(scope, a)) { 3364 return Optional.some(scope); 3365 } else if (isFunction(isRoot) && isRoot(scope)) { 3366 return Optional.none(); 3367 } else { 3368 return ancestor(scope, a, isRoot); 3369 } 3370 } 3371 3372 var ancestor$1 = function (scope, predicate, isRoot) { 3373 var element = scope.dom; 3374 var stop = isFunction(isRoot) ? isRoot : never; 3375 while (element.parentNode) { 3376 element = element.parentNode; 3377 var el = SugarElement.fromDom(element); 3378 if (predicate(el)) { 3379 return Optional.some(el); 3380 } else if (stop(el)) { 3381 break; 3382 } 3383 } 3384 return Optional.none(); 3385 }; 3386 var closest$2 = function (scope, predicate, isRoot) { 3387 var is = function (s, test) { 3388 return test(s); 3389 }; 3390 return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot); 3391 }; 3392 var descendant$1 = function (scope, predicate) { 3393 var descend = function (node) { 3394 for (var i = 0; i < node.childNodes.length; i++) { 3395 var child_1 = SugarElement.fromDom(node.childNodes[i]); 3396 if (predicate(child_1)) { 3397 return Optional.some(child_1); 3398 } 3399 var res = descend(node.childNodes[i]); 3400 if (res.isSome()) { 3401 return res; 3402 } 3403 } 3404 return Optional.none(); 3405 }; 3406 return descend(scope.dom); 3407 }; 3408 3409 var first$1 = function (selector) { 3410 return one(selector); 3411 }; 3412 var ancestor = function (scope, selector, isRoot) { 3413 return ancestor$1(scope, function (e) { 3414 return is$1(e, selector); 3415 }, isRoot); 3416 }; 3417 var descendant = function (scope, selector) { 3418 return one(selector, scope); 3419 }; 3420 var closest$1 = function (scope, selector, isRoot) { 3421 var is = function (element, selector) { 3422 return is$1(element, selector); 3423 }; 3424 return ClosestOrAncestor(is, ancestor, scope, selector, isRoot); 3425 }; 3426 3427 var BACKSPACE = [8]; 3428 var TAB = [9]; 3429 var ENTER = [13]; 3430 var ESCAPE = [27]; 3431 var SPACE = [32]; 3432 var LEFT = [37]; 3433 var UP = [38]; 3434 var RIGHT = [39]; 3435 var DOWN = [40]; 3436 3437 var cyclePrev = function (values, index, predicate) { 3438 var before = reverse(values.slice(0, index)); 3439 var after = reverse(values.slice(index + 1)); 3440 return find$2(before.concat(after), predicate); 3441 }; 3442 var tryPrev = function (values, index, predicate) { 3443 var before = reverse(values.slice(0, index)); 3444 return find$2(before, predicate); 3445 }; 3446 var cycleNext = function (values, index, predicate) { 3447 var before = values.slice(0, index); 3448 var after = values.slice(index + 1); 3449 return find$2(after.concat(before), predicate); 3450 }; 3451 var tryNext = function (values, index, predicate) { 3452 var after = values.slice(index + 1); 3453 return find$2(after, predicate); 3454 }; 3455 3456 var inSet = function (keys) { 3457 return function (event) { 3458 var raw = event.raw; 3459 return contains$1(keys, raw.which); 3460 }; 3461 }; 3462 var and = function (preds) { 3463 return function (event) { 3464 return forall(preds, function (pred) { 3465 return pred(event); 3466 }); 3467 }; 3468 }; 3469 var isShift = function (event) { 3470 var raw = event.raw; 3471 return raw.shiftKey === true; 3472 }; 3473 var isControl = function (event) { 3474 var raw = event.raw; 3475 return raw.ctrlKey === true; 3476 }; 3477 var isNotShift = not(isShift); 3478 3479 var rule = function (matches, action) { 3480 return { 3481 matches: matches, 3482 classification: action 3483 }; 3484 }; 3485 var choose = function (transitions, event) { 3486 var transition = find$2(transitions, function (t) { 3487 return t.matches(event); 3488 }); 3489 return transition.map(function (t) { 3490 return t.classification; 3491 }); 3492 }; 3493 3494 var cycleBy = function (value, delta, min, max) { 3495 var r = value + delta; 3496 if (r > max) { 3497 return min; 3498 } else if (r < min) { 3499 return max; 3500 } else { 3501 return r; 3502 } 3503 }; 3504 var clamp = function (value, min, max) { 3505 return Math.min(Math.max(value, min), max); 3506 }; 3507 3508 var dehighlightAllExcept = function (component, hConfig, hState, skip) { 3509 var highlighted = descendants(component.element, '.' + hConfig.highlightClass); 3510 each$1(highlighted, function (h) { 3511 if (!exists(skip, function (skipComp) { 3512 return skipComp.element === h; 3513 })) { 3514 remove$3(h, hConfig.highlightClass); 3515 component.getSystem().getByDom(h).each(function (target) { 3516 hConfig.onDehighlight(component, target); 3517 emit(target, dehighlight$1()); 3518 }); 3519 } 3520 }); 3521 }; 3522 var dehighlightAll = function (component, hConfig, hState) { 3523 return dehighlightAllExcept(component, hConfig, hState, []); 3524 }; 3525 var dehighlight = function (component, hConfig, hState, target) { 3526 if (isHighlighted(component, hConfig, hState, target)) { 3527 remove$3(target.element, hConfig.highlightClass); 3528 hConfig.onDehighlight(component, target); 3529 emit(target, dehighlight$1()); 3530 } 3531 }; 3532 var highlight = function (component, hConfig, hState, target) { 3533 dehighlightAllExcept(component, hConfig, hState, [target]); 3534 if (!isHighlighted(component, hConfig, hState, target)) { 3535 add$1(target.element, hConfig.highlightClass); 3536 hConfig.onHighlight(component, target); 3537 emit(target, highlight$1()); 3538 } 3539 }; 3540 var highlightFirst = function (component, hConfig, hState) { 3541 getFirst(component, hConfig).each(function (firstComp) { 3542 highlight(component, hConfig, hState, firstComp); 3543 }); 3544 }; 3545 var highlightLast = function (component, hConfig, hState) { 3546 getLast(component, hConfig).each(function (lastComp) { 3547 highlight(component, hConfig, hState, lastComp); 3548 }); 3549 }; 3550 var highlightAt = function (component, hConfig, hState, index) { 3551 getByIndex(component, hConfig, hState, index).fold(function (err) { 3552 throw err; 3553 }, function (firstComp) { 3554 highlight(component, hConfig, hState, firstComp); 3555 }); 3556 }; 3557 var highlightBy = function (component, hConfig, hState, predicate) { 3558 var candidates = getCandidates(component, hConfig); 3559 var targetComp = find$2(candidates, predicate); 3560 targetComp.each(function (c) { 3561 highlight(component, hConfig, hState, c); 3562 }); 3563 }; 3564 var isHighlighted = function (component, hConfig, hState, queryTarget) { 3565 return has(queryTarget.element, hConfig.highlightClass); 3566 }; 3567 var getHighlighted = function (component, hConfig, _hState) { 3568 return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) { 3569 return component.getSystem().getByDom(e).toOptional(); 3570 }); 3571 }; 3572 var getByIndex = function (component, hConfig, hState, index) { 3573 var items = descendants(component.element, '.' + hConfig.itemClass); 3574 return Optional.from(items[index]).fold(function () { 3575 return Result.error(new Error('No element found with index ' + index)); 3576 }, component.getSystem().getByDom); 3577 }; 3578 var getFirst = function (component, hConfig, _hState) { 3579 return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) { 3580 return component.getSystem().getByDom(e).toOptional(); 3581 }); 3582 }; 3583 var getLast = function (component, hConfig, _hState) { 3584 var items = descendants(component.element, '.' + hConfig.itemClass); 3585 var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none(); 3586 return last.bind(function (c) { 3587 return component.getSystem().getByDom(c).toOptional(); 3588 }); 3589 }; 3590 var getDelta = function (component, hConfig, hState, delta) { 3591 var items = descendants(component.element, '.' + hConfig.itemClass); 3592 var current = findIndex$1(items, function (item) { 3593 return has(item, hConfig.highlightClass); 3594 }); 3595 return current.bind(function (selected) { 3596 var dest = cycleBy(selected, delta, 0, items.length - 1); 3597 return component.getSystem().getByDom(items[dest]).toOptional(); 3598 }); 3599 }; 3600 var getPrevious = function (component, hConfig, hState) { 3601 return getDelta(component, hConfig, hState, -1); 3602 }; 3603 var getNext = function (component, hConfig, hState) { 3604 return getDelta(component, hConfig, hState, +1); 3605 }; 3606 var getCandidates = function (component, hConfig, _hState) { 3607 var items = descendants(component.element, '.' + hConfig.itemClass); 3608 return cat(map$2(items, function (i) { 3609 return component.getSystem().getByDom(i).toOptional(); 3610 })); 3611 }; 3612 3613 var HighlightApis = /*#__PURE__*/Object.freeze({ 3614 __proto__: null, 3615 dehighlightAll: dehighlightAll, 3616 dehighlight: dehighlight, 3617 highlight: highlight, 3618 highlightFirst: highlightFirst, 3619 highlightLast: highlightLast, 3620 highlightAt: highlightAt, 3621 highlightBy: highlightBy, 3622 isHighlighted: isHighlighted, 3623 getHighlighted: getHighlighted, 3624 getFirst: getFirst, 3625 getLast: getLast, 3626 getPrevious: getPrevious, 3627 getNext: getNext, 3628 getCandidates: getCandidates 3629 }); 3630 3631 var HighlightSchema = [ 3632 required$1('highlightClass'), 3633 required$1('itemClass'), 3634 onHandler('onHighlight'), 3635 onHandler('onDehighlight') 3636 ]; 3637 3638 var Highlighting = create$5({ 3639 fields: HighlightSchema, 3640 name: 'highlighting', 3641 apis: HighlightApis 3642 }); 3643 3644 var reportFocusShifting = function (component, prevFocus, newFocus) { 3645 var noChange = prevFocus.exists(function (p) { 3646 return newFocus.exists(function (n) { 3647 return eq(n, p); 3648 }); 3649 }); 3650 if (!noChange) { 3651 emitWith(component, focusShifted(), { 3652 prevFocus: prevFocus, 3653 newFocus: newFocus 3654 }); 3655 } 3656 }; 3657 var dom$2 = function () { 3658 var get = function (component) { 3659 return search(component.element); 3660 }; 3661 var set = function (component, focusee) { 3662 var prevFocus = get(component); 3663 component.getSystem().triggerFocus(focusee, component.element); 3664 var newFocus = get(component); 3665 reportFocusShifting(component, prevFocus, newFocus); 3666 }; 3667 return { 3668 get: get, 3669 set: set 3670 }; 3671 }; 3672 var highlights = function () { 3673 var get = function (component) { 3674 return Highlighting.getHighlighted(component).map(function (item) { 3675 return item.element; 3676 }); 3677 }; 3678 var set = function (component, element) { 3679 var prevFocus = get(component); 3680 component.getSystem().getByDom(element).fold(noop, function (item) { 3681 Highlighting.highlight(component, item); 3682 }); 3683 var newFocus = get(component); 3684 reportFocusShifting(component, prevFocus, newFocus); 3685 }; 3686 return { 3687 get: get, 3688 set: set 3689 }; 3690 }; 3691 3692 var FocusInsideModes; 3693 (function (FocusInsideModes) { 3694 FocusInsideModes['OnFocusMode'] = 'onFocus'; 3695 FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace'; 3696 FocusInsideModes['OnApiMode'] = 'onApi'; 3697 }(FocusInsideModes || (FocusInsideModes = {}))); 3698 3699 var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) { 3700 var schema = function () { 3701 return infoSchema.concat([ 3702 defaulted('focusManager', dom$2()), 3703 defaultedOf('focusInside', 'onFocus', valueOf(function (val) { 3704 return contains$1([ 3705 'onFocus', 3706 'onEnterOrSpace', 3707 'onApi' 3708 ], val) ? Result.value(val) : Result.error('Invalid value for focusInside'); 3709 })), 3710 output('handler', me), 3711 output('state', stateInit), 3712 output('sendFocusIn', optFocusIn) 3713 ]); 3714 }; 3715 var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) { 3716 var rules = getRules(component, simulatedEvent, keyingConfig, keyingState); 3717 return choose(rules, simulatedEvent.event).bind(function (rule) { 3718 return rule(component, simulatedEvent, keyingConfig, keyingState); 3719 }); 3720 }; 3721 var toEvents = function (keyingConfig, keyingState) { 3722 var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) { 3723 return run(focus$4(), function (component, simulatedEvent) { 3724 focusIn(component, keyingConfig, keyingState); 3725 simulatedEvent.stop(); 3726 }); 3727 }); 3728 var tryGoInsideComponent = function (component, simulatedEvent) { 3729 var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event); 3730 if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) { 3731 optFocusIn(keyingConfig).each(function (focusIn) { 3732 focusIn(component, keyingConfig, keyingState); 3733 simulatedEvent.stop(); 3734 }); 3735 } 3736 }; 3737 var keyboardEvents = [ 3738 run(keydown(), function (component, simulatedEvent) { 3739 processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () { 3740 tryGoInsideComponent(component, simulatedEvent); 3741 }, function (_) { 3742 simulatedEvent.stop(); 3743 }); 3744 }), 3745 run(keyup(), function (component, simulatedEvent) { 3746 processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) { 3747 simulatedEvent.stop(); 3748 }); 3749 }) 3750 ]; 3751 return derive$3(onFocusHandler.toArray().concat(keyboardEvents)); 3752 }; 3753 var me = { 3754 schema: schema, 3755 processKey: processKey, 3756 toEvents: toEvents 3757 }; 3758 return me; 3759 }; 3760 3761 var create$4 = function (cyclicField) { 3762 var schema = [ 3763 option('onEscape'), 3764 option('onEnter'), 3765 defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'), 3766 defaulted('firstTabstop', 0), 3767 defaulted('useTabstopAt', always), 3768 option('visibilitySelector') 3769 ].concat([cyclicField]); 3770 var isVisible = function (tabbingConfig, element) { 3771 var target = tabbingConfig.visibilitySelector.bind(function (sel) { 3772 return closest$1(element, sel); 3773 }).getOr(element); 3774 return get$7(target) > 0; 3775 }; 3776 var findInitial = function (component, tabbingConfig) { 3777 var tabstops = descendants(component.element, tabbingConfig.selector); 3778 var visibles = filter$2(tabstops, function (elem) { 3779 return isVisible(tabbingConfig, elem); 3780 }); 3781 return Optional.from(visibles[tabbingConfig.firstTabstop]); 3782 }; 3783 var findCurrent = function (component, tabbingConfig) { 3784 return tabbingConfig.focusManager.get(component).bind(function (elem) { 3785 return closest$1(elem, tabbingConfig.selector); 3786 }); 3787 }; 3788 var isTabstop = function (tabbingConfig, element) { 3789 return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element); 3790 }; 3791 var focusIn = function (component, tabbingConfig, _tabbingState) { 3792 findInitial(component, tabbingConfig).each(function (target) { 3793 tabbingConfig.focusManager.set(component, target); 3794 }); 3795 }; 3796 var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) { 3797 return cycle(tabstops, stopIndex, function (elem) { 3798 return isTabstop(tabbingConfig, elem); 3799 }).fold(function () { 3800 return tabbingConfig.cyclic ? Optional.some(true) : Optional.none(); 3801 }, function (target) { 3802 tabbingConfig.focusManager.set(component, target); 3803 return Optional.some(true); 3804 }); 3805 }; 3806 var go = function (component, _simulatedEvent, tabbingConfig, cycle) { 3807 var tabstops = descendants(component.element, tabbingConfig.selector); 3808 return findCurrent(component, tabbingConfig).bind(function (tabstop) { 3809 var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop)); 3810 return optStopIndex.bind(function (stopIndex) { 3811 return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle); 3812 }); 3813 }); 3814 }; 3815 var goBackwards = function (component, simulatedEvent, tabbingConfig) { 3816 var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev; 3817 return go(component, simulatedEvent, tabbingConfig, navigate); 3818 }; 3819 var goForwards = function (component, simulatedEvent, tabbingConfig) { 3820 var navigate = tabbingConfig.cyclic ? cycleNext : tryNext; 3821 return go(component, simulatedEvent, tabbingConfig, navigate); 3822 }; 3823 var execute = function (component, simulatedEvent, tabbingConfig) { 3824 return tabbingConfig.onEnter.bind(function (f) { 3825 return f(component, simulatedEvent); 3826 }); 3827 }; 3828 var exit = function (component, simulatedEvent, tabbingConfig) { 3829 return tabbingConfig.onEscape.bind(function (f) { 3830 return f(component, simulatedEvent); 3831 }); 3832 }; 3833 var getKeydownRules = constant$1([ 3834 rule(and([ 3835 isShift, 3836 inSet(TAB) 3837 ]), goBackwards), 3838 rule(inSet(TAB), goForwards), 3839 rule(inSet(ESCAPE), exit), 3840 rule(and([ 3841 isNotShift, 3842 inSet(ENTER) 3843 ]), execute) 3844 ]); 3845 var getKeyupRules = constant$1([]); 3846 return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () { 3847 return Optional.some(focusIn); 3848 }); 3849 }; 3850 3851 var AcyclicType = create$4(customField('cyclic', never)); 3852 3853 var CyclicType = create$4(customField('cyclic', always)); 3854 3855 var inside = function (target) { 3856 return name$1(target) === 'input' && get$b(target, 'type') !== 'radio' || name$1(target) === 'textarea'; 3857 }; 3858 3859 var doDefaultExecute = function (component, _simulatedEvent, focused) { 3860 dispatch(component, focused, execute$5()); 3861 return Optional.some(true); 3862 }; 3863 var defaultExecute = function (component, simulatedEvent, focused) { 3864 var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event); 3865 return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused); 3866 }; 3867 var stopEventForFirefox = function (_component, _simulatedEvent) { 3868 return Optional.some(true); 3869 }; 3870 3871 var schema$f = [ 3872 defaulted('execute', defaultExecute), 3873 defaulted('useSpace', false), 3874 defaulted('useEnter', true), 3875 defaulted('useControlEnter', false), 3876 defaulted('useDown', false) 3877 ]; 3878 var execute$4 = function (component, simulatedEvent, executeConfig) { 3879 return executeConfig.execute(component, simulatedEvent, component.element); 3880 }; 3881 var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) { 3882 var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : []; 3883 var enterExec = executeConfig.useEnter ? ENTER : []; 3884 var downExec = executeConfig.useDown ? DOWN : []; 3885 var execKeys = spaceExec.concat(enterExec).concat(downExec); 3886 return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([ 3887 isControl, 3888 inSet(ENTER) 3889 ]), execute$4)] : []); 3890 }; 3891 var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) { 3892 return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : []; 3893 }; 3894 var ExecutionType = typical(schema$f, NoState.init, getKeydownRules$5, getKeyupRules$5, function () { 3895 return Optional.none(); 3896 }); 3897 3898 var singleton$1 = function (doRevoke) { 3899 var subject = Cell(Optional.none()); 3900 var revoke = function () { 3901 return subject.get().each(doRevoke); 3902 }; 3903 var clear = function () { 3904 revoke(); 3905 subject.set(Optional.none()); 3906 }; 3907 var isSet = function () { 3908 return subject.get().isSome(); 3909 }; 3910 var get = function () { 3911 return subject.get(); 3912 }; 3913 var set = function (s) { 3914 revoke(); 3915 subject.set(Optional.some(s)); 3916 }; 3917 return { 3918 clear: clear, 3919 isSet: isSet, 3920 get: get, 3921 set: set 3922 }; 3923 }; 3924 var destroyable = function () { 3925 return singleton$1(function (s) { 3926 return s.destroy(); 3927 }); 3928 }; 3929 var api$2 = function () { 3930 var subject = destroyable(); 3931 var run = function (f) { 3932 return subject.get().each(f); 3933 }; 3934 return __assign(__assign({}, subject), { run: run }); 3935 }; 3936 var value = function () { 3937 var subject = singleton$1(noop); 3938 var on = function (f) { 3939 return subject.get().each(f); 3940 }; 3941 return __assign(__assign({}, subject), { on: on }); 3942 }; 3943 3944 var flatgrid$1 = function () { 3945 var dimensions = value(); 3946 var setGridSize = function (numRows, numColumns) { 3947 dimensions.set({ 3948 numRows: numRows, 3949 numColumns: numColumns 3950 }); 3951 }; 3952 var getNumRows = function () { 3953 return dimensions.get().map(function (d) { 3954 return d.numRows; 3955 }); 3956 }; 3957 var getNumColumns = function () { 3958 return dimensions.get().map(function (d) { 3959 return d.numColumns; 3960 }); 3961 }; 3962 return nu$2({ 3963 readState: function () { 3964 return dimensions.get().map(function (d) { 3965 return { 3966 numRows: String(d.numRows), 3967 numColumns: String(d.numColumns) 3968 }; 3969 }).getOr({ 3970 numRows: '?', 3971 numColumns: '?' 3972 }); 3973 }, 3974 setGridSize: setGridSize, 3975 getNumRows: getNumRows, 3976 getNumColumns: getNumColumns 3977 }); 3978 }; 3979 var init$5 = function (spec) { 3980 return spec.state(spec); 3981 }; 3982 3983 var KeyingState = /*#__PURE__*/Object.freeze({ 3984 __proto__: null, 3985 flatgrid: flatgrid$1, 3986 init: init$5 3987 }); 3988 3989 var onDirection = function (isLtr, isRtl) { 3990 return function (element) { 3991 return getDirection(element) === 'rtl' ? isRtl : isLtr; 3992 }; 3993 }; 3994 var getDirection = function (element) { 3995 return get$8(element, 'direction') === 'rtl' ? 'rtl' : 'ltr'; 3996 }; 3997 3998 var useH = function (movement) { 3999 return function (component, simulatedEvent, config, state) { 4000 var move = movement(component.element); 4001 return use(move, component, simulatedEvent, config, state); 4002 }; 4003 }; 4004 var west = function (moveLeft, moveRight) { 4005 var movement = onDirection(moveLeft, moveRight); 4006 return useH(movement); 4007 }; 4008 var east = function (moveLeft, moveRight) { 4009 var movement = onDirection(moveRight, moveLeft); 4010 return useH(movement); 4011 }; 4012 var useV = function (move) { 4013 return function (component, simulatedEvent, config, state) { 4014 return use(move, component, simulatedEvent, config, state); 4015 }; 4016 }; 4017 var use = function (move, component, simulatedEvent, config, state) { 4018 var outcome = config.focusManager.get(component).bind(function (focused) { 4019 return move(component.element, focused, config, state); 4020 }); 4021 return outcome.map(function (newFocus) { 4022 config.focusManager.set(component, newFocus); 4023 return true; 4024 }); 4025 }; 4026 var north = useV; 4027 var south = useV; 4028 var move$1 = useV; 4029 4030 var isHidden = function (dom) { 4031 return dom.offsetWidth <= 0 && dom.offsetHeight <= 0; 4032 }; 4033 var isVisible = function (element) { 4034 return !isHidden(element.dom); 4035 }; 4036 4037 var locate = function (candidates, predicate) { 4038 return findIndex$1(candidates, predicate).map(function (index) { 4039 return { 4040 index: index, 4041 candidates: candidates 4042 }; 4043 }); 4044 }; 4045 4046 var locateVisible = function (container, current, selector) { 4047 var predicate = function (x) { 4048 return eq(x, current); 4049 }; 4050 var candidates = descendants(container, selector); 4051 var visible = filter$2(candidates, isVisible); 4052 return locate(visible, predicate); 4053 }; 4054 var findIndex = function (elements, target) { 4055 return findIndex$1(elements, function (elem) { 4056 return eq(target, elem); 4057 }); 4058 }; 4059 4060 var withGrid = function (values, index, numCols, f) { 4061 var oldRow = Math.floor(index / numCols); 4062 var oldColumn = index % numCols; 4063 return f(oldRow, oldColumn).bind(function (address) { 4064 var newIndex = address.row * numCols + address.column; 4065 return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none(); 4066 }); 4067 }; 4068 var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) { 4069 return withGrid(values, index, numCols, function (oldRow, oldColumn) { 4070 var onLastRow = oldRow === numRows - 1; 4071 var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols; 4072 var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1); 4073 return Optional.some({ 4074 row: oldRow, 4075 column: newColumn 4076 }); 4077 }); 4078 }; 4079 var cycleVertical$1 = function (values, index, numRows, numCols, delta) { 4080 return withGrid(values, index, numCols, function (oldRow, oldColumn) { 4081 var newRow = cycleBy(oldRow, delta, 0, numRows - 1); 4082 var onLastRow = newRow === numRows - 1; 4083 var colsInRow = onLastRow ? values.length - newRow * numCols : numCols; 4084 var newCol = clamp(oldColumn, 0, colsInRow - 1); 4085 return Optional.some({ 4086 row: newRow, 4087 column: newCol 4088 }); 4089 }); 4090 }; 4091 var cycleRight$1 = function (values, index, numRows, numCols) { 4092 return cycleHorizontal$1(values, index, numRows, numCols, +1); 4093 }; 4094 var cycleLeft$1 = function (values, index, numRows, numCols) { 4095 return cycleHorizontal$1(values, index, numRows, numCols, -1); 4096 }; 4097 var cycleUp$1 = function (values, index, numRows, numCols) { 4098 return cycleVertical$1(values, index, numRows, numCols, -1); 4099 }; 4100 var cycleDown$1 = function (values, index, numRows, numCols) { 4101 return cycleVertical$1(values, index, numRows, numCols, +1); 4102 }; 4103 4104 var schema$e = [ 4105 required$1('selector'), 4106 defaulted('execute', defaultExecute), 4107 onKeyboardHandler('onEscape'), 4108 defaulted('captureTab', false), 4109 initSize() 4110 ]; 4111 var focusIn$3 = function (component, gridConfig, _gridState) { 4112 descendant(component.element, gridConfig.selector).each(function (first) { 4113 gridConfig.focusManager.set(component, first); 4114 }); 4115 }; 4116 var findCurrent$1 = function (component, gridConfig) { 4117 return gridConfig.focusManager.get(component).bind(function (elem) { 4118 return closest$1(elem, gridConfig.selector); 4119 }); 4120 }; 4121 var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) { 4122 return findCurrent$1(component, gridConfig).bind(function (focused) { 4123 return gridConfig.execute(component, simulatedEvent, focused); 4124 }); 4125 }; 4126 var doMove$2 = function (cycle) { 4127 return function (element, focused, gridConfig, gridState) { 4128 return locateVisible(element, focused, gridConfig.selector).bind(function (identified) { 4129 return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns)); 4130 }); 4131 }; 4132 }; 4133 var handleTab = function (_component, _simulatedEvent, gridConfig) { 4134 return gridConfig.captureTab ? Optional.some(true) : Optional.none(); 4135 }; 4136 var doEscape$1 = function (component, simulatedEvent, gridConfig) { 4137 return gridConfig.onEscape(component, simulatedEvent); 4138 }; 4139 var moveLeft$3 = doMove$2(cycleLeft$1); 4140 var moveRight$3 = doMove$2(cycleRight$1); 4141 var moveNorth$1 = doMove$2(cycleUp$1); 4142 var moveSouth$1 = doMove$2(cycleDown$1); 4143 var getKeydownRules$4 = constant$1([ 4144 rule(inSet(LEFT), west(moveLeft$3, moveRight$3)), 4145 rule(inSet(RIGHT), east(moveLeft$3, moveRight$3)), 4146 rule(inSet(UP), north(moveNorth$1)), 4147 rule(inSet(DOWN), south(moveSouth$1)), 4148 rule(and([ 4149 isShift, 4150 inSet(TAB) 4151 ]), handleTab), 4152 rule(and([ 4153 isNotShift, 4154 inSet(TAB) 4155 ]), handleTab), 4156 rule(inSet(ESCAPE), doEscape$1), 4157 rule(inSet(SPACE.concat(ENTER)), execute$3) 4158 ]); 4159 var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 4160 var FlatgridType = typical(schema$e, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () { 4161 return Optional.some(focusIn$3); 4162 }); 4163 4164 var horizontal = function (container, selector, current, delta) { 4165 var isDisabledButton = function (candidate) { 4166 return name$1(candidate) === 'button' && get$b(candidate, 'disabled') === 'disabled'; 4167 }; 4168 var tryCycle = function (initial, index, candidates) { 4169 var newIndex = cycleBy(index, delta, 0, candidates.length - 1); 4170 if (newIndex === initial) { 4171 return Optional.none(); 4172 } else { 4173 return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]); 4174 } 4175 }; 4176 return locateVisible(container, current, selector).bind(function (identified) { 4177 var index = identified.index; 4178 var candidates = identified.candidates; 4179 return tryCycle(index, index, candidates); 4180 }); 4181 }; 4182 4183 var schema$d = [ 4184 required$1('selector'), 4185 defaulted('getInitial', Optional.none), 4186 defaulted('execute', defaultExecute), 4187 onKeyboardHandler('onEscape'), 4188 defaulted('executeOnMove', false), 4189 defaulted('allowVertical', true) 4190 ]; 4191 var findCurrent = function (component, flowConfig) { 4192 return flowConfig.focusManager.get(component).bind(function (elem) { 4193 return closest$1(elem, flowConfig.selector); 4194 }); 4195 }; 4196 var execute$2 = function (component, simulatedEvent, flowConfig) { 4197 return findCurrent(component, flowConfig).bind(function (focused) { 4198 return flowConfig.execute(component, simulatedEvent, focused); 4199 }); 4200 }; 4201 var focusIn$2 = function (component, flowConfig, _state) { 4202 flowConfig.getInitial(component).orThunk(function () { 4203 return descendant(component.element, flowConfig.selector); 4204 }).each(function (first) { 4205 flowConfig.focusManager.set(component, first); 4206 }); 4207 }; 4208 var moveLeft$2 = function (element, focused, info) { 4209 return horizontal(element, info.selector, focused, -1); 4210 }; 4211 var moveRight$2 = function (element, focused, info) { 4212 return horizontal(element, info.selector, focused, +1); 4213 }; 4214 var doMove$1 = function (movement) { 4215 return function (component, simulatedEvent, flowConfig, flowState) { 4216 return movement(component, simulatedEvent, flowConfig, flowState).bind(function () { 4217 return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true); 4218 }); 4219 }; 4220 }; 4221 var doEscape = function (component, simulatedEvent, flowConfig) { 4222 return flowConfig.onEscape(component, simulatedEvent); 4223 }; 4224 var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) { 4225 var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []); 4226 var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []); 4227 return [ 4228 rule(inSet(westMovers), doMove$1(west(moveLeft$2, moveRight$2))), 4229 rule(inSet(eastMovers), doMove$1(east(moveLeft$2, moveRight$2))), 4230 rule(inSet(ENTER), execute$2), 4231 rule(inSet(SPACE), execute$2), 4232 rule(inSet(ESCAPE), doEscape) 4233 ]; 4234 }; 4235 var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 4236 var FlowType = typical(schema$d, NoState.init, getKeydownRules$3, getKeyupRules$3, function () { 4237 return Optional.some(focusIn$2); 4238 }); 4239 4240 var toCell = function (matrix, rowIndex, columnIndex) { 4241 return Optional.from(matrix[rowIndex]).bind(function (row) { 4242 return Optional.from(row[columnIndex]).map(function (cell) { 4243 return { 4244 rowIndex: rowIndex, 4245 columnIndex: columnIndex, 4246 cell: cell 4247 }; 4248 }); 4249 }); 4250 }; 4251 var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) { 4252 var row = matrix[rowIndex]; 4253 var colsInRow = row.length; 4254 var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1); 4255 return toCell(matrix, rowIndex, newColIndex); 4256 }; 4257 var cycleVertical = function (matrix, colIndex, startRow, deltaRow) { 4258 var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1); 4259 var colsInNextRow = matrix[nextRowIndex].length; 4260 var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1); 4261 return toCell(matrix, nextRowIndex, nextColIndex); 4262 }; 4263 var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) { 4264 var row = matrix[rowIndex]; 4265 var colsInRow = row.length; 4266 var newColIndex = clamp(startCol + deltaCol, 0, colsInRow - 1); 4267 return toCell(matrix, rowIndex, newColIndex); 4268 }; 4269 var moveVertical = function (matrix, colIndex, startRow, deltaRow) { 4270 var nextRowIndex = clamp(startRow + deltaRow, 0, matrix.length - 1); 4271 var colsInNextRow = matrix[nextRowIndex].length; 4272 var nextColIndex = clamp(colIndex, 0, colsInNextRow - 1); 4273 return toCell(matrix, nextRowIndex, nextColIndex); 4274 }; 4275 var cycleRight = function (matrix, startRow, startCol) { 4276 return cycleHorizontal(matrix, startRow, startCol, +1); 4277 }; 4278 var cycleLeft = function (matrix, startRow, startCol) { 4279 return cycleHorizontal(matrix, startRow, startCol, -1); 4280 }; 4281 var cycleUp = function (matrix, startRow, startCol) { 4282 return cycleVertical(matrix, startCol, startRow, -1); 4283 }; 4284 var cycleDown = function (matrix, startRow, startCol) { 4285 return cycleVertical(matrix, startCol, startRow, +1); 4286 }; 4287 var moveLeft$1 = function (matrix, startRow, startCol) { 4288 return moveHorizontal(matrix, startRow, startCol, -1); 4289 }; 4290 var moveRight$1 = function (matrix, startRow, startCol) { 4291 return moveHorizontal(matrix, startRow, startCol, +1); 4292 }; 4293 var moveUp$1 = function (matrix, startRow, startCol) { 4294 return moveVertical(matrix, startCol, startRow, -1); 4295 }; 4296 var moveDown$1 = function (matrix, startRow, startCol) { 4297 return moveVertical(matrix, startCol, startRow, +1); 4298 }; 4299 4300 var schema$c = [ 4301 requiredObjOf('selectors', [ 4302 required$1('row'), 4303 required$1('cell') 4304 ]), 4305 defaulted('cycles', true), 4306 defaulted('previousSelector', Optional.none), 4307 defaulted('execute', defaultExecute) 4308 ]; 4309 var focusIn$1 = function (component, matrixConfig, _state) { 4310 var focused = matrixConfig.previousSelector(component).orThunk(function () { 4311 var selectors = matrixConfig.selectors; 4312 return descendant(component.element, selectors.cell); 4313 }); 4314 focused.each(function (cell) { 4315 matrixConfig.focusManager.set(component, cell); 4316 }); 4317 }; 4318 var execute$1 = function (component, simulatedEvent, matrixConfig) { 4319 return search(component.element).bind(function (focused) { 4320 return matrixConfig.execute(component, simulatedEvent, focused); 4321 }); 4322 }; 4323 var toMatrix = function (rows, matrixConfig) { 4324 return map$2(rows, function (row) { 4325 return descendants(row, matrixConfig.selectors.cell); 4326 }); 4327 }; 4328 var doMove = function (ifCycle, ifMove) { 4329 return function (element, focused, matrixConfig) { 4330 var move = matrixConfig.cycles ? ifCycle : ifMove; 4331 return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) { 4332 var cellsInRow = descendants(inRow, matrixConfig.selectors.cell); 4333 return findIndex(cellsInRow, focused).bind(function (colIndex) { 4334 var allRows = descendants(element, matrixConfig.selectors.row); 4335 return findIndex(allRows, inRow).bind(function (rowIndex) { 4336 var matrix = toMatrix(allRows, matrixConfig); 4337 return move(matrix, rowIndex, colIndex).map(function (next) { 4338 return next.cell; 4339 }); 4340 }); 4341 }); 4342 }); 4343 }; 4344 }; 4345 var moveLeft = doMove(cycleLeft, moveLeft$1); 4346 var moveRight = doMove(cycleRight, moveRight$1); 4347 var moveNorth = doMove(cycleUp, moveUp$1); 4348 var moveSouth = doMove(cycleDown, moveDown$1); 4349 var getKeydownRules$2 = constant$1([ 4350 rule(inSet(LEFT), west(moveLeft, moveRight)), 4351 rule(inSet(RIGHT), east(moveLeft, moveRight)), 4352 rule(inSet(UP), north(moveNorth)), 4353 rule(inSet(DOWN), south(moveSouth)), 4354 rule(inSet(SPACE.concat(ENTER)), execute$1) 4355 ]); 4356 var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 4357 var MatrixType = typical(schema$c, NoState.init, getKeydownRules$2, getKeyupRules$2, function () { 4358 return Optional.some(focusIn$1); 4359 }); 4360 4361 var schema$b = [ 4362 required$1('selector'), 4363 defaulted('execute', defaultExecute), 4364 defaulted('moveOnTab', false) 4365 ]; 4366 var execute = function (component, simulatedEvent, menuConfig) { 4367 return menuConfig.focusManager.get(component).bind(function (focused) { 4368 return menuConfig.execute(component, simulatedEvent, focused); 4369 }); 4370 }; 4371 var focusIn = function (component, menuConfig, _state) { 4372 descendant(component.element, menuConfig.selector).each(function (first) { 4373 menuConfig.focusManager.set(component, first); 4374 }); 4375 }; 4376 var moveUp = function (element, focused, info) { 4377 return horizontal(element, info.selector, focused, -1); 4378 }; 4379 var moveDown = function (element, focused, info) { 4380 return horizontal(element, info.selector, focused, +1); 4381 }; 4382 var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) { 4383 return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none(); 4384 }; 4385 var fireTab = function (component, simulatedEvent, menuConfig, menuState) { 4386 return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none(); 4387 }; 4388 var getKeydownRules$1 = constant$1([ 4389 rule(inSet(UP), move$1(moveUp)), 4390 rule(inSet(DOWN), move$1(moveDown)), 4391 rule(and([ 4392 isShift, 4393 inSet(TAB) 4394 ]), fireShiftTab), 4395 rule(and([ 4396 isNotShift, 4397 inSet(TAB) 4398 ]), fireTab), 4399 rule(inSet(ENTER), execute), 4400 rule(inSet(SPACE), execute) 4401 ]); 4402 var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 4403 var MenuType = typical(schema$b, NoState.init, getKeydownRules$1, getKeyupRules$1, function () { 4404 return Optional.some(focusIn); 4405 }); 4406 4407 var schema$a = [ 4408 onKeyboardHandler('onSpace'), 4409 onKeyboardHandler('onEnter'), 4410 onKeyboardHandler('onShiftEnter'), 4411 onKeyboardHandler('onLeft'), 4412 onKeyboardHandler('onRight'), 4413 onKeyboardHandler('onTab'), 4414 onKeyboardHandler('onShiftTab'), 4415 onKeyboardHandler('onUp'), 4416 onKeyboardHandler('onDown'), 4417 onKeyboardHandler('onEscape'), 4418 defaulted('stopSpaceKeyup', false), 4419 option('focusIn') 4420 ]; 4421 var getKeydownRules = function (component, simulatedEvent, specialInfo) { 4422 return [ 4423 rule(inSet(SPACE), specialInfo.onSpace), 4424 rule(and([ 4425 isNotShift, 4426 inSet(ENTER) 4427 ]), specialInfo.onEnter), 4428 rule(and([ 4429 isShift, 4430 inSet(ENTER) 4431 ]), specialInfo.onShiftEnter), 4432 rule(and([ 4433 isShift, 4434 inSet(TAB) 4435 ]), specialInfo.onShiftTab), 4436 rule(and([ 4437 isNotShift, 4438 inSet(TAB) 4439 ]), specialInfo.onTab), 4440 rule(inSet(UP), specialInfo.onUp), 4441 rule(inSet(DOWN), specialInfo.onDown), 4442 rule(inSet(LEFT), specialInfo.onLeft), 4443 rule(inSet(RIGHT), specialInfo.onRight), 4444 rule(inSet(SPACE), specialInfo.onSpace), 4445 rule(inSet(ESCAPE), specialInfo.onEscape) 4446 ]; 4447 }; 4448 var getKeyupRules = function (component, simulatedEvent, specialInfo) { 4449 return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : []; 4450 }; 4451 var SpecialType = typical(schema$a, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) { 4452 return specialInfo.focusIn; 4453 }); 4454 4455 var acyclic = AcyclicType.schema(); 4456 var cyclic = CyclicType.schema(); 4457 var flow = FlowType.schema(); 4458 var flatgrid = FlatgridType.schema(); 4459 var matrix = MatrixType.schema(); 4460 var execution = ExecutionType.schema(); 4461 var menu = MenuType.schema(); 4462 var special = SpecialType.schema(); 4463 4464 var KeyboardBranches = /*#__PURE__*/Object.freeze({ 4465 __proto__: null, 4466 acyclic: acyclic, 4467 cyclic: cyclic, 4468 flow: flow, 4469 flatgrid: flatgrid, 4470 matrix: matrix, 4471 execution: execution, 4472 menu: menu, 4473 special: special 4474 }); 4475 4476 var isFlatgridState = function (keyState) { 4477 return hasNonNullableKey(keyState, 'setGridSize'); 4478 }; 4479 var Keying = createModes({ 4480 branchKey: 'mode', 4481 branches: KeyboardBranches, 4482 name: 'keying', 4483 active: { 4484 events: function (keyingConfig, keyingState) { 4485 var handler = keyingConfig.handler; 4486 return handler.toEvents(keyingConfig, keyingState); 4487 } 4488 }, 4489 apis: { 4490 focusIn: function (component, keyConfig, keyState) { 4491 keyConfig.sendFocusIn(keyConfig).fold(function () { 4492 component.getSystem().triggerFocus(component.element, component.element); 4493 }, function (sendFocusIn) { 4494 sendFocusIn(component, keyConfig, keyState); 4495 }); 4496 }, 4497 setGridSize: function (component, keyConfig, keyState, numRows, numColumns) { 4498 if (!isFlatgridState(keyState)) { 4499 console.error('Layout does not support setGridSize'); 4500 } else { 4501 keyState.setGridSize(numRows, numColumns); 4502 } 4503 } 4504 }, 4505 state: KeyingState 4506 }); 4507 4508 var field$1 = function (name, forbidden) { 4509 return defaultedObjOf(name, {}, map$2(forbidden, function (f) { 4510 return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name); 4511 }).concat([customField('dump', identity)])); 4512 }; 4513 var get$6 = function (data) { 4514 return data.dump; 4515 }; 4516 var augment = function (data, original) { 4517 return __assign(__assign({}, derive$2(original)), data.dump); 4518 }; 4519 var SketchBehaviours = { 4520 field: field$1, 4521 augment: augment, 4522 get: get$6 4523 }; 4524 4525 var _placeholder = 'placeholder'; 4526 var adt$5 = Adt.generate([ 4527 { 4528 single: [ 4529 'required', 4530 'valueThunk' 4531 ] 4532 }, 4533 { 4534 multiple: [ 4535 'required', 4536 'valueThunks' 4537 ] 4538 } 4539 ]); 4540 var isSubstituted = function (spec) { 4541 return has$2(spec, 'uiType'); 4542 }; 4543 var subPlaceholder = function (owner, detail, compSpec, placeholders) { 4544 if (owner.exists(function (o) { 4545 return o !== compSpec.owner; 4546 })) { 4547 return adt$5.single(true, constant$1(compSpec)); 4548 } 4549 return get$c(placeholders, compSpec.name).fold(function () { 4550 throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2)); 4551 }, function (newSpec) { 4552 return newSpec.replace(); 4553 }); 4554 }; 4555 var scan = function (owner, detail, compSpec, placeholders) { 4556 if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) { 4557 return subPlaceholder(owner, detail, compSpec, placeholders); 4558 } else { 4559 return adt$5.single(false, constant$1(compSpec)); 4560 } 4561 }; 4562 var substitute = function (owner, detail, compSpec, placeholders) { 4563 var base = scan(owner, detail, compSpec, placeholders); 4564 return base.fold(function (req, valueThunk) { 4565 var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail); 4566 var childSpecs = get$c(value, 'components').getOr([]); 4567 var substituted = bind$3(childSpecs, function (c) { 4568 return substitute(owner, detail, c, placeholders); 4569 }); 4570 return [__assign(__assign({}, value), { components: substituted })]; 4571 }, function (req, valuesThunk) { 4572 if (isSubstituted(compSpec)) { 4573 var values = valuesThunk(detail, compSpec.config, compSpec.validated); 4574 var preprocessor = compSpec.validated.preprocess.getOr(identity); 4575 return preprocessor(values); 4576 } else { 4577 return valuesThunk(detail); 4578 } 4579 }); 4580 }; 4581 var substituteAll = function (owner, detail, components, placeholders) { 4582 return bind$3(components, function (c) { 4583 return substitute(owner, detail, c, placeholders); 4584 }); 4585 }; 4586 var oneReplace = function (label, replacements) { 4587 var called = false; 4588 var used = function () { 4589 return called; 4590 }; 4591 var replace = function () { 4592 if (called) { 4593 throw new Error('Trying to use the same placeholder more than once: ' + label); 4594 } 4595 called = true; 4596 return replacements; 4597 }; 4598 var required = function () { 4599 return replacements.fold(function (req, _) { 4600 return req; 4601 }, function (req, _) { 4602 return req; 4603 }); 4604 }; 4605 return { 4606 name: constant$1(label), 4607 required: required, 4608 used: used, 4609 replace: replace 4610 }; 4611 }; 4612 var substitutePlaces = function (owner, detail, components, placeholders) { 4613 var ps = map$1(placeholders, function (ph, name) { 4614 return oneReplace(name, ph); 4615 }); 4616 var outcome = substituteAll(owner, detail, components, ps); 4617 each(ps, function (p) { 4618 if (p.used() === false && p.required()) { 4619 throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2)); 4620 } 4621 }); 4622 return outcome; 4623 }; 4624 var single$2 = adt$5.single; 4625 var multiple = adt$5.multiple; 4626 var placeholder = constant$1(_placeholder); 4627 4628 var unique = 0; 4629 var generate$4 = function (prefix) { 4630 var date = new Date(); 4631 var time = date.getTime(); 4632 var random = Math.floor(Math.random() * 1000000000); 4633 unique++; 4634 return prefix + '_' + random + unique + String(time); 4635 }; 4636 4637 var adt$4 = Adt.generate([ 4638 { required: ['data'] }, 4639 { external: ['data'] }, 4640 { optional: ['data'] }, 4641 { group: ['data'] } 4642 ]); 4643 var fFactory = defaulted('factory', { sketch: identity }); 4644 var fSchema = defaulted('schema', []); 4645 var fName = required$1('name'); 4646 var fPname = field$2('pname', 'pname', defaultedThunk(function (typeSpec) { 4647 return '<alloy.' + generate$4(typeSpec.name) + '>'; 4648 }), anyValue()); 4649 var fGroupSchema = customField('schema', function () { 4650 return [option('preprocess')]; 4651 }); 4652 var fDefaults = defaulted('defaults', constant$1({})); 4653 var fOverrides = defaulted('overrides', constant$1({})); 4654 var requiredSpec = objOf([ 4655 fFactory, 4656 fSchema, 4657 fName, 4658 fPname, 4659 fDefaults, 4660 fOverrides 4661 ]); 4662 var externalSpec = objOf([ 4663 fFactory, 4664 fSchema, 4665 fName, 4666 fDefaults, 4667 fOverrides 4668 ]); 4669 var optionalSpec = objOf([ 4670 fFactory, 4671 fSchema, 4672 fName, 4673 fPname, 4674 fDefaults, 4675 fOverrides 4676 ]); 4677 var groupSpec = objOf([ 4678 fFactory, 4679 fGroupSchema, 4680 fName, 4681 required$1('unit'), 4682 fPname, 4683 fDefaults, 4684 fOverrides 4685 ]); 4686 var asNamedPart = function (part) { 4687 return part.fold(Optional.some, Optional.none, Optional.some, Optional.some); 4688 }; 4689 var name = function (part) { 4690 var get = function (data) { 4691 return data.name; 4692 }; 4693 return part.fold(get, get, get, get); 4694 }; 4695 var convert$1 = function (adtConstructor, partSchema) { 4696 return function (spec) { 4697 var data = asRawOrDie$1('Converting part type', partSchema, spec); 4698 return adtConstructor(data); 4699 }; 4700 }; 4701 var required = convert$1(adt$4.required, requiredSpec); 4702 convert$1(adt$4.external, externalSpec); 4703 var optional = convert$1(adt$4.optional, optionalSpec); 4704 var group = convert$1(adt$4.group, groupSpec); 4705 var original = constant$1('entirety'); 4706 4707 var combine$2 = function (detail, data, partSpec, partValidated) { 4708 return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated)); 4709 }; 4710 var subs = function (owner, detail, parts) { 4711 var internals = {}; 4712 var externals = {}; 4713 each$1(parts, function (part) { 4714 part.fold(function (data) { 4715 internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) { 4716 return data.factory.sketch(combine$2(detail, data, partSpec, partValidated)); 4717 }); 4718 }, function (data) { 4719 var partSpec = detail.parts[data.name]; 4720 externals[data.name] = constant$1(data.factory.sketch(combine$2(detail, data, partSpec[original()]), partSpec)); 4721 }, function (data) { 4722 internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) { 4723 return data.factory.sketch(combine$2(detail, data, partSpec, partValidated)); 4724 }); 4725 }, function (data) { 4726 internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) { 4727 var units = detail[data.name]; 4728 return map$2(units, function (u) { 4729 return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u))); 4730 }); 4731 }); 4732 }); 4733 }); 4734 return { 4735 internals: constant$1(internals), 4736 externals: constant$1(externals) 4737 }; 4738 }; 4739 4740 var generate$3 = function (owner, parts) { 4741 var r = {}; 4742 each$1(parts, function (part) { 4743 asNamedPart(part).each(function (np) { 4744 var g = doGenerateOne(owner, np.pname); 4745 r[np.name] = function (config) { 4746 var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config); 4747 return __assign(__assign({}, g), { 4748 config: config, 4749 validated: validated 4750 }); 4751 }; 4752 }); 4753 }); 4754 return r; 4755 }; 4756 var doGenerateOne = function (owner, pname) { 4757 return { 4758 uiType: placeholder(), 4759 owner: owner, 4760 name: pname 4761 }; 4762 }; 4763 var generateOne = function (owner, pname, config) { 4764 return { 4765 uiType: placeholder(), 4766 owner: owner, 4767 name: pname, 4768 config: config, 4769 validated: {} 4770 }; 4771 }; 4772 var schemas = function (parts) { 4773 return bind$3(parts, function (part) { 4774 return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) { 4775 return requiredObjOf(data.name, data.schema.concat([snapshot(original())])); 4776 }).toArray(); 4777 }); 4778 }; 4779 var names = function (parts) { 4780 return map$2(parts, name); 4781 }; 4782 var substitutes = function (owner, detail, parts) { 4783 return subs(owner, detail, parts); 4784 }; 4785 var components = function (owner, detail, internals) { 4786 return substitutePlaces(Optional.some(owner), detail, detail.components, internals); 4787 }; 4788 var getPart = function (component, detail, partKey) { 4789 var uid = detail.partUids[partKey]; 4790 return component.getSystem().getByUid(uid).toOptional(); 4791 }; 4792 var getPartOrDie = function (component, detail, partKey) { 4793 return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey); 4794 }; 4795 var getAllParts = function (component, detail) { 4796 var system = component.getSystem(); 4797 return map$1(detail.partUids, function (pUid, _k) { 4798 return constant$1(system.getByUid(pUid)); 4799 }); 4800 }; 4801 var defaultUids = function (baseUid, partTypes) { 4802 var partNames = names(partTypes); 4803 return wrapAll(map$2(partNames, function (pn) { 4804 return { 4805 key: pn, 4806 value: baseUid + '-' + pn 4807 }; 4808 })); 4809 }; 4810 var defaultUidsSchema = function (partTypes) { 4811 return field$2('partUids', 'partUids', mergeWithThunk(function (spec) { 4812 return defaultUids(spec.uid, partTypes); 4813 }), anyValue()); 4814 }; 4815 4816 var premadeTag = generate$4('alloy-premade'); 4817 var premade$1 = function (comp) { 4818 return wrap(premadeTag, comp); 4819 }; 4820 var getPremade = function (spec) { 4821 return get$c(spec, premadeTag); 4822 }; 4823 var makeApi = function (f) { 4824 return markAsSketchApi(function (component) { 4825 var rest = []; 4826 for (var _i = 1; _i < arguments.length; _i++) { 4827 rest[_i - 1] = arguments[_i]; 4828 } 4829 return f.apply(void 0, __spreadArray([ 4830 component.getApis(), 4831 component 4832 ], rest, false)); 4833 }, f); 4834 }; 4835 4836 var prefix$1 = constant$1('alloy-id-'); 4837 var idAttr$1 = constant$1('data-alloy-id'); 4838 4839 var prefix = prefix$1(); 4840 var idAttr = idAttr$1(); 4841 var write = function (label, elem) { 4842 var id = generate$4(prefix + label); 4843 writeOnly(elem, id); 4844 return id; 4845 }; 4846 var writeOnly = function (elem, uid) { 4847 Object.defineProperty(elem.dom, idAttr, { 4848 value: uid, 4849 writable: true 4850 }); 4851 }; 4852 var read = function (elem) { 4853 var id = isElement(elem) ? elem.dom[idAttr] : null; 4854 return Optional.from(id); 4855 }; 4856 var generate$2 = function (prefix) { 4857 return generate$4(prefix); 4858 }; 4859 4860 var base = function (partSchemas, partUidsSchemas) { 4861 var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : []; 4862 return ps.concat([ 4863 required$1('uid'), 4864 defaulted('dom', {}), 4865 defaulted('components', []), 4866 snapshot('originalSpec'), 4867 defaulted('debug.sketcher', {}) 4868 ]).concat(partUidsSchemas); 4869 }; 4870 var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) { 4871 var baseS = base(partSchemas, partUidsSchemas); 4872 return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec); 4873 }; 4874 4875 var single$1 = function (owner, schema, factory, spec) { 4876 var specWithUid = supplyUid(spec); 4877 var detail = asRawOrDie(owner, schema, specWithUid, [], []); 4878 return factory(detail, specWithUid); 4879 }; 4880 var composite$1 = function (owner, schema, partTypes, factory, spec) { 4881 var specWithUid = supplyUid(spec); 4882 var partSchemas = schemas(partTypes); 4883 var partUidsSchema = defaultUidsSchema(partTypes); 4884 var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]); 4885 var subs = substitutes(owner, detail, partTypes); 4886 var components$1 = components(owner, detail, subs.internals()); 4887 return factory(detail, components$1, specWithUid, subs.externals()); 4888 }; 4889 var hasUid = function (spec) { 4890 return has$2(spec, 'uid'); 4891 }; 4892 var supplyUid = function (spec) { 4893 return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$2('uid') }); 4894 }; 4895 4896 var isSketchSpec$1 = function (spec) { 4897 return spec.uid !== undefined; 4898 }; 4899 var singleSchema = objOfOnly([ 4900 required$1('name'), 4901 required$1('factory'), 4902 required$1('configFields'), 4903 defaulted('apis', {}), 4904 defaulted('extraApis', {}) 4905 ]); 4906 var compositeSchema = objOfOnly([ 4907 required$1('name'), 4908 required$1('factory'), 4909 required$1('configFields'), 4910 required$1('partFields'), 4911 defaulted('apis', {}), 4912 defaulted('extraApis', {}) 4913 ]); 4914 var single = function (rawConfig) { 4915 var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig); 4916 var sketch = function (spec) { 4917 return single$1(config.name, config.configFields, config.factory, spec); 4918 }; 4919 var apis = map$1(config.apis, makeApi); 4920 var extraApis = map$1(config.extraApis, function (f, k) { 4921 return markAsExtraApi(f, k); 4922 }); 4923 return __assign(__assign({ 4924 name: config.name, 4925 configFields: config.configFields, 4926 sketch: sketch 4927 }, apis), extraApis); 4928 }; 4929 var composite = function (rawConfig) { 4930 var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig); 4931 var sketch = function (spec) { 4932 return composite$1(config.name, config.configFields, config.partFields, config.factory, spec); 4933 }; 4934 var parts = generate$3(config.name, config.partFields); 4935 var apis = map$1(config.apis, makeApi); 4936 var extraApis = map$1(config.extraApis, function (f, k) { 4937 return markAsExtraApi(f, k); 4938 }); 4939 return __assign(__assign({ 4940 name: config.name, 4941 partFields: config.partFields, 4942 configFields: config.configFields, 4943 sketch: sketch, 4944 parts: parts 4945 }, apis), extraApis); 4946 }; 4947 4948 var factory$5 = function (detail) { 4949 var events = events$8(detail.action); 4950 var tag = detail.dom.tag; 4951 var lookupAttr = function (attr) { 4952 return get$c(detail.dom, 'attributes').bind(function (attrs) { 4953 return get$c(attrs, attr); 4954 }); 4955 }; 4956 var getModAttributes = function () { 4957 if (tag === 'button') { 4958 var type = lookupAttr('type').getOr('button'); 4959 var roleAttrs = lookupAttr('role').map(function (role) { 4960 return { role: role }; 4961 }).getOr({}); 4962 return __assign({ type: type }, roleAttrs); 4963 } else { 4964 var role = lookupAttr('role').getOr('button'); 4965 return { role: role }; 4966 } 4967 }; 4968 return { 4969 uid: detail.uid, 4970 dom: detail.dom, 4971 components: detail.components, 4972 events: events, 4973 behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [ 4974 Focusing.config({}), 4975 Keying.config({ 4976 mode: 'execution', 4977 useSpace: true, 4978 useEnter: true 4979 }) 4980 ]), 4981 domModification: { attributes: getModAttributes() }, 4982 eventOrder: detail.eventOrder 4983 }; 4984 }; 4985 var Button = single({ 4986 name: 'Button', 4987 factory: factory$5, 4988 configFields: [ 4989 defaulted('uid', undefined), 4990 required$1('dom'), 4991 defaulted('components', []), 4992 SketchBehaviours.field('buttonBehaviours', [ 4993 Focusing, 4994 Keying 4995 ]), 4996 option('action'), 4997 option('role'), 4998 defaulted('eventOrder', {}) 4999 ] 5000 }); 5001 5002 var exhibit$3 = function () { 5003 return nu$3({ 5004 styles: { 5005 '-webkit-user-select': 'none', 5006 'user-select': 'none', 5007 '-ms-user-select': 'none', 5008 '-moz-user-select': '-moz-none' 5009 }, 5010 attributes: { unselectable: 'on' } 5011 }); 5012 }; 5013 var events$6 = function () { 5014 return derive$3([abort(selectstart(), always)]); 5015 }; 5016 5017 var ActiveUnselecting = /*#__PURE__*/Object.freeze({ 5018 __proto__: null, 5019 events: events$6, 5020 exhibit: exhibit$3 5021 }); 5022 5023 var Unselecting = create$5({ 5024 fields: [], 5025 name: 'unselecting', 5026 active: ActiveUnselecting 5027 }); 5028 5029 var getAttrs$1 = function (elem) { 5030 var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : []; 5031 return foldl(attributes, function (b, attr) { 5032 var _a; 5033 if (attr.name === 'class') { 5034 return b; 5035 } else { 5036 return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a)); 5037 } 5038 }, {}); 5039 }; 5040 var getClasses = function (elem) { 5041 return Array.prototype.slice.call(elem.dom.classList, 0); 5042 }; 5043 var fromHtml = function (html) { 5044 var elem = SugarElement.fromHtml(html); 5045 var children$1 = children(elem); 5046 var attrs = getAttrs$1(elem); 5047 var classes = getClasses(elem); 5048 var contents = children$1.length === 0 ? {} : { innerHtml: get$9(elem) }; 5049 return __assign({ 5050 tag: name$1(elem), 5051 classes: classes, 5052 attributes: attrs 5053 }, contents); 5054 }; 5055 5056 var dom$1 = function (rawHtml) { 5057 var html = supplant(rawHtml, { prefix: prefix$2 }); 5058 return fromHtml(html); 5059 }; 5060 var spec = function (rawHtml) { 5061 return { dom: dom$1(rawHtml) }; 5062 }; 5063 5064 var forToolbarCommand = function (editor, command) { 5065 return forToolbar(command, function () { 5066 editor.execCommand(command); 5067 }, {}, editor); 5068 }; 5069 var getToggleBehaviours = function (command) { 5070 return derive$2([ 5071 Toggling.config({ 5072 toggleClass: resolve('toolbar-button-selected'), 5073 toggleOnExecute: false, 5074 aria: { mode: 'pressed' } 5075 }), 5076 format(command, function (button, status) { 5077 var toggle = status ? Toggling.on : Toggling.off; 5078 toggle(button); 5079 }) 5080 ]); 5081 }; 5082 var forToolbarStateCommand = function (editor, command) { 5083 var extraBehaviours = getToggleBehaviours(command); 5084 return forToolbar(command, function () { 5085 editor.execCommand(command); 5086 }, extraBehaviours, editor); 5087 }; 5088 var forToolbarStateAction = function (editor, clazz, command, action) { 5089 var extraBehaviours = getToggleBehaviours(command); 5090 return forToolbar(clazz, action, extraBehaviours, editor); 5091 }; 5092 var getToolbarIconButton = function (clazz, editor) { 5093 var icons = editor.ui.registry.getAll().icons; 5094 var optOxideIcon = Optional.from(icons[clazz]); 5095 return optOxideIcon.fold(function () { 5096 return dom$1('<span class="$prefix}-toolbar-button $prefix}-toolbar-group-item $prefix}-icon-' + clazz + ' $prefix}-icon"></span>'); 5097 }, function (icon) { 5098 return dom$1('<span class="$prefix}-toolbar-button $prefix}-toolbar-group-item">' + icon + '</span>'); 5099 }); 5100 }; 5101 var forToolbar = function (clazz, action, extraBehaviours, editor) { 5102 return Button.sketch({ 5103 dom: getToolbarIconButton(clazz, editor), 5104 action: action, 5105 buttonBehaviours: deepMerge(derive$2([Unselecting.config({})]), extraBehaviours) 5106 }); 5107 }; 5108 5109 var labelPart = optional({ 5110 schema: [required$1('dom')], 5111 name: 'label' 5112 }); 5113 var edgePart = function (name) { 5114 return optional({ 5115 name: '' + name + '-edge', 5116 overrides: function (detail) { 5117 var action = detail.model.manager.edgeActions[name]; 5118 return action.fold(function () { 5119 return {}; 5120 }, function (a) { 5121 return { 5122 events: derive$3([ 5123 runActionExtra(touchstart(), function (comp, se, d) { 5124 return a(comp, d); 5125 }, [detail]), 5126 runActionExtra(mousedown(), function (comp, se, d) { 5127 return a(comp, d); 5128 }, [detail]), 5129 runActionExtra(mousemove(), function (comp, se, det) { 5130 if (det.mouseIsDown.get()) { 5131 a(comp, det); 5132 } 5133 }, [detail]) 5134 ]) 5135 }; 5136 }); 5137 } 5138 }); 5139 }; 5140 var tlEdgePart = edgePart('top-left'); 5141 var tedgePart = edgePart('top'); 5142 var trEdgePart = edgePart('top-right'); 5143 var redgePart = edgePart('right'); 5144 var brEdgePart = edgePart('bottom-right'); 5145 var bedgePart = edgePart('bottom'); 5146 var blEdgePart = edgePart('bottom-left'); 5147 var ledgePart = edgePart('left'); 5148 var thumbPart = required({ 5149 name: 'thumb', 5150 defaults: constant$1({ dom: { styles: { position: 'absolute' } } }), 5151 overrides: function (detail) { 5152 return { 5153 events: derive$3([ 5154 redirectToPart(touchstart(), detail, 'spectrum'), 5155 redirectToPart(touchmove(), detail, 'spectrum'), 5156 redirectToPart(touchend(), detail, 'spectrum'), 5157 redirectToPart(mousedown(), detail, 'spectrum'), 5158 redirectToPart(mousemove(), detail, 'spectrum'), 5159 redirectToPart(mouseup(), detail, 'spectrum') 5160 ]) 5161 }; 5162 } 5163 }); 5164 var spectrumPart = required({ 5165 schema: [customField('mouseIsDown', function () { 5166 return Cell(false); 5167 })], 5168 name: 'spectrum', 5169 overrides: function (detail) { 5170 var modelDetail = detail.model; 5171 var model = modelDetail.manager; 5172 var setValueFrom = function (component, simulatedEvent) { 5173 return model.getValueFromEvent(simulatedEvent).map(function (value) { 5174 return model.setValueFrom(component, detail, value); 5175 }); 5176 }; 5177 return { 5178 behaviours: derive$2([ 5179 Keying.config({ 5180 mode: 'special', 5181 onLeft: function (spectrum) { 5182 return model.onLeft(spectrum, detail); 5183 }, 5184 onRight: function (spectrum) { 5185 return model.onRight(spectrum, detail); 5186 }, 5187 onUp: function (spectrum) { 5188 return model.onUp(spectrum, detail); 5189 }, 5190 onDown: function (spectrum) { 5191 return model.onDown(spectrum, detail); 5192 } 5193 }), 5194 Focusing.config({}) 5195 ]), 5196 events: derive$3([ 5197 run(touchstart(), setValueFrom), 5198 run(touchmove(), setValueFrom), 5199 run(mousedown(), setValueFrom), 5200 run(mousemove(), function (spectrum, se) { 5201 if (detail.mouseIsDown.get()) { 5202 setValueFrom(spectrum, se); 5203 } 5204 }) 5205 ]) 5206 }; 5207 } 5208 }); 5209 var SliderParts = [ 5210 labelPart, 5211 ledgePart, 5212 redgePart, 5213 tedgePart, 5214 bedgePart, 5215 tlEdgePart, 5216 trEdgePart, 5217 blEdgePart, 5218 brEdgePart, 5219 thumbPart, 5220 spectrumPart 5221 ]; 5222 5223 var onLoad$4 = function (component, repConfig, repState) { 5224 repConfig.store.manager.onLoad(component, repConfig, repState); 5225 }; 5226 var onUnload$2 = function (component, repConfig, repState) { 5227 repConfig.store.manager.onUnload(component, repConfig, repState); 5228 }; 5229 var setValue$3 = function (component, repConfig, repState, data) { 5230 repConfig.store.manager.setValue(component, repConfig, repState, data); 5231 }; 5232 var getValue$4 = function (component, repConfig, repState) { 5233 return repConfig.store.manager.getValue(component, repConfig, repState); 5234 }; 5235 var getState$1 = function (component, repConfig, repState) { 5236 return repState; 5237 }; 5238 5239 var RepresentApis = /*#__PURE__*/Object.freeze({ 5240 __proto__: null, 5241 onLoad: onLoad$4, 5242 onUnload: onUnload$2, 5243 setValue: setValue$3, 5244 getValue: getValue$4, 5245 getState: getState$1 5246 }); 5247 5248 var events$5 = function (repConfig, repState) { 5249 var es = repConfig.resetOnDom ? [ 5250 runOnAttached(function (comp, _se) { 5251 onLoad$4(comp, repConfig, repState); 5252 }), 5253 runOnDetached(function (comp, _se) { 5254 onUnload$2(comp, repConfig, repState); 5255 }) 5256 ] : [loadEvent(repConfig, repState, onLoad$4)]; 5257 return derive$3(es); 5258 }; 5259 5260 var ActiveRepresenting = /*#__PURE__*/Object.freeze({ 5261 __proto__: null, 5262 events: events$5 5263 }); 5264 5265 var memory = function () { 5266 var data = Cell(null); 5267 var readState = function () { 5268 return { 5269 mode: 'memory', 5270 value: data.get() 5271 }; 5272 }; 5273 var isNotSet = function () { 5274 return data.get() === null; 5275 }; 5276 var clear = function () { 5277 data.set(null); 5278 }; 5279 return nu$2({ 5280 set: data.set, 5281 get: data.get, 5282 isNotSet: isNotSet, 5283 clear: clear, 5284 readState: readState 5285 }); 5286 }; 5287 var manual = function () { 5288 var readState = noop; 5289 return nu$2({ readState: readState }); 5290 }; 5291 var dataset = function () { 5292 var dataByValue = Cell({}); 5293 var dataByText = Cell({}); 5294 var readState = function () { 5295 return { 5296 mode: 'dataset', 5297 dataByValue: dataByValue.get(), 5298 dataByText: dataByText.get() 5299 }; 5300 }; 5301 var clear = function () { 5302 dataByValue.set({}); 5303 dataByText.set({}); 5304 }; 5305 var lookup = function (itemString) { 5306 return get$c(dataByValue.get(), itemString).orThunk(function () { 5307 return get$c(dataByText.get(), itemString); 5308 }); 5309 }; 5310 var update = function (items) { 5311 var currentDataByValue = dataByValue.get(); 5312 var currentDataByText = dataByText.get(); 5313 var newDataByValue = {}; 5314 var newDataByText = {}; 5315 each$1(items, function (item) { 5316 newDataByValue[item.value] = item; 5317 get$c(item, 'meta').each(function (meta) { 5318 get$c(meta, 'text').each(function (text) { 5319 newDataByText[text] = item; 5320 }); 5321 }); 5322 }); 5323 dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue)); 5324 dataByText.set(__assign(__assign({}, currentDataByText), newDataByText)); 5325 }; 5326 return nu$2({ 5327 readState: readState, 5328 lookup: lookup, 5329 update: update, 5330 clear: clear 5331 }); 5332 }; 5333 var init$4 = function (spec) { 5334 return spec.store.manager.state(spec); 5335 }; 5336 5337 var RepresentState = /*#__PURE__*/Object.freeze({ 5338 __proto__: null, 5339 memory: memory, 5340 dataset: dataset, 5341 manual: manual, 5342 init: init$4 5343 }); 5344 5345 var setValue$2 = function (component, repConfig, repState, data) { 5346 var store = repConfig.store; 5347 repState.update([data]); 5348 store.setValue(component, data); 5349 repConfig.onSetValue(component, data); 5350 }; 5351 var getValue$3 = function (component, repConfig, repState) { 5352 var store = repConfig.store; 5353 var key = store.getDataKey(component); 5354 return repState.lookup(key).getOrThunk(function () { 5355 return store.getFallbackEntry(key); 5356 }); 5357 }; 5358 var onLoad$3 = function (component, repConfig, repState) { 5359 var store = repConfig.store; 5360 store.initialValue.each(function (data) { 5361 setValue$2(component, repConfig, repState, data); 5362 }); 5363 }; 5364 var onUnload$1 = function (component, repConfig, repState) { 5365 repState.clear(); 5366 }; 5367 var DatasetStore = [ 5368 option('initialValue'), 5369 required$1('getFallbackEntry'), 5370 required$1('getDataKey'), 5371 required$1('setValue'), 5372 output('manager', { 5373 setValue: setValue$2, 5374 getValue: getValue$3, 5375 onLoad: onLoad$3, 5376 onUnload: onUnload$1, 5377 state: dataset 5378 }) 5379 ]; 5380 5381 var getValue$2 = function (component, repConfig, _repState) { 5382 return repConfig.store.getValue(component); 5383 }; 5384 var setValue$1 = function (component, repConfig, _repState, data) { 5385 repConfig.store.setValue(component, data); 5386 repConfig.onSetValue(component, data); 5387 }; 5388 var onLoad$2 = function (component, repConfig, _repState) { 5389 repConfig.store.initialValue.each(function (data) { 5390 repConfig.store.setValue(component, data); 5391 }); 5392 }; 5393 var ManualStore = [ 5394 required$1('getValue'), 5395 defaulted('setValue', noop), 5396 option('initialValue'), 5397 output('manager', { 5398 setValue: setValue$1, 5399 getValue: getValue$2, 5400 onLoad: onLoad$2, 5401 onUnload: noop, 5402 state: NoState.init 5403 }) 5404 ]; 5405 5406 var setValue = function (component, repConfig, repState, data) { 5407 repState.set(data); 5408 repConfig.onSetValue(component, data); 5409 }; 5410 var getValue$1 = function (component, repConfig, repState) { 5411 return repState.get(); 5412 }; 5413 var onLoad$1 = function (component, repConfig, repState) { 5414 repConfig.store.initialValue.each(function (initVal) { 5415 if (repState.isNotSet()) { 5416 repState.set(initVal); 5417 } 5418 }); 5419 }; 5420 var onUnload = function (component, repConfig, repState) { 5421 repState.clear(); 5422 }; 5423 var MemoryStore = [ 5424 option('initialValue'), 5425 output('manager', { 5426 setValue: setValue, 5427 getValue: getValue$1, 5428 onLoad: onLoad$1, 5429 onUnload: onUnload, 5430 state: memory 5431 }) 5432 ]; 5433 5434 var RepresentSchema = [ 5435 defaultedOf('store', { mode: 'memory' }, choose$1('mode', { 5436 memory: MemoryStore, 5437 manual: ManualStore, 5438 dataset: DatasetStore 5439 })), 5440 onHandler('onSetValue'), 5441 defaulted('resetOnDom', false) 5442 ]; 5443 5444 var Representing = create$5({ 5445 fields: RepresentSchema, 5446 name: 'representing', 5447 active: ActiveRepresenting, 5448 apis: RepresentApis, 5449 extra: { 5450 setValueFrom: function (component, source) { 5451 var value = Representing.getValue(source); 5452 Representing.setValue(component, value); 5453 } 5454 }, 5455 state: RepresentState 5456 }); 5457 5458 var api$1 = Dimension('width', function (element) { 5459 return element.dom.offsetWidth; 5460 }); 5461 var set$4 = function (element, h) { 5462 return api$1.set(element, h); 5463 }; 5464 var get$5 = function (element) { 5465 return api$1.get(element); 5466 }; 5467 5468 var r$1 = function (left, top) { 5469 var translate = function (x, y) { 5470 return r$1(left + x, top + y); 5471 }; 5472 return { 5473 left: left, 5474 top: top, 5475 translate: translate 5476 }; 5477 }; 5478 var SugarPosition = r$1; 5479 5480 var _sliderChangeEvent = 'slider.change.value'; 5481 var sliderChangeEvent = constant$1(_sliderChangeEvent); 5482 var isTouchEvent = function (evt) { 5483 return evt.type.indexOf('touch') !== -1; 5484 }; 5485 var getEventSource = function (simulatedEvent) { 5486 var evt = simulatedEvent.event.raw; 5487 if (isTouchEvent(evt)) { 5488 var touchEvent = evt; 5489 return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) { 5490 return SugarPosition(t.clientX, t.clientY); 5491 }) : Optional.none(); 5492 } else { 5493 var mouseEvent = evt; 5494 return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) { 5495 return SugarPosition(me.clientX, me.clientY); 5496 }) : Optional.none(); 5497 } 5498 }; 5499 5500 var t = 'top', r = 'right', b = 'bottom', l = 'left'; 5501 var minX = function (detail) { 5502 return detail.model.minX; 5503 }; 5504 var minY = function (detail) { 5505 return detail.model.minY; 5506 }; 5507 var min1X = function (detail) { 5508 return detail.model.minX - 1; 5509 }; 5510 var min1Y = function (detail) { 5511 return detail.model.minY - 1; 5512 }; 5513 var maxX = function (detail) { 5514 return detail.model.maxX; 5515 }; 5516 var maxY = function (detail) { 5517 return detail.model.maxY; 5518 }; 5519 var max1X = function (detail) { 5520 return detail.model.maxX + 1; 5521 }; 5522 var max1Y = function (detail) { 5523 return detail.model.maxY + 1; 5524 }; 5525 var range$1 = function (detail, max, min) { 5526 return max(detail) - min(detail); 5527 }; 5528 var xRange = function (detail) { 5529 return range$1(detail, maxX, minX); 5530 }; 5531 var yRange = function (detail) { 5532 return range$1(detail, maxY, minY); 5533 }; 5534 var halfX = function (detail) { 5535 return xRange(detail) / 2; 5536 }; 5537 var halfY = function (detail) { 5538 return yRange(detail) / 2; 5539 }; 5540 var step = function (detail) { 5541 return detail.stepSize; 5542 }; 5543 var snap = function (detail) { 5544 return detail.snapToGrid; 5545 }; 5546 var snapStart = function (detail) { 5547 return detail.snapStart; 5548 }; 5549 var rounded = function (detail) { 5550 return detail.rounded; 5551 }; 5552 var hasEdge = function (detail, edgeName) { 5553 return detail[edgeName + '-edge'] !== undefined; 5554 }; 5555 var hasLEdge = function (detail) { 5556 return hasEdge(detail, l); 5557 }; 5558 var hasREdge = function (detail) { 5559 return hasEdge(detail, r); 5560 }; 5561 var hasTEdge = function (detail) { 5562 return hasEdge(detail, t); 5563 }; 5564 var hasBEdge = function (detail) { 5565 return hasEdge(detail, b); 5566 }; 5567 var currentValue = function (detail) { 5568 return detail.model.value.get(); 5569 }; 5570 5571 var xValue = function (x) { 5572 return { x: x }; 5573 }; 5574 var yValue = function (y) { 5575 return { y: y }; 5576 }; 5577 var xyValue = function (x, y) { 5578 return { 5579 x: x, 5580 y: y 5581 }; 5582 }; 5583 var fireSliderChange$3 = function (component, value) { 5584 emitWith(component, sliderChangeEvent(), { value: value }); 5585 }; 5586 var setToTLEdgeXY = function (edge, detail) { 5587 fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail))); 5588 }; 5589 var setToTEdge = function (edge, detail) { 5590 fireSliderChange$3(edge, yValue(min1Y(detail))); 5591 }; 5592 var setToTEdgeXY = function (edge, detail) { 5593 fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail))); 5594 }; 5595 var setToTREdgeXY = function (edge, detail) { 5596 fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail))); 5597 }; 5598 var setToREdge = function (edge, detail) { 5599 fireSliderChange$3(edge, xValue(max1X(detail))); 5600 }; 5601 var setToREdgeXY = function (edge, detail) { 5602 fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail))); 5603 }; 5604 var setToBREdgeXY = function (edge, detail) { 5605 fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail))); 5606 }; 5607 var setToBEdge = function (edge, detail) { 5608 fireSliderChange$3(edge, yValue(max1Y(detail))); 5609 }; 5610 var setToBEdgeXY = function (edge, detail) { 5611 fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail))); 5612 }; 5613 var setToBLEdgeXY = function (edge, detail) { 5614 fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail))); 5615 }; 5616 var setToLEdge = function (edge, detail) { 5617 fireSliderChange$3(edge, xValue(min1X(detail))); 5618 }; 5619 var setToLEdgeXY = function (edge, detail) { 5620 fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail))); 5621 }; 5622 5623 var reduceBy = function (value, min, max, step) { 5624 if (value < min) { 5625 return value; 5626 } else if (value > max) { 5627 return max; 5628 } else if (value === min) { 5629 return min - 1; 5630 } else { 5631 return Math.max(min, value - step); 5632 } 5633 }; 5634 var increaseBy = function (value, min, max, step) { 5635 if (value > max) { 5636 return value; 5637 } else if (value < min) { 5638 return min; 5639 } else if (value === max) { 5640 return max + 1; 5641 } else { 5642 return Math.min(max, value + step); 5643 } 5644 }; 5645 var capValue = function (value, min, max) { 5646 return Math.max(min, Math.min(max, value)); 5647 }; 5648 var snapValueOf = function (value, min, max, step, snapStart) { 5649 return snapStart.fold(function () { 5650 var initValue = value - min; 5651 var extraValue = Math.round(initValue / step) * step; 5652 return capValue(min + extraValue, min - 1, max + 1); 5653 }, function (start) { 5654 var remainder = (value - start) % step; 5655 var adjustment = Math.round(remainder / step); 5656 var rawSteps = Math.floor((value - start) / step); 5657 var maxSteps = Math.floor((max - start) / step); 5658 var numSteps = Math.min(maxSteps, rawSteps + adjustment); 5659 var r = start + numSteps * step; 5660 return Math.max(start, r); 5661 }); 5662 }; 5663 var findOffsetOf = function (value, min, max) { 5664 return Math.min(max, Math.max(value, min)) - min; 5665 }; 5666 var findValueOf = function (args) { 5667 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; 5668 var capMin = hasMinEdge ? min - 1 : min; 5669 var capMax = hasMaxEdge ? max + 1 : max; 5670 if (value < minBound) { 5671 return capMin; 5672 } else if (value > maxBound) { 5673 return capMax; 5674 } else { 5675 var offset = findOffsetOf(value, minBound, maxBound); 5676 var newValue = capValue(offset / screenRange * range + min, capMin, capMax); 5677 if (snap && newValue >= min && newValue <= max) { 5678 return snapValueOf(newValue, min, max, step, snapStart); 5679 } else if (rounded) { 5680 return Math.round(newValue); 5681 } else { 5682 return newValue; 5683 } 5684 } 5685 }; 5686 var findOffsetOfValue$2 = function (args) { 5687 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; 5688 if (value < min) { 5689 return hasMinEdge ? 0 : centerMinEdge; 5690 } else if (value > max) { 5691 return hasMaxEdge ? maxBound : centerMaxEdge; 5692 } else { 5693 return (value - min) / range * maxOffset; 5694 } 5695 }; 5696 5697 var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height'; 5698 var getBounds$1 = function (component) { 5699 return component.element.dom.getBoundingClientRect(); 5700 }; 5701 var getBoundsProperty = function (bounds, property) { 5702 return bounds[property]; 5703 }; 5704 var getMinXBounds = function (component) { 5705 var bounds = getBounds$1(component); 5706 return getBoundsProperty(bounds, left); 5707 }; 5708 var getMaxXBounds = function (component) { 5709 var bounds = getBounds$1(component); 5710 return getBoundsProperty(bounds, right); 5711 }; 5712 var getMinYBounds = function (component) { 5713 var bounds = getBounds$1(component); 5714 return getBoundsProperty(bounds, top); 5715 }; 5716 var getMaxYBounds = function (component) { 5717 var bounds = getBounds$1(component); 5718 return getBoundsProperty(bounds, bottom); 5719 }; 5720 var getXScreenRange = function (component) { 5721 var bounds = getBounds$1(component); 5722 return getBoundsProperty(bounds, width); 5723 }; 5724 var getYScreenRange = function (component) { 5725 var bounds = getBounds$1(component); 5726 return getBoundsProperty(bounds, height); 5727 }; 5728 var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) { 5729 return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge; 5730 }; 5731 var getXCenterOffSetOf = function (component, spectrum) { 5732 var componentBounds = getBounds$1(component); 5733 var spectrumBounds = getBounds$1(spectrum); 5734 var componentMinEdge = getBoundsProperty(componentBounds, left); 5735 var componentMaxEdge = getBoundsProperty(componentBounds, right); 5736 var spectrumMinEdge = getBoundsProperty(spectrumBounds, left); 5737 return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge); 5738 }; 5739 var getYCenterOffSetOf = function (component, spectrum) { 5740 var componentBounds = getBounds$1(component); 5741 var spectrumBounds = getBounds$1(spectrum); 5742 var componentMinEdge = getBoundsProperty(componentBounds, top); 5743 var componentMaxEdge = getBoundsProperty(componentBounds, bottom); 5744 var spectrumMinEdge = getBoundsProperty(spectrumBounds, top); 5745 return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge); 5746 }; 5747 5748 var fireSliderChange$2 = function (spectrum, value) { 5749 emitWith(spectrum, sliderChangeEvent(), { value: value }); 5750 }; 5751 var sliderValue$2 = function (x) { 5752 return { x: x }; 5753 }; 5754 var findValueOfOffset$1 = function (spectrum, detail, left) { 5755 var args = { 5756 min: minX(detail), 5757 max: maxX(detail), 5758 range: xRange(detail), 5759 value: left, 5760 step: step(detail), 5761 snap: snap(detail), 5762 snapStart: snapStart(detail), 5763 rounded: rounded(detail), 5764 hasMinEdge: hasLEdge(detail), 5765 hasMaxEdge: hasREdge(detail), 5766 minBound: getMinXBounds(spectrum), 5767 maxBound: getMaxXBounds(spectrum), 5768 screenRange: getXScreenRange(spectrum) 5769 }; 5770 return findValueOf(args); 5771 }; 5772 var setValueFrom$2 = function (spectrum, detail, value) { 5773 var xValue = findValueOfOffset$1(spectrum, detail, value); 5774 var sliderVal = sliderValue$2(xValue); 5775 fireSliderChange$2(spectrum, sliderVal); 5776 return xValue; 5777 }; 5778 var setToMin$2 = function (spectrum, detail) { 5779 var min = minX(detail); 5780 fireSliderChange$2(spectrum, sliderValue$2(min)); 5781 }; 5782 var setToMax$2 = function (spectrum, detail) { 5783 var max = maxX(detail); 5784 fireSliderChange$2(spectrum, sliderValue$2(max)); 5785 }; 5786 var moveBy$2 = function (direction, spectrum, detail) { 5787 var f = direction > 0 ? increaseBy : reduceBy; 5788 var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail)); 5789 fireSliderChange$2(spectrum, sliderValue$2(xValue)); 5790 return Optional.some(xValue); 5791 }; 5792 var handleMovement$2 = function (direction) { 5793 return function (spectrum, detail) { 5794 return moveBy$2(direction, spectrum, detail).map(always); 5795 }; 5796 }; 5797 var getValueFromEvent$2 = function (simulatedEvent) { 5798 var pos = getEventSource(simulatedEvent); 5799 return pos.map(function (p) { 5800 return p.left; 5801 }); 5802 }; 5803 var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) { 5804 var minOffset = 0; 5805 var maxOffset = getXScreenRange(spectrum); 5806 var centerMinEdge = minEdge.bind(function (edge) { 5807 return Optional.some(getXCenterOffSetOf(edge, spectrum)); 5808 }).getOr(minOffset); 5809 var centerMaxEdge = maxEdge.bind(function (edge) { 5810 return Optional.some(getXCenterOffSetOf(edge, spectrum)); 5811 }).getOr(maxOffset); 5812 var args = { 5813 min: minX(detail), 5814 max: maxX(detail), 5815 range: xRange(detail), 5816 value: value, 5817 hasMinEdge: hasLEdge(detail), 5818 hasMaxEdge: hasREdge(detail), 5819 minBound: getMinXBounds(spectrum), 5820 minOffset: minOffset, 5821 maxBound: getMaxXBounds(spectrum), 5822 maxOffset: maxOffset, 5823 centerMinEdge: centerMinEdge, 5824 centerMaxEdge: centerMaxEdge 5825 }; 5826 return findOffsetOfValue$2(args); 5827 }; 5828 var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) { 5829 var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge); 5830 return getMinXBounds(spectrum) - getMinXBounds(slider) + offset; 5831 }; 5832 var setPositionFromValue$2 = function (slider, thumb, detail, edges) { 5833 var value = currentValue(detail); 5834 var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail); 5835 var thumbRadius = get$5(thumb.element) / 2; 5836 set$5(thumb.element, 'left', pos - thumbRadius + 'px'); 5837 }; 5838 var onLeft$2 = handleMovement$2(-1); 5839 var onRight$2 = handleMovement$2(1); 5840 var onUp$2 = Optional.none; 5841 var onDown$2 = Optional.none; 5842 var edgeActions$2 = { 5843 'top-left': Optional.none(), 5844 'top': Optional.none(), 5845 'top-right': Optional.none(), 5846 'right': Optional.some(setToREdge), 5847 'bottom-right': Optional.none(), 5848 'bottom': Optional.none(), 5849 'bottom-left': Optional.none(), 5850 'left': Optional.some(setToLEdge) 5851 }; 5852 5853 var HorizontalModel = /*#__PURE__*/Object.freeze({ 5854 __proto__: null, 5855 setValueFrom: setValueFrom$2, 5856 setToMin: setToMin$2, 5857 setToMax: setToMax$2, 5858 findValueOfOffset: findValueOfOffset$1, 5859 getValueFromEvent: getValueFromEvent$2, 5860 findPositionOfValue: findPositionOfValue$1, 5861 setPositionFromValue: setPositionFromValue$2, 5862 onLeft: onLeft$2, 5863 onRight: onRight$2, 5864 onUp: onUp$2, 5865 onDown: onDown$2, 5866 edgeActions: edgeActions$2 5867 }); 5868 5869 var fireSliderChange$1 = function (spectrum, value) { 5870 emitWith(spectrum, sliderChangeEvent(), { value: value }); 5871 }; 5872 var sliderValue$1 = function (y) { 5873 return { y: y }; 5874 }; 5875 var findValueOfOffset = function (spectrum, detail, top) { 5876 var args = { 5877 min: minY(detail), 5878 max: maxY(detail), 5879 range: yRange(detail), 5880 value: top, 5881 step: step(detail), 5882 snap: snap(detail), 5883 snapStart: snapStart(detail), 5884 rounded: rounded(detail), 5885 hasMinEdge: hasTEdge(detail), 5886 hasMaxEdge: hasBEdge(detail), 5887 minBound: getMinYBounds(spectrum), 5888 maxBound: getMaxYBounds(spectrum), 5889 screenRange: getYScreenRange(spectrum) 5890 }; 5891 return findValueOf(args); 5892 }; 5893 var setValueFrom$1 = function (spectrum, detail, value) { 5894 var yValue = findValueOfOffset(spectrum, detail, value); 5895 var sliderVal = sliderValue$1(yValue); 5896 fireSliderChange$1(spectrum, sliderVal); 5897 return yValue; 5898 }; 5899 var setToMin$1 = function (spectrum, detail) { 5900 var min = minY(detail); 5901 fireSliderChange$1(spectrum, sliderValue$1(min)); 5902 }; 5903 var setToMax$1 = function (spectrum, detail) { 5904 var max = maxY(detail); 5905 fireSliderChange$1(spectrum, sliderValue$1(max)); 5906 }; 5907 var moveBy$1 = function (direction, spectrum, detail) { 5908 var f = direction > 0 ? increaseBy : reduceBy; 5909 var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail)); 5910 fireSliderChange$1(spectrum, sliderValue$1(yValue)); 5911 return Optional.some(yValue); 5912 }; 5913 var handleMovement$1 = function (direction) { 5914 return function (spectrum, detail) { 5915 return moveBy$1(direction, spectrum, detail).map(always); 5916 }; 5917 }; 5918 var getValueFromEvent$1 = function (simulatedEvent) { 5919 var pos = getEventSource(simulatedEvent); 5920 return pos.map(function (p) { 5921 return p.top; 5922 }); 5923 }; 5924 var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) { 5925 var minOffset = 0; 5926 var maxOffset = getYScreenRange(spectrum); 5927 var centerMinEdge = minEdge.bind(function (edge) { 5928 return Optional.some(getYCenterOffSetOf(edge, spectrum)); 5929 }).getOr(minOffset); 5930 var centerMaxEdge = maxEdge.bind(function (edge) { 5931 return Optional.some(getYCenterOffSetOf(edge, spectrum)); 5932 }).getOr(maxOffset); 5933 var args = { 5934 min: minY(detail), 5935 max: maxY(detail), 5936 range: yRange(detail), 5937 value: value, 5938 hasMinEdge: hasTEdge(detail), 5939 hasMaxEdge: hasBEdge(detail), 5940 minBound: getMinYBounds(spectrum), 5941 minOffset: minOffset, 5942 maxBound: getMaxYBounds(spectrum), 5943 maxOffset: maxOffset, 5944 centerMinEdge: centerMinEdge, 5945 centerMaxEdge: centerMaxEdge 5946 }; 5947 return findOffsetOfValue$2(args); 5948 }; 5949 var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) { 5950 var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge); 5951 return getMinYBounds(spectrum) - getMinYBounds(slider) + offset; 5952 }; 5953 var setPositionFromValue$1 = function (slider, thumb, detail, edges) { 5954 var value = currentValue(detail); 5955 var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail); 5956 var thumbRadius = get$7(thumb.element) / 2; 5957 set$5(thumb.element, 'top', pos - thumbRadius + 'px'); 5958 }; 5959 var onLeft$1 = Optional.none; 5960 var onRight$1 = Optional.none; 5961 var onUp$1 = handleMovement$1(-1); 5962 var onDown$1 = handleMovement$1(1); 5963 var edgeActions$1 = { 5964 'top-left': Optional.none(), 5965 'top': Optional.some(setToTEdge), 5966 'top-right': Optional.none(), 5967 'right': Optional.none(), 5968 'bottom-right': Optional.none(), 5969 'bottom': Optional.some(setToBEdge), 5970 'bottom-left': Optional.none(), 5971 'left': Optional.none() 5972 }; 5973 5974 var VerticalModel = /*#__PURE__*/Object.freeze({ 5975 __proto__: null, 5976 setValueFrom: setValueFrom$1, 5977 setToMin: setToMin$1, 5978 setToMax: setToMax$1, 5979 findValueOfOffset: findValueOfOffset, 5980 getValueFromEvent: getValueFromEvent$1, 5981 findPositionOfValue: findPositionOfValue, 5982 setPositionFromValue: setPositionFromValue$1, 5983 onLeft: onLeft$1, 5984 onRight: onRight$1, 5985 onUp: onUp$1, 5986 onDown: onDown$1, 5987 edgeActions: edgeActions$1 5988 }); 5989 5990 var fireSliderChange = function (spectrum, value) { 5991 emitWith(spectrum, sliderChangeEvent(), { value: value }); 5992 }; 5993 var sliderValue = function (x, y) { 5994 return { 5995 x: x, 5996 y: y 5997 }; 5998 }; 5999 var setValueFrom = function (spectrum, detail, value) { 6000 var xValue = findValueOfOffset$1(spectrum, detail, value.left); 6001 var yValue = findValueOfOffset(spectrum, detail, value.top); 6002 var val = sliderValue(xValue, yValue); 6003 fireSliderChange(spectrum, val); 6004 return val; 6005 }; 6006 var moveBy = function (direction, isVerticalMovement, spectrum, detail) { 6007 var f = direction > 0 ? increaseBy : reduceBy; 6008 var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail)); 6009 var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail)); 6010 fireSliderChange(spectrum, sliderValue(xValue, yValue)); 6011 return Optional.some(xValue); 6012 }; 6013 var handleMovement = function (direction, isVerticalMovement) { 6014 return function (spectrum, detail) { 6015 return moveBy(direction, isVerticalMovement, spectrum, detail).map(always); 6016 }; 6017 }; 6018 var setToMin = function (spectrum, detail) { 6019 var mX = minX(detail); 6020 var mY = minY(detail); 6021 fireSliderChange(spectrum, sliderValue(mX, mY)); 6022 }; 6023 var setToMax = function (spectrum, detail) { 6024 var mX = maxX(detail); 6025 var mY = maxY(detail); 6026 fireSliderChange(spectrum, sliderValue(mX, mY)); 6027 }; 6028 var getValueFromEvent = function (simulatedEvent) { 6029 return getEventSource(simulatedEvent); 6030 }; 6031 var setPositionFromValue = function (slider, thumb, detail, edges) { 6032 var value = currentValue(detail); 6033 var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail); 6034 var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail); 6035 var thumbXRadius = get$5(thumb.element) / 2; 6036 var thumbYRadius = get$7(thumb.element) / 2; 6037 set$5(thumb.element, 'left', xPos - thumbXRadius + 'px'); 6038 set$5(thumb.element, 'top', yPos - thumbYRadius + 'px'); 6039 }; 6040 var onLeft = handleMovement(-1, false); 6041 var onRight = handleMovement(1, false); 6042 var onUp = handleMovement(-1, true); 6043 var onDown = handleMovement(1, true); 6044 var edgeActions = { 6045 'top-left': Optional.some(setToTLEdgeXY), 6046 'top': Optional.some(setToTEdgeXY), 6047 'top-right': Optional.some(setToTREdgeXY), 6048 'right': Optional.some(setToREdgeXY), 6049 'bottom-right': Optional.some(setToBREdgeXY), 6050 'bottom': Optional.some(setToBEdgeXY), 6051 'bottom-left': Optional.some(setToBLEdgeXY), 6052 'left': Optional.some(setToLEdgeXY) 6053 }; 6054 6055 var TwoDModel = /*#__PURE__*/Object.freeze({ 6056 __proto__: null, 6057 setValueFrom: setValueFrom, 6058 setToMin: setToMin, 6059 setToMax: setToMax, 6060 getValueFromEvent: getValueFromEvent, 6061 setPositionFromValue: setPositionFromValue, 6062 onLeft: onLeft, 6063 onRight: onRight, 6064 onUp: onUp, 6065 onDown: onDown, 6066 edgeActions: edgeActions 6067 }); 6068 6069 var SliderSchema = [ 6070 defaulted('stepSize', 1), 6071 defaulted('onChange', noop), 6072 defaulted('onChoose', noop), 6073 defaulted('onInit', noop), 6074 defaulted('onDragStart', noop), 6075 defaulted('onDragEnd', noop), 6076 defaulted('snapToGrid', false), 6077 defaulted('rounded', true), 6078 option('snapStart'), 6079 requiredOf('model', choose$1('mode', { 6080 x: [ 6081 defaulted('minX', 0), 6082 defaulted('maxX', 100), 6083 customField('value', function (spec) { 6084 return Cell(spec.mode.minX); 6085 }), 6086 required$1('getInitialValue'), 6087 output('manager', HorizontalModel) 6088 ], 6089 y: [ 6090 defaulted('minY', 0), 6091 defaulted('maxY', 100), 6092 customField('value', function (spec) { 6093 return Cell(spec.mode.minY); 6094 }), 6095 required$1('getInitialValue'), 6096 output('manager', VerticalModel) 6097 ], 6098 xy: [ 6099 defaulted('minX', 0), 6100 defaulted('maxX', 100), 6101 defaulted('minY', 0), 6102 defaulted('maxY', 100), 6103 customField('value', function (spec) { 6104 return Cell({ 6105 x: spec.mode.minX, 6106 y: spec.mode.minY 6107 }); 6108 }), 6109 required$1('getInitialValue'), 6110 output('manager', TwoDModel) 6111 ] 6112 })), 6113 field$1('sliderBehaviours', [ 6114 Keying, 6115 Representing 6116 ]), 6117 customField('mouseIsDown', function () { 6118 return Cell(false); 6119 }) 6120 ]; 6121 6122 var mouseReleased = constant$1('mouse.released'); 6123 6124 var sketch$9 = function (detail, components, _spec, _externals) { 6125 var _a; 6126 var getThumb = function (component) { 6127 return getPartOrDie(component, detail, 'thumb'); 6128 }; 6129 var getSpectrum = function (component) { 6130 return getPartOrDie(component, detail, 'spectrum'); 6131 }; 6132 var getLeftEdge = function (component) { 6133 return getPart(component, detail, 'left-edge'); 6134 }; 6135 var getRightEdge = function (component) { 6136 return getPart(component, detail, 'right-edge'); 6137 }; 6138 var getTopEdge = function (component) { 6139 return getPart(component, detail, 'top-edge'); 6140 }; 6141 var getBottomEdge = function (component) { 6142 return getPart(component, detail, 'bottom-edge'); 6143 }; 6144 var modelDetail = detail.model; 6145 var model = modelDetail.manager; 6146 var refresh = function (slider, thumb) { 6147 model.setPositionFromValue(slider, thumb, detail, { 6148 getLeftEdge: getLeftEdge, 6149 getRightEdge: getRightEdge, 6150 getTopEdge: getTopEdge, 6151 getBottomEdge: getBottomEdge, 6152 getSpectrum: getSpectrum 6153 }); 6154 }; 6155 var setValue = function (slider, newValue) { 6156 modelDetail.value.set(newValue); 6157 var thumb = getThumb(slider); 6158 refresh(slider, thumb); 6159 }; 6160 var changeValue = function (slider, newValue) { 6161 setValue(slider, newValue); 6162 var thumb = getThumb(slider); 6163 detail.onChange(slider, thumb, newValue); 6164 return Optional.some(true); 6165 }; 6166 var resetToMin = function (slider) { 6167 model.setToMin(slider, detail); 6168 }; 6169 var resetToMax = function (slider) { 6170 model.setToMax(slider, detail); 6171 }; 6172 var choose = function (slider) { 6173 var fireOnChoose = function () { 6174 getPart(slider, detail, 'thumb').each(function (thumb) { 6175 var value = modelDetail.value.get(); 6176 detail.onChoose(slider, thumb, value); 6177 }); 6178 }; 6179 var wasDown = detail.mouseIsDown.get(); 6180 detail.mouseIsDown.set(false); 6181 if (wasDown) { 6182 fireOnChoose(); 6183 } 6184 }; 6185 var onDragStart = function (slider, simulatedEvent) { 6186 simulatedEvent.stop(); 6187 detail.mouseIsDown.set(true); 6188 detail.onDragStart(slider, getThumb(slider)); 6189 }; 6190 var onDragEnd = function (slider, simulatedEvent) { 6191 simulatedEvent.stop(); 6192 detail.onDragEnd(slider, getThumb(slider)); 6193 choose(slider); 6194 }; 6195 return { 6196 uid: detail.uid, 6197 dom: detail.dom, 6198 components: components, 6199 behaviours: augment(detail.sliderBehaviours, [ 6200 Keying.config({ 6201 mode: 'special', 6202 focusIn: function (slider) { 6203 return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always); 6204 } 6205 }), 6206 Representing.config({ 6207 store: { 6208 mode: 'manual', 6209 getValue: function (_) { 6210 return modelDetail.value.get(); 6211 } 6212 } 6213 }), 6214 Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) }) 6215 ]), 6216 events: derive$3([ 6217 run(sliderChangeEvent(), function (slider, simulatedEvent) { 6218 changeValue(slider, simulatedEvent.event.value); 6219 }), 6220 runOnAttached(function (slider, _simulatedEvent) { 6221 var getInitial = modelDetail.getInitialValue(); 6222 modelDetail.value.set(getInitial); 6223 var thumb = getThumb(slider); 6224 refresh(slider, thumb); 6225 var spectrum = getSpectrum(slider); 6226 detail.onInit(slider, thumb, spectrum, modelDetail.value.get()); 6227 }), 6228 run(touchstart(), onDragStart), 6229 run(touchend(), onDragEnd), 6230 run(mousedown(), onDragStart), 6231 run(mouseup(), onDragEnd) 6232 ]), 6233 apis: { 6234 resetToMin: resetToMin, 6235 resetToMax: resetToMax, 6236 setValue: setValue, 6237 refresh: refresh 6238 }, 6239 domModification: { styles: { position: 'relative' } } 6240 }; 6241 }; 6242 6243 var Slider = composite({ 6244 name: 'Slider', 6245 configFields: SliderSchema, 6246 partFields: SliderParts, 6247 factory: sketch$9, 6248 apis: { 6249 setValue: function (apis, slider, value) { 6250 apis.setValue(slider, value); 6251 }, 6252 resetToMin: function (apis, slider) { 6253 apis.resetToMin(slider); 6254 }, 6255 resetToMax: function (apis, slider) { 6256 apis.resetToMax(slider); 6257 }, 6258 refresh: function (apis, slider) { 6259 apis.refresh(slider); 6260 } 6261 } 6262 }); 6263 6264 var button = function (realm, clazz, makeItems, editor) { 6265 return forToolbar(clazz, function () { 6266 var items = makeItems(); 6267 realm.setContextToolbar([{ 6268 label: clazz + ' group', 6269 items: items 6270 }]); 6271 }, {}, editor); 6272 }; 6273 6274 var BLACK = -1; 6275 var makeSlider$1 = function (spec$1) { 6276 var getColor = function (hue) { 6277 if (hue < 0) { 6278 return 'black'; 6279 } else if (hue > 360) { 6280 return 'white'; 6281 } else { 6282 return 'hsl(' + hue + ', 100%, 50%)'; 6283 } 6284 }; 6285 var onInit = function (slider, thumb, spectrum, value) { 6286 var color = getColor(value.x()); 6287 set$5(thumb.element, 'background-color', color); 6288 }; 6289 var onChange = function (slider, thumb, value) { 6290 var color = getColor(value.x()); 6291 set$5(thumb.element, 'background-color', color); 6292 spec$1.onChange(slider, thumb, color); 6293 }; 6294 return Slider.sketch({ 6295 dom: dom$1('<div class="$prefix}-slider $prefix}-hue-slider-container"></div>'), 6296 components: [ 6297 Slider.parts['left-edge'](spec('<div class="$prefix}-hue-slider-black"></div>')), 6298 Slider.parts.spectrum({ 6299 dom: dom$1('<div class="$prefix}-slider-gradient-container"></div>'), 6300 components: [spec('<div class="$prefix}-slider-gradient"></div>')], 6301 behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })]) 6302 }), 6303 Slider.parts['right-edge'](spec('<div class="$prefix}-hue-slider-white"></div>')), 6304 Slider.parts.thumb({ 6305 dom: dom$1('<div class="$prefix}-slider-thumb"></div>'), 6306 behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })]) 6307 }) 6308 ], 6309 onChange: onChange, 6310 onDragStart: function (slider, thumb) { 6311 Toggling.on(thumb); 6312 }, 6313 onDragEnd: function (slider, thumb) { 6314 Toggling.off(thumb); 6315 }, 6316 onInit: onInit, 6317 stepSize: 10, 6318 model: { 6319 mode: 'x', 6320 minX: 0, 6321 maxX: 360, 6322 getInitialValue: function () { 6323 return { x: spec$1.getInitialValue() }; 6324 } 6325 }, 6326 sliderBehaviours: derive$2([orientation(Slider.refresh)]) 6327 }); 6328 }; 6329 var makeItems$1 = function (spec) { 6330 return [makeSlider$1(spec)]; 6331 }; 6332 var sketch$8 = function (realm, editor) { 6333 var spec = { 6334 onChange: function (slider, thumb, color) { 6335 editor.undoManager.transact(function () { 6336 editor.formatter.apply('forecolor', { value: color }); 6337 editor.nodeChanged(); 6338 }); 6339 }, 6340 getInitialValue: constant$1(BLACK) 6341 }; 6342 return button(realm, 'color-levels', function () { 6343 return makeItems$1(spec); 6344 }, editor); 6345 }; 6346 6347 var candidatesArray = [ 6348 '9px', 6349 '10px', 6350 '11px', 6351 '12px', 6352 '14px', 6353 '16px', 6354 '18px', 6355 '20px', 6356 '24px', 6357 '32px', 6358 '36px' 6359 ]; 6360 var defaultSize = 'medium'; 6361 var defaultIndex = 2; 6362 var indexToSize = function (index) { 6363 return Optional.from(candidatesArray[index]); 6364 }; 6365 var sizeToIndex = function (size) { 6366 return findIndex$1(candidatesArray, function (v) { 6367 return v === size; 6368 }); 6369 }; 6370 var getRawOrComputed = function (isRoot, rawStart) { 6371 var optStart = isElement(rawStart) ? Optional.some(rawStart) : parent(rawStart).filter(isElement); 6372 return optStart.map(function (start) { 6373 var inline = closest$2(start, function (elem) { 6374 return getRaw(elem, 'font-size').isSome(); 6375 }, isRoot).bind(function (elem) { 6376 return getRaw(elem, 'font-size'); 6377 }); 6378 return inline.getOrThunk(function () { 6379 return get$8(start, 'font-size'); 6380 }); 6381 }).getOr(''); 6382 }; 6383 var getSize = function (editor) { 6384 var node = editor.selection.getStart(); 6385 var elem = SugarElement.fromDom(node); 6386 var root = SugarElement.fromDom(editor.getBody()); 6387 var isRoot = function (e) { 6388 return eq(root, e); 6389 }; 6390 var elemSize = getRawOrComputed(isRoot, elem); 6391 return find$2(candidatesArray, function (size) { 6392 return elemSize === size; 6393 }).getOr(defaultSize); 6394 }; 6395 var applySize = function (editor, value) { 6396 var currentValue = getSize(editor); 6397 if (currentValue !== value) { 6398 editor.execCommand('fontSize', false, value); 6399 } 6400 }; 6401 var get$4 = function (editor) { 6402 var size = getSize(editor); 6403 return sizeToIndex(size).getOr(defaultIndex); 6404 }; 6405 var apply = function (editor, index) { 6406 indexToSize(index).each(function (size) { 6407 applySize(editor, size); 6408 }); 6409 }; 6410 var candidates = constant$1(candidatesArray); 6411 6412 var schema$9 = objOfOnly([ 6413 required$1('getInitialValue'), 6414 required$1('onChange'), 6415 required$1('category'), 6416 required$1('sizes') 6417 ]); 6418 var sketch$7 = function (rawSpec) { 6419 var spec$1 = asRawOrDie$1('SizeSlider', schema$9, rawSpec); 6420 var isValidValue = function (valueIndex) { 6421 return valueIndex >= 0 && valueIndex < spec$1.sizes.length; 6422 }; 6423 var onChange = function (slider, thumb, valueIndex) { 6424 var index = valueIndex.x(); 6425 if (isValidValue(index)) { 6426 spec$1.onChange(index); 6427 } 6428 }; 6429 return Slider.sketch({ 6430 dom: { 6431 tag: 'div', 6432 classes: [ 6433 resolve('slider-' + spec$1.category + '-size-container'), 6434 resolve('slider'), 6435 resolve('slider-size-container') 6436 ] 6437 }, 6438 onChange: onChange, 6439 onDragStart: function (slider, thumb) { 6440 Toggling.on(thumb); 6441 }, 6442 onDragEnd: function (slider, thumb) { 6443 Toggling.off(thumb); 6444 }, 6445 model: { 6446 mode: 'x', 6447 minX: 0, 6448 maxX: spec$1.sizes.length - 1, 6449 getInitialValue: function () { 6450 return { x: spec$1.getInitialValue() }; 6451 } 6452 }, 6453 stepSize: 1, 6454 snapToGrid: true, 6455 sliderBehaviours: derive$2([orientation(Slider.refresh)]), 6456 components: [ 6457 Slider.parts.spectrum({ 6458 dom: dom$1('<div class="$prefix}-slider-size-container"></div>'), 6459 components: [spec('<div class="$prefix}-slider-size-line"></div>')] 6460 }), 6461 Slider.parts.thumb({ 6462 dom: dom$1('<div class="$prefix}-slider-thumb"></div>'), 6463 behaviours: derive$2([Toggling.config({ toggleClass: resolve('thumb-active') })]) 6464 }) 6465 ] 6466 }); 6467 }; 6468 6469 var sizes = candidates(); 6470 var makeSlider = function (spec) { 6471 return sketch$7({ 6472 onChange: spec.onChange, 6473 sizes: sizes, 6474 category: 'font', 6475 getInitialValue: spec.getInitialValue 6476 }); 6477 }; 6478 var makeItems = function (spec$1) { 6479 return [ 6480 spec('<span class="$prefix}-toolbar-button $prefix}-icon-small-font $prefix}-icon"></span>'), 6481 makeSlider(spec$1), 6482 spec('<span class="$prefix}-toolbar-button $prefix}-icon-large-font $prefix}-icon"></span>') 6483 ]; 6484 }; 6485 var sketch$6 = function (realm, editor) { 6486 var spec = { 6487 onChange: function (value) { 6488 apply(editor, value); 6489 }, 6490 getInitialValue: function () { 6491 return get$4(editor); 6492 } 6493 }; 6494 return button(realm, 'font-size', function () { 6495 return makeItems(spec); 6496 }, editor); 6497 }; 6498 6499 var record = function (spec) { 6500 var uid = isSketchSpec$1(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$2('memento'); 6501 var get = function (anyInSystem) { 6502 return anyInSystem.getSystem().getByUid(uid).getOrDie(); 6503 }; 6504 var getOpt = function (anyInSystem) { 6505 return anyInSystem.getSystem().getByUid(uid).toOptional(); 6506 }; 6507 var asSpec = function () { 6508 return __assign(__assign({}, spec), { uid: uid }); 6509 }; 6510 return { 6511 get: get, 6512 getOpt: getOpt, 6513 asSpec: asSpec 6514 }; 6515 }; 6516 6517 var exports$1 = {}, module = { exports: exports$1 }; 6518 (function (define, exports, module, require) { 6519 (function (global, factory) { 6520 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()); 6521 }(this, function () { 6522 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; 6523 var promise = { exports: {} }; 6524 (function (module) { 6525 (function (root) { 6526 var setTimeoutFunc = setTimeout; 6527 function noop() { 6528 } 6529 function bind(fn, thisArg) { 6530 return function () { 6531 fn.apply(thisArg, arguments); 6532 }; 6533 } 6534 function Promise(fn) { 6535 if (typeof this !== 'object') 6536 throw new TypeError('Promises must be constructed via new'); 6537 if (typeof fn !== 'function') 6538 throw new TypeError('not a function'); 6539 this._state = 0; 6540 this._handled = false; 6541 this._value = undefined; 6542 this._deferreds = []; 6543 doResolve(fn, this); 6544 } 6545 function handle(self, deferred) { 6546 while (self._state === 3) { 6547 self = self._value; 6548 } 6549 if (self._state === 0) { 6550 self._deferreds.push(deferred); 6551 return; 6552 } 6553 self._handled = true; 6554 Promise._immediateFn(function () { 6555 var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; 6556 if (cb === null) { 6557 (self._state === 1 ? resolve : reject)(deferred.promise, self._value); 6558 return; 6559 } 6560 var ret; 6561 try { 6562 ret = cb(self._value); 6563 } catch (e) { 6564 reject(deferred.promise, e); 6565 return; 6566 } 6567 resolve(deferred.promise, ret); 6568 }); 6569 } 6570 function resolve(self, newValue) { 6571 try { 6572 if (newValue === self) 6573 throw new TypeError('A promise cannot be resolved with itself.'); 6574 if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { 6575 var then = newValue.then; 6576 if (newValue instanceof Promise) { 6577 self._state = 3; 6578 self._value = newValue; 6579 finale(self); 6580 return; 6581 } else if (typeof then === 'function') { 6582 doResolve(bind(then, newValue), self); 6583 return; 6584 } 6585 } 6586 self._state = 1; 6587 self._value = newValue; 6588 finale(self); 6589 } catch (e) { 6590 reject(self, e); 6591 } 6592 } 6593 function reject(self, newValue) { 6594 self._state = 2; 6595 self._value = newValue; 6596 finale(self); 6597 } 6598 function finale(self) { 6599 if (self._state === 2 && self._deferreds.length === 0) { 6600 Promise._immediateFn(function () { 6601 if (!self._handled) { 6602 Promise._unhandledRejectionFn(self._value); 6603 } 6604 }); 6605 } 6606 for (var i = 0, len = self._deferreds.length; i < len; i++) { 6607 handle(self, self._deferreds[i]); 6608 } 6609 self._deferreds = null; 6610 } 6611 function Handler(onFulfilled, onRejected, promise) { 6612 this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; 6613 this.onRejected = typeof onRejected === 'function' ? onRejected : null; 6614 this.promise = promise; 6615 } 6616 function doResolve(fn, self) { 6617 var done = false; 6618 try { 6619 fn(function (value) { 6620 if (done) 6621 return; 6622 done = true; 6623 resolve(self, value); 6624 }, function (reason) { 6625 if (done) 6626 return; 6627 done = true; 6628 reject(self, reason); 6629 }); 6630 } catch (ex) { 6631 if (done) 6632 return; 6633 done = true; 6634 reject(self, ex); 6635 } 6636 } 6637 Promise.prototype['catch'] = function (onRejected) { 6638 return this.then(null, onRejected); 6639 }; 6640 Promise.prototype.then = function (onFulfilled, onRejected) { 6641 var prom = new this.constructor(noop); 6642 handle(this, new Handler(onFulfilled, onRejected, prom)); 6643 return prom; 6644 }; 6645 Promise.all = function (arr) { 6646 var args = Array.prototype.slice.call(arr); 6647 return new Promise(function (resolve, reject) { 6648 if (args.length === 0) 6649 return resolve([]); 6650 var remaining = args.length; 6651 function res(i, val) { 6652 try { 6653 if (val && (typeof val === 'object' || typeof val === 'function')) { 6654 var then = val.then; 6655 if (typeof then === 'function') { 6656 then.call(val, function (val) { 6657 res(i, val); 6658 }, reject); 6659 return; 6660 } 6661 } 6662 args[i] = val; 6663 if (--remaining === 0) { 6664 resolve(args); 6665 } 6666 } catch (ex) { 6667 reject(ex); 6668 } 6669 } 6670 for (var i = 0; i < args.length; i++) { 6671 res(i, args[i]); 6672 } 6673 }); 6674 }; 6675 Promise.resolve = function (value) { 6676 if (value && typeof value === 'object' && value.constructor === Promise) { 6677 return value; 6678 } 6679 return new Promise(function (resolve) { 6680 resolve(value); 6681 }); 6682 }; 6683 Promise.reject = function (value) { 6684 return new Promise(function (resolve, reject) { 6685 reject(value); 6686 }); 6687 }; 6688 Promise.race = function (values) { 6689 return new Promise(function (resolve, reject) { 6690 for (var i = 0, len = values.length; i < len; i++) { 6691 values[i].then(resolve, reject); 6692 } 6693 }); 6694 }; 6695 Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) { 6696 setImmediate(fn); 6697 } : function (fn) { 6698 setTimeoutFunc(fn, 0); 6699 }; 6700 Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { 6701 if (typeof console !== 'undefined' && console) { 6702 console.warn('Possible Unhandled Promise Rejection:', err); 6703 } 6704 }; 6705 Promise._setImmediateFn = function _setImmediateFn(fn) { 6706 Promise._immediateFn = fn; 6707 }; 6708 Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) { 6709 Promise._unhandledRejectionFn = fn; 6710 }; 6711 if (module.exports) { 6712 module.exports = Promise; 6713 } else if (!root.Promise) { 6714 root.Promise = Promise; 6715 } 6716 }(commonjsGlobal)); 6717 }(promise)); 6718 var promisePolyfill = promise.exports; 6719 var Global = function () { 6720 if (typeof window !== 'undefined') { 6721 return window; 6722 } else { 6723 return Function('return this;')(); 6724 } 6725 }(); 6726 var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill }; 6727 return promisePolyfill_1; 6728 })); 6729 }(undefined, exports$1, module)); 6730 var Promise$1 = module.exports.boltExport; 6731 6732 var blobToDataUri = function (blob) { 6733 return new Promise$1(function (resolve) { 6734 var reader = new FileReader(); 6735 reader.onloadend = function () { 6736 resolve(reader.result); 6737 }; 6738 reader.readAsDataURL(blob); 6739 }); 6740 }; 6741 var blobToBase64$1 = function (blob) { 6742 return blobToDataUri(blob).then(function (dataUri) { 6743 return dataUri.split(',')[1]; 6744 }); 6745 }; 6746 6747 var blobToBase64 = function (blob) { 6748 return blobToBase64$1(blob); 6749 }; 6750 6751 var addImage = function (editor, blob) { 6752 blobToBase64(blob).then(function (base64) { 6753 editor.undoManager.transact(function () { 6754 var cache = editor.editorUpload.blobCache; 6755 var info = cache.create(generate$4('mceu'), blob, base64); 6756 cache.add(info); 6757 var img = editor.dom.createHTML('img', { src: info.blobUri() }); 6758 editor.insertContent(img); 6759 }); 6760 }); 6761 }; 6762 var extractBlob = function (simulatedEvent) { 6763 var event = simulatedEvent.event.raw; 6764 var files = event.target.files || event.dataTransfer.files; 6765 return Optional.from(files[0]); 6766 }; 6767 var sketch$5 = function (editor) { 6768 var pickerDom = { 6769 tag: 'input', 6770 attributes: { 6771 accept: 'image/*', 6772 type: 'file', 6773 title: '' 6774 }, 6775 styles: { 6776 visibility: 'hidden', 6777 position: 'absolute' 6778 } 6779 }; 6780 var memPicker = record({ 6781 dom: pickerDom, 6782 events: derive$3([ 6783 cutter(click()), 6784 run(change(), function (picker, simulatedEvent) { 6785 extractBlob(simulatedEvent).each(function (blob) { 6786 addImage(editor, blob); 6787 }); 6788 }) 6789 ]) 6790 }); 6791 return Button.sketch({ 6792 dom: getToolbarIconButton('image', editor), 6793 components: [memPicker.asSpec()], 6794 action: function (button) { 6795 var picker = memPicker.get(button); 6796 picker.element.dom.click(); 6797 } 6798 }); 6799 }; 6800 6801 var get$3 = function (element) { 6802 return element.dom.textContent; 6803 }; 6804 var set$3 = function (element, value) { 6805 element.dom.textContent = value; 6806 }; 6807 6808 var isNotEmpty = function (val) { 6809 return val.length > 0; 6810 }; 6811 var defaultToEmpty = function (str) { 6812 return str === undefined || str === null ? '' : str; 6813 }; 6814 var noLink = function (editor) { 6815 var text = editor.selection.getContent({ format: 'text' }); 6816 return { 6817 url: '', 6818 text: text, 6819 title: '', 6820 target: '', 6821 link: Optional.none() 6822 }; 6823 }; 6824 var fromLink = function (link) { 6825 var text = get$3(link); 6826 var url = get$b(link, 'href'); 6827 var title = get$b(link, 'title'); 6828 var target = get$b(link, 'target'); 6829 return { 6830 url: defaultToEmpty(url), 6831 text: text !== url ? defaultToEmpty(text) : '', 6832 title: defaultToEmpty(title), 6833 target: defaultToEmpty(target), 6834 link: Optional.some(link) 6835 }; 6836 }; 6837 var getInfo = function (editor) { 6838 return query(editor).fold(function () { 6839 return noLink(editor); 6840 }, function (link) { 6841 return fromLink(link); 6842 }); 6843 }; 6844 var wasSimple = function (link) { 6845 var prevHref = get$b(link, 'href'); 6846 var prevText = get$3(link); 6847 return prevHref === prevText; 6848 }; 6849 var getTextToApply = function (link, url, info) { 6850 return info.text.toOptional().filter(isNotEmpty).fold(function () { 6851 return wasSimple(link) ? Optional.some(url) : Optional.none(); 6852 }, Optional.some); 6853 }; 6854 var unlinkIfRequired = function (editor, info) { 6855 var activeLink = info.link.bind(identity); 6856 activeLink.each(function (_link) { 6857 editor.execCommand('unlink'); 6858 }); 6859 }; 6860 var getAttrs = function (url, info) { 6861 var attrs = {}; 6862 attrs.href = url; 6863 info.title.toOptional().filter(isNotEmpty).each(function (title) { 6864 attrs.title = title; 6865 }); 6866 info.target.toOptional().filter(isNotEmpty).each(function (target) { 6867 attrs.target = target; 6868 }); 6869 return attrs; 6870 }; 6871 var applyInfo = function (editor, info) { 6872 info.url.toOptional().filter(isNotEmpty).fold(function () { 6873 unlinkIfRequired(editor, info); 6874 }, function (url) { 6875 var attrs = getAttrs(url, info); 6876 var activeLink = info.link.bind(identity); 6877 activeLink.fold(function () { 6878 var text = info.text.toOptional().filter(isNotEmpty).getOr(url); 6879 editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text))); 6880 }, function (link) { 6881 var text = getTextToApply(link, url, info); 6882 setAll$1(link, attrs); 6883 text.each(function (newText) { 6884 set$3(link, newText); 6885 }); 6886 }); 6887 }); 6888 }; 6889 var query = function (editor) { 6890 var start = SugarElement.fromDom(editor.selection.getStart()); 6891 return closest$1(start, 'a'); 6892 }; 6893 6894 var platform = detect$1(); 6895 var preserve$1 = function (f, editor) { 6896 var rng = editor.selection.getRng(); 6897 f(); 6898 editor.selection.setRng(rng); 6899 }; 6900 var forAndroid = function (editor, f) { 6901 var wrapper = platform.os.isAndroid() ? preserve$1 : apply$1; 6902 wrapper(f, editor); 6903 }; 6904 6905 var events$4 = function (name, eventHandlers) { 6906 var events = derive$3(eventHandlers); 6907 return create$5({ 6908 fields: [required$1('enabled')], 6909 name: name, 6910 active: { events: constant$1(events) } 6911 }); 6912 }; 6913 var config = function (name, eventHandlers) { 6914 var me = events$4(name, eventHandlers); 6915 return { 6916 key: name, 6917 value: { 6918 config: {}, 6919 me: me, 6920 configAsRaw: constant$1({}), 6921 initialConfig: {}, 6922 state: NoState 6923 } 6924 }; 6925 }; 6926 6927 var getCurrent = function (component, composeConfig, _composeState) { 6928 return composeConfig.find(component); 6929 }; 6930 6931 var ComposeApis = /*#__PURE__*/Object.freeze({ 6932 __proto__: null, 6933 getCurrent: getCurrent 6934 }); 6935 6936 var ComposeSchema = [required$1('find')]; 6937 6938 var Composing = create$5({ 6939 fields: ComposeSchema, 6940 name: 'composing', 6941 apis: ComposeApis 6942 }); 6943 6944 var factory$4 = function (detail) { 6945 var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']); 6946 return { 6947 uid: detail.uid, 6948 dom: __assign({ 6949 tag: 'div', 6950 attributes: __assign({ role: 'presentation' }, attributes) 6951 }, domWithoutAttributes), 6952 components: detail.components, 6953 behaviours: get$6(detail.containerBehaviours), 6954 events: detail.events, 6955 domModification: detail.domModification, 6956 eventOrder: detail.eventOrder 6957 }; 6958 }; 6959 var Container = single({ 6960 name: 'Container', 6961 factory: factory$4, 6962 configFields: [ 6963 defaulted('components', []), 6964 field$1('containerBehaviours', []), 6965 defaulted('events', {}), 6966 defaulted('domModification', {}), 6967 defaulted('eventOrder', {}) 6968 ] 6969 }); 6970 6971 var factory$3 = function (detail) { 6972 return { 6973 uid: detail.uid, 6974 dom: detail.dom, 6975 behaviours: SketchBehaviours.augment(detail.dataBehaviours, [ 6976 Representing.config({ 6977 store: { 6978 mode: 'memory', 6979 initialValue: detail.getInitialValue() 6980 } 6981 }), 6982 Composing.config({ find: Optional.some }) 6983 ]), 6984 events: derive$3([runOnAttached(function (component, _simulatedEvent) { 6985 Representing.setValue(component, detail.getInitialValue()); 6986 })]) 6987 }; 6988 }; 6989 var DataField = single({ 6990 name: 'DataField', 6991 factory: factory$3, 6992 configFields: [ 6993 required$1('uid'), 6994 required$1('dom'), 6995 required$1('getInitialValue'), 6996 SketchBehaviours.field('dataBehaviours', [ 6997 Representing, 6998 Composing 6999 ]) 7000 ] 7001 }); 7002 7003 var get$2 = function (element) { 7004 return element.dom.value; 7005 }; 7006 var set$2 = function (element, value) { 7007 if (value === undefined) { 7008 throw new Error('Value.set was undefined'); 7009 } 7010 element.dom.value = value; 7011 }; 7012 7013 var schema$8 = constant$1([ 7014 option('data'), 7015 defaulted('inputAttributes', {}), 7016 defaulted('inputStyles', {}), 7017 defaulted('tag', 'input'), 7018 defaulted('inputClasses', []), 7019 onHandler('onSetValue'), 7020 defaulted('styles', {}), 7021 defaulted('eventOrder', {}), 7022 field$1('inputBehaviours', [ 7023 Representing, 7024 Focusing 7025 ]), 7026 defaulted('selectOnFocus', true) 7027 ]); 7028 var focusBehaviours = function (detail) { 7029 return derive$2([Focusing.config({ 7030 onFocus: !detail.selectOnFocus ? noop : function (component) { 7031 var input = component.element; 7032 var value = get$2(input); 7033 input.dom.setSelectionRange(0, value.length); 7034 } 7035 })]); 7036 }; 7037 var behaviours = function (detail) { 7038 return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({ 7039 store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) { 7040 return { initialValue: data }; 7041 }).getOr({})), { 7042 getValue: function (input) { 7043 return get$2(input.element); 7044 }, 7045 setValue: function (input, data) { 7046 var current = get$2(input.element); 7047 if (current !== data) { 7048 set$2(input.element, data); 7049 } 7050 } 7051 }), 7052 onSetValue: detail.onSetValue 7053 })])); 7054 }; 7055 var dom = function (detail) { 7056 return { 7057 tag: detail.tag, 7058 attributes: __assign({ type: 'text' }, detail.inputAttributes), 7059 styles: detail.inputStyles, 7060 classes: detail.inputClasses 7061 }; 7062 }; 7063 7064 var factory$2 = function (detail, _spec) { 7065 return { 7066 uid: detail.uid, 7067 dom: dom(detail), 7068 components: [], 7069 behaviours: behaviours(detail), 7070 eventOrder: detail.eventOrder 7071 }; 7072 }; 7073 var Input = single({ 7074 name: 'Input', 7075 configFields: schema$8(), 7076 factory: factory$2 7077 }); 7078 7079 var exhibit$2 = function (base, tabConfig) { 7080 return nu$3({ 7081 attributes: wrapAll([{ 7082 key: tabConfig.tabAttr, 7083 value: 'true' 7084 }]) 7085 }); 7086 }; 7087 7088 var ActiveTabstopping = /*#__PURE__*/Object.freeze({ 7089 __proto__: null, 7090 exhibit: exhibit$2 7091 }); 7092 7093 var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')]; 7094 7095 var Tabstopping = create$5({ 7096 fields: TabstopSchema, 7097 name: 'tabstopping', 7098 active: ActiveTabstopping 7099 }); 7100 7101 var global$3 = tinymce.util.Tools.resolve('tinymce.util.I18n'); 7102 7103 var clearInputBehaviour = 'input-clearing'; 7104 var field = function (name, placeholder) { 7105 var inputSpec = record(Input.sketch({ 7106 inputAttributes: { placeholder: global$3.translate(placeholder) }, 7107 onSetValue: function (input, _data) { 7108 emit(input, input$1()); 7109 }, 7110 inputBehaviours: derive$2([ 7111 Composing.config({ find: Optional.some }), 7112 Tabstopping.config({}), 7113 Keying.config({ mode: 'execution' }) 7114 ]), 7115 selectOnFocus: false 7116 })); 7117 var buttonSpec = record(Button.sketch({ 7118 dom: dom$1('<button class="$prefix}-input-container-x $prefix}-icon-cancel-circle $prefix}-icon"></button>'), 7119 action: function (button) { 7120 var input = inputSpec.get(button); 7121 Representing.setValue(input, ''); 7122 } 7123 })); 7124 return { 7125 name: name, 7126 spec: Container.sketch({ 7127 dom: dom$1('<div class="$prefix}-input-container"></div>'), 7128 components: [ 7129 inputSpec.asSpec(), 7130 buttonSpec.asSpec() 7131 ], 7132 containerBehaviours: derive$2([ 7133 Toggling.config({ toggleClass: resolve('input-container-empty') }), 7134 Composing.config({ 7135 find: function (comp) { 7136 return Optional.some(inputSpec.get(comp)); 7137 } 7138 }), 7139 config(clearInputBehaviour, [run(input$1(), function (iContainer) { 7140 var input = inputSpec.get(iContainer); 7141 var val = Representing.getValue(input); 7142 var f = val.length > 0 ? Toggling.off : Toggling.on; 7143 f(iContainer); 7144 })]) 7145 ]) 7146 }) 7147 }; 7148 }; 7149 var hidden = function (name) { 7150 return { 7151 name: name, 7152 spec: DataField.sketch({ 7153 dom: { 7154 tag: 'span', 7155 styles: { display: 'none' } 7156 }, 7157 getInitialValue: function () { 7158 return Optional.none(); 7159 } 7160 }) 7161 }; 7162 }; 7163 7164 var nativeDisabled = [ 7165 'input', 7166 'button', 7167 'textarea', 7168 'select' 7169 ]; 7170 var onLoad = function (component, disableConfig, disableState) { 7171 var f = disableConfig.disabled() ? disable : enable; 7172 f(component, disableConfig); 7173 }; 7174 var hasNative = function (component, config) { 7175 return config.useNative === true && contains$1(nativeDisabled, name$1(component.element)); 7176 }; 7177 var nativeIsDisabled = function (component) { 7178 return has$1(component.element, 'disabled'); 7179 }; 7180 var nativeDisable = function (component) { 7181 set$8(component.element, 'disabled', 'disabled'); 7182 }; 7183 var nativeEnable = function (component) { 7184 remove$6(component.element, 'disabled'); 7185 }; 7186 var ariaIsDisabled = function (component) { 7187 return get$b(component.element, 'aria-disabled') === 'true'; 7188 }; 7189 var ariaDisable = function (component) { 7190 set$8(component.element, 'aria-disabled', 'true'); 7191 }; 7192 var ariaEnable = function (component) { 7193 set$8(component.element, 'aria-disabled', 'false'); 7194 }; 7195 var disable = function (component, disableConfig, _disableState) { 7196 disableConfig.disableClass.each(function (disableClass) { 7197 add$1(component.element, disableClass); 7198 }); 7199 var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable; 7200 f(component); 7201 disableConfig.onDisabled(component); 7202 }; 7203 var enable = function (component, disableConfig, _disableState) { 7204 disableConfig.disableClass.each(function (disableClass) { 7205 remove$3(component.element, disableClass); 7206 }); 7207 var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable; 7208 f(component); 7209 disableConfig.onEnabled(component); 7210 }; 7211 var isDisabled = function (component, disableConfig) { 7212 return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component); 7213 }; 7214 var set$1 = function (component, disableConfig, disableState, disabled) { 7215 var f = disabled ? disable : enable; 7216 f(component, disableConfig); 7217 }; 7218 7219 var DisableApis = /*#__PURE__*/Object.freeze({ 7220 __proto__: null, 7221 enable: enable, 7222 disable: disable, 7223 isDisabled: isDisabled, 7224 onLoad: onLoad, 7225 set: set$1 7226 }); 7227 7228 var exhibit$1 = function (base, disableConfig) { 7229 return nu$3({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] }); 7230 }; 7231 var events$3 = function (disableConfig, disableState) { 7232 return derive$3([ 7233 abort(execute$5(), function (component, _simulatedEvent) { 7234 return isDisabled(component, disableConfig); 7235 }), 7236 loadEvent(disableConfig, disableState, onLoad) 7237 ]); 7238 }; 7239 7240 var ActiveDisable = /*#__PURE__*/Object.freeze({ 7241 __proto__: null, 7242 exhibit: exhibit$1, 7243 events: events$3 7244 }); 7245 7246 var DisableSchema = [ 7247 defaultedFunction('disabled', never), 7248 defaulted('useNative', true), 7249 option('disableClass'), 7250 onHandler('onDisabled'), 7251 onHandler('onEnabled') 7252 ]; 7253 7254 var Disabling = create$5({ 7255 fields: DisableSchema, 7256 name: 'disabling', 7257 active: ActiveDisable, 7258 apis: DisableApis 7259 }); 7260 7261 var owner$1 = 'form'; 7262 var schema$7 = [field$1('formBehaviours', [Representing])]; 7263 var getPartName = function (name) { 7264 return '<alloy.field.' + name + '>'; 7265 }; 7266 var sketch$4 = function (fSpec) { 7267 var parts = function () { 7268 var record = []; 7269 var field = function (name, config) { 7270 record.push(name); 7271 return generateOne(owner$1, getPartName(name), config); 7272 }; 7273 return { 7274 field: field, 7275 record: constant$1(record) 7276 }; 7277 }(); 7278 var spec = fSpec(parts); 7279 var partNames = parts.record(); 7280 var fieldParts = map$2(partNames, function (n) { 7281 return required({ 7282 name: n, 7283 pname: getPartName(n) 7284 }); 7285 }); 7286 return composite$1(owner$1, schema$7, fieldParts, make$4, spec); 7287 }; 7288 var toResult = function (o, e) { 7289 return o.fold(function () { 7290 return Result.error(e); 7291 }, Result.value); 7292 }; 7293 var make$4 = function (detail, components) { 7294 return { 7295 uid: detail.uid, 7296 dom: detail.dom, 7297 components: components, 7298 behaviours: augment(detail.formBehaviours, [Representing.config({ 7299 store: { 7300 mode: 'manual', 7301 getValue: function (form) { 7302 var resPs = getAllParts(form, detail); 7303 return map$1(resPs, function (resPThunk, pName) { 7304 return resPThunk().bind(function (v) { 7305 var opt = Composing.getCurrent(v); 7306 return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element))); 7307 }).map(Representing.getValue); 7308 }); 7309 }, 7310 setValue: function (form, values) { 7311 each(values, function (newValue, key) { 7312 getPart(form, detail, key).each(function (wrapper) { 7313 Composing.getCurrent(wrapper).each(function (field) { 7314 Representing.setValue(field, newValue); 7315 }); 7316 }); 7317 }); 7318 } 7319 } 7320 })]), 7321 apis: { 7322 getField: function (form, key) { 7323 return getPart(form, detail, key).bind(Composing.getCurrent); 7324 } 7325 } 7326 }; 7327 }; 7328 var Form = { 7329 getField: makeApi(function (apis, component, key) { 7330 return apis.getField(component, key); 7331 }), 7332 sketch: sketch$4 7333 }; 7334 7335 var SWIPING_LEFT = 1; 7336 var SWIPING_RIGHT = -1; 7337 var SWIPING_NONE = 0; 7338 var init$3 = function (xValue) { 7339 return { 7340 xValue: xValue, 7341 points: [] 7342 }; 7343 }; 7344 var move = function (model, xValue) { 7345 if (xValue === model.xValue) { 7346 return model; 7347 } 7348 var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT; 7349 var newPoint = { 7350 direction: currentDirection, 7351 xValue: xValue 7352 }; 7353 var priorPoints = function () { 7354 if (model.points.length === 0) { 7355 return []; 7356 } else { 7357 var prev = model.points[model.points.length - 1]; 7358 return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points; 7359 } 7360 }(); 7361 return { 7362 xValue: xValue, 7363 points: priorPoints.concat([newPoint]) 7364 }; 7365 }; 7366 var complete = function (model) { 7367 if (model.points.length === 0) { 7368 return SWIPING_NONE; 7369 } else { 7370 var firstDirection = model.points[0].direction; 7371 var lastDirection = model.points[model.points.length - 1].direction; 7372 return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE; 7373 } 7374 }; 7375 7376 var sketch$3 = function (rawSpec) { 7377 var navigateEvent = 'navigateEvent'; 7378 var wrapperAdhocEvents = 'serializer-wrapper-events'; 7379 var formAdhocEvents = 'form-events'; 7380 var schema = objOf([ 7381 required$1('fields'), 7382 defaulted('maxFieldIndex', rawSpec.fields.length - 1), 7383 required$1('onExecute'), 7384 required$1('getInitialValue'), 7385 customField('state', function () { 7386 return { 7387 dialogSwipeState: value(), 7388 currentScreen: Cell(0) 7389 }; 7390 }) 7391 ]); 7392 var spec$1 = asRawOrDie$1('SerialisedDialog', schema, rawSpec); 7393 var navigationButton = function (direction, directionName, enabled) { 7394 return Button.sketch({ 7395 dom: dom$1('<span class="$prefix}-icon-' + directionName + ' $prefix}-icon"></span>'), 7396 action: function (button) { 7397 emitWith(button, navigateEvent, { direction: direction }); 7398 }, 7399 buttonBehaviours: derive$2([Disabling.config({ 7400 disableClass: resolve('toolbar-navigation-disabled'), 7401 disabled: function () { 7402 return !enabled; 7403 } 7404 })]) 7405 }); 7406 }; 7407 var reposition = function (dialog, message) { 7408 descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) { 7409 set$5(parent, 'left', -spec$1.state.currentScreen.get() * message.width + 'px'); 7410 }); 7411 }; 7412 var navigate = function (dialog, direction) { 7413 var screens = descendants(dialog.element, '.' + resolve('serialised-dialog-screen')); 7414 descendant(dialog.element, '.' + resolve('serialised-dialog-chain')).each(function (parent) { 7415 if (spec$1.state.currentScreen.get() + direction >= 0 && spec$1.state.currentScreen.get() + direction < screens.length) { 7416 getRaw(parent, 'left').each(function (left) { 7417 var currentLeft = parseInt(left, 10); 7418 var w = get$5(screens[0]); 7419 set$5(parent, 'left', currentLeft - direction * w + 'px'); 7420 }); 7421 spec$1.state.currentScreen.set(spec$1.state.currentScreen.get() + direction); 7422 } 7423 }); 7424 }; 7425 var focusInput = function (dialog) { 7426 var inputs = descendants(dialog.element, 'input'); 7427 var optInput = Optional.from(inputs[spec$1.state.currentScreen.get()]); 7428 optInput.each(function (input) { 7429 dialog.getSystem().getByDom(input).each(function (inputComp) { 7430 dispatchFocus(dialog, inputComp.element); 7431 }); 7432 }); 7433 var dotitems = memDots.get(dialog); 7434 Highlighting.highlightAt(dotitems, spec$1.state.currentScreen.get()); 7435 }; 7436 var resetState = function () { 7437 spec$1.state.currentScreen.set(0); 7438 spec$1.state.dialogSwipeState.clear(); 7439 }; 7440 var memForm = record(Form.sketch(function (parts) { 7441 return { 7442 dom: dom$1('<div class="$prefix}-serialised-dialog"></div>'), 7443 components: [Container.sketch({ 7444 dom: dom$1('<div class="$prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'), 7445 components: map$2(spec$1.fields, function (field, i) { 7446 return i <= spec$1.maxFieldIndex ? Container.sketch({ 7447 dom: dom$1('<div class="$prefix}-serialised-dialog-screen"></div>'), 7448 components: [ 7449 navigationButton(-1, 'previous', i > 0), 7450 parts.field(field.name, field.spec), 7451 navigationButton(+1, 'next', i < spec$1.maxFieldIndex) 7452 ] 7453 }) : parts.field(field.name, field.spec); 7454 }) 7455 })], 7456 formBehaviours: derive$2([ 7457 orientation(function (dialog, message) { 7458 reposition(dialog, message); 7459 }), 7460 Keying.config({ 7461 mode: 'special', 7462 focusIn: function (dialog, _specialInfo) { 7463 focusInput(dialog); 7464 }, 7465 onTab: function (dialog, _specialInfo) { 7466 navigate(dialog, +1); 7467 return Optional.some(true); 7468 }, 7469 onShiftTab: function (dialog, _specialInfo) { 7470 navigate(dialog, -1); 7471 return Optional.some(true); 7472 } 7473 }), 7474 config(formAdhocEvents, [ 7475 runOnAttached(function (dialog, _simulatedEvent) { 7476 resetState(); 7477 var dotitems = memDots.get(dialog); 7478 Highlighting.highlightFirst(dotitems); 7479 spec$1.getInitialValue(dialog).each(function (v) { 7480 Representing.setValue(dialog, v); 7481 }); 7482 }), 7483 runOnExecute(spec$1.onExecute), 7484 run(transitionend(), function (dialog, simulatedEvent) { 7485 var event = simulatedEvent.event; 7486 if (event.raw.propertyName === 'left') { 7487 focusInput(dialog); 7488 } 7489 }), 7490 run(navigateEvent, function (dialog, simulatedEvent) { 7491 var event = simulatedEvent.event; 7492 var direction = event.direction; 7493 navigate(dialog, direction); 7494 }) 7495 ]) 7496 ]) 7497 }; 7498 })); 7499 var memDots = record({ 7500 dom: dom$1('<div class="$prefix}-dot-container"></div>'), 7501 behaviours: derive$2([Highlighting.config({ 7502 highlightClass: resolve('dot-active'), 7503 itemClass: resolve('dot-item') 7504 })]), 7505 components: bind$3(spec$1.fields, function (_f, i) { 7506 return i <= spec$1.maxFieldIndex ? [spec('<div class="$prefix}-dot-item $prefix}-icon-full-dot $prefix}-icon"></div>')] : []; 7507 }) 7508 }); 7509 return { 7510 dom: dom$1('<div class="$prefix}-serializer-wrapper"></div>'), 7511 components: [ 7512 memForm.asSpec(), 7513 memDots.asSpec() 7514 ], 7515 behaviours: derive$2([ 7516 Keying.config({ 7517 mode: 'special', 7518 focusIn: function (wrapper) { 7519 var form = memForm.get(wrapper); 7520 Keying.focusIn(form); 7521 } 7522 }), 7523 config(wrapperAdhocEvents, [ 7524 run(touchstart(), function (_wrapper, simulatedEvent) { 7525 var event = simulatedEvent.event; 7526 spec$1.state.dialogSwipeState.set(init$3(event.raw.touches[0].clientX)); 7527 }), 7528 run(touchmove(), function (_wrapper, simulatedEvent) { 7529 var event = simulatedEvent.event; 7530 spec$1.state.dialogSwipeState.on(function (state) { 7531 simulatedEvent.event.prevent(); 7532 spec$1.state.dialogSwipeState.set(move(state, event.raw.touches[0].clientX)); 7533 }); 7534 }), 7535 run(touchend(), function (wrapper, _simulatedEvent) { 7536 spec$1.state.dialogSwipeState.on(function (state) { 7537 var dialog = memForm.get(wrapper); 7538 var direction = -1 * complete(state); 7539 navigate(dialog, direction); 7540 }); 7541 }) 7542 ]) 7543 ]) 7544 }; 7545 }; 7546 7547 var getGroups = cached(function (realm, editor) { 7548 return [{ 7549 label: 'the link group', 7550 items: [sketch$3({ 7551 fields: [ 7552 field('url', 'Type or paste URL'), 7553 field('text', 'Link text'), 7554 field('title', 'Link title'), 7555 field('target', 'Link target'), 7556 hidden('link') 7557 ], 7558 maxFieldIndex: [ 7559 'url', 7560 'text', 7561 'title', 7562 'target' 7563 ].length - 1, 7564 getInitialValue: function () { 7565 return Optional.some(getInfo(editor)); 7566 }, 7567 onExecute: function (dialog, _simulatedEvent) { 7568 var info = Representing.getValue(dialog); 7569 applyInfo(editor, info); 7570 realm.restoreToolbar(); 7571 editor.focus(); 7572 } 7573 })] 7574 }]; 7575 }); 7576 var sketch$2 = function (realm, editor) { 7577 return forToolbarStateAction(editor, 'link', 'link', function () { 7578 var groups = getGroups(realm, editor); 7579 realm.setContextToolbar(groups); 7580 forAndroid(editor, function () { 7581 realm.focusToolbar(); 7582 }); 7583 query(editor).each(function (link) { 7584 editor.selection.select(link.dom); 7585 }); 7586 }); 7587 }; 7588 7589 var isRecursive = function (component, originator, target) { 7590 return eq(originator, component.element) && !eq(originator, target); 7591 }; 7592 var events$2 = derive$3([can(focus$4(), function (component, simulatedEvent) { 7593 var event = simulatedEvent.event; 7594 var originator = event.originator; 7595 var target = event.target; 7596 if (isRecursive(component, originator, target)) { 7597 console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers'); 7598 return false; 7599 } else { 7600 return true; 7601 } 7602 })]); 7603 7604 var DefaultEvents = /*#__PURE__*/Object.freeze({ 7605 __proto__: null, 7606 events: events$2 7607 }); 7608 7609 var make$3 = identity; 7610 7611 var NoContextApi = function (getComp) { 7612 var getMessage = function (event) { 7613 return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : ''); 7614 }; 7615 var fail = function (event) { 7616 return function () { 7617 throw new Error(getMessage(event)); 7618 }; 7619 }; 7620 var warn = function (event) { 7621 return function () { 7622 console.warn(getMessage(event)); 7623 }; 7624 }; 7625 return { 7626 debugInfo: constant$1('fake'), 7627 triggerEvent: warn('triggerEvent'), 7628 triggerFocus: warn('triggerFocus'), 7629 triggerEscape: warn('triggerEscape'), 7630 broadcast: warn('broadcast'), 7631 broadcastOn: warn('broadcastOn'), 7632 broadcastEvent: warn('broadcastEvent'), 7633 build: fail('build'), 7634 addToWorld: fail('addToWorld'), 7635 removeFromWorld: fail('removeFromWorld'), 7636 addToGui: fail('addToGui'), 7637 removeFromGui: fail('removeFromGui'), 7638 getByUid: fail('getByUid'), 7639 getByDom: fail('getByDom'), 7640 isConnected: never 7641 }; 7642 }; 7643 var singleton = NoContextApi(); 7644 7645 var generateFrom$1 = function (spec, all) { 7646 var schema = map$2(all, function (a) { 7647 return optionObjOf(a.name(), [ 7648 required$1('config'), 7649 defaulted('state', NoState) 7650 ]); 7651 }); 7652 var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) { 7653 throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2)); 7654 }, identity); 7655 return { 7656 list: all, 7657 data: map$1(validated, function (optBlobThunk) { 7658 var output = optBlobThunk.map(function (blob) { 7659 return { 7660 config: blob.config, 7661 state: blob.state.init(blob.config) 7662 }; 7663 }); 7664 return constant$1(output); 7665 }) 7666 }; 7667 }; 7668 var getBehaviours$1 = function (bData) { 7669 return bData.list; 7670 }; 7671 var getData = function (bData) { 7672 return bData.data; 7673 }; 7674 7675 var byInnerKey = function (data, tuple) { 7676 var r = {}; 7677 each(data, function (detail, key) { 7678 each(detail, function (value, indexKey) { 7679 var chain = get$c(r, indexKey).getOr([]); 7680 r[indexKey] = chain.concat([tuple(key, value)]); 7681 }); 7682 }); 7683 return r; 7684 }; 7685 7686 var combine$1 = function (info, baseMod, behaviours, base) { 7687 var modsByBehaviour = __assign({}, baseMod); 7688 each$1(behaviours, function (behaviour) { 7689 modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base); 7690 }); 7691 var byAspect = byInnerKey(modsByBehaviour, function (name, modification) { 7692 return { 7693 name: name, 7694 modification: modification 7695 }; 7696 }); 7697 var combineObjects = function (objects) { 7698 return foldr(objects, function (b, a) { 7699 return __assign(__assign({}, a.modification), b); 7700 }, {}); 7701 }; 7702 var combinedClasses = foldr(byAspect.classes, function (b, a) { 7703 return a.modification.concat(b); 7704 }, []); 7705 var combinedAttributes = combineObjects(byAspect.attributes); 7706 var combinedStyles = combineObjects(byAspect.styles); 7707 return nu$3({ 7708 classes: combinedClasses, 7709 attributes: combinedAttributes, 7710 styles: combinedStyles 7711 }); 7712 }; 7713 7714 var sortKeys = function (label, keyName, array, order) { 7715 try { 7716 var sorted = sort(array, function (a, b) { 7717 var aKey = a[keyName]; 7718 var bKey = b[keyName]; 7719 var aIndex = order.indexOf(aKey); 7720 var bIndex = order.indexOf(bKey); 7721 if (aIndex === -1) { 7722 throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2)); 7723 } 7724 if (bIndex === -1) { 7725 throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2)); 7726 } 7727 if (aIndex < bIndex) { 7728 return -1; 7729 } else if (bIndex < aIndex) { 7730 return 1; 7731 } else { 7732 return 0; 7733 } 7734 }); 7735 return Result.value(sorted); 7736 } catch (err) { 7737 return Result.error([err]); 7738 } 7739 }; 7740 7741 var uncurried = function (handler, purpose) { 7742 return { 7743 handler: handler, 7744 purpose: purpose 7745 }; 7746 }; 7747 var curried = function (handler, purpose) { 7748 return { 7749 cHandler: handler, 7750 purpose: purpose 7751 }; 7752 }; 7753 var curryArgs = function (descHandler, extraArgs) { 7754 return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose); 7755 }; 7756 var getCurried = function (descHandler) { 7757 return descHandler.cHandler; 7758 }; 7759 7760 var behaviourTuple = function (name, handler) { 7761 return { 7762 name: name, 7763 handler: handler 7764 }; 7765 }; 7766 var nameToHandlers = function (behaviours, info) { 7767 var r = {}; 7768 each$1(behaviours, function (behaviour) { 7769 r[behaviour.name()] = behaviour.handlers(info); 7770 }); 7771 return r; 7772 }; 7773 var groupByEvents = function (info, behaviours, base) { 7774 var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info)); 7775 return byInnerKey(behaviourEvents, behaviourTuple); 7776 }; 7777 var combine = function (info, eventOrder, behaviours, base) { 7778 var byEventName = groupByEvents(info, behaviours, base); 7779 return combineGroups(byEventName, eventOrder); 7780 }; 7781 var assemble = function (rawHandler) { 7782 var handler = read$1(rawHandler); 7783 return function (component, simulatedEvent) { 7784 var rest = []; 7785 for (var _i = 2; _i < arguments.length; _i++) { 7786 rest[_i - 2] = arguments[_i]; 7787 } 7788 var args = [ 7789 component, 7790 simulatedEvent 7791 ].concat(rest); 7792 if (handler.abort.apply(undefined, args)) { 7793 simulatedEvent.stop(); 7794 } else if (handler.can.apply(undefined, args)) { 7795 handler.run.apply(undefined, args); 7796 } 7797 }; 7798 }; 7799 var missingOrderError = function (eventName, tuples) { 7800 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) { 7801 return c.name; 7802 }), null, 2)]); 7803 }; 7804 var fuse = function (tuples, eventOrder, eventName) { 7805 var order = eventOrder[eventName]; 7806 if (!order) { 7807 return missingOrderError(eventName, tuples); 7808 } else { 7809 return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) { 7810 var handlers = map$2(sortedTuples, function (tuple) { 7811 return tuple.handler; 7812 }); 7813 return fuse$1(handlers); 7814 }); 7815 } 7816 }; 7817 var combineGroups = function (byEventName, eventOrder) { 7818 var r = mapToArray(byEventName, function (tuples, eventName) { 7819 var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName); 7820 return combined.map(function (handler) { 7821 var assembled = assemble(handler); 7822 var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) { 7823 return exists(tuples, function (t) { 7824 return t.name === o; 7825 }); 7826 }).join(' > ') : tuples[0].name; 7827 return wrap(eventName, uncurried(assembled, purpose)); 7828 }); 7829 }); 7830 return consolidate(r, {}); 7831 }; 7832 7833 var _a; 7834 var baseBehaviour = 'alloy.base.behaviour'; 7835 var schema$6 = objOf([ 7836 field$2('dom', 'dom', required$2(), objOf([ 7837 required$1('tag'), 7838 defaulted('styles', {}), 7839 defaulted('classes', []), 7840 defaulted('attributes', {}), 7841 option('value'), 7842 option('innerHtml') 7843 ])), 7844 required$1('components'), 7845 required$1('uid'), 7846 defaulted('events', {}), 7847 defaulted('apis', {}), 7848 field$2('eventOrder', 'eventOrder', mergeWith((_a = {}, _a[execute$5()] = [ 7849 'disabling', 7850 baseBehaviour, 7851 'toggling', 7852 'typeaheadevents' 7853 ], _a[focus$4()] = [ 7854 baseBehaviour, 7855 'focusing', 7856 'keying' 7857 ], _a[systemInit()] = [ 7858 baseBehaviour, 7859 'disabling', 7860 'toggling', 7861 'representing' 7862 ], _a[input$1()] = [ 7863 baseBehaviour, 7864 'representing', 7865 'streaming', 7866 'invalidating' 7867 ], _a[detachedFromDom()] = [ 7868 baseBehaviour, 7869 'representing', 7870 'item-events', 7871 'tooltipping' 7872 ], _a[mousedown()] = [ 7873 'focusing', 7874 baseBehaviour, 7875 'item-type-events' 7876 ], _a[touchstart()] = [ 7877 'focusing', 7878 baseBehaviour, 7879 'item-type-events' 7880 ], _a[mouseover()] = [ 7881 'item-type-events', 7882 'tooltipping' 7883 ], _a[receive$1()] = [ 7884 'receiving', 7885 'reflecting', 7886 'tooltipping' 7887 ], _a)), anyValue()), 7888 option('domModification') 7889 ]); 7890 var toInfo = function (spec) { 7891 return asRaw('custom.definition', schema$6, spec); 7892 }; 7893 var toDefinition = function (detail) { 7894 return __assign(__assign({}, detail.dom), { 7895 uid: detail.uid, 7896 domChildren: map$2(detail.components, function (comp) { 7897 return comp.element; 7898 }) 7899 }); 7900 }; 7901 var toModification = function (detail) { 7902 return detail.domModification.fold(function () { 7903 return nu$3({}); 7904 }, nu$3); 7905 }; 7906 var toEvents = function (info) { 7907 return info.events; 7908 }; 7909 7910 var add = function (element, classes) { 7911 each$1(classes, function (x) { 7912 add$1(element, x); 7913 }); 7914 }; 7915 var remove$1 = function (element, classes) { 7916 each$1(classes, function (x) { 7917 remove$3(element, x); 7918 }); 7919 }; 7920 7921 var renderToDom = function (definition) { 7922 var subject = SugarElement.fromTag(definition.tag); 7923 setAll$1(subject, definition.attributes); 7924 add(subject, definition.classes); 7925 setAll(subject, definition.styles); 7926 definition.innerHtml.each(function (html) { 7927 return set$7(subject, html); 7928 }); 7929 var children = definition.domChildren; 7930 append$1(subject, children); 7931 definition.value.each(function (value) { 7932 set$2(subject, value); 7933 }); 7934 if (!definition.uid) { 7935 debugger; 7936 } 7937 writeOnly(subject, definition.uid); 7938 return subject; 7939 }; 7940 7941 var getBehaviours = function (spec) { 7942 var behaviours = get$c(spec, 'behaviours').getOr({}); 7943 return bind$3(keys(behaviours), function (name) { 7944 var behaviour = behaviours[name]; 7945 return isNonNullable(behaviour) ? [behaviour.me] : []; 7946 }); 7947 }; 7948 var generateFrom = function (spec, all) { 7949 return generateFrom$1(spec, all); 7950 }; 7951 var generate$1 = function (spec) { 7952 var all = getBehaviours(spec); 7953 return generateFrom(spec, all); 7954 }; 7955 7956 var getDomDefinition = function (info, bList, bData) { 7957 var definition = toDefinition(info); 7958 var infoModification = toModification(info); 7959 var baseModification = { 'alloy.base.modification': infoModification }; 7960 var modification = bList.length > 0 ? combine$1(bData, baseModification, bList, definition) : infoModification; 7961 return merge(definition, modification); 7962 }; 7963 var getEvents = function (info, bList, bData) { 7964 var baseEvents = { 'alloy.base.behaviour': toEvents(info) }; 7965 return combine(bData, info.eventOrder, bList, baseEvents).getOrDie(); 7966 }; 7967 var build$2 = function (spec) { 7968 var getMe = function () { 7969 return me; 7970 }; 7971 var systemApi = Cell(singleton); 7972 var info = getOrDie(toInfo(spec)); 7973 var bBlob = generate$1(spec); 7974 var bList = getBehaviours$1(bBlob); 7975 var bData = getData(bBlob); 7976 var modDefinition = getDomDefinition(info, bList, bData); 7977 var item = renderToDom(modDefinition); 7978 var events = getEvents(info, bList, bData); 7979 var subcomponents = Cell(info.components); 7980 var connect = function (newApi) { 7981 systemApi.set(newApi); 7982 }; 7983 var disconnect = function () { 7984 systemApi.set(NoContextApi(getMe)); 7985 }; 7986 var syncComponents = function () { 7987 var children$1 = children(item); 7988 var subs = bind$3(children$1, function (child) { 7989 return systemApi.get().getByDom(child).fold(function () { 7990 return []; 7991 }, pure$2); 7992 }); 7993 subcomponents.set(subs); 7994 }; 7995 var config = function (behaviour) { 7996 var b = bData; 7997 var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () { 7998 throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2)); 7999 }; 8000 return f(); 8001 }; 8002 var hasConfigured = function (behaviour) { 8003 return isFunction(bData[behaviour.name()]); 8004 }; 8005 var getApis = function () { 8006 return info.apis; 8007 }; 8008 var readState = function (behaviourName) { 8009 return bData[behaviourName]().map(function (b) { 8010 return b.state.readState(); 8011 }).getOr('not enabled'); 8012 }; 8013 var me = { 8014 uid: spec.uid, 8015 getSystem: systemApi.get, 8016 config: config, 8017 hasConfigured: hasConfigured, 8018 spec: spec, 8019 readState: readState, 8020 getApis: getApis, 8021 connect: connect, 8022 disconnect: disconnect, 8023 element: item, 8024 syncComponents: syncComponents, 8025 components: subcomponents.get, 8026 events: events 8027 }; 8028 return me; 8029 }; 8030 8031 var buildSubcomponents = function (spec) { 8032 var components = get$c(spec, 'components').getOr([]); 8033 return map$2(components, build$1); 8034 }; 8035 var buildFromSpec = function (userSpec) { 8036 var _a = make$3(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']); 8037 var components = buildSubcomponents(spec); 8038 var completeSpec = __assign(__assign({}, spec), { 8039 events: __assign(__assign({}, DefaultEvents), specEvents), 8040 components: components 8041 }); 8042 return Result.value(build$2(completeSpec)); 8043 }; 8044 var text = function (textContent) { 8045 var element = SugarElement.fromText(textContent); 8046 return external({ element: element }); 8047 }; 8048 var external = function (spec) { 8049 var extSpec = asRawOrDie$1('external.component', objOfOnly([ 8050 required$1('element'), 8051 option('uid') 8052 ]), spec); 8053 var systemApi = Cell(NoContextApi()); 8054 var connect = function (newApi) { 8055 systemApi.set(newApi); 8056 }; 8057 var disconnect = function () { 8058 systemApi.set(NoContextApi(function () { 8059 return me; 8060 })); 8061 }; 8062 var uid = extSpec.uid.getOrThunk(function () { 8063 return generate$2('external'); 8064 }); 8065 writeOnly(extSpec.element, uid); 8066 var me = { 8067 uid: uid, 8068 getSystem: systemApi.get, 8069 config: Optional.none, 8070 hasConfigured: never, 8071 connect: connect, 8072 disconnect: disconnect, 8073 getApis: function () { 8074 return {}; 8075 }, 8076 element: extSpec.element, 8077 spec: spec, 8078 readState: constant$1('No state'), 8079 syncComponents: noop, 8080 components: constant$1([]), 8081 events: {} 8082 }; 8083 return premade$1(me); 8084 }; 8085 var uids = generate$2; 8086 var isSketchSpec = function (spec) { 8087 return has$2(spec, 'uid'); 8088 }; 8089 var build$1 = function (spec) { 8090 return getPremade(spec).getOrThunk(function () { 8091 var userSpecWithUid = isSketchSpec(spec) ? spec : __assign({ uid: uids('') }, spec); 8092 return buildFromSpec(userSpecWithUid).getOrDie(); 8093 }); 8094 }; 8095 var premade = premade$1; 8096 8097 var hoverEvent = 'alloy.item-hover'; 8098 var focusEvent = 'alloy.item-focus'; 8099 var onHover = function (item) { 8100 if (search(item.element).isNone() || Focusing.isFocused(item)) { 8101 if (!Focusing.isFocused(item)) { 8102 Focusing.focus(item); 8103 } 8104 emitWith(item, hoverEvent, { item: item }); 8105 } 8106 }; 8107 var onFocus = function (item) { 8108 emitWith(item, focusEvent, { item: item }); 8109 }; 8110 var hover = constant$1(hoverEvent); 8111 var focus$1 = constant$1(focusEvent); 8112 8113 var builder$2 = function (detail) { 8114 return { 8115 dom: detail.dom, 8116 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 } : {}) }), 8117 behaviours: SketchBehaviours.augment(detail.itemBehaviours, [ 8118 detail.toggling.fold(Toggling.revoke, function (tConfig) { 8119 return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig)); 8120 }), 8121 Focusing.config({ 8122 ignore: detail.ignoreFocus, 8123 stopMousedown: detail.ignoreFocus, 8124 onFocus: function (component) { 8125 onFocus(component); 8126 } 8127 }), 8128 Keying.config({ mode: 'execution' }), 8129 Representing.config({ 8130 store: { 8131 mode: 'memory', 8132 initialValue: detail.data 8133 } 8134 }), 8135 config('item-type-events', __spreadArray(__spreadArray([], pointerEvents(), true), [ 8136 run(mouseover(), onHover), 8137 run(focusItem(), Focusing.focus) 8138 ], false)) 8139 ]), 8140 components: detail.components, 8141 eventOrder: detail.eventOrder 8142 }; 8143 }; 8144 var schema$5 = [ 8145 required$1('data'), 8146 required$1('components'), 8147 required$1('dom'), 8148 defaulted('hasSubmenu', false), 8149 option('toggling'), 8150 SketchBehaviours.field('itemBehaviours', [ 8151 Toggling, 8152 Focusing, 8153 Keying, 8154 Representing 8155 ]), 8156 defaulted('ignoreFocus', false), 8157 defaulted('domModification', {}), 8158 output('builder', builder$2), 8159 defaulted('eventOrder', {}) 8160 ]; 8161 8162 var builder$1 = function (detail) { 8163 return { 8164 dom: detail.dom, 8165 components: detail.components, 8166 events: derive$3([stopper(focusItem())]) 8167 }; 8168 }; 8169 var schema$4 = [ 8170 required$1('dom'), 8171 required$1('components'), 8172 output('builder', builder$1) 8173 ]; 8174 8175 var owner = constant$1('item-widget'); 8176 var parts$3 = constant$1([required({ 8177 name: 'widget', 8178 overrides: function (detail) { 8179 return { 8180 behaviours: derive$2([Representing.config({ 8181 store: { 8182 mode: 'manual', 8183 getValue: function (_component) { 8184 return detail.data; 8185 }, 8186 setValue: noop 8187 } 8188 })]) 8189 }; 8190 } 8191 })]); 8192 8193 var builder = function (detail) { 8194 var subs = substitutes(owner(), detail, parts$3()); 8195 var components$1 = components(owner(), detail, subs.internals()); 8196 var focusWidget = function (component) { 8197 return getPart(component, detail, 'widget').map(function (widget) { 8198 Keying.focusIn(widget); 8199 return widget; 8200 }); 8201 }; 8202 var onHorizontalArrow = function (component, simulatedEvent) { 8203 return inside(simulatedEvent.event.target) ? Optional.none() : function () { 8204 if (detail.autofocus) { 8205 simulatedEvent.setSource(component.element); 8206 return Optional.none(); 8207 } else { 8208 return Optional.none(); 8209 } 8210 }(); 8211 }; 8212 return { 8213 dom: detail.dom, 8214 components: components$1, 8215 domModification: detail.domModification, 8216 events: derive$3([ 8217 runOnExecute(function (component, simulatedEvent) { 8218 focusWidget(component).each(function (_widget) { 8219 simulatedEvent.stop(); 8220 }); 8221 }), 8222 run(mouseover(), onHover), 8223 run(focusItem(), function (component, _simulatedEvent) { 8224 if (detail.autofocus) { 8225 focusWidget(component); 8226 } else { 8227 Focusing.focus(component); 8228 } 8229 }) 8230 ]), 8231 behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [ 8232 Representing.config({ 8233 store: { 8234 mode: 'memory', 8235 initialValue: detail.data 8236 } 8237 }), 8238 Focusing.config({ 8239 ignore: detail.ignoreFocus, 8240 onFocus: function (component) { 8241 onFocus(component); 8242 } 8243 }), 8244 Keying.config({ 8245 mode: 'special', 8246 focusIn: detail.autofocus ? function (component) { 8247 focusWidget(component); 8248 } : revoke(), 8249 onLeft: onHorizontalArrow, 8250 onRight: onHorizontalArrow, 8251 onEscape: function (component, simulatedEvent) { 8252 if (!Focusing.isFocused(component) && !detail.autofocus) { 8253 Focusing.focus(component); 8254 return Optional.some(true); 8255 } else if (detail.autofocus) { 8256 simulatedEvent.setSource(component.element); 8257 return Optional.none(); 8258 } else { 8259 return Optional.none(); 8260 } 8261 } 8262 }) 8263 ]) 8264 }; 8265 }; 8266 var schema$3 = [ 8267 required$1('uid'), 8268 required$1('data'), 8269 required$1('components'), 8270 required$1('dom'), 8271 defaulted('autofocus', false), 8272 defaulted('ignoreFocus', false), 8273 SketchBehaviours.field('widgetBehaviours', [ 8274 Representing, 8275 Focusing, 8276 Keying 8277 ]), 8278 defaulted('domModification', {}), 8279 defaultUidsSchema(parts$3()), 8280 output('builder', builder) 8281 ]; 8282 8283 var itemSchema = choose$1('type', { 8284 widget: schema$3, 8285 item: schema$5, 8286 separator: schema$4 8287 }); 8288 var configureGrid = function (detail, movementInfo) { 8289 return { 8290 mode: 'flatgrid', 8291 selector: '.' + detail.markers.item, 8292 initSize: { 8293 numColumns: movementInfo.initSize.numColumns, 8294 numRows: movementInfo.initSize.numRows 8295 }, 8296 focusManager: detail.focusManager 8297 }; 8298 }; 8299 var configureMatrix = function (detail, movementInfo) { 8300 return { 8301 mode: 'matrix', 8302 selectors: { 8303 row: movementInfo.rowSelector, 8304 cell: '.' + detail.markers.item 8305 }, 8306 focusManager: detail.focusManager 8307 }; 8308 }; 8309 var configureMenu = function (detail, movementInfo) { 8310 return { 8311 mode: 'menu', 8312 selector: '.' + detail.markers.item, 8313 moveOnTab: movementInfo.moveOnTab, 8314 focusManager: detail.focusManager 8315 }; 8316 }; 8317 var parts$2 = constant$1([group({ 8318 factory: { 8319 sketch: function (spec) { 8320 var itemInfo = asRawOrDie$1('menu.spec item', itemSchema, spec); 8321 return itemInfo.builder(itemInfo); 8322 } 8323 }, 8324 name: 'items', 8325 unit: 'item', 8326 defaults: function (detail, u) { 8327 return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$2('item') }); 8328 }, 8329 overrides: function (detail, u) { 8330 return { 8331 type: u.type, 8332 ignoreFocus: detail.fakeFocus, 8333 domModification: { classes: [detail.markers.item] } 8334 }; 8335 } 8336 })]); 8337 var schema$2 = constant$1([ 8338 required$1('value'), 8339 required$1('items'), 8340 required$1('dom'), 8341 required$1('components'), 8342 defaulted('eventOrder', {}), 8343 field$1('menuBehaviours', [ 8344 Highlighting, 8345 Representing, 8346 Composing, 8347 Keying 8348 ]), 8349 defaultedOf('movement', { 8350 mode: 'menu', 8351 moveOnTab: true 8352 }, choose$1('mode', { 8353 grid: [ 8354 initSize(), 8355 output('config', configureGrid) 8356 ], 8357 matrix: [ 8358 output('config', configureMatrix), 8359 required$1('rowSelector') 8360 ], 8361 menu: [ 8362 defaulted('moveOnTab', true), 8363 output('config', configureMenu) 8364 ] 8365 })), 8366 itemMarkers(), 8367 defaulted('fakeFocus', false), 8368 defaulted('focusManager', dom$2()), 8369 onHandler('onHighlight') 8370 ]); 8371 8372 var focus = constant$1('alloy.menu-focus'); 8373 8374 var make$2 = function (detail, components, _spec, _externals) { 8375 return { 8376 uid: detail.uid, 8377 dom: detail.dom, 8378 markers: detail.markers, 8379 behaviours: augment(detail.menuBehaviours, [ 8380 Highlighting.config({ 8381 highlightClass: detail.markers.selectedItem, 8382 itemClass: detail.markers.item, 8383 onHighlight: detail.onHighlight 8384 }), 8385 Representing.config({ 8386 store: { 8387 mode: 'memory', 8388 initialValue: detail.value 8389 } 8390 }), 8391 Composing.config({ find: Optional.some }), 8392 Keying.config(detail.movement.config(detail, detail.movement)) 8393 ]), 8394 events: derive$3([ 8395 run(focus$1(), function (menu, simulatedEvent) { 8396 var event = simulatedEvent.event; 8397 menu.getSystem().getByDom(event.target).each(function (item) { 8398 Highlighting.highlight(menu, item); 8399 simulatedEvent.stop(); 8400 emitWith(menu, focus(), { 8401 menu: menu, 8402 item: item 8403 }); 8404 }); 8405 }), 8406 run(hover(), function (menu, simulatedEvent) { 8407 var item = simulatedEvent.event.item; 8408 Highlighting.highlight(menu, item); 8409 }) 8410 ]), 8411 components: components, 8412 eventOrder: detail.eventOrder, 8413 domModification: { attributes: { role: 'menu' } } 8414 }; 8415 }; 8416 8417 var Menu = composite({ 8418 name: 'Menu', 8419 configFields: schema$2(), 8420 partFields: parts$2(), 8421 factory: make$2 8422 }); 8423 8424 var preserve = function (f, container) { 8425 var dos = getRootNode(container); 8426 var refocus = active(dos).bind(function (focused) { 8427 var hasFocus = function (elem) { 8428 return eq(focused, elem); 8429 }; 8430 return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus); 8431 }); 8432 var result = f(container); 8433 refocus.each(function (oldFocus) { 8434 active(dos).filter(function (newFocus) { 8435 return eq(newFocus, oldFocus); 8436 }).fold(function () { 8437 focus$3(oldFocus); 8438 }, noop); 8439 }); 8440 return result; 8441 }; 8442 8443 var set = function (component, replaceConfig, replaceState, data) { 8444 preserve(function () { 8445 var newChildren = map$2(data, component.getSystem().build); 8446 replaceChildren(component, newChildren); 8447 }, component.element); 8448 }; 8449 var insert = function (component, replaceConfig, insertion, childSpec) { 8450 var child = component.getSystem().build(childSpec); 8451 attachWith(component, child, insertion); 8452 }; 8453 var append = function (component, replaceConfig, replaceState, appendee) { 8454 insert(component, replaceConfig, append$2, appendee); 8455 }; 8456 var prepend = function (component, replaceConfig, replaceState, prependee) { 8457 insert(component, replaceConfig, prepend$1, prependee); 8458 }; 8459 var remove = function (component, replaceConfig, replaceState, removee) { 8460 var children = contents(component); 8461 var foundChild = find$2(children, function (child) { 8462 return eq(removee.element, child.element); 8463 }); 8464 foundChild.each(detach); 8465 }; 8466 var contents = function (component, _replaceConfig) { 8467 return component.components(); 8468 }; 8469 var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) { 8470 var children = contents(component); 8471 return Optional.from(children[replaceeIndex]).map(function (replacee) { 8472 remove(component, replaceConfig, replaceState, replacee); 8473 replacer.each(function (r) { 8474 insert(component, replaceConfig, function (p, c) { 8475 appendAt(p, c, replaceeIndex); 8476 }, r); 8477 }); 8478 return replacee; 8479 }); 8480 }; 8481 var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) { 8482 var children = contents(component); 8483 return findIndex$1(children, replaceePred).bind(function (replaceeIndex) { 8484 return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer); 8485 }); 8486 }; 8487 8488 var ReplaceApis = /*#__PURE__*/Object.freeze({ 8489 __proto__: null, 8490 append: append, 8491 prepend: prepend, 8492 remove: remove, 8493 replaceAt: replaceAt, 8494 replaceBy: replaceBy, 8495 set: set, 8496 contents: contents 8497 }); 8498 8499 var Replacing = create$5({ 8500 fields: [], 8501 name: 'replacing', 8502 apis: ReplaceApis 8503 }); 8504 8505 var transpose = function (obj) { 8506 return tupleMap(obj, function (v, k) { 8507 return { 8508 k: v, 8509 v: k 8510 }; 8511 }); 8512 }; 8513 var trace = function (items, byItem, byMenu, finish) { 8514 return get$c(byMenu, finish).bind(function (triggerItem) { 8515 return get$c(items, triggerItem).bind(function (triggerMenu) { 8516 var rest = trace(items, byItem, byMenu, triggerMenu); 8517 return Optional.some([triggerMenu].concat(rest)); 8518 }); 8519 }).getOr([]); 8520 }; 8521 var generate = function (menus, expansions) { 8522 var items = {}; 8523 each(menus, function (menuItems, menu) { 8524 each$1(menuItems, function (item) { 8525 items[item] = menu; 8526 }); 8527 }); 8528 var byItem = expansions; 8529 var byMenu = transpose(expansions); 8530 var menuPaths = map$1(byMenu, function (_triggerItem, submenu) { 8531 return [submenu].concat(trace(items, byItem, byMenu, submenu)); 8532 }); 8533 return map$1(items, function (menu) { 8534 return get$c(menuPaths, menu).getOr([menu]); 8535 }); 8536 }; 8537 8538 var init$2 = function () { 8539 var expansions = Cell({}); 8540 var menus = Cell({}); 8541 var paths = Cell({}); 8542 var primary = value(); 8543 var directory = Cell({}); 8544 var clear = function () { 8545 expansions.set({}); 8546 menus.set({}); 8547 paths.set({}); 8548 primary.clear(); 8549 }; 8550 var isClear = function () { 8551 return primary.get().isNone(); 8552 }; 8553 var setMenuBuilt = function (menuName, built) { 8554 var _a; 8555 menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = { 8556 type: 'prepared', 8557 menu: built 8558 }, _a))); 8559 }; 8560 var setContents = function (sPrimary, sMenus, sExpansions, dir) { 8561 primary.set(sPrimary); 8562 expansions.set(sExpansions); 8563 menus.set(sMenus); 8564 directory.set(dir); 8565 var sPaths = generate(dir, sExpansions); 8566 paths.set(sPaths); 8567 }; 8568 var getTriggeringItem = function (menuValue) { 8569 return find(expansions.get(), function (v, _k) { 8570 return v === menuValue; 8571 }); 8572 }; 8573 var getTriggerData = function (menuValue, getItemByValue, path) { 8574 return getPreparedMenu(menuValue).bind(function (menu) { 8575 return getTriggeringItem(menuValue).bind(function (triggeringItemValue) { 8576 return getItemByValue(triggeringItemValue).map(function (triggeredItem) { 8577 return { 8578 triggeredMenu: menu, 8579 triggeringItem: triggeredItem, 8580 triggeringPath: path 8581 }; 8582 }); 8583 }); 8584 }); 8585 }; 8586 var getTriggeringPath = function (itemValue, getItemByValue) { 8587 var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) { 8588 return getPreparedMenu(menuValue).isSome(); 8589 }); 8590 return get$c(paths.get(), itemValue).bind(function (path) { 8591 var revPath = reverse(extraPath.concat(path)); 8592 var triggers = bind$3(revPath, function (menuValue, menuIndex) { 8593 return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () { 8594 return is(primary.get(), menuValue) ? [] : [Optional.none()]; 8595 }, function (data) { 8596 return [Optional.some(data)]; 8597 }); 8598 }); 8599 return sequence(triggers); 8600 }); 8601 }; 8602 var expand = function (itemValue) { 8603 return get$c(expansions.get(), itemValue).map(function (menu) { 8604 var current = get$c(paths.get(), itemValue).getOr([]); 8605 return [menu].concat(current); 8606 }); 8607 }; 8608 var collapse = function (itemValue) { 8609 return get$c(paths.get(), itemValue).bind(function (path) { 8610 return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none(); 8611 }); 8612 }; 8613 var refresh = function (itemValue) { 8614 return get$c(paths.get(), itemValue); 8615 }; 8616 var getPreparedMenu = function (menuValue) { 8617 return lookupMenu(menuValue).bind(extractPreparedMenu); 8618 }; 8619 var lookupMenu = function (menuValue) { 8620 return get$c(menus.get(), menuValue); 8621 }; 8622 var lookupItem = function (itemValue) { 8623 return get$c(expansions.get(), itemValue); 8624 }; 8625 var otherMenus = function (path) { 8626 var menuValues = directory.get(); 8627 return difference(keys(menuValues), path); 8628 }; 8629 var getPrimary = function () { 8630 return primary.get().bind(getPreparedMenu); 8631 }; 8632 var getMenus = function () { 8633 return menus.get(); 8634 }; 8635 return { 8636 setMenuBuilt: setMenuBuilt, 8637 setContents: setContents, 8638 expand: expand, 8639 refresh: refresh, 8640 collapse: collapse, 8641 lookupMenu: lookupMenu, 8642 lookupItem: lookupItem, 8643 otherMenus: otherMenus, 8644 getPrimary: getPrimary, 8645 getMenus: getMenus, 8646 clear: clear, 8647 isClear: isClear, 8648 getTriggeringPath: getTriggeringPath 8649 }; 8650 }; 8651 var extractPreparedMenu = function (prep) { 8652 return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none(); 8653 }; 8654 var LayeredState = { 8655 init: init$2, 8656 extractPreparedMenu: extractPreparedMenu 8657 }; 8658 8659 var make$1 = function (detail, _rawUiSpec) { 8660 var submenuParentItems = value(); 8661 var buildMenus = function (container, primaryName, menus) { 8662 return map$1(menus, function (spec, name) { 8663 var makeSketch = function () { 8664 return Menu.sketch(__assign(__assign({}, spec), { 8665 value: name, 8666 markers: detail.markers, 8667 fakeFocus: detail.fakeFocus, 8668 onHighlight: detail.onHighlight, 8669 focusManager: detail.fakeFocus ? highlights() : dom$2() 8670 })); 8671 }; 8672 return name === primaryName ? { 8673 type: 'prepared', 8674 menu: container.getSystem().build(makeSketch()) 8675 } : { 8676 type: 'notbuilt', 8677 nbMenu: makeSketch 8678 }; 8679 }); 8680 }; 8681 var layeredState = LayeredState.init(); 8682 var setup = function (container) { 8683 var componentMap = buildMenus(container, detail.data.primary, detail.data.menus); 8684 var directory = toDirectory(); 8685 layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory); 8686 return layeredState.getPrimary(); 8687 }; 8688 var getItemValue = function (item) { 8689 return Representing.getValue(item).value; 8690 }; 8691 var getItemByValue = function (_container, menus, itemValue) { 8692 return findMap(menus, function (menu) { 8693 if (!menu.getSystem().isConnected()) { 8694 return Optional.none(); 8695 } 8696 var candidates = Highlighting.getCandidates(menu); 8697 return find$2(candidates, function (c) { 8698 return getItemValue(c) === itemValue; 8699 }); 8700 }); 8701 }; 8702 var toDirectory = function (_container) { 8703 return map$1(detail.data.menus, function (data, _menuName) { 8704 return bind$3(data.items, function (item) { 8705 return item.type === 'separator' ? [] : [item.data.value]; 8706 }); 8707 }); 8708 }; 8709 var setActiveMenu = function (container, menu) { 8710 Highlighting.highlight(container, menu); 8711 Highlighting.getHighlighted(menu).orThunk(function () { 8712 return Highlighting.getFirst(menu); 8713 }).each(function (item) { 8714 dispatch(container, item.element, focusItem()); 8715 }); 8716 }; 8717 var getMenus = function (state, menuValues) { 8718 return cat(map$2(menuValues, function (mv) { 8719 return state.lookupMenu(mv).bind(function (prep) { 8720 return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none(); 8721 }); 8722 })); 8723 }; 8724 var closeOthers = function (container, state, path) { 8725 var others = getMenus(state, state.otherMenus(path)); 8726 each$1(others, function (o) { 8727 remove$1(o.element, [detail.markers.backgroundMenu]); 8728 if (!detail.stayInDom) { 8729 Replacing.remove(container, o); 8730 } 8731 }); 8732 }; 8733 var getSubmenuParents = function (container) { 8734 return submenuParentItems.get().getOrThunk(function () { 8735 var r = {}; 8736 var items = descendants(container.element, '.' + detail.markers.item); 8737 var parentItems = filter$2(items, function (i) { 8738 return get$b(i, 'aria-haspopup') === 'true'; 8739 }); 8740 each$1(parentItems, function (i) { 8741 container.getSystem().getByDom(i).each(function (itemComp) { 8742 var key = getItemValue(itemComp); 8743 r[key] = itemComp; 8744 }); 8745 }); 8746 submenuParentItems.set(r); 8747 return r; 8748 }); 8749 }; 8750 var updateAriaExpansions = function (container, path) { 8751 var parentItems = getSubmenuParents(container); 8752 each(parentItems, function (v, k) { 8753 var expanded = contains$1(path, k); 8754 set$8(v.element, 'aria-expanded', expanded); 8755 }); 8756 }; 8757 var updateMenuPath = function (container, state, path) { 8758 return Optional.from(path[0]).bind(function (latestMenuName) { 8759 return state.lookupMenu(latestMenuName).bind(function (menuPrep) { 8760 if (menuPrep.type === 'notbuilt') { 8761 return Optional.none(); 8762 } else { 8763 var activeMenu = menuPrep.menu; 8764 var rest = getMenus(state, path.slice(1)); 8765 each$1(rest, function (r) { 8766 add$1(r.element, detail.markers.backgroundMenu); 8767 }); 8768 if (!inBody(activeMenu.element)) { 8769 Replacing.append(container, premade(activeMenu)); 8770 } 8771 remove$1(activeMenu.element, [detail.markers.backgroundMenu]); 8772 setActiveMenu(container, activeMenu); 8773 closeOthers(container, state, path); 8774 return Optional.some(activeMenu); 8775 } 8776 }); 8777 }); 8778 }; 8779 var ExpandHighlightDecision; 8780 (function (ExpandHighlightDecision) { 8781 ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu'; 8782 ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent'; 8783 }(ExpandHighlightDecision || (ExpandHighlightDecision = {}))); 8784 var buildIfRequired = function (container, menuName, menuPrep) { 8785 if (menuPrep.type === 'notbuilt') { 8786 var menu = container.getSystem().build(menuPrep.nbMenu()); 8787 layeredState.setMenuBuilt(menuName, menu); 8788 return menu; 8789 } else { 8790 return menuPrep.menu; 8791 } 8792 }; 8793 var expandRight = function (container, item, decision) { 8794 if (decision === void 0) { 8795 decision = ExpandHighlightDecision.HighlightSubmenu; 8796 } 8797 if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) { 8798 return Optional.some(item); 8799 } else { 8800 var value = getItemValue(item); 8801 return layeredState.expand(value).bind(function (path) { 8802 updateAriaExpansions(container, path); 8803 return Optional.from(path[0]).bind(function (menuName) { 8804 return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) { 8805 var activeMenu = buildIfRequired(container, menuName, activeMenuPrep); 8806 if (!inBody(activeMenu.element)) { 8807 Replacing.append(container, premade(activeMenu)); 8808 } 8809 detail.onOpenSubmenu(container, item, activeMenu, reverse(path)); 8810 if (decision === ExpandHighlightDecision.HighlightSubmenu) { 8811 Highlighting.highlightFirst(activeMenu); 8812 return updateMenuPath(container, layeredState, path); 8813 } else { 8814 Highlighting.dehighlightAll(activeMenu); 8815 return Optional.some(item); 8816 } 8817 }); 8818 }); 8819 }); 8820 } 8821 }; 8822 var collapseLeft = function (container, item) { 8823 var value = getItemValue(item); 8824 return layeredState.collapse(value).bind(function (path) { 8825 updateAriaExpansions(container, path); 8826 return updateMenuPath(container, layeredState, path).map(function (activeMenu) { 8827 detail.onCollapseMenu(container, item, activeMenu); 8828 return activeMenu; 8829 }); 8830 }); 8831 }; 8832 var updateView = function (container, item) { 8833 var value = getItemValue(item); 8834 return layeredState.refresh(value).bind(function (path) { 8835 updateAriaExpansions(container, path); 8836 return updateMenuPath(container, layeredState, path); 8837 }); 8838 }; 8839 var onRight = function (container, item) { 8840 return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu); 8841 }; 8842 var onLeft = function (container, item) { 8843 return inside(item.element) ? Optional.none() : collapseLeft(container, item); 8844 }; 8845 var onEscape = function (container, item) { 8846 return collapseLeft(container, item).orThunk(function () { 8847 return detail.onEscape(container, item).map(function () { 8848 return container; 8849 }); 8850 }); 8851 }; 8852 var keyOnItem = function (f) { 8853 return function (container, simulatedEvent) { 8854 return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) { 8855 return container.getSystem().getByDom(target).toOptional().bind(function (item) { 8856 return f(container, item).map(always); 8857 }); 8858 }); 8859 }; 8860 }; 8861 var events = derive$3([ 8862 run(focus(), function (sandbox, simulatedEvent) { 8863 var item = simulatedEvent.event.item; 8864 layeredState.lookupItem(getItemValue(item)).each(function () { 8865 var menu = simulatedEvent.event.menu; 8866 Highlighting.highlight(sandbox, menu); 8867 var value = getItemValue(simulatedEvent.event.item); 8868 layeredState.refresh(value).each(function (path) { 8869 return closeOthers(sandbox, layeredState, path); 8870 }); 8871 }); 8872 }), 8873 runOnExecute(function (component, simulatedEvent) { 8874 var target = simulatedEvent.event.target; 8875 component.getSystem().getByDom(target).each(function (item) { 8876 var itemValue = getItemValue(item); 8877 if (itemValue.indexOf('collapse-item') === 0) { 8878 collapseLeft(component, item); 8879 } 8880 expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () { 8881 detail.onExecute(component, item); 8882 }, noop); 8883 }); 8884 }), 8885 runOnAttached(function (container, _simulatedEvent) { 8886 setup(container).each(function (primary) { 8887 Replacing.append(container, premade(primary)); 8888 detail.onOpenMenu(container, primary); 8889 if (detail.highlightImmediately) { 8890 setActiveMenu(container, primary); 8891 } 8892 }); 8893 }) 8894 ].concat(detail.navigateOnHover ? [run(hover(), function (sandbox, simulatedEvent) { 8895 var item = simulatedEvent.event.item; 8896 updateView(sandbox, item); 8897 expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent); 8898 detail.onHover(sandbox, item); 8899 })] : [])); 8900 var getActiveItem = function (container) { 8901 return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted); 8902 }; 8903 var collapseMenuApi = function (container) { 8904 getActiveItem(container).each(function (currentItem) { 8905 collapseLeft(container, currentItem); 8906 }); 8907 }; 8908 var highlightPrimary = function (container) { 8909 layeredState.getPrimary().each(function (primary) { 8910 setActiveMenu(container, primary); 8911 }); 8912 }; 8913 var extractMenuFromContainer = function (container) { 8914 return Optional.from(container.components()[0]).filter(function (comp) { 8915 return get$b(comp.element, 'role') === 'menu'; 8916 }); 8917 }; 8918 var repositionMenus = function (container) { 8919 var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) { 8920 return getActiveItem(container).bind(function (currentItem) { 8921 var itemValue = getItemValue(currentItem); 8922 var allMenus = values(layeredState.getMenus()); 8923 var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu)); 8924 return layeredState.getTriggeringPath(itemValue, function (v) { 8925 return getItemByValue(container, preparedMenus, v); 8926 }); 8927 }).map(function (triggeringPath) { 8928 return { 8929 primary: primary, 8930 triggeringPath: triggeringPath 8931 }; 8932 }); 8933 }); 8934 maybeActivePrimary.fold(function () { 8935 extractMenuFromContainer(container).each(function (primaryMenu) { 8936 detail.onRepositionMenu(container, primaryMenu, []); 8937 }); 8938 }, function (_a) { 8939 var primary = _a.primary, triggeringPath = _a.triggeringPath; 8940 detail.onRepositionMenu(container, primary, triggeringPath); 8941 }); 8942 }; 8943 var apis = { 8944 collapseMenu: collapseMenuApi, 8945 highlightPrimary: highlightPrimary, 8946 repositionMenus: repositionMenus 8947 }; 8948 return { 8949 uid: detail.uid, 8950 dom: detail.dom, 8951 markers: detail.markers, 8952 behaviours: augment(detail.tmenuBehaviours, [ 8953 Keying.config({ 8954 mode: 'special', 8955 onRight: keyOnItem(onRight), 8956 onLeft: keyOnItem(onLeft), 8957 onEscape: keyOnItem(onEscape), 8958 focusIn: function (container, _keyInfo) { 8959 layeredState.getPrimary().each(function (primary) { 8960 dispatch(container, primary.element, focusItem()); 8961 }); 8962 } 8963 }), 8964 Highlighting.config({ 8965 highlightClass: detail.markers.selectedMenu, 8966 itemClass: detail.markers.menu 8967 }), 8968 Composing.config({ 8969 find: function (container) { 8970 return Highlighting.getHighlighted(container); 8971 } 8972 }), 8973 Replacing.config({}) 8974 ]), 8975 eventOrder: detail.eventOrder, 8976 apis: apis, 8977 events: events 8978 }; 8979 }; 8980 var collapseItem$1 = constant$1('collapse-item'); 8981 8982 var tieredData = function (primary, menus, expansions) { 8983 return { 8984 primary: primary, 8985 menus: menus, 8986 expansions: expansions 8987 }; 8988 }; 8989 var singleData = function (name, menu) { 8990 return { 8991 primary: name, 8992 menus: wrap(name, menu), 8993 expansions: {} 8994 }; 8995 }; 8996 var collapseItem = function (text) { 8997 return { 8998 value: generate$4(collapseItem$1()), 8999 meta: { text: text } 9000 }; 9001 }; 9002 var tieredMenu = single({ 9003 name: 'TieredMenu', 9004 configFields: [ 9005 onStrictKeyboardHandler('onExecute'), 9006 onStrictKeyboardHandler('onEscape'), 9007 onStrictHandler('onOpenMenu'), 9008 onStrictHandler('onOpenSubmenu'), 9009 onHandler('onRepositionMenu'), 9010 onHandler('onCollapseMenu'), 9011 defaulted('highlightImmediately', true), 9012 requiredObjOf('data', [ 9013 required$1('primary'), 9014 required$1('menus'), 9015 required$1('expansions') 9016 ]), 9017 defaulted('fakeFocus', false), 9018 onHandler('onHighlight'), 9019 onHandler('onHover'), 9020 tieredMenuMarkers(), 9021 required$1('dom'), 9022 defaulted('navigateOnHover', true), 9023 defaulted('stayInDom', false), 9024 field$1('tmenuBehaviours', [ 9025 Keying, 9026 Highlighting, 9027 Composing, 9028 Replacing 9029 ]), 9030 defaulted('eventOrder', {}) 9031 ], 9032 apis: { 9033 collapseMenu: function (apis, tmenu) { 9034 apis.collapseMenu(tmenu); 9035 }, 9036 highlightPrimary: function (apis, tmenu) { 9037 apis.highlightPrimary(tmenu); 9038 }, 9039 repositionMenus: function (apis, tmenu) { 9040 apis.repositionMenus(tmenu); 9041 } 9042 }, 9043 factory: make$1, 9044 extraApis: { 9045 tieredData: tieredData, 9046 singleData: singleData, 9047 collapseItem: collapseItem 9048 } 9049 }); 9050 9051 var findRoute = function (component, transConfig, transState, route) { 9052 return get$c(transConfig.routes, route.start).bind(function (sConfig) { 9053 return get$c(sConfig, route.destination); 9054 }); 9055 }; 9056 var getTransition = function (comp, transConfig, transState) { 9057 var route = getCurrentRoute(comp, transConfig); 9058 return route.bind(function (r) { 9059 return getTransitionOf(comp, transConfig, transState, r); 9060 }); 9061 }; 9062 var getTransitionOf = function (comp, transConfig, transState, route) { 9063 return findRoute(comp, transConfig, transState, route).bind(function (r) { 9064 return r.transition.map(function (t) { 9065 return { 9066 transition: t, 9067 route: r 9068 }; 9069 }); 9070 }); 9071 }; 9072 var disableTransition = function (comp, transConfig, transState) { 9073 getTransition(comp, transConfig, transState).each(function (routeTransition) { 9074 var t = routeTransition.transition; 9075 remove$3(comp.element, t.transitionClass); 9076 remove$6(comp.element, transConfig.destinationAttr); 9077 }); 9078 }; 9079 var getNewRoute = function (comp, transConfig, transState, destination) { 9080 return { 9081 start: get$b(comp.element, transConfig.stateAttr), 9082 destination: destination 9083 }; 9084 }; 9085 var getCurrentRoute = function (comp, transConfig, _transState) { 9086 var el = comp.element; 9087 return getOpt(el, transConfig.destinationAttr).map(function (destination) { 9088 return { 9089 start: get$b(comp.element, transConfig.stateAttr), 9090 destination: destination 9091 }; 9092 }); 9093 }; 9094 var jumpTo = function (comp, transConfig, transState, destination) { 9095 disableTransition(comp, transConfig, transState); 9096 if (has$1(comp.element, transConfig.stateAttr) && get$b(comp.element, transConfig.stateAttr) !== destination) { 9097 transConfig.onFinish(comp, destination); 9098 } 9099 set$8(comp.element, transConfig.stateAttr, destination); 9100 }; 9101 var fasttrack = function (comp, transConfig, _transState, _destination) { 9102 if (has$1(comp.element, transConfig.destinationAttr)) { 9103 getOpt(comp.element, transConfig.destinationAttr).each(function (destination) { 9104 set$8(comp.element, transConfig.stateAttr, destination); 9105 }); 9106 remove$6(comp.element, transConfig.destinationAttr); 9107 } 9108 }; 9109 var progressTo = function (comp, transConfig, transState, destination) { 9110 fasttrack(comp, transConfig); 9111 var route = getNewRoute(comp, transConfig, transState, destination); 9112 getTransitionOf(comp, transConfig, transState, route).fold(function () { 9113 jumpTo(comp, transConfig, transState, destination); 9114 }, function (routeTransition) { 9115 disableTransition(comp, transConfig, transState); 9116 var t = routeTransition.transition; 9117 add$1(comp.element, t.transitionClass); 9118 set$8(comp.element, transConfig.destinationAttr, destination); 9119 }); 9120 }; 9121 var getState = function (comp, transConfig, _transState) { 9122 return getOpt(comp.element, transConfig.stateAttr); 9123 }; 9124 9125 var TransitionApis = /*#__PURE__*/Object.freeze({ 9126 __proto__: null, 9127 findRoute: findRoute, 9128 disableTransition: disableTransition, 9129 getCurrentRoute: getCurrentRoute, 9130 jumpTo: jumpTo, 9131 progressTo: progressTo, 9132 getState: getState 9133 }); 9134 9135 var events$1 = function (transConfig, transState) { 9136 return derive$3([ 9137 run(transitionend(), function (component, simulatedEvent) { 9138 var raw = simulatedEvent.event.raw; 9139 getCurrentRoute(component, transConfig).each(function (route) { 9140 findRoute(component, transConfig, transState, route).each(function (rInfo) { 9141 rInfo.transition.each(function (rTransition) { 9142 if (raw.propertyName === rTransition.property) { 9143 jumpTo(component, transConfig, transState, route.destination); 9144 transConfig.onTransition(component, route); 9145 } 9146 }); 9147 }); 9148 }); 9149 }), 9150 runOnAttached(function (comp, _se) { 9151 jumpTo(comp, transConfig, transState, transConfig.initialState); 9152 }) 9153 ]); 9154 }; 9155 9156 var ActiveTransitioning = /*#__PURE__*/Object.freeze({ 9157 __proto__: null, 9158 events: events$1 9159 }); 9160 9161 var TransitionSchema = [ 9162 defaulted('destinationAttr', 'data-transitioning-destination'), 9163 defaulted('stateAttr', 'data-transitioning-state'), 9164 required$1('initialState'), 9165 onHandler('onTransition'), 9166 onHandler('onFinish'), 9167 requiredOf('routes', setOf(Result.value, setOf(Result.value, objOfOnly([optionObjOfOnly('transition', [ 9168 required$1('property'), 9169 required$1('transitionClass') 9170 ])])))) 9171 ]; 9172 9173 var createRoutes = function (routes) { 9174 var r = {}; 9175 each(routes, function (v, k) { 9176 var waypoints = k.split('<->'); 9177 r[waypoints[0]] = wrap(waypoints[1], v); 9178 r[waypoints[1]] = wrap(waypoints[0], v); 9179 }); 9180 return r; 9181 }; 9182 var createBistate = function (first, second, transitions) { 9183 return wrapAll([ 9184 { 9185 key: first, 9186 value: wrap(second, transitions) 9187 }, 9188 { 9189 key: second, 9190 value: wrap(first, transitions) 9191 } 9192 ]); 9193 }; 9194 var createTristate = function (first, second, third, transitions) { 9195 return wrapAll([ 9196 { 9197 key: first, 9198 value: wrapAll([ 9199 { 9200 key: second, 9201 value: transitions 9202 }, 9203 { 9204 key: third, 9205 value: transitions 9206 } 9207 ]) 9208 }, 9209 { 9210 key: second, 9211 value: wrapAll([ 9212 { 9213 key: first, 9214 value: transitions 9215 }, 9216 { 9217 key: third, 9218 value: transitions 9219 } 9220 ]) 9221 }, 9222 { 9223 key: third, 9224 value: wrapAll([ 9225 { 9226 key: first, 9227 value: transitions 9228 }, 9229 { 9230 key: second, 9231 value: transitions 9232 } 9233 ]) 9234 } 9235 ]); 9236 }; 9237 var Transitioning = create$5({ 9238 fields: TransitionSchema, 9239 name: 'transitioning', 9240 active: ActiveTransitioning, 9241 apis: TransitionApis, 9242 extra: { 9243 createRoutes: createRoutes, 9244 createBistate: createBistate, 9245 createTristate: createTristate 9246 } 9247 }); 9248 9249 var scrollableStyle = resolve('scrollable'); 9250 var register$2 = function (element) { 9251 add$1(element, scrollableStyle); 9252 }; 9253 var deregister = function (element) { 9254 remove$3(element, scrollableStyle); 9255 }; 9256 var scrollable = scrollableStyle; 9257 9258 var getValue = function (item) { 9259 return get$c(item, 'format').getOr(item.title); 9260 }; 9261 var convert = function (formats, memMenuThunk) { 9262 var mainMenu = makeMenu('Styles', [].concat(map$2(formats.items, function (k) { 9263 return makeItem(getValue(k), k.title, k.isSelected(), k.getPreview(), hasNonNullableKey(formats.expansions, getValue(k))); 9264 })), memMenuThunk, false); 9265 var submenus = map$1(formats.menus, function (menuItems, menuName) { 9266 var items = map$2(menuItems, function (item) { 9267 return makeItem(getValue(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasNonNullableKey(formats.expansions, getValue(item))); 9268 }); 9269 return makeMenu(menuName, items, memMenuThunk, true); 9270 }); 9271 var menus = deepMerge(submenus, wrap('styles', mainMenu)); 9272 var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions); 9273 return { tmenu: tmenu }; 9274 }; 9275 var makeItem = function (value, text, selected, preview, isMenu) { 9276 return { 9277 data: { 9278 value: value, 9279 text: text 9280 }, 9281 type: 'item', 9282 dom: { 9283 tag: 'div', 9284 classes: isMenu ? [resolve('styles-item-is-menu')] : [] 9285 }, 9286 toggling: { 9287 toggleOnExecute: false, 9288 toggleClass: resolve('format-matches'), 9289 selected: selected 9290 }, 9291 itemBehaviours: derive$2(isMenu ? [] : [format(value, function (comp, status) { 9292 var toggle = status ? Toggling.on : Toggling.off; 9293 toggle(comp); 9294 })]), 9295 components: [{ 9296 dom: { 9297 tag: 'div', 9298 attributes: { style: preview }, 9299 innerHtml: text 9300 } 9301 }] 9302 }; 9303 }; 9304 var makeMenu = function (value, items, memMenuThunk, collapsable) { 9305 return { 9306 value: value, 9307 dom: { tag: 'div' }, 9308 components: [ 9309 Button.sketch({ 9310 dom: { 9311 tag: 'div', 9312 classes: [resolve('styles-collapser')] 9313 }, 9314 components: collapsable ? [ 9315 { 9316 dom: { 9317 tag: 'span', 9318 classes: [resolve('styles-collapse-icon')] 9319 } 9320 }, 9321 text(value) 9322 ] : [text(value)], 9323 action: function (item) { 9324 if (collapsable) { 9325 var comp = memMenuThunk().get(item); 9326 tieredMenu.collapseMenu(comp); 9327 } 9328 } 9329 }), 9330 { 9331 dom: { 9332 tag: 'div', 9333 classes: [resolve('styles-menu-items-container')] 9334 }, 9335 components: [Menu.parts.items({})], 9336 behaviours: derive$2([config('adhoc-scrollable-menu', [ 9337 runOnAttached(function (component, _simulatedEvent) { 9338 set$5(component.element, 'overflow-y', 'auto'); 9339 set$5(component.element, '-webkit-overflow-scrolling', 'touch'); 9340 register$2(component.element); 9341 }), 9342 runOnDetached(function (component) { 9343 remove$2(component.element, 'overflow-y'); 9344 remove$2(component.element, '-webkit-overflow-scrolling'); 9345 deregister(component.element); 9346 }) 9347 ])]) 9348 } 9349 ], 9350 items: items, 9351 menuBehaviours: derive$2([Transitioning.config({ 9352 initialState: 'after', 9353 routes: Transitioning.createTristate('before', 'current', 'after', { 9354 transition: { 9355 property: 'transform', 9356 transitionClass: 'transitioning' 9357 } 9358 }) 9359 })]) 9360 }; 9361 }; 9362 var sketch$1 = function (settings) { 9363 var dataset = convert(settings.formats, function () { 9364 return memMenu; 9365 }); 9366 var memMenu = record(tieredMenu.sketch({ 9367 dom: { 9368 tag: 'div', 9369 classes: [resolve('styles-menu')] 9370 }, 9371 components: [], 9372 fakeFocus: true, 9373 stayInDom: true, 9374 onExecute: function (_tmenu, item) { 9375 var v = Representing.getValue(item); 9376 settings.handle(item, v.value); 9377 return Optional.none(); 9378 }, 9379 onEscape: function () { 9380 return Optional.none(); 9381 }, 9382 onOpenMenu: function (container, menu) { 9383 var w = get$5(container.element); 9384 set$4(menu.element, w); 9385 Transitioning.jumpTo(menu, 'current'); 9386 }, 9387 onOpenSubmenu: function (container, item, submenu) { 9388 var w = get$5(container.element); 9389 var menu = ancestor(item.element, '[role="menu"]').getOrDie('hacky'); 9390 var menuComp = container.getSystem().getByDom(menu).getOrDie(); 9391 set$4(submenu.element, w); 9392 Transitioning.progressTo(menuComp, 'before'); 9393 Transitioning.jumpTo(submenu, 'after'); 9394 Transitioning.progressTo(submenu, 'current'); 9395 }, 9396 onCollapseMenu: function (container, item, menu) { 9397 var submenu = ancestor(item.element, '[role="menu"]').getOrDie('hacky'); 9398 var submenuComp = container.getSystem().getByDom(submenu).getOrDie(); 9399 Transitioning.progressTo(submenuComp, 'after'); 9400 Transitioning.progressTo(menu, 'current'); 9401 }, 9402 navigateOnHover: false, 9403 highlightImmediately: true, 9404 data: dataset.tmenu, 9405 markers: { 9406 backgroundMenu: resolve('styles-background-menu'), 9407 menu: resolve('styles-menu'), 9408 selectedMenu: resolve('styles-selected-menu'), 9409 item: resolve('styles-item'), 9410 selectedItem: resolve('styles-selected-item') 9411 } 9412 })); 9413 return memMenu.asSpec(); 9414 }; 9415 9416 var getFromExpandingItem = function (item) { 9417 var newItem = deepMerge(exclude(item, ['items']), { menu: true }); 9418 var rest = expand(item.items); 9419 var newMenus = deepMerge(rest.menus, wrap(item.title, rest.items)); 9420 var newExpansions = deepMerge(rest.expansions, wrap(item.title, item.title)); 9421 return { 9422 item: newItem, 9423 menus: newMenus, 9424 expansions: newExpansions 9425 }; 9426 }; 9427 var getFromItem = function (item) { 9428 return hasNonNullableKey(item, 'items') ? getFromExpandingItem(item) : { 9429 item: item, 9430 menus: {}, 9431 expansions: {} 9432 }; 9433 }; 9434 var expand = function (items) { 9435 return foldr(items, function (acc, item) { 9436 var newData = getFromItem(item); 9437 return { 9438 menus: deepMerge(acc.menus, newData.menus), 9439 items: [newData.item].concat(acc.items), 9440 expansions: deepMerge(acc.expansions, newData.expansions) 9441 }; 9442 }, { 9443 menus: {}, 9444 expansions: {}, 9445 items: [] 9446 }); 9447 }; 9448 9449 var register$1 = function (editor) { 9450 var isSelectedFor = function (format) { 9451 return function () { 9452 return editor.formatter.match(format); 9453 }; 9454 }; 9455 var getPreview = function (format) { 9456 return function () { 9457 return editor.formatter.getCssText(format); 9458 }; 9459 }; 9460 var enrichSupported = function (item) { 9461 return deepMerge(item, { 9462 isSelected: isSelectedFor(item.format), 9463 getPreview: getPreview(item.format) 9464 }); 9465 }; 9466 var enrichMenu = function (item) { 9467 return deepMerge(item, { 9468 isSelected: never, 9469 getPreview: constant$1('') 9470 }); 9471 }; 9472 var enrichCustom = function (item) { 9473 var formatName = generate$4(item.title); 9474 var newItem = deepMerge(item, { 9475 format: formatName, 9476 isSelected: isSelectedFor(formatName), 9477 getPreview: getPreview(formatName) 9478 }); 9479 editor.formatter.register(formatName, newItem); 9480 return newItem; 9481 }; 9482 var doEnrich = function (items) { 9483 return map$2(items, function (item) { 9484 if (hasNonNullableKey(item, 'items')) { 9485 var newItems = doEnrich(item.items); 9486 return deepMerge(enrichMenu(item), { items: newItems }); 9487 } else if (hasNonNullableKey(item, 'format')) { 9488 return enrichSupported(item); 9489 } else { 9490 return enrichCustom(item); 9491 } 9492 }); 9493 }; 9494 return doEnrich(getStyleFormats(editor)); 9495 }; 9496 var prune = function (editor, formats) { 9497 var doPrune = function (items) { 9498 return bind$3(items, function (item) { 9499 if (item.items !== undefined) { 9500 var newItems = doPrune(item.items); 9501 return newItems.length > 0 ? [item] : []; 9502 } else { 9503 var keep = hasNonNullableKey(item, 'format') ? editor.formatter.canApply(item.format) : true; 9504 return keep ? [item] : []; 9505 } 9506 }); 9507 }; 9508 var prunedItems = doPrune(formats); 9509 return expand(prunedItems); 9510 }; 9511 var ui = function (editor, formats, onDone) { 9512 var pruned = prune(editor, formats); 9513 return sketch$1({ 9514 formats: pruned, 9515 handle: function (item, value) { 9516 editor.undoManager.transact(function () { 9517 if (Toggling.isOn(item)) { 9518 editor.formatter.remove(value); 9519 } else { 9520 editor.formatter.apply(value); 9521 } 9522 }); 9523 onDone(); 9524 } 9525 }); 9526 }; 9527 9528 var extract = function (rawToolbar) { 9529 var toolbar = rawToolbar.replace(/\|/g, ' ').trim(); 9530 return toolbar.length > 0 ? toolbar.split(/\s+/) : []; 9531 }; 9532 var identifyFromArray = function (toolbar) { 9533 return bind$3(toolbar, function (item) { 9534 return isArray(item) ? identifyFromArray(item) : extract(item); 9535 }); 9536 }; 9537 var identify = function (editor) { 9538 var toolbar = getToolbar(editor); 9539 return isArray(toolbar) ? identifyFromArray(toolbar) : extract(toolbar); 9540 }; 9541 var setup$3 = function (realm, editor) { 9542 var commandSketch = function (name) { 9543 return function () { 9544 return forToolbarCommand(editor, name); 9545 }; 9546 }; 9547 var stateCommandSketch = function (name) { 9548 return function () { 9549 return forToolbarStateCommand(editor, name); 9550 }; 9551 }; 9552 var actionSketch = function (name, query, action) { 9553 return function () { 9554 return forToolbarStateAction(editor, name, query, action); 9555 }; 9556 }; 9557 var undo = commandSketch('undo'); 9558 var redo = commandSketch('redo'); 9559 var bold = stateCommandSketch('bold'); 9560 var italic = stateCommandSketch('italic'); 9561 var underline = stateCommandSketch('underline'); 9562 var removeformat = commandSketch('removeformat'); 9563 var link = function () { 9564 return sketch$2(realm, editor); 9565 }; 9566 var unlink = actionSketch('unlink', 'link', function () { 9567 editor.execCommand('unlink', null, false); 9568 }); 9569 var image = function () { 9570 return sketch$5(editor); 9571 }; 9572 var bullist = actionSketch('unordered-list', 'ul', function () { 9573 editor.execCommand('InsertUnorderedList', null, false); 9574 }); 9575 var numlist = actionSketch('ordered-list', 'ol', function () { 9576 editor.execCommand('InsertOrderedList', null, false); 9577 }); 9578 var fontsizeselect = function () { 9579 return sketch$6(realm, editor); 9580 }; 9581 var forecolor = function () { 9582 return sketch$8(realm, editor); 9583 }; 9584 var styleFormats = register$1(editor); 9585 var styleFormatsMenu = function () { 9586 return ui(editor, styleFormats, function () { 9587 editor.fire('scrollIntoView'); 9588 }); 9589 }; 9590 var styleselect = function () { 9591 return forToolbar('style-formats', function (button) { 9592 editor.fire('toReading'); 9593 realm.dropup.appear(styleFormatsMenu, Toggling.on, button); 9594 }, derive$2([ 9595 Toggling.config({ 9596 toggleClass: resolve('toolbar-button-selected'), 9597 toggleOnExecute: false, 9598 aria: { mode: 'pressed' } 9599 }), 9600 Receiving.config({ 9601 channels: wrapAll([ 9602 receive(orientationChanged, Toggling.off), 9603 receive(dropupDismissed, Toggling.off) 9604 ]) 9605 }) 9606 ]), editor); 9607 }; 9608 var feature = function (prereq, sketch) { 9609 return { 9610 isSupported: function () { 9611 var buttons = editor.ui.registry.getAll().buttons; 9612 return prereq.forall(function (p) { 9613 return hasNonNullableKey(buttons, p); 9614 }); 9615 }, 9616 sketch: sketch 9617 }; 9618 }; 9619 return { 9620 undo: feature(Optional.none(), undo), 9621 redo: feature(Optional.none(), redo), 9622 bold: feature(Optional.none(), bold), 9623 italic: feature(Optional.none(), italic), 9624 underline: feature(Optional.none(), underline), 9625 removeformat: feature(Optional.none(), removeformat), 9626 link: feature(Optional.none(), link), 9627 unlink: feature(Optional.none(), unlink), 9628 image: feature(Optional.none(), image), 9629 bullist: feature(Optional.some('bullist'), bullist), 9630 numlist: feature(Optional.some('numlist'), numlist), 9631 fontsizeselect: feature(Optional.none(), fontsizeselect), 9632 forecolor: feature(Optional.none(), forecolor), 9633 styleselect: feature(Optional.none(), styleselect) 9634 }; 9635 }; 9636 var detect = function (editor, features) { 9637 var itemNames = identify(editor); 9638 var present = {}; 9639 return bind$3(itemNames, function (iName) { 9640 var r = !hasNonNullableKey(present, iName) && hasNonNullableKey(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : []; 9641 present[iName] = true; 9642 return r; 9643 }); 9644 }; 9645 9646 var mkEvent = function (target, x, y, stop, prevent, kill, raw) { 9647 return { 9648 target: target, 9649 x: x, 9650 y: y, 9651 stop: stop, 9652 prevent: prevent, 9653 kill: kill, 9654 raw: raw 9655 }; 9656 }; 9657 var fromRawEvent = function (rawEvent) { 9658 var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target)); 9659 var stop = function () { 9660 return rawEvent.stopPropagation(); 9661 }; 9662 var prevent = function () { 9663 return rawEvent.preventDefault(); 9664 }; 9665 var kill = compose(prevent, stop); 9666 return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent); 9667 }; 9668 var handle = function (filter, handler) { 9669 return function (rawEvent) { 9670 if (filter(rawEvent)) { 9671 handler(fromRawEvent(rawEvent)); 9672 } 9673 }; 9674 }; 9675 var binder = function (element, event, filter, handler, useCapture) { 9676 var wrapped = handle(filter, handler); 9677 element.dom.addEventListener(event, wrapped, useCapture); 9678 return { unbind: curry(unbind, element, event, wrapped, useCapture) }; 9679 }; 9680 var bind$1 = function (element, event, filter, handler) { 9681 return binder(element, event, filter, handler, false); 9682 }; 9683 var capture$1 = function (element, event, filter, handler) { 9684 return binder(element, event, filter, handler, true); 9685 }; 9686 var unbind = function (element, event, handler, useCapture) { 9687 element.dom.removeEventListener(event, handler, useCapture); 9688 }; 9689 9690 var filter = always; 9691 var bind = function (element, event, handler) { 9692 return bind$1(element, event, filter, handler); 9693 }; 9694 var capture = function (element, event, handler) { 9695 return capture$1(element, event, filter, handler); 9696 }; 9697 9698 var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay'); 9699 9700 var INTERVAL = 50; 9701 var INSURANCE = 1000 / INTERVAL; 9702 var get$1 = function (outerWindow) { 9703 var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches; 9704 return { isPortrait: constant$1(isPortrait) }; 9705 }; 9706 var getActualWidth = function (outerWindow) { 9707 var isIos = detect$1().os.isiOS(); 9708 var isPortrait = get$1(outerWindow).isPortrait(); 9709 return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width; 9710 }; 9711 var onChange = function (outerWindow, listeners) { 9712 var win = SugarElement.fromDom(outerWindow); 9713 var poller = null; 9714 var change = function () { 9715 global$2.clearInterval(poller); 9716 var orientation = get$1(outerWindow); 9717 listeners.onChange(orientation); 9718 onAdjustment(function () { 9719 listeners.onReady(orientation); 9720 }); 9721 }; 9722 var orientationHandle = bind(win, 'orientationchange', change); 9723 var onAdjustment = function (f) { 9724 global$2.clearInterval(poller); 9725 var flag = outerWindow.innerHeight; 9726 var insurance = 0; 9727 poller = global$2.setInterval(function () { 9728 if (flag !== outerWindow.innerHeight) { 9729 global$2.clearInterval(poller); 9730 f(Optional.some(outerWindow.innerHeight)); 9731 } else if (insurance > INSURANCE) { 9732 global$2.clearInterval(poller); 9733 f(Optional.none()); 9734 } 9735 insurance++; 9736 }, INTERVAL); 9737 }; 9738 var destroy = function () { 9739 orientationHandle.unbind(); 9740 }; 9741 return { 9742 onAdjustment: onAdjustment, 9743 destroy: destroy 9744 }; 9745 }; 9746 9747 var setStart = function (rng, situ) { 9748 situ.fold(function (e) { 9749 rng.setStartBefore(e.dom); 9750 }, function (e, o) { 9751 rng.setStart(e.dom, o); 9752 }, function (e) { 9753 rng.setStartAfter(e.dom); 9754 }); 9755 }; 9756 var setFinish = function (rng, situ) { 9757 situ.fold(function (e) { 9758 rng.setEndBefore(e.dom); 9759 }, function (e, o) { 9760 rng.setEnd(e.dom, o); 9761 }, function (e) { 9762 rng.setEndAfter(e.dom); 9763 }); 9764 }; 9765 var relativeToNative = function (win, startSitu, finishSitu) { 9766 var range = win.document.createRange(); 9767 setStart(range, startSitu); 9768 setFinish(range, finishSitu); 9769 return range; 9770 }; 9771 var exactToNative = function (win, start, soffset, finish, foffset) { 9772 var rng = win.document.createRange(); 9773 rng.setStart(start.dom, soffset); 9774 rng.setEnd(finish.dom, foffset); 9775 return rng; 9776 }; 9777 var toRect$1 = function (rect) { 9778 return { 9779 left: rect.left, 9780 top: rect.top, 9781 right: rect.right, 9782 bottom: rect.bottom, 9783 width: rect.width, 9784 height: rect.height 9785 }; 9786 }; 9787 var getFirstRect$1 = function (rng) { 9788 var rects = rng.getClientRects(); 9789 var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect(); 9790 return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect$1) : Optional.none(); 9791 }; 9792 9793 var adt$3 = Adt.generate([ 9794 { 9795 ltr: [ 9796 'start', 9797 'soffset', 9798 'finish', 9799 'foffset' 9800 ] 9801 }, 9802 { 9803 rtl: [ 9804 'start', 9805 'soffset', 9806 'finish', 9807 'foffset' 9808 ] 9809 } 9810 ]); 9811 var fromRange = function (win, type, range) { 9812 return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset); 9813 }; 9814 var getRanges = function (win, selection) { 9815 return selection.match({ 9816 domRange: function (rng) { 9817 return { 9818 ltr: constant$1(rng), 9819 rtl: Optional.none 9820 }; 9821 }, 9822 relative: function (startSitu, finishSitu) { 9823 return { 9824 ltr: cached(function () { 9825 return relativeToNative(win, startSitu, finishSitu); 9826 }), 9827 rtl: cached(function () { 9828 return Optional.some(relativeToNative(win, finishSitu, startSitu)); 9829 }) 9830 }; 9831 }, 9832 exact: function (start, soffset, finish, foffset) { 9833 return { 9834 ltr: cached(function () { 9835 return exactToNative(win, start, soffset, finish, foffset); 9836 }), 9837 rtl: cached(function () { 9838 return Optional.some(exactToNative(win, finish, foffset, start, soffset)); 9839 }) 9840 }; 9841 } 9842 }); 9843 }; 9844 var doDiagnose = function (win, ranges) { 9845 var rng = ranges.ltr(); 9846 if (rng.collapsed) { 9847 var reversed = ranges.rtl().filter(function (rev) { 9848 return rev.collapsed === false; 9849 }); 9850 return reversed.map(function (rev) { 9851 return adt$3.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset); 9852 }).getOrThunk(function () { 9853 return fromRange(win, adt$3.ltr, rng); 9854 }); 9855 } else { 9856 return fromRange(win, adt$3.ltr, rng); 9857 } 9858 }; 9859 var diagnose = function (win, selection) { 9860 var ranges = getRanges(win, selection); 9861 return doDiagnose(win, ranges); 9862 }; 9863 var asLtrRange = function (win, selection) { 9864 var diagnosis = diagnose(win, selection); 9865 return diagnosis.match({ 9866 ltr: function (start, soffset, finish, foffset) { 9867 var rng = win.document.createRange(); 9868 rng.setStart(start.dom, soffset); 9869 rng.setEnd(finish.dom, foffset); 9870 return rng; 9871 }, 9872 rtl: function (start, soffset, finish, foffset) { 9873 var rng = win.document.createRange(); 9874 rng.setStart(finish.dom, foffset); 9875 rng.setEnd(start.dom, soffset); 9876 return rng; 9877 } 9878 }); 9879 }; 9880 adt$3.ltr; 9881 adt$3.rtl; 9882 9883 var create$3 = function (start, soffset, finish, foffset) { 9884 return { 9885 start: start, 9886 soffset: soffset, 9887 finish: finish, 9888 foffset: foffset 9889 }; 9890 }; 9891 var SimRange = { create: create$3 }; 9892 9893 var NodeValue = function (is, name) { 9894 var get = function (element) { 9895 if (!is(element)) { 9896 throw new Error('Can only get ' + name + ' value of a ' + name + ' node'); 9897 } 9898 return getOption(element).getOr(''); 9899 }; 9900 var getOption = function (element) { 9901 return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none(); 9902 }; 9903 var set = function (element, value) { 9904 if (!is(element)) { 9905 throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node'); 9906 } 9907 element.dom.nodeValue = value; 9908 }; 9909 return { 9910 get: get, 9911 getOption: getOption, 9912 set: set 9913 }; 9914 }; 9915 9916 var api = NodeValue(isText, 'text'); 9917 var getOption = function (element) { 9918 return api.getOption(element); 9919 }; 9920 9921 var getEnd = function (element) { 9922 return name$1(element) === 'img' ? 1 : getOption(element).fold(function () { 9923 return children(element).length; 9924 }, function (v) { 9925 return v.length; 9926 }); 9927 }; 9928 9929 var adt$2 = Adt.generate([ 9930 { before: ['element'] }, 9931 { 9932 on: [ 9933 'element', 9934 'offset' 9935 ] 9936 }, 9937 { after: ['element'] } 9938 ]); 9939 var cata = function (subject, onBefore, onOn, onAfter) { 9940 return subject.fold(onBefore, onOn, onAfter); 9941 }; 9942 var getStart$1 = function (situ) { 9943 return situ.fold(identity, identity, identity); 9944 }; 9945 var before = adt$2.before; 9946 var on = adt$2.on; 9947 var after$1 = adt$2.after; 9948 var Situ = { 9949 before: before, 9950 on: on, 9951 after: after$1, 9952 cata: cata, 9953 getStart: getStart$1 9954 }; 9955 9956 var adt$1 = Adt.generate([ 9957 { domRange: ['rng'] }, 9958 { 9959 relative: [ 9960 'startSitu', 9961 'finishSitu' 9962 ] 9963 }, 9964 { 9965 exact: [ 9966 'start', 9967 'soffset', 9968 'finish', 9969 'foffset' 9970 ] 9971 } 9972 ]); 9973 var exactFromRange = function (simRange) { 9974 return adt$1.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset); 9975 }; 9976 var getStart = function (selection) { 9977 return selection.match({ 9978 domRange: function (rng) { 9979 return SugarElement.fromDom(rng.startContainer); 9980 }, 9981 relative: function (startSitu, _finishSitu) { 9982 return Situ.getStart(startSitu); 9983 }, 9984 exact: function (start, _soffset, _finish, _foffset) { 9985 return start; 9986 } 9987 }); 9988 }; 9989 var domRange = adt$1.domRange; 9990 var relative = adt$1.relative; 9991 var exact = adt$1.exact; 9992 var getWin$1 = function (selection) { 9993 var start = getStart(selection); 9994 return defaultView(start); 9995 }; 9996 var range = SimRange.create; 9997 var SimSelection = { 9998 domRange: domRange, 9999 relative: relative, 10000 exact: exact, 10001 exactFromRange: exactFromRange, 10002 getWin: getWin$1, 10003 range: range 10004 }; 10005 10006 var beforeSpecial = function (element, offset) { 10007 var name = name$1(element); 10008 if ('input' === name) { 10009 return Situ.after(element); 10010 } else if (!contains$1([ 10011 'br', 10012 'img' 10013 ], name)) { 10014 return Situ.on(element, offset); 10015 } else { 10016 return offset === 0 ? Situ.before(element) : Situ.after(element); 10017 } 10018 }; 10019 var preprocessExact = function (start, soffset, finish, foffset) { 10020 var startSitu = beforeSpecial(start, soffset); 10021 var finishSitu = beforeSpecial(finish, foffset); 10022 return SimSelection.relative(startSitu, finishSitu); 10023 }; 10024 10025 var makeRange = function (start, soffset, finish, foffset) { 10026 var doc = owner$2(start); 10027 var rng = doc.dom.createRange(); 10028 rng.setStart(start.dom, soffset); 10029 rng.setEnd(finish.dom, foffset); 10030 return rng; 10031 }; 10032 var after = function (start, soffset, finish, foffset) { 10033 var r = makeRange(start, soffset, finish, foffset); 10034 var same = eq(start, finish) && soffset === foffset; 10035 return r.collapsed && !same; 10036 }; 10037 10038 var getNativeSelection = function (win) { 10039 return Optional.from(win.getSelection()); 10040 }; 10041 var doSetNativeRange = function (win, rng) { 10042 getNativeSelection(win).each(function (selection) { 10043 selection.removeAllRanges(); 10044 selection.addRange(rng); 10045 }); 10046 }; 10047 var doSetRange = function (win, start, soffset, finish, foffset) { 10048 var rng = exactToNative(win, start, soffset, finish, foffset); 10049 doSetNativeRange(win, rng); 10050 }; 10051 var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) { 10052 selection.collapse(start.dom, soffset); 10053 selection.extend(finish.dom, foffset); 10054 }; 10055 var setRangeFromRelative = function (win, relative) { 10056 return diagnose(win, relative).match({ 10057 ltr: function (start, soffset, finish, foffset) { 10058 doSetRange(win, start, soffset, finish, foffset); 10059 }, 10060 rtl: function (start, soffset, finish, foffset) { 10061 getNativeSelection(win).each(function (selection) { 10062 if (selection.setBaseAndExtent) { 10063 selection.setBaseAndExtent(start.dom, soffset, finish.dom, foffset); 10064 } else if (selection.extend) { 10065 try { 10066 setLegacyRtlRange(win, selection, start, soffset, finish, foffset); 10067 } catch (e) { 10068 doSetRange(win, finish, foffset, start, soffset); 10069 } 10070 } else { 10071 doSetRange(win, finish, foffset, start, soffset); 10072 } 10073 }); 10074 } 10075 }); 10076 }; 10077 var setExact = function (win, start, soffset, finish, foffset) { 10078 var relative = preprocessExact(start, soffset, finish, foffset); 10079 setRangeFromRelative(win, relative); 10080 }; 10081 var readRange = function (selection) { 10082 if (selection.rangeCount > 0) { 10083 var firstRng = selection.getRangeAt(0); 10084 var lastRng = selection.getRangeAt(selection.rangeCount - 1); 10085 return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset)); 10086 } else { 10087 return Optional.none(); 10088 } 10089 }; 10090 var doGetExact = function (selection) { 10091 if (selection.anchorNode === null || selection.focusNode === null) { 10092 return readRange(selection); 10093 } else { 10094 var anchor = SugarElement.fromDom(selection.anchorNode); 10095 var focus_1 = SugarElement.fromDom(selection.focusNode); 10096 return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection); 10097 } 10098 }; 10099 var getExact = function (win) { 10100 return getNativeSelection(win).filter(function (sel) { 10101 return sel.rangeCount > 0; 10102 }).bind(doGetExact); 10103 }; 10104 var get = function (win) { 10105 return getExact(win).map(function (range) { 10106 return SimSelection.exact(range.start, range.soffset, range.finish, range.foffset); 10107 }); 10108 }; 10109 var getFirstRect = function (win, selection) { 10110 var rng = asLtrRange(win, selection); 10111 return getFirstRect$1(rng); 10112 }; 10113 var clear = function (win) { 10114 getNativeSelection(win).each(function (selection) { 10115 return selection.removeAllRanges(); 10116 }); 10117 }; 10118 10119 var getBodyFromFrame = function (frame) { 10120 return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document.body)); 10121 }; 10122 var getDocFromFrame = function (frame) { 10123 return Optional.some(SugarElement.fromDom(frame.dom.contentWindow.document)); 10124 }; 10125 var getWinFromFrame = function (frame) { 10126 return Optional.from(frame.dom.contentWindow); 10127 }; 10128 var getSelectionFromFrame = function (frame) { 10129 var optWin = getWinFromFrame(frame); 10130 return optWin.bind(getExact); 10131 }; 10132 var getFrame = function (editor) { 10133 return editor.getFrame(); 10134 }; 10135 var getOrDerive = function (name, f) { 10136 return function (editor) { 10137 var g = editor[name].getOrThunk(function () { 10138 var frame = getFrame(editor); 10139 return function () { 10140 return f(frame); 10141 }; 10142 }); 10143 return g(); 10144 }; 10145 }; 10146 var getOrListen = function (editor, doc, name, type) { 10147 return editor[name].getOrThunk(function () { 10148 return function (handler) { 10149 return bind(doc, type, handler); 10150 }; 10151 }); 10152 }; 10153 var getActiveApi = function (editor) { 10154 var frame = getFrame(editor); 10155 var tryFallbackBox = function (win) { 10156 var isCollapsed = function (sel) { 10157 return eq(sel.start, sel.finish) && sel.soffset === sel.foffset; 10158 }; 10159 var toStartRect = function (sel) { 10160 var rect = sel.start.dom.getBoundingClientRect(); 10161 return rect.width > 0 || rect.height > 0 ? Optional.some(rect) : Optional.none(); 10162 }; 10163 return getExact(win).filter(isCollapsed).bind(toStartRect); 10164 }; 10165 return getBodyFromFrame(frame).bind(function (body) { 10166 return getDocFromFrame(frame).bind(function (doc) { 10167 return getWinFromFrame(frame).map(function (win) { 10168 var html = SugarElement.fromDom(doc.dom.documentElement); 10169 var getCursorBox = editor.getCursorBox.getOrThunk(function () { 10170 return function () { 10171 return get(win).bind(function (sel) { 10172 return getFirstRect(win, sel).orThunk(function () { 10173 return tryFallbackBox(win); 10174 }); 10175 }); 10176 }; 10177 }); 10178 var setSelection = editor.setSelection.getOrThunk(function () { 10179 return function (start, soffset, finish, foffset) { 10180 setExact(win, start, soffset, finish, foffset); 10181 }; 10182 }); 10183 var clearSelection = editor.clearSelection.getOrThunk(function () { 10184 return function () { 10185 clear(win); 10186 }; 10187 }); 10188 return { 10189 body: body, 10190 doc: doc, 10191 win: win, 10192 html: html, 10193 getSelection: curry(getSelectionFromFrame, frame), 10194 setSelection: setSelection, 10195 clearSelection: clearSelection, 10196 frame: frame, 10197 onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'), 10198 onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'SelectionChange'), 10199 onDomChanged: editor.onDomChanged, 10200 onScrollToCursor: editor.onScrollToCursor, 10201 onScrollToElement: editor.onScrollToElement, 10202 onToReading: editor.onToReading, 10203 onToEditing: editor.onToEditing, 10204 onToolbarScrollStart: editor.onToolbarScrollStart, 10205 onTouchContent: editor.onTouchContent, 10206 onTapContent: editor.onTapContent, 10207 onTouchToolstrip: editor.onTouchToolstrip, 10208 getCursorBox: getCursorBox 10209 }; 10210 }); 10211 }); 10212 }); 10213 }; 10214 var getWin = getOrDerive('getWin', getWinFromFrame); 10215 10216 var tag = function () { 10217 var head = first$1('head').getOrDie(); 10218 var nu = function () { 10219 var meta = SugarElement.fromTag('meta'); 10220 set$8(meta, 'name', 'viewport'); 10221 append$2(head, meta); 10222 return meta; 10223 }; 10224 var element = first$1('meta[name="viewport"]').getOrThunk(nu); 10225 var backup = get$b(element, 'content'); 10226 var maximize = function () { 10227 set$8(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0'); 10228 }; 10229 var restore = function () { 10230 if (backup !== undefined && backup !== null && backup.length > 0) { 10231 set$8(element, 'content', backup); 10232 } else { 10233 set$8(element, 'content', 'user-scalable=yes'); 10234 } 10235 }; 10236 return { 10237 maximize: maximize, 10238 restore: restore 10239 }; 10240 }; 10241 10242 var attr = 'data-ephox-mobile-fullscreen-style'; 10243 var siblingStyles = 'display:none!important;'; 10244 var ancestorPosition = 'position:absolute!important;'; 10245 var ancestorStyles = 'top:0!important;left:0!important;margin:0!important;padding:0!important;width:100%!important;height:100%!important;overflow:visible!important;'; 10246 var bgFallback = 'background-color:rgb(255,255,255)!important;'; 10247 var isAndroid = detect$1().os.isAndroid(); 10248 var matchColor = function (editorBody) { 10249 var color = get$8(editorBody, 'background-color'); 10250 return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback; 10251 }; 10252 var clobberStyles = function (container, editorBody) { 10253 var gatherSiblings = function (element) { 10254 return siblings(element, '*'); 10255 }; 10256 var clobber = function (clobberStyle) { 10257 return function (element) { 10258 var styles = get$b(element, 'style'); 10259 var backup = styles === undefined ? 'no-styles' : styles.trim(); 10260 if (backup === clobberStyle) { 10261 return; 10262 } else { 10263 set$8(element, attr, backup); 10264 set$8(element, 'style', clobberStyle); 10265 } 10266 }; 10267 }; 10268 var ancestors$1 = ancestors(container, '*'); 10269 var siblings$1 = bind$3(ancestors$1, gatherSiblings); 10270 var bgColor = matchColor(editorBody); 10271 each$1(siblings$1, clobber(siblingStyles)); 10272 each$1(ancestors$1, clobber(ancestorPosition + ancestorStyles + bgColor)); 10273 var containerStyles = isAndroid === true ? '' : ancestorPosition; 10274 clobber(containerStyles + ancestorStyles + bgColor)(container); 10275 }; 10276 var restoreStyles = function () { 10277 var clobberedEls = all('[' + attr + ']'); 10278 each$1(clobberedEls, function (element) { 10279 var restore = get$b(element, attr); 10280 if (restore !== 'no-styles') { 10281 set$8(element, 'style', restore); 10282 } else { 10283 remove$6(element, 'style'); 10284 } 10285 remove$6(element, attr); 10286 }); 10287 }; 10288 10289 var DelayedFunction = function (fun, delay) { 10290 var ref = null; 10291 var schedule = function () { 10292 var args = []; 10293 for (var _i = 0; _i < arguments.length; _i++) { 10294 args[_i] = arguments[_i]; 10295 } 10296 ref = setTimeout(function () { 10297 fun.apply(null, args); 10298 ref = null; 10299 }, delay); 10300 }; 10301 var cancel = function () { 10302 if (ref !== null) { 10303 clearTimeout(ref); 10304 ref = null; 10305 } 10306 }; 10307 return { 10308 cancel: cancel, 10309 schedule: schedule 10310 }; 10311 }; 10312 10313 var SIGNIFICANT_MOVE = 5; 10314 var LONGPRESS_DELAY = 400; 10315 var getTouch = function (event) { 10316 var raw = event.raw; 10317 if (raw.touches === undefined || raw.touches.length !== 1) { 10318 return Optional.none(); 10319 } 10320 return Optional.some(raw.touches[0]); 10321 }; 10322 var isFarEnough = function (touch, data) { 10323 var distX = Math.abs(touch.clientX - data.x); 10324 var distY = Math.abs(touch.clientY - data.y); 10325 return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE; 10326 }; 10327 var monitor$1 = function (settings) { 10328 var startData = value(); 10329 var longpressFired = Cell(false); 10330 var longpress$1 = DelayedFunction(function (event) { 10331 settings.triggerEvent(longpress(), event); 10332 longpressFired.set(true); 10333 }, LONGPRESS_DELAY); 10334 var handleTouchstart = function (event) { 10335 getTouch(event).each(function (touch) { 10336 longpress$1.cancel(); 10337 var data = { 10338 x: touch.clientX, 10339 y: touch.clientY, 10340 target: event.target 10341 }; 10342 longpress$1.schedule(event); 10343 longpressFired.set(false); 10344 startData.set(data); 10345 }); 10346 return Optional.none(); 10347 }; 10348 var handleTouchmove = function (event) { 10349 longpress$1.cancel(); 10350 getTouch(event).each(function (touch) { 10351 startData.on(function (data) { 10352 if (isFarEnough(touch, data)) { 10353 startData.clear(); 10354 } 10355 }); 10356 }); 10357 return Optional.none(); 10358 }; 10359 var handleTouchend = function (event) { 10360 longpress$1.cancel(); 10361 var isSame = function (data) { 10362 return eq(data.target, event.target); 10363 }; 10364 return startData.get().filter(isSame).map(function (_data) { 10365 if (longpressFired.get()) { 10366 event.prevent(); 10367 return false; 10368 } else { 10369 return settings.triggerEvent(tap(), event); 10370 } 10371 }); 10372 }; 10373 var handlers = wrapAll([ 10374 { 10375 key: touchstart(), 10376 value: handleTouchstart 10377 }, 10378 { 10379 key: touchmove(), 10380 value: handleTouchmove 10381 }, 10382 { 10383 key: touchend(), 10384 value: handleTouchend 10385 } 10386 ]); 10387 var fireIfReady = function (event, type) { 10388 return get$c(handlers, type).bind(function (handler) { 10389 return handler(event); 10390 }); 10391 }; 10392 return { fireIfReady: fireIfReady }; 10393 }; 10394 10395 var monitor = function (editorApi) { 10396 var tapEvent = monitor$1({ 10397 triggerEvent: function (type, evt) { 10398 editorApi.onTapContent(evt); 10399 } 10400 }); 10401 var onTouchend = function () { 10402 return bind(editorApi.body, 'touchend', function (evt) { 10403 tapEvent.fireIfReady(evt, 'touchend'); 10404 }); 10405 }; 10406 var onTouchmove = function () { 10407 return bind(editorApi.body, 'touchmove', function (evt) { 10408 tapEvent.fireIfReady(evt, 'touchmove'); 10409 }); 10410 }; 10411 var fireTouchstart = function (evt) { 10412 tapEvent.fireIfReady(evt, 'touchstart'); 10413 }; 10414 return { 10415 fireTouchstart: fireTouchstart, 10416 onTouchend: onTouchend, 10417 onTouchmove: onTouchmove 10418 }; 10419 }; 10420 10421 var isAndroid6 = detect$1().os.version.major >= 6; 10422 var initEvents$1 = function (editorApi, toolstrip, alloy) { 10423 var tapping = monitor(editorApi); 10424 var outerDoc = owner$2(toolstrip); 10425 var isRanged = function (sel) { 10426 return !eq(sel.start, sel.finish) || sel.soffset !== sel.foffset; 10427 }; 10428 var hasRangeInUi = function () { 10429 return active(outerDoc).filter(function (input) { 10430 return name$1(input) === 'input'; 10431 }).exists(function (input) { 10432 return input.dom.selectionStart !== input.dom.selectionEnd; 10433 }); 10434 }; 10435 var updateMargin = function () { 10436 var rangeInContent = editorApi.doc.dom.hasFocus() && editorApi.getSelection().exists(isRanged); 10437 alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off); 10438 }; 10439 var listeners = [ 10440 bind(editorApi.body, 'touchstart', function (evt) { 10441 editorApi.onTouchContent(); 10442 tapping.fireTouchstart(evt); 10443 }), 10444 tapping.onTouchmove(), 10445 tapping.onTouchend(), 10446 bind(toolstrip, 'touchstart', function (_evt) { 10447 editorApi.onTouchToolstrip(); 10448 }), 10449 editorApi.onToReading(function () { 10450 blur$1(editorApi.body); 10451 }), 10452 editorApi.onToEditing(noop), 10453 editorApi.onScrollToCursor(function (tinyEvent) { 10454 tinyEvent.preventDefault(); 10455 editorApi.getCursorBox().each(function (bounds) { 10456 var cWin = editorApi.win; 10457 var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight; 10458 var cScrollBy = isOutside ? bounds.bottom - cWin.innerHeight + 50 : 0; 10459 if (cScrollBy !== 0) { 10460 cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy); 10461 } 10462 }); 10463 }) 10464 ].concat(isAndroid6 === true ? [] : [ 10465 bind(SugarElement.fromDom(editorApi.win), 'blur', function () { 10466 alloy.getByDom(toolstrip).each(Toggling.off); 10467 }), 10468 bind(outerDoc, 'select', updateMargin), 10469 bind(editorApi.doc, 'selectionchange', updateMargin) 10470 ]); 10471 var destroy = function () { 10472 each$1(listeners, function (l) { 10473 l.unbind(); 10474 }); 10475 }; 10476 return { destroy: destroy }; 10477 }; 10478 10479 var safeParse = function (element, attribute) { 10480 var parsed = parseInt(get$b(element, attribute), 10); 10481 return isNaN(parsed) ? 0 : parsed; 10482 }; 10483 10484 var COLLAPSED_WIDTH = 2; 10485 var collapsedRect = function (rect) { 10486 return __assign(__assign({}, rect), { width: COLLAPSED_WIDTH }); 10487 }; 10488 var toRect = function (rawRect) { 10489 return { 10490 left: rawRect.left, 10491 top: rawRect.top, 10492 right: rawRect.right, 10493 bottom: rawRect.bottom, 10494 width: rawRect.width, 10495 height: rawRect.height 10496 }; 10497 }; 10498 var getRectsFromRange = function (range) { 10499 if (!range.collapsed) { 10500 return map$2(range.getClientRects(), toRect); 10501 } else { 10502 var start_1 = SugarElement.fromDom(range.startContainer); 10503 return parent(start_1).bind(function (parent) { 10504 var selection = SimSelection.exact(start_1, range.startOffset, parent, getEnd(parent)); 10505 var optRect = getFirstRect(range.startContainer.ownerDocument.defaultView, selection); 10506 return optRect.map(collapsedRect).map(pure$2); 10507 }).getOr([]); 10508 } 10509 }; 10510 var getRectangles = function (cWin) { 10511 var sel = cWin.getSelection(); 10512 return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : []; 10513 }; 10514 10515 var autocompleteHack = function () { 10516 return function (f) { 10517 global$2.setTimeout(function () { 10518 f(); 10519 }, 0); 10520 }; 10521 }; 10522 var resume$1 = function (cWin) { 10523 cWin.focus(); 10524 var iBody = SugarElement.fromDom(cWin.document.body); 10525 var inInput = active().exists(function (elem) { 10526 return contains$1([ 10527 'input', 10528 'textarea' 10529 ], name$1(elem)); 10530 }); 10531 var transaction = inInput ? autocompleteHack() : apply$1; 10532 transaction(function () { 10533 active().each(blur$1); 10534 focus$3(iBody); 10535 }); 10536 }; 10537 10538 var EXTRA_SPACING = 50; 10539 var data = 'data-' + resolve('last-outer-height'); 10540 var setLastHeight = function (cBody, value) { 10541 set$8(cBody, data, value); 10542 }; 10543 var getLastHeight = function (cBody) { 10544 return safeParse(cBody, data); 10545 }; 10546 var getBoundsFrom = function (rect) { 10547 return { 10548 top: rect.top, 10549 bottom: rect.top + rect.height 10550 }; 10551 }; 10552 var getBounds = function (cWin) { 10553 var rects = getRectangles(cWin); 10554 return rects.length > 0 ? Optional.some(rects[0]).map(getBoundsFrom) : Optional.none(); 10555 }; 10556 var findDelta = function (outerWindow, cBody) { 10557 var last = getLastHeight(cBody); 10558 var current = outerWindow.innerHeight; 10559 return last > current ? Optional.some(last - current) : Optional.none(); 10560 }; 10561 var calculate = function (cWin, bounds, delta) { 10562 var isOutside = bounds.top > cWin.innerHeight || bounds.bottom > cWin.innerHeight; 10563 return isOutside ? Math.min(delta, bounds.bottom - cWin.innerHeight + EXTRA_SPACING) : 0; 10564 }; 10565 var setup$2 = function (outerWindow, cWin) { 10566 var cBody = SugarElement.fromDom(cWin.document.body); 10567 var toEditing = function () { 10568 resume$1(cWin); 10569 }; 10570 var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () { 10571 findDelta(outerWindow, cBody).each(function (delta) { 10572 getBounds(cWin).each(function (bounds) { 10573 var cScrollBy = calculate(cWin, bounds, delta); 10574 if (cScrollBy !== 0) { 10575 cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy); 10576 } 10577 }); 10578 }); 10579 setLastHeight(cBody, outerWindow.innerHeight); 10580 }); 10581 setLastHeight(cBody, outerWindow.innerHeight); 10582 var destroy = function () { 10583 onResize.unbind(); 10584 }; 10585 return { 10586 toEditing: toEditing, 10587 destroy: destroy 10588 }; 10589 }; 10590 10591 var create$2 = function (platform, mask) { 10592 var meta = tag(); 10593 var androidApi = api$2(); 10594 var androidEvents = api$2(); 10595 var enter = function () { 10596 mask.hide(); 10597 add$1(platform.container, resolve('fullscreen-maximized')); 10598 add$1(platform.container, resolve('android-maximized')); 10599 meta.maximize(); 10600 add$1(platform.body, resolve('android-scroll-reload')); 10601 androidApi.set(setup$2(platform.win, getWin(platform.editor).getOrDie('no'))); 10602 getActiveApi(platform.editor).each(function (editorApi) { 10603 clobberStyles(platform.container, editorApi.body); 10604 androidEvents.set(initEvents$1(editorApi, platform.toolstrip, platform.alloy)); 10605 }); 10606 }; 10607 var exit = function () { 10608 meta.restore(); 10609 mask.show(); 10610 remove$3(platform.container, resolve('fullscreen-maximized')); 10611 remove$3(platform.container, resolve('android-maximized')); 10612 restoreStyles(); 10613 remove$3(platform.body, resolve('android-scroll-reload')); 10614 androidEvents.clear(); 10615 androidApi.clear(); 10616 }; 10617 return { 10618 enter: enter, 10619 exit: exit 10620 }; 10621 }; 10622 10623 var first = function (fn, rate) { 10624 var timer = null; 10625 var cancel = function () { 10626 if (!isNull(timer)) { 10627 clearTimeout(timer); 10628 timer = null; 10629 } 10630 }; 10631 var throttle = function () { 10632 var args = []; 10633 for (var _i = 0; _i < arguments.length; _i++) { 10634 args[_i] = arguments[_i]; 10635 } 10636 if (isNull(timer)) { 10637 timer = setTimeout(function () { 10638 timer = null; 10639 fn.apply(null, args); 10640 }, rate); 10641 } 10642 }; 10643 return { 10644 cancel: cancel, 10645 throttle: throttle 10646 }; 10647 }; 10648 var last = function (fn, rate) { 10649 var timer = null; 10650 var cancel = function () { 10651 if (!isNull(timer)) { 10652 clearTimeout(timer); 10653 timer = null; 10654 } 10655 }; 10656 var throttle = function () { 10657 var args = []; 10658 for (var _i = 0; _i < arguments.length; _i++) { 10659 args[_i] = arguments[_i]; 10660 } 10661 cancel(); 10662 timer = setTimeout(function () { 10663 timer = null; 10664 fn.apply(null, args); 10665 }, rate); 10666 }; 10667 return { 10668 cancel: cancel, 10669 throttle: throttle 10670 }; 10671 }; 10672 10673 var sketch = function (onView, _translate) { 10674 var memIcon = record(Container.sketch({ 10675 dom: dom$1('<div aria-hidden="true" class="$prefix}-mask-tap-icon"></div>'), 10676 containerBehaviours: derive$2([Toggling.config({ 10677 toggleClass: resolve('mask-tap-icon-selected'), 10678 toggleOnExecute: false 10679 })]) 10680 })); 10681 var onViewThrottle = first(onView, 200); 10682 return Container.sketch({ 10683 dom: dom$1('<div class="$prefix}-disabled-mask"></div>'), 10684 components: [Container.sketch({ 10685 dom: dom$1('<div class="$prefix}-content-container"></div>'), 10686 components: [Button.sketch({ 10687 dom: dom$1('<div class="$prefix}-content-tap-section"></div>'), 10688 components: [memIcon.asSpec()], 10689 action: function (_button) { 10690 onViewThrottle.throttle(); 10691 }, 10692 buttonBehaviours: derive$2([Toggling.config({ toggleClass: resolve('mask-tap-icon-selected') })]) 10693 })] 10694 })] 10695 }); 10696 }; 10697 10698 var unbindNoop = constant$1({ unbind: noop }); 10699 var MobileSchema = objOf([ 10700 requiredObjOf('editor', [ 10701 required$1('getFrame'), 10702 option('getBody'), 10703 option('getDoc'), 10704 option('getWin'), 10705 option('getSelection'), 10706 option('setSelection'), 10707 option('clearSelection'), 10708 option('cursorSaver'), 10709 option('onKeyup'), 10710 option('onNodeChanged'), 10711 option('getCursorBox'), 10712 required$1('onDomChanged'), 10713 defaulted('onTouchContent', noop), 10714 defaulted('onTapContent', noop), 10715 defaulted('onTouchToolstrip', noop), 10716 defaulted('onScrollToCursor', unbindNoop), 10717 defaulted('onScrollToElement', unbindNoop), 10718 defaulted('onToEditing', unbindNoop), 10719 defaulted('onToReading', unbindNoop), 10720 defaulted('onToolbarScrollStart', identity) 10721 ]), 10722 required$1('socket'), 10723 required$1('toolstrip'), 10724 required$1('dropup'), 10725 required$1('toolbar'), 10726 required$1('container'), 10727 required$1('alloy'), 10728 customField('win', function (spec) { 10729 return owner$2(spec.socket).dom.defaultView; 10730 }), 10731 customField('body', function (spec) { 10732 return SugarElement.fromDom(spec.socket.dom.ownerDocument.body); 10733 }), 10734 defaulted('translate', identity), 10735 defaulted('setReadOnly', noop), 10736 defaulted('readOnlyOnInit', always) 10737 ]); 10738 10739 var produce$1 = function (raw) { 10740 var mobile = asRawOrDie$1('Getting AndroidWebapp schema', MobileSchema, raw); 10741 set$5(mobile.toolstrip, 'width', '100%'); 10742 var onTap = function () { 10743 mobile.setReadOnly(mobile.readOnlyOnInit()); 10744 mode.enter(); 10745 }; 10746 var mask = build$1(sketch(onTap, mobile.translate)); 10747 mobile.alloy.add(mask); 10748 var maskApi = { 10749 show: function () { 10750 mobile.alloy.add(mask); 10751 }, 10752 hide: function () { 10753 mobile.alloy.remove(mask); 10754 } 10755 }; 10756 append$2(mobile.container, mask.element); 10757 var mode = create$2(mobile, maskApi); 10758 return { 10759 setReadOnly: mobile.setReadOnly, 10760 refreshStructure: noop, 10761 enter: mode.enter, 10762 exit: mode.exit, 10763 destroy: noop 10764 }; 10765 }; 10766 10767 var schema$1 = constant$1([ 10768 required$1('dom'), 10769 defaulted('shell', true), 10770 field$1('toolbarBehaviours', [Replacing]) 10771 ]); 10772 var enhanceGroups = function () { 10773 return { behaviours: derive$2([Replacing.config({})]) }; 10774 }; 10775 var parts$1 = constant$1([optional({ 10776 name: 'groups', 10777 overrides: enhanceGroups 10778 })]); 10779 10780 var factory$1 = function (detail, components, _spec, _externals) { 10781 var setGroups = function (toolbar, groups) { 10782 getGroupContainer(toolbar).fold(function () { 10783 console.error('Toolbar was defined to not be a shell, but no groups container was specified in components'); 10784 throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components'); 10785 }, function (container) { 10786 Replacing.set(container, groups); 10787 }); 10788 }; 10789 var getGroupContainer = function (component) { 10790 return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups'); 10791 }; 10792 var extra = detail.shell ? { 10793 behaviours: [Replacing.config({})], 10794 components: [] 10795 } : { 10796 behaviours: [], 10797 components: components 10798 }; 10799 return { 10800 uid: detail.uid, 10801 dom: detail.dom, 10802 components: extra.components, 10803 behaviours: augment(detail.toolbarBehaviours, extra.behaviours), 10804 apis: { setGroups: setGroups }, 10805 domModification: { attributes: { role: 'group' } } 10806 }; 10807 }; 10808 var Toolbar = composite({ 10809 name: 'Toolbar', 10810 configFields: schema$1(), 10811 partFields: parts$1(), 10812 factory: factory$1, 10813 apis: { 10814 setGroups: function (apis, toolbar, groups) { 10815 apis.setGroups(toolbar, groups); 10816 } 10817 } 10818 }); 10819 10820 var schema = constant$1([ 10821 required$1('items'), 10822 markers(['itemSelector']), 10823 field$1('tgroupBehaviours', [Keying]) 10824 ]); 10825 var parts = constant$1([group({ 10826 name: 'items', 10827 unit: 'item' 10828 })]); 10829 10830 var factory = function (detail, components, _spec, _externals) { 10831 return { 10832 uid: detail.uid, 10833 dom: detail.dom, 10834 components: components, 10835 behaviours: augment(detail.tgroupBehaviours, [Keying.config({ 10836 mode: 'flow', 10837 selector: detail.markers.itemSelector 10838 })]), 10839 domModification: { attributes: { role: 'toolbar' } } 10840 }; 10841 }; 10842 var ToolbarGroup = composite({ 10843 name: 'ToolbarGroup', 10844 configFields: schema(), 10845 partFields: parts(), 10846 factory: factory 10847 }); 10848 10849 var dataHorizontal = 'data-' + resolve('horizontal-scroll'); 10850 var canScrollVertically = function (container) { 10851 container.dom.scrollTop = 1; 10852 var result = container.dom.scrollTop !== 0; 10853 container.dom.scrollTop = 0; 10854 return result; 10855 }; 10856 var canScrollHorizontally = function (container) { 10857 container.dom.scrollLeft = 1; 10858 var result = container.dom.scrollLeft !== 0; 10859 container.dom.scrollLeft = 0; 10860 return result; 10861 }; 10862 var hasVerticalScroll = function (container) { 10863 return container.dom.scrollTop > 0 || canScrollVertically(container); 10864 }; 10865 var hasHorizontalScroll = function (container) { 10866 return container.dom.scrollLeft > 0 || canScrollHorizontally(container); 10867 }; 10868 var markAsHorizontal = function (container) { 10869 set$8(container, dataHorizontal, 'true'); 10870 }; 10871 var hasScroll = function (container) { 10872 return get$b(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container); 10873 }; 10874 var exclusive = function (scope, selector) { 10875 return bind(scope, 'touchmove', function (event) { 10876 closest$1(event.target, selector).filter(hasScroll).fold(function () { 10877 event.prevent(); 10878 }, noop); 10879 }); 10880 }; 10881 10882 var ScrollingToolbar = function () { 10883 var makeGroup = function (gSpec) { 10884 var scrollClass = gSpec.scrollable === true ? '$prefix}-toolbar-scrollable-group' : ''; 10885 return { 10886 dom: dom$1('<div aria-label="' + gSpec.label + '" class="$prefix}-toolbar-group ' + scrollClass + '"></div>'), 10887 tgroupBehaviours: derive$2([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, _simulatedEvent) { 10888 set$5(component.element, 'overflow-x', 'auto'); 10889 markAsHorizontal(component.element); 10890 register$2(component.element); 10891 })] : [])]), 10892 components: [Container.sketch({ components: [ToolbarGroup.parts.items({})] })], 10893 markers: { itemSelector: '.' + resolve('toolbar-group-item') }, 10894 items: gSpec.items 10895 }; 10896 }; 10897 var toolbar = build$1(Toolbar.sketch({ 10898 dom: dom$1('<div class="$prefix}-toolbar"></div>'), 10899 components: [Toolbar.parts.groups({})], 10900 toolbarBehaviours: derive$2([ 10901 Toggling.config({ 10902 toggleClass: resolve('context-toolbar'), 10903 toggleOnExecute: false, 10904 aria: { mode: 'none' } 10905 }), 10906 Keying.config({ mode: 'cyclic' }) 10907 ]), 10908 shell: true 10909 })); 10910 var wrapper = build$1(Container.sketch({ 10911 dom: { classes: [resolve('toolstrip')] }, 10912 components: [premade(toolbar)], 10913 containerBehaviours: derive$2([Toggling.config({ 10914 toggleClass: resolve('android-selection-context-toolbar'), 10915 toggleOnExecute: false 10916 })]) 10917 })); 10918 var resetGroups = function () { 10919 Toolbar.setGroups(toolbar, initGroups.get()); 10920 Toggling.off(toolbar); 10921 }; 10922 var initGroups = Cell([]); 10923 var setGroups = function (gs) { 10924 initGroups.set(gs); 10925 resetGroups(); 10926 }; 10927 var createGroups = function (gs) { 10928 return map$2(gs, compose(ToolbarGroup.sketch, makeGroup)); 10929 }; 10930 var refresh = function () { 10931 }; 10932 var setContextToolbar = function (gs) { 10933 Toggling.on(toolbar); 10934 Toolbar.setGroups(toolbar, gs); 10935 }; 10936 var restoreToolbar = function () { 10937 if (Toggling.isOn(toolbar)) { 10938 resetGroups(); 10939 } 10940 }; 10941 var focus = function () { 10942 Keying.focusIn(toolbar); 10943 }; 10944 return { 10945 wrapper: wrapper, 10946 toolbar: toolbar, 10947 createGroups: createGroups, 10948 setGroups: setGroups, 10949 setContextToolbar: setContextToolbar, 10950 restoreToolbar: restoreToolbar, 10951 refresh: refresh, 10952 focus: focus 10953 }; 10954 }; 10955 10956 var makeEditSwitch = function (webapp) { 10957 return build$1(Button.sketch({ 10958 dom: dom$1('<div class="$prefix}-mask-edit-icon $prefix}-icon"></div>'), 10959 action: function () { 10960 webapp.run(function (w) { 10961 w.setReadOnly(false); 10962 }); 10963 } 10964 })); 10965 }; 10966 var makeSocket = function () { 10967 return build$1(Container.sketch({ 10968 dom: dom$1('<div class="$prefix}-editor-socket"></div>'), 10969 components: [], 10970 containerBehaviours: derive$2([Replacing.config({})]) 10971 })); 10972 }; 10973 var showEdit = function (socket, switchToEdit) { 10974 Replacing.append(socket, premade(switchToEdit)); 10975 }; 10976 var hideEdit = function (socket, switchToEdit) { 10977 Replacing.remove(socket, switchToEdit); 10978 }; 10979 var updateMode = function (socket, switchToEdit, readOnly, root) { 10980 var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega; 10981 swap(root); 10982 var f = readOnly ? showEdit : hideEdit; 10983 f(socket, switchToEdit); 10984 }; 10985 10986 var getAnimationRoot = function (component, slideConfig) { 10987 return slideConfig.getAnimationRoot.fold(function () { 10988 return component.element; 10989 }, function (get) { 10990 return get(component); 10991 }); 10992 }; 10993 10994 var getDimensionProperty = function (slideConfig) { 10995 return slideConfig.dimension.property; 10996 }; 10997 var getDimension = function (slideConfig, elem) { 10998 return slideConfig.dimension.getDimension(elem); 10999 }; 11000 var disableTransitions = function (component, slideConfig) { 11001 var root = getAnimationRoot(component, slideConfig); 11002 remove$1(root, [ 11003 slideConfig.shrinkingClass, 11004 slideConfig.growingClass 11005 ]); 11006 }; 11007 var setShrunk = function (component, slideConfig) { 11008 remove$3(component.element, slideConfig.openClass); 11009 add$1(component.element, slideConfig.closedClass); 11010 set$5(component.element, getDimensionProperty(slideConfig), '0px'); 11011 reflow(component.element); 11012 }; 11013 var setGrown = function (component, slideConfig) { 11014 remove$3(component.element, slideConfig.closedClass); 11015 add$1(component.element, slideConfig.openClass); 11016 remove$2(component.element, getDimensionProperty(slideConfig)); 11017 }; 11018 var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) { 11019 slideState.setCollapsed(); 11020 set$5(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element)); 11021 reflow(component.element); 11022 disableTransitions(component, slideConfig); 11023 setShrunk(component, slideConfig); 11024 slideConfig.onStartShrink(component); 11025 slideConfig.onShrunk(component); 11026 }; 11027 var doStartShrink = function (component, slideConfig, slideState, calculatedSize) { 11028 var size = calculatedSize.getOrThunk(function () { 11029 return getDimension(slideConfig, component.element); 11030 }); 11031 slideState.setCollapsed(); 11032 set$5(component.element, getDimensionProperty(slideConfig), size); 11033 reflow(component.element); 11034 var root = getAnimationRoot(component, slideConfig); 11035 remove$3(root, slideConfig.growingClass); 11036 add$1(root, slideConfig.shrinkingClass); 11037 setShrunk(component, slideConfig); 11038 slideConfig.onStartShrink(component); 11039 }; 11040 var doStartSmartShrink = function (component, slideConfig, slideState) { 11041 var size = getDimension(slideConfig, component.element); 11042 var shrinker = size === '0px' ? doImmediateShrink : doStartShrink; 11043 shrinker(component, slideConfig, slideState, Optional.some(size)); 11044 }; 11045 var doStartGrow = function (component, slideConfig, slideState) { 11046 var root = getAnimationRoot(component, slideConfig); 11047 var wasShrinking = has(root, slideConfig.shrinkingClass); 11048 var beforeSize = getDimension(slideConfig, component.element); 11049 setGrown(component, slideConfig); 11050 var fullSize = getDimension(slideConfig, component.element); 11051 var startPartialGrow = function () { 11052 set$5(component.element, getDimensionProperty(slideConfig), beforeSize); 11053 reflow(component.element); 11054 }; 11055 var startCompleteGrow = function () { 11056 setShrunk(component, slideConfig); 11057 }; 11058 var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow; 11059 setStartSize(); 11060 remove$3(root, slideConfig.shrinkingClass); 11061 add$1(root, slideConfig.growingClass); 11062 setGrown(component, slideConfig); 11063 set$5(component.element, getDimensionProperty(slideConfig), fullSize); 11064 slideState.setExpanded(); 11065 slideConfig.onStartGrow(component); 11066 }; 11067 var refresh$1 = function (component, slideConfig, slideState) { 11068 if (slideState.isExpanded()) { 11069 remove$2(component.element, getDimensionProperty(slideConfig)); 11070 var fullSize = getDimension(slideConfig, component.element); 11071 set$5(component.element, getDimensionProperty(slideConfig), fullSize); 11072 } 11073 }; 11074 var grow = function (component, slideConfig, slideState) { 11075 if (!slideState.isExpanded()) { 11076 doStartGrow(component, slideConfig, slideState); 11077 } 11078 }; 11079 var shrink = function (component, slideConfig, slideState) { 11080 if (slideState.isExpanded()) { 11081 doStartSmartShrink(component, slideConfig, slideState); 11082 } 11083 }; 11084 var immediateShrink = function (component, slideConfig, slideState) { 11085 if (slideState.isExpanded()) { 11086 doImmediateShrink(component, slideConfig, slideState); 11087 } 11088 }; 11089 var hasGrown = function (component, slideConfig, slideState) { 11090 return slideState.isExpanded(); 11091 }; 11092 var hasShrunk = function (component, slideConfig, slideState) { 11093 return slideState.isCollapsed(); 11094 }; 11095 var isGrowing = function (component, slideConfig, _slideState) { 11096 var root = getAnimationRoot(component, slideConfig); 11097 return has(root, slideConfig.growingClass) === true; 11098 }; 11099 var isShrinking = function (component, slideConfig, _slideState) { 11100 var root = getAnimationRoot(component, slideConfig); 11101 return has(root, slideConfig.shrinkingClass) === true; 11102 }; 11103 var isTransitioning = function (component, slideConfig, slideState) { 11104 return isGrowing(component, slideConfig) || isShrinking(component, slideConfig); 11105 }; 11106 var toggleGrow = function (component, slideConfig, slideState) { 11107 var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow; 11108 f(component, slideConfig, slideState); 11109 }; 11110 11111 var SlidingApis = /*#__PURE__*/Object.freeze({ 11112 __proto__: null, 11113 refresh: refresh$1, 11114 grow: grow, 11115 shrink: shrink, 11116 immediateShrink: immediateShrink, 11117 hasGrown: hasGrown, 11118 hasShrunk: hasShrunk, 11119 isGrowing: isGrowing, 11120 isShrinking: isShrinking, 11121 isTransitioning: isTransitioning, 11122 toggleGrow: toggleGrow, 11123 disableTransitions: disableTransitions 11124 }); 11125 11126 var exhibit = function (base, slideConfig, _slideState) { 11127 var expanded = slideConfig.expanded; 11128 return expanded ? nu$3({ 11129 classes: [slideConfig.openClass], 11130 styles: {} 11131 }) : nu$3({ 11132 classes: [slideConfig.closedClass], 11133 styles: wrap(slideConfig.dimension.property, '0px') 11134 }); 11135 }; 11136 var events = function (slideConfig, slideState) { 11137 return derive$3([runOnSource(transitionend(), function (component, simulatedEvent) { 11138 var raw = simulatedEvent.event.raw; 11139 if (raw.propertyName === slideConfig.dimension.property) { 11140 disableTransitions(component, slideConfig); 11141 if (slideState.isExpanded()) { 11142 remove$2(component.element, slideConfig.dimension.property); 11143 } 11144 var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk; 11145 notify(component); 11146 } 11147 })]); 11148 }; 11149 11150 var ActiveSliding = /*#__PURE__*/Object.freeze({ 11151 __proto__: null, 11152 exhibit: exhibit, 11153 events: events 11154 }); 11155 11156 var SlidingSchema = [ 11157 required$1('closedClass'), 11158 required$1('openClass'), 11159 required$1('shrinkingClass'), 11160 required$1('growingClass'), 11161 option('getAnimationRoot'), 11162 onHandler('onShrunk'), 11163 onHandler('onStartShrink'), 11164 onHandler('onGrown'), 11165 onHandler('onStartGrow'), 11166 defaulted('expanded', false), 11167 requiredOf('dimension', choose$1('property', { 11168 width: [ 11169 output('property', 'width'), 11170 output('getDimension', function (elem) { 11171 return get$5(elem) + 'px'; 11172 }) 11173 ], 11174 height: [ 11175 output('property', 'height'), 11176 output('getDimension', function (elem) { 11177 return get$7(elem) + 'px'; 11178 }) 11179 ] 11180 })) 11181 ]; 11182 11183 var init$1 = function (spec) { 11184 var state = Cell(spec.expanded); 11185 var readState = function () { 11186 return 'expanded: ' + state.get(); 11187 }; 11188 return nu$2({ 11189 isExpanded: function () { 11190 return state.get() === true; 11191 }, 11192 isCollapsed: function () { 11193 return state.get() === false; 11194 }, 11195 setCollapsed: curry(state.set, false), 11196 setExpanded: curry(state.set, true), 11197 readState: readState 11198 }); 11199 }; 11200 11201 var SlidingState = /*#__PURE__*/Object.freeze({ 11202 __proto__: null, 11203 init: init$1 11204 }); 11205 11206 var Sliding = create$5({ 11207 fields: SlidingSchema, 11208 name: 'sliding', 11209 active: ActiveSliding, 11210 apis: SlidingApis, 11211 state: SlidingState 11212 }); 11213 11214 var build = function (refresh, scrollIntoView) { 11215 var dropup = build$1(Container.sketch({ 11216 dom: { 11217 tag: 'div', 11218 classes: [resolve('dropup')] 11219 }, 11220 components: [], 11221 containerBehaviours: derive$2([ 11222 Replacing.config({}), 11223 Sliding.config({ 11224 closedClass: resolve('dropup-closed'), 11225 openClass: resolve('dropup-open'), 11226 shrinkingClass: resolve('dropup-shrinking'), 11227 growingClass: resolve('dropup-growing'), 11228 dimension: { property: 'height' }, 11229 onShrunk: function (component) { 11230 refresh(); 11231 scrollIntoView(); 11232 Replacing.set(component, []); 11233 }, 11234 onGrown: function (_component) { 11235 refresh(); 11236 scrollIntoView(); 11237 } 11238 }), 11239 orientation(function (_component, _data) { 11240 disappear(noop); 11241 }) 11242 ]) 11243 })); 11244 var appear = function (menu, update, component) { 11245 if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) { 11246 window.requestAnimationFrame(function () { 11247 update(component); 11248 Replacing.set(dropup, [menu()]); 11249 Sliding.grow(dropup); 11250 }); 11251 } 11252 }; 11253 var disappear = function (onReadyToShrink) { 11254 window.requestAnimationFrame(function () { 11255 onReadyToShrink(); 11256 Sliding.shrink(dropup); 11257 }); 11258 }; 11259 return { 11260 appear: appear, 11261 disappear: disappear, 11262 component: dropup, 11263 element: dropup.element 11264 }; 11265 }; 11266 11267 var closest = function (scope, selector, isRoot) { 11268 return closest$1(scope, selector, isRoot).isSome(); 11269 }; 11270 11271 var isDangerous = function (event) { 11272 var keyEv = event.raw; 11273 return keyEv.which === BACKSPACE[0] && !contains$1([ 11274 'input', 11275 'textarea' 11276 ], name$1(event.target)) && !closest(event.target, '[contenteditable="true"]'); 11277 }; 11278 var isFirefox = function () { 11279 return detect$1().browser.isFirefox(); 11280 }; 11281 var bindFocus = function (container, handler) { 11282 if (isFirefox()) { 11283 return capture(container, 'focus', handler); 11284 } else { 11285 return bind(container, 'focusin', handler); 11286 } 11287 }; 11288 var bindBlur = function (container, handler) { 11289 if (isFirefox()) { 11290 return capture(container, 'blur', handler); 11291 } else { 11292 return bind(container, 'focusout', handler); 11293 } 11294 }; 11295 var setup$1 = function (container, rawSettings) { 11296 var settings = __assign({ stopBackspace: true }, rawSettings); 11297 var pointerEvents = [ 11298 'touchstart', 11299 'touchmove', 11300 'touchend', 11301 'touchcancel', 11302 'gesturestart', 11303 'mousedown', 11304 'mouseup', 11305 'mouseover', 11306 'mousemove', 11307 'mouseout', 11308 'click' 11309 ]; 11310 var tapEvent = monitor$1(settings); 11311 var simpleEvents = map$2(pointerEvents.concat([ 11312 'selectstart', 11313 'input', 11314 'contextmenu', 11315 'change', 11316 'transitionend', 11317 'transitioncancel', 11318 'drag', 11319 'dragstart', 11320 'dragend', 11321 'dragenter', 11322 'dragleave', 11323 'dragover', 11324 'drop', 11325 'keyup' 11326 ]), function (type) { 11327 return bind(container, type, function (event) { 11328 tapEvent.fireIfReady(event, type).each(function (tapStopped) { 11329 if (tapStopped) { 11330 event.kill(); 11331 } 11332 }); 11333 var stopped = settings.triggerEvent(type, event); 11334 if (stopped) { 11335 event.kill(); 11336 } 11337 }); 11338 }); 11339 var pasteTimeout = value(); 11340 var onPaste = bind(container, 'paste', function (event) { 11341 tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) { 11342 if (tapStopped) { 11343 event.kill(); 11344 } 11345 }); 11346 var stopped = settings.triggerEvent('paste', event); 11347 if (stopped) { 11348 event.kill(); 11349 } 11350 pasteTimeout.set(setTimeout(function () { 11351 settings.triggerEvent(postPaste(), event); 11352 }, 0)); 11353 }); 11354 var onKeydown = bind(container, 'keydown', function (event) { 11355 var stopped = settings.triggerEvent('keydown', event); 11356 if (stopped) { 11357 event.kill(); 11358 } else if (settings.stopBackspace && isDangerous(event)) { 11359 event.prevent(); 11360 } 11361 }); 11362 var onFocusIn = bindFocus(container, function (event) { 11363 var stopped = settings.triggerEvent('focusin', event); 11364 if (stopped) { 11365 event.kill(); 11366 } 11367 }); 11368 var focusoutTimeout = value(); 11369 var onFocusOut = bindBlur(container, function (event) { 11370 var stopped = settings.triggerEvent('focusout', event); 11371 if (stopped) { 11372 event.kill(); 11373 } 11374 focusoutTimeout.set(setTimeout(function () { 11375 settings.triggerEvent(postBlur(), event); 11376 }, 0)); 11377 }); 11378 var unbind = function () { 11379 each$1(simpleEvents, function (e) { 11380 e.unbind(); 11381 }); 11382 onKeydown.unbind(); 11383 onFocusIn.unbind(); 11384 onFocusOut.unbind(); 11385 onPaste.unbind(); 11386 pasteTimeout.on(clearTimeout); 11387 focusoutTimeout.on(clearTimeout); 11388 }; 11389 return { unbind: unbind }; 11390 }; 11391 11392 var derive$1 = function (rawEvent, rawTarget) { 11393 var source = get$c(rawEvent, 'target').getOr(rawTarget); 11394 return Cell(source); 11395 }; 11396 11397 var fromSource = function (event, source) { 11398 var stopper = Cell(false); 11399 var cutter = Cell(false); 11400 var stop = function () { 11401 stopper.set(true); 11402 }; 11403 var cut = function () { 11404 cutter.set(true); 11405 }; 11406 return { 11407 stop: stop, 11408 cut: cut, 11409 isStopped: stopper.get, 11410 isCut: cutter.get, 11411 event: event, 11412 setSource: source.set, 11413 getSource: source.get 11414 }; 11415 }; 11416 var fromExternal = function (event) { 11417 var stopper = Cell(false); 11418 var stop = function () { 11419 stopper.set(true); 11420 }; 11421 return { 11422 stop: stop, 11423 cut: noop, 11424 isStopped: stopper.get, 11425 isCut: never, 11426 event: event, 11427 setSource: die('Cannot set source of a broadcasted event'), 11428 getSource: die('Cannot get source of a broadcasted event') 11429 }; 11430 }; 11431 11432 var adt = Adt.generate([ 11433 { stopped: [] }, 11434 { resume: ['element'] }, 11435 { complete: [] } 11436 ]); 11437 var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) { 11438 var handler = lookup(eventType, target); 11439 var simulatedEvent = fromSource(rawEvent, source); 11440 return handler.fold(function () { 11441 logger.logEventNoHandlers(eventType, target); 11442 return adt.complete(); 11443 }, function (handlerInfo) { 11444 var descHandler = handlerInfo.descHandler; 11445 var eventHandler = getCurried(descHandler); 11446 eventHandler(simulatedEvent); 11447 if (simulatedEvent.isStopped()) { 11448 logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose); 11449 return adt.stopped(); 11450 } else if (simulatedEvent.isCut()) { 11451 logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose); 11452 return adt.complete(); 11453 } else { 11454 return parent(handlerInfo.element).fold(function () { 11455 logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose); 11456 return adt.complete(); 11457 }, function (parent) { 11458 logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose); 11459 return adt.resume(parent); 11460 }); 11461 } 11462 }); 11463 }; 11464 var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) { 11465 return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) { 11466 return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger); 11467 }, never); 11468 }; 11469 var triggerHandler = function (lookup, eventType, rawEvent, target, logger) { 11470 var source = derive$1(rawEvent, target); 11471 return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger); 11472 }; 11473 var broadcast = function (listeners, rawEvent, _logger) { 11474 var simulatedEvent = fromExternal(rawEvent); 11475 each$1(listeners, function (listener) { 11476 var descHandler = listener.descHandler; 11477 var handler = getCurried(descHandler); 11478 handler(simulatedEvent); 11479 }); 11480 return simulatedEvent.isStopped(); 11481 }; 11482 var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) { 11483 return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger); 11484 }; 11485 var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) { 11486 var source = derive$1(rawEvent, rawTarget); 11487 return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger); 11488 }; 11489 11490 var eventHandler = function (element, descHandler) { 11491 return { 11492 element: element, 11493 descHandler: descHandler 11494 }; 11495 }; 11496 var broadcastHandler = function (id, handler) { 11497 return { 11498 id: id, 11499 descHandler: handler 11500 }; 11501 }; 11502 var EventRegistry = function () { 11503 var registry = {}; 11504 var registerId = function (extraArgs, id, events) { 11505 each(events, function (v, k) { 11506 var handlers = registry[k] !== undefined ? registry[k] : {}; 11507 handlers[id] = curryArgs(v, extraArgs); 11508 registry[k] = handlers; 11509 }); 11510 }; 11511 var findHandler = function (handlers, elem) { 11512 return read(elem).bind(function (id) { 11513 return get$c(handlers, id); 11514 }).map(function (descHandler) { 11515 return eventHandler(elem, descHandler); 11516 }); 11517 }; 11518 var filterByType = function (type) { 11519 return get$c(registry, type).map(function (handlers) { 11520 return mapToArray(handlers, function (f, id) { 11521 return broadcastHandler(id, f); 11522 }); 11523 }).getOr([]); 11524 }; 11525 var find = function (isAboveRoot, type, target) { 11526 return get$c(registry, type).bind(function (handlers) { 11527 return closest$3(target, function (elem) { 11528 return findHandler(handlers, elem); 11529 }, isAboveRoot); 11530 }); 11531 }; 11532 var unregisterId = function (id) { 11533 each(registry, function (handlersById, _eventName) { 11534 if (has$2(handlersById, id)) { 11535 delete handlersById[id]; 11536 } 11537 }); 11538 }; 11539 return { 11540 registerId: registerId, 11541 unregisterId: unregisterId, 11542 filterByType: filterByType, 11543 find: find 11544 }; 11545 }; 11546 11547 var Registry = function () { 11548 var events = EventRegistry(); 11549 var components = {}; 11550 var readOrTag = function (component) { 11551 var elem = component.element; 11552 return read(elem).getOrThunk(function () { 11553 return write('uid-', component.element); 11554 }); 11555 }; 11556 var failOnDuplicate = function (component, tagId) { 11557 var conflict = components[tagId]; 11558 if (conflict === component) { 11559 unregister(component); 11560 } else { 11561 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'); 11562 } 11563 }; 11564 var register = function (component) { 11565 var tagId = readOrTag(component); 11566 if (hasNonNullableKey(components, tagId)) { 11567 failOnDuplicate(component, tagId); 11568 } 11569 var extraArgs = [component]; 11570 events.registerId(extraArgs, tagId, component.events); 11571 components[tagId] = component; 11572 }; 11573 var unregister = function (component) { 11574 read(component.element).each(function (tagId) { 11575 delete components[tagId]; 11576 events.unregisterId(tagId); 11577 }); 11578 }; 11579 var filter = function (type) { 11580 return events.filterByType(type); 11581 }; 11582 var find = function (isAboveRoot, type, target) { 11583 return events.find(isAboveRoot, type, target); 11584 }; 11585 var getById = function (id) { 11586 return get$c(components, id); 11587 }; 11588 return { 11589 find: find, 11590 filter: filter, 11591 register: register, 11592 unregister: unregister, 11593 getById: getById 11594 }; 11595 }; 11596 11597 var takeover$1 = function (root) { 11598 var isAboveRoot = function (el) { 11599 return parent(root.element).fold(always, function (parent) { 11600 return eq(el, parent); 11601 }); 11602 }; 11603 var registry = Registry(); 11604 var lookup = function (eventName, target) { 11605 return registry.find(isAboveRoot, eventName, target); 11606 }; 11607 var domEvents = setup$1(root.element, { 11608 triggerEvent: function (eventName, event) { 11609 return monitorEvent(eventName, event.target, function (logger) { 11610 return triggerUntilStopped(lookup, eventName, event, logger); 11611 }); 11612 } 11613 }); 11614 var systemApi = { 11615 debugInfo: constant$1('real'), 11616 triggerEvent: function (eventName, target, data) { 11617 monitorEvent(eventName, target, function (logger) { 11618 return triggerOnUntilStopped(lookup, eventName, data, target, logger); 11619 }); 11620 }, 11621 triggerFocus: function (target, originator) { 11622 read(target).fold(function () { 11623 focus$3(target); 11624 }, function (_alloyId) { 11625 monitorEvent(focus$4(), target, function (logger) { 11626 triggerHandler(lookup, focus$4(), { 11627 originator: originator, 11628 kill: noop, 11629 prevent: noop, 11630 target: target 11631 }, target, logger); 11632 return false; 11633 }); 11634 }); 11635 }, 11636 triggerEscape: function (comp, simulatedEvent) { 11637 systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event); 11638 }, 11639 getByUid: function (uid) { 11640 return getByUid(uid); 11641 }, 11642 getByDom: function (elem) { 11643 return getByDom(elem); 11644 }, 11645 build: build$1, 11646 addToGui: function (c) { 11647 add(c); 11648 }, 11649 removeFromGui: function (c) { 11650 remove(c); 11651 }, 11652 addToWorld: function (c) { 11653 addToWorld(c); 11654 }, 11655 removeFromWorld: function (c) { 11656 removeFromWorld(c); 11657 }, 11658 broadcast: function (message) { 11659 broadcast$1(message); 11660 }, 11661 broadcastOn: function (channels, message) { 11662 broadcastOn(channels, message); 11663 }, 11664 broadcastEvent: function (eventName, event) { 11665 broadcastEvent(eventName, event); 11666 }, 11667 isConnected: always 11668 }; 11669 var addToWorld = function (component) { 11670 component.connect(systemApi); 11671 if (!isText(component.element)) { 11672 registry.register(component); 11673 each$1(component.components(), addToWorld); 11674 systemApi.triggerEvent(systemInit(), component.element, { target: component.element }); 11675 } 11676 }; 11677 var removeFromWorld = function (component) { 11678 if (!isText(component.element)) { 11679 each$1(component.components(), removeFromWorld); 11680 registry.unregister(component); 11681 } 11682 component.disconnect(); 11683 }; 11684 var add = function (component) { 11685 attach(root, component); 11686 }; 11687 var remove = function (component) { 11688 detach(component); 11689 }; 11690 var destroy = function () { 11691 domEvents.unbind(); 11692 remove$7(root.element); 11693 }; 11694 var broadcastData = function (data) { 11695 var receivers = registry.filter(receive$1()); 11696 each$1(receivers, function (receiver) { 11697 var descHandler = receiver.descHandler; 11698 var handler = getCurried(descHandler); 11699 handler(data); 11700 }); 11701 }; 11702 var broadcast$1 = function (message) { 11703 broadcastData({ 11704 universal: true, 11705 data: message 11706 }); 11707 }; 11708 var broadcastOn = function (channels, message) { 11709 broadcastData({ 11710 universal: false, 11711 channels: channels, 11712 data: message 11713 }); 11714 }; 11715 var broadcastEvent = function (eventName, event) { 11716 var listeners = registry.filter(eventName); 11717 return broadcast(listeners, event); 11718 }; 11719 var getByUid = function (uid) { 11720 return registry.getById(uid).fold(function () { 11721 return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.')); 11722 }, Result.value); 11723 }; 11724 var getByDom = function (elem) { 11725 var uid = read(elem).getOr('not found'); 11726 return getByUid(uid); 11727 }; 11728 addToWorld(root); 11729 return { 11730 root: root, 11731 element: root.element, 11732 destroy: destroy, 11733 add: add, 11734 remove: remove, 11735 getByUid: getByUid, 11736 getByDom: getByDom, 11737 addToWorld: addToWorld, 11738 removeFromWorld: removeFromWorld, 11739 broadcast: broadcast$1, 11740 broadcastOn: broadcastOn, 11741 broadcastEvent: broadcastEvent 11742 }; 11743 }; 11744 11745 var READ_ONLY_MODE_CLASS = resolve('readonly-mode'); 11746 var EDIT_MODE_CLASS = resolve('edit-mode'); 11747 function OuterContainer (spec) { 11748 var root = build$1(Container.sketch({ 11749 dom: { classes: [resolve('outer-container')].concat(spec.classes) }, 11750 containerBehaviours: derive$2([Swapping.config({ 11751 alpha: READ_ONLY_MODE_CLASS, 11752 omega: EDIT_MODE_CLASS 11753 })]) 11754 })); 11755 return takeover$1(root); 11756 } 11757 11758 function AndroidRealm (scrollIntoView) { 11759 var alloy = OuterContainer({ classes: [resolve('android-container')] }); 11760 var toolbar = ScrollingToolbar(); 11761 var webapp = api$2(); 11762 var switchToEdit = makeEditSwitch(webapp); 11763 var socket = makeSocket(); 11764 var dropup = build(noop, scrollIntoView); 11765 alloy.add(toolbar.wrapper); 11766 alloy.add(socket); 11767 alloy.add(dropup.component); 11768 var setToolbarGroups = function (rawGroups) { 11769 var groups = toolbar.createGroups(rawGroups); 11770 toolbar.setGroups(groups); 11771 }; 11772 var setContextToolbar = function (rawGroups) { 11773 var groups = toolbar.createGroups(rawGroups); 11774 toolbar.setContextToolbar(groups); 11775 }; 11776 var focusToolbar = function () { 11777 toolbar.focus(); 11778 }; 11779 var restoreToolbar = function () { 11780 toolbar.restoreToolbar(); 11781 }; 11782 var init = function (spec) { 11783 webapp.set(produce$1(spec)); 11784 }; 11785 var exit = function () { 11786 webapp.run(function (w) { 11787 w.exit(); 11788 Replacing.remove(socket, switchToEdit); 11789 }); 11790 }; 11791 var updateMode$1 = function (readOnly) { 11792 updateMode(socket, switchToEdit, readOnly, alloy.root); 11793 }; 11794 return { 11795 system: alloy, 11796 element: alloy.element, 11797 init: init, 11798 exit: exit, 11799 setToolbarGroups: setToolbarGroups, 11800 setContextToolbar: setContextToolbar, 11801 focusToolbar: focusToolbar, 11802 restoreToolbar: restoreToolbar, 11803 updateMode: updateMode$1, 11804 socket: socket, 11805 dropup: dropup 11806 }; 11807 } 11808 11809 var input = function (parent, operation) { 11810 var input = SugarElement.fromTag('input'); 11811 setAll(input, { 11812 opacity: '0', 11813 position: 'absolute', 11814 top: '-1000px', 11815 left: '-1000px' 11816 }); 11817 append$2(parent, input); 11818 focus$3(input); 11819 operation(input); 11820 remove$7(input); 11821 }; 11822 11823 var refresh = function (winScope) { 11824 var sel = winScope.getSelection(); 11825 if (sel.rangeCount > 0) { 11826 var br = sel.getRangeAt(0); 11827 var r = winScope.document.createRange(); 11828 r.setStart(br.startContainer, br.startOffset); 11829 r.setEnd(br.endContainer, br.endOffset); 11830 sel.removeAllRanges(); 11831 sel.addRange(r); 11832 } 11833 }; 11834 11835 var resume = function (cWin, frame) { 11836 active().each(function (active) { 11837 if (!eq(active, frame)) { 11838 blur$1(active); 11839 } 11840 }); 11841 cWin.focus(); 11842 focus$3(SugarElement.fromDom(cWin.document.body)); 11843 refresh(cWin); 11844 }; 11845 11846 var stubborn = function (outerBody, cWin, page, frame) { 11847 var toEditing = function () { 11848 resume(cWin, frame); 11849 }; 11850 var toReading = function () { 11851 input(outerBody, blur$1); 11852 }; 11853 var captureInput = bind(page, 'keydown', function (evt) { 11854 if (!contains$1([ 11855 'input', 11856 'textarea' 11857 ], name$1(evt.target))) { 11858 toEditing(); 11859 } 11860 }); 11861 var onToolbarTouch = noop; 11862 var destroy = function () { 11863 captureInput.unbind(); 11864 }; 11865 return { 11866 toReading: toReading, 11867 toEditing: toEditing, 11868 onToolbarTouch: onToolbarTouch, 11869 destroy: destroy 11870 }; 11871 }; 11872 11873 var initEvents = function (editorApi, iosApi, toolstrip, socket, _dropup) { 11874 var saveSelectionFirst = function () { 11875 iosApi.run(function (api) { 11876 api.highlightSelection(); 11877 }); 11878 }; 11879 var refreshIosSelection = function () { 11880 iosApi.run(function (api) { 11881 api.refreshSelection(); 11882 }); 11883 }; 11884 var scrollToY = function (yTop, height) { 11885 var y = yTop - socket.dom.scrollTop; 11886 iosApi.run(function (api) { 11887 api.scrollIntoView(y, y + height); 11888 }); 11889 }; 11890 var scrollToElement = function (_target) { 11891 scrollToY(iosApi, socket); 11892 }; 11893 var scrollToCursor = function () { 11894 editorApi.getCursorBox().each(function (box) { 11895 scrollToY(box.top, box.height); 11896 }); 11897 }; 11898 var clearSelection = function () { 11899 iosApi.run(function (api) { 11900 api.clearSelection(); 11901 }); 11902 }; 11903 var clearAndRefresh = function () { 11904 clearSelection(); 11905 refreshThrottle.throttle(); 11906 }; 11907 var refreshView = function () { 11908 scrollToCursor(); 11909 iosApi.run(function (api) { 11910 api.syncHeight(); 11911 }); 11912 }; 11913 var reposition = function () { 11914 var toolbarHeight = get$7(toolstrip); 11915 iosApi.run(function (api) { 11916 api.setViewportOffset(toolbarHeight); 11917 }); 11918 refreshIosSelection(); 11919 refreshView(); 11920 }; 11921 var toEditing = function () { 11922 iosApi.run(function (api) { 11923 api.toEditing(); 11924 }); 11925 }; 11926 var toReading = function () { 11927 iosApi.run(function (api) { 11928 api.toReading(); 11929 }); 11930 }; 11931 var onToolbarTouch = function (event) { 11932 iosApi.run(function (api) { 11933 api.onToolbarTouch(event); 11934 }); 11935 }; 11936 var tapping = monitor(editorApi); 11937 var refreshThrottle = last(refreshView, 300); 11938 var listeners = [ 11939 editorApi.onKeyup(clearAndRefresh), 11940 editorApi.onNodeChanged(refreshIosSelection), 11941 editorApi.onDomChanged(refreshThrottle.throttle), 11942 editorApi.onDomChanged(refreshIosSelection), 11943 editorApi.onScrollToCursor(function (tinyEvent) { 11944 tinyEvent.preventDefault(); 11945 refreshThrottle.throttle(); 11946 }), 11947 editorApi.onScrollToElement(function (event) { 11948 scrollToElement(event.element); 11949 }), 11950 editorApi.onToEditing(toEditing), 11951 editorApi.onToReading(toReading), 11952 bind(editorApi.doc, 'touchend', function (touchEvent) { 11953 if (eq(editorApi.html, touchEvent.target) || eq(editorApi.body, touchEvent.target)) ; 11954 }), 11955 bind(toolstrip, 'transitionend', function (transitionEvent) { 11956 if (transitionEvent.raw.propertyName === 'height') { 11957 reposition(); 11958 } 11959 }), 11960 capture(toolstrip, 'touchstart', function (touchEvent) { 11961 saveSelectionFirst(); 11962 onToolbarTouch(touchEvent); 11963 editorApi.onTouchToolstrip(); 11964 }), 11965 bind(editorApi.body, 'touchstart', function (evt) { 11966 clearSelection(); 11967 editorApi.onTouchContent(); 11968 tapping.fireTouchstart(evt); 11969 }), 11970 tapping.onTouchmove(), 11971 tapping.onTouchend(), 11972 bind(editorApi.body, 'click', function (event) { 11973 event.kill(); 11974 }), 11975 bind(toolstrip, 'touchmove', function () { 11976 editorApi.onToolbarScrollStart(); 11977 }) 11978 ]; 11979 var destroy = function () { 11980 each$1(listeners, function (l) { 11981 l.unbind(); 11982 }); 11983 }; 11984 return { destroy: destroy }; 11985 }; 11986 11987 function FakeSelection (win, frame) { 11988 var doc = win.document; 11989 var container = SugarElement.fromTag('div'); 11990 add$1(container, resolve('unfocused-selections')); 11991 append$2(SugarElement.fromDom(doc.documentElement), container); 11992 var onTouch = bind(container, 'touchstart', function (event) { 11993 event.prevent(); 11994 resume(win, frame); 11995 clear(); 11996 }); 11997 var make = function (rectangle) { 11998 var span = SugarElement.fromTag('span'); 11999 add(span, [ 12000 resolve('layer-editor'), 12001 resolve('unfocused-selection') 12002 ]); 12003 setAll(span, { 12004 left: rectangle.left + 'px', 12005 top: rectangle.top + 'px', 12006 width: rectangle.width + 'px', 12007 height: rectangle.height + 'px' 12008 }); 12009 return span; 12010 }; 12011 var update = function () { 12012 clear(); 12013 var rectangles = getRectangles(win); 12014 var spans = map$2(rectangles, make); 12015 append$1(container, spans); 12016 }; 12017 var clear = function () { 12018 empty(container); 12019 }; 12020 var destroy = function () { 12021 onTouch.unbind(); 12022 remove$7(container); 12023 }; 12024 var isActive = function () { 12025 return children(container).length > 0; 12026 }; 12027 return { 12028 update: update, 12029 isActive: isActive, 12030 destroy: destroy, 12031 clear: clear 12032 }; 12033 } 12034 12035 var nu$1 = function (baseFn) { 12036 var data = Optional.none(); 12037 var callbacks = []; 12038 var map = function (f) { 12039 return nu$1(function (nCallback) { 12040 get(function (data) { 12041 nCallback(f(data)); 12042 }); 12043 }); 12044 }; 12045 var get = function (nCallback) { 12046 if (isReady()) { 12047 call(nCallback); 12048 } else { 12049 callbacks.push(nCallback); 12050 } 12051 }; 12052 var set = function (x) { 12053 if (!isReady()) { 12054 data = Optional.some(x); 12055 run(callbacks); 12056 callbacks = []; 12057 } 12058 }; 12059 var isReady = function () { 12060 return data.isSome(); 12061 }; 12062 var run = function (cbs) { 12063 each$1(cbs, call); 12064 }; 12065 var call = function (cb) { 12066 data.each(function (x) { 12067 setTimeout(function () { 12068 cb(x); 12069 }, 0); 12070 }); 12071 }; 12072 baseFn(set); 12073 return { 12074 get: get, 12075 map: map, 12076 isReady: isReady 12077 }; 12078 }; 12079 var pure$1 = function (a) { 12080 return nu$1(function (callback) { 12081 callback(a); 12082 }); 12083 }; 12084 var LazyValue = { 12085 nu: nu$1, 12086 pure: pure$1 12087 }; 12088 12089 var errorReporter = function (err) { 12090 setTimeout(function () { 12091 throw err; 12092 }, 0); 12093 }; 12094 var make = function (run) { 12095 var get = function (callback) { 12096 run().then(callback, errorReporter); 12097 }; 12098 var map = function (fab) { 12099 return make(function () { 12100 return run().then(fab); 12101 }); 12102 }; 12103 var bind = function (aFutureB) { 12104 return make(function () { 12105 return run().then(function (v) { 12106 return aFutureB(v).toPromise(); 12107 }); 12108 }); 12109 }; 12110 var anonBind = function (futureB) { 12111 return make(function () { 12112 return run().then(function () { 12113 return futureB.toPromise(); 12114 }); 12115 }); 12116 }; 12117 var toLazy = function () { 12118 return LazyValue.nu(get); 12119 }; 12120 var toCached = function () { 12121 var cache = null; 12122 return make(function () { 12123 if (cache === null) { 12124 cache = run(); 12125 } 12126 return cache; 12127 }); 12128 }; 12129 var toPromise = run; 12130 return { 12131 map: map, 12132 bind: bind, 12133 anonBind: anonBind, 12134 toLazy: toLazy, 12135 toCached: toCached, 12136 toPromise: toPromise, 12137 get: get 12138 }; 12139 }; 12140 var nu = function (baseFn) { 12141 return make(function () { 12142 return new Promise$1(baseFn); 12143 }); 12144 }; 12145 var pure = function (a) { 12146 return make(function () { 12147 return Promise$1.resolve(a); 12148 }); 12149 }; 12150 var Future = { 12151 nu: nu, 12152 pure: pure 12153 }; 12154 12155 var adjust = function (value, destination, amount) { 12156 if (Math.abs(value - destination) <= amount) { 12157 return Optional.none(); 12158 } else if (value < destination) { 12159 return Optional.some(value + amount); 12160 } else { 12161 return Optional.some(value - amount); 12162 } 12163 }; 12164 var create$1 = function () { 12165 var interval = null; 12166 var animate = function (getCurrent, destination, amount, increment, doFinish, rate) { 12167 var finished = false; 12168 var finish = function (v) { 12169 finished = true; 12170 doFinish(v); 12171 }; 12172 global$2.clearInterval(interval); 12173 var abort = function (v) { 12174 global$2.clearInterval(interval); 12175 finish(v); 12176 }; 12177 interval = global$2.setInterval(function () { 12178 var value = getCurrent(); 12179 adjust(value, destination, amount).fold(function () { 12180 global$2.clearInterval(interval); 12181 finish(destination); 12182 }, function (s) { 12183 increment(s, abort); 12184 if (!finished) { 12185 var newValue = getCurrent(); 12186 if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) { 12187 global$2.clearInterval(interval); 12188 finish(destination); 12189 } 12190 } 12191 }); 12192 }, rate); 12193 }; 12194 return { animate: animate }; 12195 }; 12196 12197 var findDevice = function (deviceWidth, deviceHeight) { 12198 var devices = [ 12199 { 12200 width: 320, 12201 height: 480, 12202 keyboard: { 12203 portrait: 300, 12204 landscape: 240 12205 } 12206 }, 12207 { 12208 width: 320, 12209 height: 568, 12210 keyboard: { 12211 portrait: 300, 12212 landscape: 240 12213 } 12214 }, 12215 { 12216 width: 375, 12217 height: 667, 12218 keyboard: { 12219 portrait: 305, 12220 landscape: 240 12221 } 12222 }, 12223 { 12224 width: 414, 12225 height: 736, 12226 keyboard: { 12227 portrait: 320, 12228 landscape: 240 12229 } 12230 }, 12231 { 12232 width: 768, 12233 height: 1024, 12234 keyboard: { 12235 portrait: 320, 12236 landscape: 400 12237 } 12238 }, 12239 { 12240 width: 1024, 12241 height: 1366, 12242 keyboard: { 12243 portrait: 380, 12244 landscape: 460 12245 } 12246 } 12247 ]; 12248 return findMap(devices, function (device) { 12249 return someIf(deviceWidth <= device.width && deviceHeight <= device.height, device.keyboard); 12250 }).getOr({ 12251 portrait: deviceHeight / 5, 12252 landscape: deviceWidth / 4 12253 }); 12254 }; 12255 12256 var softKeyboardLimits = function (outerWindow) { 12257 return findDevice(outerWindow.screen.width, outerWindow.screen.height); 12258 }; 12259 var accountableKeyboardHeight = function (outerWindow) { 12260 var portrait = get$1(outerWindow).isPortrait(); 12261 var limits = softKeyboardLimits(outerWindow); 12262 var keyboard = portrait ? limits.portrait : limits.landscape; 12263 var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width; 12264 return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard; 12265 }; 12266 var getGreenzone = function (socket, dropup) { 12267 var outerWindow = owner$2(socket).dom.defaultView; 12268 var viewportHeight = get$7(socket) + get$7(dropup); 12269 var acc = accountableKeyboardHeight(outerWindow); 12270 return viewportHeight - acc; 12271 }; 12272 var updatePadding = function (contentBody, socket, dropup) { 12273 var greenzoneHeight = getGreenzone(socket, dropup); 12274 var deltaHeight = get$7(socket) + get$7(dropup) - greenzoneHeight; 12275 set$5(contentBody, 'padding-bottom', deltaHeight + 'px'); 12276 }; 12277 12278 var fixture = Adt.generate([ 12279 { 12280 fixed: [ 12281 'element', 12282 'property', 12283 'offsetY' 12284 ] 12285 }, 12286 { 12287 scroller: [ 12288 'element', 12289 'offsetY' 12290 ] 12291 } 12292 ]); 12293 var yFixedData = 'data-' + resolve('position-y-fixed'); 12294 var yFixedProperty = 'data-' + resolve('y-property'); 12295 var yScrollingData = 'data-' + resolve('scrolling'); 12296 var windowSizeData = 'data-' + resolve('last-window-height'); 12297 var getYFixedData = function (element) { 12298 return safeParse(element, yFixedData); 12299 }; 12300 var getYFixedProperty = function (element) { 12301 return get$b(element, yFixedProperty); 12302 }; 12303 var getLastWindowSize = function (element) { 12304 return safeParse(element, windowSizeData); 12305 }; 12306 var classifyFixed = function (element, offsetY) { 12307 var prop = getYFixedProperty(element); 12308 return fixture.fixed(element, prop, offsetY); 12309 }; 12310 var classifyScrolling = function (element, offsetY) { 12311 return fixture.scroller(element, offsetY); 12312 }; 12313 var classify = function (element) { 12314 var offsetY = getYFixedData(element); 12315 var classifier = get$b(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed; 12316 return classifier(element, offsetY); 12317 }; 12318 var findFixtures = function (container) { 12319 var candidates = descendants(container, '[' + yFixedData + ']'); 12320 return map$2(candidates, classify); 12321 }; 12322 var takeoverToolbar = function (toolbar) { 12323 var oldToolbarStyle = get$b(toolbar, 'style'); 12324 setAll(toolbar, { 12325 position: 'absolute', 12326 top: '0px' 12327 }); 12328 set$8(toolbar, yFixedData, '0px'); 12329 set$8(toolbar, yFixedProperty, 'top'); 12330 var restore = function () { 12331 set$8(toolbar, 'style', oldToolbarStyle || ''); 12332 remove$6(toolbar, yFixedData); 12333 remove$6(toolbar, yFixedProperty); 12334 }; 12335 return { restore: restore }; 12336 }; 12337 var takeoverViewport = function (toolbarHeight, height, viewport) { 12338 var oldViewportStyle = get$b(viewport, 'style'); 12339 register$2(viewport); 12340 setAll(viewport, { 12341 position: 'absolute', 12342 height: height + 'px', 12343 width: '100%', 12344 top: toolbarHeight + 'px' 12345 }); 12346 set$8(viewport, yFixedData, toolbarHeight + 'px'); 12347 set$8(viewport, yScrollingData, 'true'); 12348 set$8(viewport, yFixedProperty, 'top'); 12349 var restore = function () { 12350 deregister(viewport); 12351 set$8(viewport, 'style', oldViewportStyle || ''); 12352 remove$6(viewport, yFixedData); 12353 remove$6(viewport, yScrollingData); 12354 remove$6(viewport, yFixedProperty); 12355 }; 12356 return { restore: restore }; 12357 }; 12358 var takeoverDropup = function (dropup) { 12359 var oldDropupStyle = get$b(dropup, 'style'); 12360 setAll(dropup, { 12361 position: 'absolute', 12362 bottom: '0px' 12363 }); 12364 set$8(dropup, yFixedData, '0px'); 12365 set$8(dropup, yFixedProperty, 'bottom'); 12366 var restore = function () { 12367 set$8(dropup, 'style', oldDropupStyle || ''); 12368 remove$6(dropup, yFixedData); 12369 remove$6(dropup, yFixedProperty); 12370 }; 12371 return { restore: restore }; 12372 }; 12373 var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) { 12374 var outerWindow = owner$2(viewport).dom.defaultView; 12375 var winH = outerWindow.innerHeight; 12376 set$8(viewport, windowSizeData, winH + 'px'); 12377 return winH - toolbarHeight - dropupHeight; 12378 }; 12379 var takeover = function (viewport, contentBody, toolbar, dropup) { 12380 var outerWindow = owner$2(viewport).dom.defaultView; 12381 var toolbarSetup = takeoverToolbar(toolbar); 12382 var toolbarHeight = get$7(toolbar); 12383 var dropupHeight = get$7(dropup); 12384 var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight); 12385 var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport); 12386 var dropupSetup = takeoverDropup(dropup); 12387 var isActive = true; 12388 var restore = function () { 12389 isActive = false; 12390 toolbarSetup.restore(); 12391 viewportSetup.restore(); 12392 dropupSetup.restore(); 12393 }; 12394 var isExpanding = function () { 12395 var currentWinHeight = outerWindow.innerHeight; 12396 var lastWinHeight = getLastWindowSize(viewport); 12397 return currentWinHeight > lastWinHeight; 12398 }; 12399 var refresh = function () { 12400 if (isActive) { 12401 var newToolbarHeight = get$7(toolbar); 12402 var dropupHeight_1 = get$7(dropup); 12403 var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1); 12404 set$8(viewport, yFixedData, newToolbarHeight + 'px'); 12405 set$5(viewport, 'height', newHeight + 'px'); 12406 updatePadding(contentBody, viewport, dropup); 12407 } 12408 }; 12409 var setViewportOffset = function (newYOffset) { 12410 var offsetPx = newYOffset + 'px'; 12411 set$8(viewport, yFixedData, offsetPx); 12412 refresh(); 12413 }; 12414 updatePadding(contentBody, viewport, dropup); 12415 return { 12416 setViewportOffset: setViewportOffset, 12417 isExpanding: isExpanding, 12418 isShrinking: not(isExpanding), 12419 refresh: refresh, 12420 restore: restore 12421 }; 12422 }; 12423 12424 var animator = create$1(); 12425 var ANIMATION_STEP = 15; 12426 var NUM_TOP_ANIMATION_FRAMES = 10; 12427 var ANIMATION_RATE = 10; 12428 var lastScroll = 'data-' + resolve('last-scroll-top'); 12429 var getTop = function (element) { 12430 var raw = getRaw(element, 'top').getOr('0'); 12431 return parseInt(raw, 10); 12432 }; 12433 var getScrollTop = function (element) { 12434 return parseInt(element.dom.scrollTop, 10); 12435 }; 12436 var moveScrollAndTop = function (element, destination, finalTop) { 12437 return Future.nu(function (callback) { 12438 var getCurrent = curry(getScrollTop, element); 12439 var update = function (newScroll) { 12440 element.dom.scrollTop = newScroll; 12441 set$5(element, 'top', getTop(element) + ANIMATION_STEP + 'px'); 12442 }; 12443 var finish = function () { 12444 element.dom.scrollTop = destination; 12445 set$5(element, 'top', finalTop + 'px'); 12446 callback(destination); 12447 }; 12448 animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE); 12449 }); 12450 }; 12451 var moveOnlyScroll = function (element, destination) { 12452 return Future.nu(function (callback) { 12453 var getCurrent = curry(getScrollTop, element); 12454 set$8(element, lastScroll, getCurrent()); 12455 var update = function (newScroll, abort) { 12456 var previous = safeParse(element, lastScroll); 12457 if (previous !== element.dom.scrollTop) { 12458 abort(element.dom.scrollTop); 12459 } else { 12460 element.dom.scrollTop = newScroll; 12461 set$8(element, lastScroll, newScroll); 12462 } 12463 }; 12464 var finish = function () { 12465 element.dom.scrollTop = destination; 12466 set$8(element, lastScroll, destination); 12467 callback(destination); 12468 }; 12469 var distance = Math.abs(destination - getCurrent()); 12470 var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES); 12471 animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE); 12472 }); 12473 }; 12474 var moveOnlyTop = function (element, destination) { 12475 return Future.nu(function (callback) { 12476 var getCurrent = curry(getTop, element); 12477 var update = function (newTop) { 12478 set$5(element, 'top', newTop + 'px'); 12479 }; 12480 var finish = function () { 12481 update(destination); 12482 callback(destination); 12483 }; 12484 var distance = Math.abs(destination - getCurrent()); 12485 var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES); 12486 animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE); 12487 }); 12488 }; 12489 var updateTop = function (element, amount) { 12490 var newTop = amount + getYFixedData(element) + 'px'; 12491 set$5(element, 'top', newTop); 12492 }; 12493 var moveWindowScroll = function (toolbar, viewport, destY) { 12494 var outerWindow = owner$2(toolbar).dom.defaultView; 12495 return Future.nu(function (callback) { 12496 updateTop(toolbar, destY); 12497 updateTop(viewport, destY); 12498 outerWindow.scrollTo(0, destY); 12499 callback(destY); 12500 }); 12501 }; 12502 12503 function BackgroundActivity (doAction) { 12504 var action = Cell(LazyValue.pure({})); 12505 var start = function (value) { 12506 var future = LazyValue.nu(function (callback) { 12507 return doAction(value).get(callback); 12508 }); 12509 action.set(future); 12510 }; 12511 var idle = function (g) { 12512 action.get().get(function () { 12513 g(); 12514 }); 12515 }; 12516 return { 12517 start: start, 12518 idle: idle 12519 }; 12520 } 12521 12522 var scrollIntoView = function (cWin, socket, dropup, top, bottom) { 12523 var greenzone = getGreenzone(socket, dropup); 12524 var refreshCursor = curry(refresh, cWin); 12525 if (top > greenzone || bottom > greenzone) { 12526 moveOnlyScroll(socket, socket.dom.scrollTop - greenzone + bottom).get(refreshCursor); 12527 } else if (top < 0) { 12528 moveOnlyScroll(socket, socket.dom.scrollTop + top).get(refreshCursor); 12529 } else ; 12530 }; 12531 12532 var par$1 = function (asyncValues, nu) { 12533 return nu(function (callback) { 12534 var r = []; 12535 var count = 0; 12536 var cb = function (i) { 12537 return function (value) { 12538 r[i] = value; 12539 count++; 12540 if (count >= asyncValues.length) { 12541 callback(r); 12542 } 12543 }; 12544 }; 12545 if (asyncValues.length === 0) { 12546 callback([]); 12547 } else { 12548 each$1(asyncValues, function (asyncValue, i) { 12549 asyncValue.get(cb(i)); 12550 }); 12551 } 12552 }); 12553 }; 12554 12555 var par = function (futures) { 12556 return par$1(futures, Future.nu); 12557 }; 12558 12559 var updateFixed = function (element, property, winY, offsetY) { 12560 var destination = winY + offsetY; 12561 set$5(element, property, destination + 'px'); 12562 return Future.pure(offsetY); 12563 }; 12564 var updateScrollingFixed = function (element, winY, offsetY) { 12565 var destTop = winY + offsetY; 12566 var oldProp = getRaw(element, 'top').getOr(offsetY); 12567 var delta = destTop - parseInt(oldProp, 10); 12568 var destScroll = element.dom.scrollTop + delta; 12569 return moveScrollAndTop(element, destScroll, destTop); 12570 }; 12571 var updateFixture = function (fixture, winY) { 12572 return fixture.fold(function (element, property, offsetY) { 12573 return updateFixed(element, property, winY, offsetY); 12574 }, function (element, offsetY) { 12575 return updateScrollingFixed(element, winY, offsetY); 12576 }); 12577 }; 12578 var updatePositions = function (container, winY) { 12579 var fixtures = findFixtures(container); 12580 var updates = map$2(fixtures, function (fixture) { 12581 return updateFixture(fixture, winY); 12582 }); 12583 return par(updates); 12584 }; 12585 12586 var VIEW_MARGIN = 5; 12587 var register = function (toolstrip, socket, container, outerWindow, structure, cWin) { 12588 var scroller = BackgroundActivity(function (y) { 12589 return moveWindowScroll(toolstrip, socket, y); 12590 }); 12591 var scrollBounds = function () { 12592 var rects = getRectangles(cWin); 12593 return Optional.from(rects[0]).bind(function (rect) { 12594 var viewTop = rect.top - socket.dom.scrollTop; 12595 var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN; 12596 return outside ? Optional.some({ 12597 top: viewTop, 12598 bottom: viewTop + rect.height 12599 }) : Optional.none(); 12600 }); 12601 }; 12602 var scrollThrottle = last(function () { 12603 scroller.idle(function () { 12604 updatePositions(container, outerWindow.pageYOffset).get(function () { 12605 var extraScroll = scrollBounds(); 12606 extraScroll.each(function (extra) { 12607 socket.dom.scrollTop = socket.dom.scrollTop + extra.top; 12608 }); 12609 scroller.start(0); 12610 structure.refresh(); 12611 }); 12612 }); 12613 }, 1000); 12614 var onScroll = bind(SugarElement.fromDom(outerWindow), 'scroll', function () { 12615 if (outerWindow.pageYOffset < 0) { 12616 return; 12617 } 12618 scrollThrottle.throttle(); 12619 }); 12620 updatePositions(container, outerWindow.pageYOffset).get(identity); 12621 return { unbind: onScroll.unbind }; 12622 }; 12623 var setup = function (bag) { 12624 var cWin = bag.cWin; 12625 var ceBody = bag.ceBody; 12626 var socket = bag.socket; 12627 var toolstrip = bag.toolstrip; 12628 var contentElement = bag.contentElement; 12629 var keyboardType = bag.keyboardType; 12630 var outerWindow = bag.outerWindow; 12631 var dropup = bag.dropup; 12632 var outerBody = bag.outerBody; 12633 var structure = takeover(socket, ceBody, toolstrip, dropup); 12634 var keyboardModel = keyboardType(outerBody, cWin, body(), contentElement); 12635 var toEditing = function () { 12636 keyboardModel.toEditing(); 12637 clearSelection(); 12638 }; 12639 var toReading = function () { 12640 keyboardModel.toReading(); 12641 }; 12642 var onToolbarTouch = function (_event) { 12643 keyboardModel.onToolbarTouch(); 12644 }; 12645 var onOrientation = onChange(outerWindow, { 12646 onChange: noop, 12647 onReady: structure.refresh 12648 }); 12649 onOrientation.onAdjustment(function () { 12650 structure.refresh(); 12651 }); 12652 var onResize = bind(SugarElement.fromDom(outerWindow), 'resize', function () { 12653 if (structure.isExpanding()) { 12654 structure.refresh(); 12655 } 12656 }); 12657 var onScroll = register(toolstrip, socket, outerBody, outerWindow, structure, cWin); 12658 var unfocusedSelection = FakeSelection(cWin, contentElement); 12659 var refreshSelection = function () { 12660 if (unfocusedSelection.isActive()) { 12661 unfocusedSelection.update(); 12662 } 12663 }; 12664 var highlightSelection = function () { 12665 unfocusedSelection.update(); 12666 }; 12667 var clearSelection = function () { 12668 unfocusedSelection.clear(); 12669 }; 12670 var scrollIntoView$1 = function (top, bottom) { 12671 scrollIntoView(cWin, socket, dropup, top, bottom); 12672 }; 12673 var syncHeight = function () { 12674 set$5(contentElement, 'height', contentElement.dom.contentWindow.document.body.scrollHeight + 'px'); 12675 }; 12676 var setViewportOffset = function (newYOffset) { 12677 structure.setViewportOffset(newYOffset); 12678 moveOnlyTop(socket, newYOffset).get(identity); 12679 }; 12680 var destroy = function () { 12681 structure.restore(); 12682 onOrientation.destroy(); 12683 onScroll.unbind(); 12684 onResize.unbind(); 12685 keyboardModel.destroy(); 12686 unfocusedSelection.destroy(); 12687 input(body(), blur$1); 12688 }; 12689 return { 12690 toEditing: toEditing, 12691 toReading: toReading, 12692 onToolbarTouch: onToolbarTouch, 12693 refreshSelection: refreshSelection, 12694 clearSelection: clearSelection, 12695 highlightSelection: highlightSelection, 12696 scrollIntoView: scrollIntoView$1, 12697 updateToolbarPadding: noop, 12698 setViewportOffset: setViewportOffset, 12699 syncHeight: syncHeight, 12700 refreshStructure: structure.refresh, 12701 destroy: destroy 12702 }; 12703 }; 12704 12705 var create = function (platform, mask) { 12706 var meta = tag(); 12707 var priorState = value(); 12708 var scrollEvents = value(); 12709 var iosApi = api$2(); 12710 var iosEvents = api$2(); 12711 var enter = function () { 12712 mask.hide(); 12713 var doc = SugarElement.fromDom(document); 12714 getActiveApi(platform.editor).each(function (editorApi) { 12715 priorState.set({ 12716 socketHeight: getRaw(platform.socket, 'height'), 12717 iframeHeight: getRaw(editorApi.frame, 'height'), 12718 outerScroll: document.body.scrollTop 12719 }); 12720 scrollEvents.set({ exclusives: exclusive(doc, '.' + scrollable) }); 12721 add$1(platform.container, resolve('fullscreen-maximized')); 12722 clobberStyles(platform.container, editorApi.body); 12723 meta.maximize(); 12724 set$5(platform.socket, 'overflow', 'scroll'); 12725 set$5(platform.socket, '-webkit-overflow-scrolling', 'touch'); 12726 focus$3(editorApi.body); 12727 iosApi.set(setup({ 12728 cWin: editorApi.win, 12729 ceBody: editorApi.body, 12730 socket: platform.socket, 12731 toolstrip: platform.toolstrip, 12732 dropup: platform.dropup.element, 12733 contentElement: editorApi.frame, 12734 outerBody: platform.body, 12735 outerWindow: platform.win, 12736 keyboardType: stubborn 12737 })); 12738 iosApi.run(function (api) { 12739 api.syncHeight(); 12740 }); 12741 iosEvents.set(initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup)); 12742 }); 12743 }; 12744 var exit = function () { 12745 meta.restore(); 12746 iosEvents.clear(); 12747 iosApi.clear(); 12748 mask.show(); 12749 priorState.on(function (s) { 12750 s.socketHeight.each(function (h) { 12751 set$5(platform.socket, 'height', h); 12752 }); 12753 s.iframeHeight.each(function (h) { 12754 set$5(platform.editor.getFrame(), 'height', h); 12755 }); 12756 document.body.scrollTop = s.scrollTop; 12757 }); 12758 priorState.clear(); 12759 scrollEvents.on(function (s) { 12760 s.exclusives.unbind(); 12761 }); 12762 scrollEvents.clear(); 12763 remove$3(platform.container, resolve('fullscreen-maximized')); 12764 restoreStyles(); 12765 deregister(platform.toolbar); 12766 remove$2(platform.socket, 'overflow'); 12767 remove$2(platform.socket, '-webkit-overflow-scrolling'); 12768 blur$1(platform.editor.getFrame()); 12769 getActiveApi(platform.editor).each(function (editorApi) { 12770 editorApi.clearSelection(); 12771 }); 12772 }; 12773 var refreshStructure = function () { 12774 iosApi.run(function (api) { 12775 api.refreshStructure(); 12776 }); 12777 }; 12778 return { 12779 enter: enter, 12780 refreshStructure: refreshStructure, 12781 exit: exit 12782 }; 12783 }; 12784 12785 var produce = function (raw) { 12786 var mobile = asRawOrDie$1('Getting IosWebapp schema', MobileSchema, raw); 12787 set$5(mobile.toolstrip, 'width', '100%'); 12788 set$5(mobile.container, 'position', 'relative'); 12789 var onView = function () { 12790 mobile.setReadOnly(mobile.readOnlyOnInit()); 12791 mode.enter(); 12792 }; 12793 var mask = build$1(sketch(onView, mobile.translate)); 12794 mobile.alloy.add(mask); 12795 var maskApi = { 12796 show: function () { 12797 mobile.alloy.add(mask); 12798 }, 12799 hide: function () { 12800 mobile.alloy.remove(mask); 12801 } 12802 }; 12803 var mode = create(mobile, maskApi); 12804 return { 12805 setReadOnly: mobile.setReadOnly, 12806 refreshStructure: mode.refreshStructure, 12807 enter: mode.enter, 12808 exit: mode.exit, 12809 destroy: noop 12810 }; 12811 }; 12812 12813 function IosRealm (scrollIntoView) { 12814 var alloy = OuterContainer({ classes: [resolve('ios-container')] }); 12815 var toolbar = ScrollingToolbar(); 12816 var webapp = api$2(); 12817 var switchToEdit = makeEditSwitch(webapp); 12818 var socket = makeSocket(); 12819 var dropup = build(function () { 12820 webapp.run(function (w) { 12821 w.refreshStructure(); 12822 }); 12823 }, scrollIntoView); 12824 alloy.add(toolbar.wrapper); 12825 alloy.add(socket); 12826 alloy.add(dropup.component); 12827 var setToolbarGroups = function (rawGroups) { 12828 var groups = toolbar.createGroups(rawGroups); 12829 toolbar.setGroups(groups); 12830 }; 12831 var setContextToolbar = function (rawGroups) { 12832 var groups = toolbar.createGroups(rawGroups); 12833 toolbar.setContextToolbar(groups); 12834 }; 12835 var focusToolbar = function () { 12836 toolbar.focus(); 12837 }; 12838 var restoreToolbar = function () { 12839 toolbar.restoreToolbar(); 12840 }; 12841 var init = function (spec) { 12842 webapp.set(produce(spec)); 12843 }; 12844 var exit = function () { 12845 webapp.run(function (w) { 12846 Replacing.remove(socket, switchToEdit); 12847 w.exit(); 12848 }); 12849 }; 12850 var updateMode$1 = function (readOnly) { 12851 updateMode(socket, switchToEdit, readOnly, alloy.root); 12852 }; 12853 return { 12854 system: alloy, 12855 element: alloy.element, 12856 init: init, 12857 exit: exit, 12858 setToolbarGroups: setToolbarGroups, 12859 setContextToolbar: setContextToolbar, 12860 focusToolbar: focusToolbar, 12861 restoreToolbar: restoreToolbar, 12862 updateMode: updateMode$1, 12863 socket: socket, 12864 dropup: dropup 12865 }; 12866 } 12867 12868 var global$1 = tinymce.util.Tools.resolve('tinymce.EditorManager'); 12869 12870 var derive = function (editor) { 12871 var base = Optional.from(getSkinUrl(editor)).getOrThunk(function () { 12872 return global$1.baseURL + '/skins/ui/oxide'; 12873 }); 12874 return { 12875 content: base + '/content.mobile.min.css', 12876 ui: base + '/skin.mobile.min.css' 12877 }; 12878 }; 12879 12880 var fireChange = function (realm, command, state) { 12881 realm.system.broadcastOn([formatChanged], { 12882 command: command, 12883 state: state 12884 }); 12885 }; 12886 var init = function (realm, editor) { 12887 var allFormats = keys(editor.formatter.get()); 12888 each$1(allFormats, function (command) { 12889 editor.formatter.formatChanged(command, function (state) { 12890 fireChange(realm, command, state); 12891 }); 12892 }); 12893 each$1([ 12894 'ul', 12895 'ol' 12896 ], function (command) { 12897 editor.selection.selectorChanged(command, function (state, _data) { 12898 fireChange(realm, command, state); 12899 }); 12900 }); 12901 }; 12902 12903 var fireSkinLoaded = function (editor) { 12904 return function () { 12905 var done = function () { 12906 editor._skinLoaded = true; 12907 editor.fire('SkinLoaded'); 12908 }; 12909 if (editor.initialized) { 12910 done(); 12911 } else { 12912 editor.on('init', done); 12913 } 12914 }; 12915 }; 12916 12917 var READING = 'toReading'; 12918 var EDITING = 'toEditing'; 12919 var renderMobileTheme = function (editor) { 12920 var renderUI = function () { 12921 var targetNode = editor.getElement(); 12922 var cssUrls = derive(editor); 12923 if (isSkinDisabled(editor) === false) { 12924 var styleSheetLoader_1 = global$5.DOM.styleSheetLoader; 12925 editor.contentCSS.push(cssUrls.content); 12926 styleSheetLoader_1.load(cssUrls.ui, fireSkinLoaded(editor)); 12927 editor.on('remove', function () { 12928 return styleSheetLoader_1.unload(cssUrls.ui); 12929 }); 12930 } else { 12931 fireSkinLoaded(editor)(); 12932 } 12933 var doScrollIntoView = function () { 12934 editor.fire('ScrollIntoView'); 12935 }; 12936 var realm = detect$1().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView); 12937 var original = SugarElement.fromDom(targetNode); 12938 attachSystemAfter(original, realm.system); 12939 var findFocusIn = function (elem) { 12940 return search(elem).bind(function (focused) { 12941 return realm.system.getByDom(focused).toOptional(); 12942 }); 12943 }; 12944 var outerWindow = targetNode.ownerDocument.defaultView; 12945 var orientation = onChange(outerWindow, { 12946 onChange: function () { 12947 var alloy = realm.system; 12948 alloy.broadcastOn([orientationChanged], { width: getActualWidth(outerWindow) }); 12949 }, 12950 onReady: noop 12951 }); 12952 var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) { 12953 if (ro === false) { 12954 editor.selection.collapse(); 12955 } 12956 var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups); 12957 realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main); 12958 editor.setMode(ro === true ? 'readonly' : 'design'); 12959 editor.fire(ro === true ? READING : EDITING); 12960 realm.updateMode(ro); 12961 }; 12962 var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) { 12963 var dynamic = dynamicGroup.get(); 12964 var toolbars = { 12965 readOnly: dynamic.backToMask.concat(readOnlyGroups.get()), 12966 main: dynamic.backToMask.concat(mainGroups.get()) 12967 }; 12968 return toolbars; 12969 }; 12970 var bindHandler = function (label, handler) { 12971 editor.on(label, handler); 12972 return { 12973 unbind: function () { 12974 editor.off(label); 12975 } 12976 }; 12977 }; 12978 editor.on('init', function () { 12979 realm.init({ 12980 editor: { 12981 getFrame: function () { 12982 return SugarElement.fromDom(editor.contentAreaContainer.querySelector('iframe')); 12983 }, 12984 onDomChanged: function () { 12985 return { unbind: noop }; 12986 }, 12987 onToReading: function (handler) { 12988 return bindHandler(READING, handler); 12989 }, 12990 onToEditing: function (handler) { 12991 return bindHandler(EDITING, handler); 12992 }, 12993 onScrollToCursor: function (handler) { 12994 editor.on('ScrollIntoView', function (tinyEvent) { 12995 handler(tinyEvent); 12996 }); 12997 var unbind = function () { 12998 editor.off('ScrollIntoView'); 12999 orientation.destroy(); 13000 }; 13001 return { unbind: unbind }; 13002 }, 13003 onTouchToolstrip: function () { 13004 hideDropup(); 13005 }, 13006 onTouchContent: function () { 13007 var toolbar = SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))); 13008 findFocusIn(toolbar).each(emitExecute); 13009 realm.restoreToolbar(); 13010 hideDropup(); 13011 }, 13012 onTapContent: function (evt) { 13013 var target = evt.target; 13014 if (name$1(target) === 'img') { 13015 editor.selection.select(target.dom); 13016 evt.kill(); 13017 } else if (name$1(target) === 'a') { 13018 var component = realm.system.getByDom(SugarElement.fromDom(editor.editorContainer)); 13019 component.each(function (container) { 13020 if (Swapping.isAlpha(container)) { 13021 openLink(target.dom); 13022 } 13023 }); 13024 } 13025 } 13026 }, 13027 container: SugarElement.fromDom(editor.editorContainer), 13028 socket: SugarElement.fromDom(editor.contentAreaContainer), 13029 toolstrip: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolstrip'))), 13030 toolbar: SugarElement.fromDom(editor.editorContainer.querySelector('.' + resolve('toolbar'))), 13031 dropup: realm.dropup, 13032 alloy: realm.system, 13033 translate: noop, 13034 setReadOnly: function (ro) { 13035 setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro); 13036 }, 13037 readOnlyOnInit: function () { 13038 return readOnlyOnInit(); 13039 } 13040 }); 13041 var hideDropup = function () { 13042 realm.dropup.disappear(function () { 13043 realm.system.broadcastOn([dropupDismissed], {}); 13044 }); 13045 }; 13046 var backToMaskGroup = { 13047 label: 'The first group', 13048 scrollable: false, 13049 items: [forToolbar('back', function () { 13050 editor.selection.collapse(); 13051 realm.exit(); 13052 }, {}, editor)] 13053 }; 13054 var backToReadOnlyGroup = { 13055 label: 'Back to read only', 13056 scrollable: false, 13057 items: [forToolbar('readonly-back', function () { 13058 setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true); 13059 }, {}, editor)] 13060 }; 13061 var readOnlyGroup = { 13062 label: 'The read only mode group', 13063 scrollable: true, 13064 items: [] 13065 }; 13066 var features = setup$3(realm, editor); 13067 var items = detect(editor, features); 13068 var actionGroup = { 13069 label: 'the action group', 13070 scrollable: true, 13071 items: items 13072 }; 13073 var extraGroup = { 13074 label: 'The extra group', 13075 scrollable: false, 13076 items: [] 13077 }; 13078 var mainGroups = Cell([ 13079 actionGroup, 13080 extraGroup 13081 ]); 13082 var readOnlyGroups = Cell([ 13083 readOnlyGroup, 13084 extraGroup 13085 ]); 13086 var dynamicGroup = Cell({ 13087 backToMask: [backToMaskGroup], 13088 backToReadOnly: [backToReadOnlyGroup] 13089 }); 13090 init(realm, editor); 13091 }); 13092 editor.on('remove', function () { 13093 realm.exit(); 13094 }); 13095 editor.on('detach', function () { 13096 detachSystem(realm.system); 13097 realm.system.destroy(); 13098 }); 13099 return { 13100 iframeContainer: realm.socket.element.dom, 13101 editorContainer: realm.element.dom 13102 }; 13103 }; 13104 return { 13105 getNotificationManagerImpl: function () { 13106 return { 13107 open: constant$1({ 13108 progressBar: { value: noop }, 13109 close: noop, 13110 text: noop, 13111 getEl: constant$1(null), 13112 moveTo: noop, 13113 moveRel: noop, 13114 settings: {} 13115 }), 13116 close: noop, 13117 reposition: noop, 13118 getArgs: constant$1({}) 13119 }; 13120 }, 13121 renderUI: renderUI 13122 }; 13123 }; 13124 function Theme () { 13125 global$4.add('mobile', renderMobileTheme); 13126 } 13127 13128 Theme(); 13129 13130 }());
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Wed Sep 7 05:41:13 2022 | Chilli.vc Blog - For Webmaster,Blog-Writer,System Admin and Domainer |