[ 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 typeOf = function (x) { 13 var t = typeof x; 14 if (x === null) { 15 return 'null'; 16 } else if (t === 'object' && (Array.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'Array')) { 17 return 'array'; 18 } else if (t === 'object' && (String.prototype.isPrototypeOf(x) || x.constructor && x.constructor.name === 'String')) { 19 return 'string'; 20 } else { 21 return t; 22 } 23 }; 24 var isType$1 = function (type) { 25 return function (value) { 26 return typeOf(value) === type; 27 }; 28 }; 29 var isSimpleType = function (type) { 30 return function (value) { 31 return typeof value === type; 32 }; 33 }; 34 var eq$1 = function (t) { 35 return function (a) { 36 return t === a; 37 }; 38 }; 39 var isString = isType$1('string'); 40 var isObject = isType$1('object'); 41 var isArray = isType$1('array'); 42 var isNull = eq$1(null); 43 var isBoolean = isSimpleType('boolean'); 44 var isUndefined = eq$1(undefined); 45 var isNullable = function (a) { 46 return a === null || a === undefined; 47 }; 48 var isNonNullable = function (a) { 49 return !isNullable(a); 50 }; 51 var isFunction = isSimpleType('function'); 52 var isNumber = isSimpleType('number'); 53 var isArrayOf = function (value, pred) { 54 if (isArray(value)) { 55 for (var i = 0, len = value.length; i < len; ++i) { 56 if (!pred(value[i])) { 57 return false; 58 } 59 } 60 return true; 61 } 62 return false; 63 }; 64 65 var noop = function () { 66 }; 67 var noarg = function (f) { 68 return function () { 69 return f(); 70 }; 71 }; 72 var compose = function (fa, fb) { 73 return function () { 74 var args = []; 75 for (var _i = 0; _i < arguments.length; _i++) { 76 args[_i] = arguments[_i]; 77 } 78 return fa(fb.apply(null, args)); 79 }; 80 }; 81 var compose1 = function (fbc, fab) { 82 return function (a) { 83 return fbc(fab(a)); 84 }; 85 }; 86 var constant$1 = function (value) { 87 return function () { 88 return value; 89 }; 90 }; 91 var identity$1 = function (x) { 92 return x; 93 }; 94 var tripleEquals = function (a, b) { 95 return a === b; 96 }; 97 function curry(fn) { 98 var initialArgs = []; 99 for (var _i = 1; _i < arguments.length; _i++) { 100 initialArgs[_i - 1] = arguments[_i]; 101 } 102 return function () { 103 var restArgs = []; 104 for (var _i = 0; _i < arguments.length; _i++) { 105 restArgs[_i] = arguments[_i]; 106 } 107 var all = initialArgs.concat(restArgs); 108 return fn.apply(null, all); 109 }; 110 } 111 var not = function (f) { 112 return function (t) { 113 return !f(t); 114 }; 115 }; 116 var die = function (msg) { 117 return function () { 118 throw new Error(msg); 119 }; 120 }; 121 var never = constant$1(false); 122 var always = constant$1(true); 123 124 var global$g = tinymce.util.Tools.resolve('tinymce.ThemeManager'); 125 126 var __assign = function () { 127 __assign = Object.assign || function __assign(t) { 128 for (var s, i = 1, n = arguments.length; i < n; i++) { 129 s = arguments[i]; 130 for (var p in s) 131 if (Object.prototype.hasOwnProperty.call(s, p)) 132 t[p] = s[p]; 133 } 134 return t; 135 }; 136 return __assign.apply(this, arguments); 137 }; 138 function __rest(s, e) { 139 var t = {}; 140 for (var p in s) 141 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) 142 t[p] = s[p]; 143 if (s != null && typeof Object.getOwnPropertySymbols === 'function') 144 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { 145 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) 146 t[p[i]] = s[p[i]]; 147 } 148 return t; 149 } 150 function __spreadArray(to, from, pack) { 151 if (pack || arguments.length === 2) 152 for (var i = 0, l = from.length, ar; i < l; i++) { 153 if (ar || !(i in from)) { 154 if (!ar) 155 ar = Array.prototype.slice.call(from, 0, i); 156 ar[i] = from[i]; 157 } 158 } 159 return to.concat(ar || Array.prototype.slice.call(from)); 160 } 161 162 var none = function () { 163 return NONE; 164 }; 165 var NONE = function () { 166 var call = function (thunk) { 167 return thunk(); 168 }; 169 var id = identity$1; 170 var me = { 171 fold: function (n, _s) { 172 return n(); 173 }, 174 isSome: never, 175 isNone: always, 176 getOr: id, 177 getOrThunk: call, 178 getOrDie: function (msg) { 179 throw new Error(msg || 'error: getOrDie called on none.'); 180 }, 181 getOrNull: constant$1(null), 182 getOrUndefined: constant$1(undefined), 183 or: id, 184 orThunk: call, 185 map: none, 186 each: noop, 187 bind: none, 188 exists: never, 189 forall: always, 190 filter: function () { 191 return none(); 192 }, 193 toArray: function () { 194 return []; 195 }, 196 toString: constant$1('none()') 197 }; 198 return me; 199 }(); 200 var some = function (a) { 201 var constant_a = constant$1(a); 202 var self = function () { 203 return me; 204 }; 205 var bind = function (f) { 206 return f(a); 207 }; 208 var me = { 209 fold: function (n, s) { 210 return s(a); 211 }, 212 isSome: always, 213 isNone: never, 214 getOr: constant_a, 215 getOrThunk: constant_a, 216 getOrDie: constant_a, 217 getOrNull: constant_a, 218 getOrUndefined: constant_a, 219 or: self, 220 orThunk: self, 221 map: function (f) { 222 return some(f(a)); 223 }, 224 each: function (f) { 225 f(a); 226 }, 227 bind: bind, 228 exists: bind, 229 forall: bind, 230 filter: function (f) { 231 return f(a) ? me : NONE; 232 }, 233 toArray: function () { 234 return [a]; 235 }, 236 toString: function () { 237 return 'some(' + a + ')'; 238 } 239 }; 240 return me; 241 }; 242 var from$1 = function (value) { 243 return value === null || value === undefined ? NONE : some(value); 244 }; 245 var Optional = { 246 some: some, 247 none: none, 248 from: from$1 249 }; 250 251 var nativeSlice = Array.prototype.slice; 252 var nativeIndexOf = Array.prototype.indexOf; 253 var nativePush = Array.prototype.push; 254 var rawIndexOf = function (ts, t) { 255 return nativeIndexOf.call(ts, t); 256 }; 257 var indexOf = function (xs, x) { 258 var r = rawIndexOf(xs, x); 259 return r === -1 ? Optional.none() : Optional.some(r); 260 }; 261 var contains$2 = function (xs, x) { 262 return rawIndexOf(xs, x) > -1; 263 }; 264 var exists = function (xs, pred) { 265 for (var i = 0, len = xs.length; i < len; i++) { 266 var x = xs[i]; 267 if (pred(x, i)) { 268 return true; 269 } 270 } 271 return false; 272 }; 273 var range$2 = function (num, f) { 274 var r = []; 275 for (var i = 0; i < num; i++) { 276 r.push(f(i)); 277 } 278 return r; 279 }; 280 var chunk$1 = function (array, size) { 281 var r = []; 282 for (var i = 0; i < array.length; i += size) { 283 var s = nativeSlice.call(array, i, i + size); 284 r.push(s); 285 } 286 return r; 287 }; 288 var map$2 = function (xs, f) { 289 var len = xs.length; 290 var r = new Array(len); 291 for (var i = 0; i < len; i++) { 292 var x = xs[i]; 293 r[i] = f(x, i); 294 } 295 return r; 296 }; 297 var each$1 = function (xs, f) { 298 for (var i = 0, len = xs.length; i < len; i++) { 299 var x = xs[i]; 300 f(x, i); 301 } 302 }; 303 var eachr = function (xs, f) { 304 for (var i = xs.length - 1; i >= 0; i--) { 305 var x = xs[i]; 306 f(x, i); 307 } 308 }; 309 var partition$3 = function (xs, pred) { 310 var pass = []; 311 var fail = []; 312 for (var i = 0, len = xs.length; i < len; i++) { 313 var x = xs[i]; 314 var arr = pred(x, i) ? pass : fail; 315 arr.push(x); 316 } 317 return { 318 pass: pass, 319 fail: fail 320 }; 321 }; 322 var filter$2 = function (xs, pred) { 323 var r = []; 324 for (var i = 0, len = xs.length; i < len; i++) { 325 var x = xs[i]; 326 if (pred(x, i)) { 327 r.push(x); 328 } 329 } 330 return r; 331 }; 332 var foldr = function (xs, f, acc) { 333 eachr(xs, function (x, i) { 334 acc = f(acc, x, i); 335 }); 336 return acc; 337 }; 338 var foldl = function (xs, f, acc) { 339 each$1(xs, function (x, i) { 340 acc = f(acc, x, i); 341 }); 342 return acc; 343 }; 344 var findUntil = function (xs, pred, until) { 345 for (var i = 0, len = xs.length; i < len; i++) { 346 var x = xs[i]; 347 if (pred(x, i)) { 348 return Optional.some(x); 349 } else if (until(x, i)) { 350 break; 351 } 352 } 353 return Optional.none(); 354 }; 355 var find$5 = function (xs, pred) { 356 return findUntil(xs, pred, never); 357 }; 358 var findIndex$1 = function (xs, pred) { 359 for (var i = 0, len = xs.length; i < len; i++) { 360 var x = xs[i]; 361 if (pred(x, i)) { 362 return Optional.some(i); 363 } 364 } 365 return Optional.none(); 366 }; 367 var flatten = function (xs) { 368 var r = []; 369 for (var i = 0, len = xs.length; i < len; ++i) { 370 if (!isArray(xs[i])) { 371 throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs); 372 } 373 nativePush.apply(r, xs[i]); 374 } 375 return r; 376 }; 377 var bind$3 = function (xs, f) { 378 return flatten(map$2(xs, f)); 379 }; 380 var forall = function (xs, pred) { 381 for (var i = 0, len = xs.length; i < len; ++i) { 382 var x = xs[i]; 383 if (pred(x, i) !== true) { 384 return false; 385 } 386 } 387 return true; 388 }; 389 var reverse = function (xs) { 390 var r = nativeSlice.call(xs, 0); 391 r.reverse(); 392 return r; 393 }; 394 var difference = function (a1, a2) { 395 return filter$2(a1, function (x) { 396 return !contains$2(a2, x); 397 }); 398 }; 399 var mapToObject = function (xs, f) { 400 var r = {}; 401 for (var i = 0, len = xs.length; i < len; i++) { 402 var x = xs[i]; 403 r[String(x)] = f(x, i); 404 } 405 return r; 406 }; 407 var pure$2 = function (x) { 408 return [x]; 409 }; 410 var sort = function (xs, comparator) { 411 var copy = nativeSlice.call(xs, 0); 412 copy.sort(comparator); 413 return copy; 414 }; 415 var get$f = function (xs, i) { 416 return i >= 0 && i < xs.length ? Optional.some(xs[i]) : Optional.none(); 417 }; 418 var head = function (xs) { 419 return get$f(xs, 0); 420 }; 421 var last$2 = function (xs) { 422 return get$f(xs, xs.length - 1); 423 }; 424 var from = isFunction(Array.from) ? Array.from : function (x) { 425 return nativeSlice.call(x); 426 }; 427 var findMap = function (arr, f) { 428 for (var i = 0; i < arr.length; i++) { 429 var r = f(arr[i], i); 430 if (r.isSome()) { 431 return r; 432 } 433 } 434 return Optional.none(); 435 }; 436 437 var keys = Object.keys; 438 var hasOwnProperty = Object.hasOwnProperty; 439 var each = function (obj, f) { 440 var props = keys(obj); 441 for (var k = 0, len = props.length; k < len; k++) { 442 var i = props[k]; 443 var x = obj[i]; 444 f(x, i); 445 } 446 }; 447 var map$1 = function (obj, f) { 448 return tupleMap(obj, function (x, i) { 449 return { 450 k: i, 451 v: f(x, i) 452 }; 453 }); 454 }; 455 var tupleMap = function (obj, f) { 456 var r = {}; 457 each(obj, function (x, i) { 458 var tuple = f(x, i); 459 r[tuple.k] = tuple.v; 460 }); 461 return r; 462 }; 463 var objAcc = function (r) { 464 return function (x, i) { 465 r[i] = x; 466 }; 467 }; 468 var internalFilter = function (obj, pred, onTrue, onFalse) { 469 var r = {}; 470 each(obj, function (x, i) { 471 (pred(x, i) ? onTrue : onFalse)(x, i); 472 }); 473 return r; 474 }; 475 var filter$1 = function (obj, pred) { 476 var t = {}; 477 internalFilter(obj, pred, objAcc(t), noop); 478 return t; 479 }; 480 var mapToArray = function (obj, f) { 481 var r = []; 482 each(obj, function (value, name) { 483 r.push(f(value, name)); 484 }); 485 return r; 486 }; 487 var find$4 = function (obj, pred) { 488 var props = keys(obj); 489 for (var k = 0, len = props.length; k < len; k++) { 490 var i = props[k]; 491 var x = obj[i]; 492 if (pred(x, i, obj)) { 493 return Optional.some(x); 494 } 495 } 496 return Optional.none(); 497 }; 498 var values = function (obj) { 499 return mapToArray(obj, identity$1); 500 }; 501 var get$e = function (obj, key) { 502 return has$2(obj, key) ? Optional.from(obj[key]) : Optional.none(); 503 }; 504 var has$2 = function (obj, key) { 505 return hasOwnProperty.call(obj, key); 506 }; 507 var hasNonNullableKey = function (obj, key) { 508 return has$2(obj, key) && obj[key] !== undefined && obj[key] !== null; 509 }; 510 511 var is$1 = function (lhs, rhs, comparator) { 512 if (comparator === void 0) { 513 comparator = tripleEquals; 514 } 515 return lhs.exists(function (left) { 516 return comparator(left, rhs); 517 }); 518 }; 519 var equals = function (lhs, rhs, comparator) { 520 if (comparator === void 0) { 521 comparator = tripleEquals; 522 } 523 return lift2(lhs, rhs, comparator).getOr(lhs.isNone() && rhs.isNone()); 524 }; 525 var cat = function (arr) { 526 var r = []; 527 var push = function (x) { 528 r.push(x); 529 }; 530 for (var i = 0; i < arr.length; i++) { 531 arr[i].each(push); 532 } 533 return r; 534 }; 535 var sequence = function (arr) { 536 var r = []; 537 for (var i = 0; i < arr.length; i++) { 538 var x = arr[i]; 539 if (x.isSome()) { 540 r.push(x.getOrDie()); 541 } else { 542 return Optional.none(); 543 } 544 } 545 return Optional.some(r); 546 }; 547 var lift2 = function (oa, ob, f) { 548 return oa.isSome() && ob.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie())) : Optional.none(); 549 }; 550 var lift3 = function (oa, ob, oc, f) { 551 return oa.isSome() && ob.isSome() && oc.isSome() ? Optional.some(f(oa.getOrDie(), ob.getOrDie(), oc.getOrDie())) : Optional.none(); 552 }; 553 var mapFrom = function (a, f) { 554 return a !== undefined && a !== null ? Optional.some(f(a)) : Optional.none(); 555 }; 556 var someIf = function (b, a) { 557 return b ? Optional.some(a) : Optional.none(); 558 }; 559 560 var addToEnd = function (str, suffix) { 561 return str + suffix; 562 }; 563 var removeFromStart = function (str, numChars) { 564 return str.substring(numChars); 565 }; 566 567 var checkRange = function (str, substr, start) { 568 return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr; 569 }; 570 var removeLeading = function (str, prefix) { 571 return startsWith(str, prefix) ? removeFromStart(str, prefix.length) : str; 572 }; 573 var ensureTrailing = function (str, suffix) { 574 return endsWith(str, suffix) ? str : addToEnd(str, suffix); 575 }; 576 var contains$1 = function (str, substr) { 577 return str.indexOf(substr) !== -1; 578 }; 579 var startsWith = function (str, prefix) { 580 return checkRange(str, prefix, 0); 581 }; 582 var endsWith = function (str, suffix) { 583 return checkRange(str, suffix, str.length - suffix.length); 584 }; 585 var blank = function (r) { 586 return function (s) { 587 return s.replace(r, ''); 588 }; 589 }; 590 var trim$1 = blank(/^\s+|\s+$/g); 591 var isNotEmpty = function (s) { 592 return s.length > 0; 593 }; 594 var isEmpty = function (s) { 595 return !isNotEmpty(s); 596 }; 597 598 var isSupported$1 = function (dom) { 599 return dom.style !== undefined && isFunction(dom.style.getPropertyValue); 600 }; 601 602 var fromHtml$2 = function (html, scope) { 603 var doc = scope || document; 604 var div = doc.createElement('div'); 605 div.innerHTML = html; 606 if (!div.hasChildNodes() || div.childNodes.length > 1) { 607 console.error('HTML does not have a single root node', html); 608 throw new Error('HTML must have a single root node'); 609 } 610 return fromDom(div.childNodes[0]); 611 }; 612 var fromTag = function (tag, scope) { 613 var doc = scope || document; 614 var node = doc.createElement(tag); 615 return fromDom(node); 616 }; 617 var fromText = function (text, scope) { 618 var doc = scope || document; 619 var node = doc.createTextNode(text); 620 return fromDom(node); 621 }; 622 var fromDom = function (node) { 623 if (node === null || node === undefined) { 624 throw new Error('Node cannot be null or undefined'); 625 } 626 return { dom: node }; 627 }; 628 var fromPoint = function (docElm, x, y) { 629 return Optional.from(docElm.dom.elementFromPoint(x, y)).map(fromDom); 630 }; 631 var SugarElement = { 632 fromHtml: fromHtml$2, 633 fromTag: fromTag, 634 fromText: fromText, 635 fromDom: fromDom, 636 fromPoint: fromPoint 637 }; 638 639 typeof window !== 'undefined' ? window : Function('return this;')(); 640 641 var DOCUMENT = 9; 642 var DOCUMENT_FRAGMENT = 11; 643 var ELEMENT = 1; 644 var TEXT = 3; 645 646 var name$2 = function (element) { 647 var r = element.dom.nodeName; 648 return r.toLowerCase(); 649 }; 650 var type = function (element) { 651 return element.dom.nodeType; 652 }; 653 var isType = function (t) { 654 return function (element) { 655 return type(element) === t; 656 }; 657 }; 658 var isElement$2 = isType(ELEMENT); 659 var isText$1 = isType(TEXT); 660 var isDocument = isType(DOCUMENT); 661 var isDocumentFragment = isType(DOCUMENT_FRAGMENT); 662 663 var cached = function (f) { 664 var called = false; 665 var r; 666 return function () { 667 var args = []; 668 for (var _i = 0; _i < arguments.length; _i++) { 669 args[_i] = arguments[_i]; 670 } 671 if (!called) { 672 called = true; 673 r = f.apply(null, args); 674 } 675 return r; 676 }; 677 }; 678 679 var DeviceType = function (os, browser, userAgent, mediaMatch) { 680 var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true; 681 var isiPhone = os.isiOS() && !isiPad; 682 var isMobile = os.isiOS() || os.isAndroid(); 683 var isTouch = isMobile || mediaMatch('(pointer:coarse)'); 684 var isTablet = isiPad || !isiPhone && isMobile && mediaMatch('(min-device-width:768px)'); 685 var isPhone = isiPhone || isMobile && !isTablet; 686 var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false; 687 var isDesktop = !isPhone && !isTablet && !iOSwebview; 688 return { 689 isiPad: constant$1(isiPad), 690 isiPhone: constant$1(isiPhone), 691 isTablet: constant$1(isTablet), 692 isPhone: constant$1(isPhone), 693 isTouch: constant$1(isTouch), 694 isAndroid: os.isAndroid, 695 isiOS: os.isiOS, 696 isWebView: constant$1(iOSwebview), 697 isDesktop: constant$1(isDesktop) 698 }; 699 }; 700 701 var firstMatch = function (regexes, s) { 702 for (var i = 0; i < regexes.length; i++) { 703 var x = regexes[i]; 704 if (x.test(s)) { 705 return x; 706 } 707 } 708 return undefined; 709 }; 710 var find$3 = function (regexes, agent) { 711 var r = firstMatch(regexes, agent); 712 if (!r) { 713 return { 714 major: 0, 715 minor: 0 716 }; 717 } 718 var group = function (i) { 719 return Number(agent.replace(r, '$' + i)); 720 }; 721 return nu$d(group(1), group(2)); 722 }; 723 var detect$4 = function (versionRegexes, agent) { 724 var cleanedAgent = String(agent).toLowerCase(); 725 if (versionRegexes.length === 0) { 726 return unknown$3(); 727 } 728 return find$3(versionRegexes, cleanedAgent); 729 }; 730 var unknown$3 = function () { 731 return nu$d(0, 0); 732 }; 733 var nu$d = function (major, minor) { 734 return { 735 major: major, 736 minor: minor 737 }; 738 }; 739 var Version = { 740 nu: nu$d, 741 detect: detect$4, 742 unknown: unknown$3 743 }; 744 745 var detectBrowser$1 = function (browsers, userAgentData) { 746 return findMap(userAgentData.brands, function (uaBrand) { 747 var lcBrand = uaBrand.brand.toLowerCase(); 748 return find$5(browsers, function (browser) { 749 var _a; 750 return lcBrand === ((_a = browser.brand) === null || _a === void 0 ? void 0 : _a.toLowerCase()); 751 }).map(function (info) { 752 return { 753 current: info.name, 754 version: Version.nu(parseInt(uaBrand.version, 10), 0) 755 }; 756 }); 757 }); 758 }; 759 760 var detect$3 = function (candidates, userAgent) { 761 var agent = String(userAgent).toLowerCase(); 762 return find$5(candidates, function (candidate) { 763 return candidate.search(agent); 764 }); 765 }; 766 var detectBrowser = function (browsers, userAgent) { 767 return detect$3(browsers, userAgent).map(function (browser) { 768 var version = Version.detect(browser.versionRegexes, userAgent); 769 return { 770 current: browser.name, 771 version: version 772 }; 773 }); 774 }; 775 var detectOs = function (oses, userAgent) { 776 return detect$3(oses, userAgent).map(function (os) { 777 var version = Version.detect(os.versionRegexes, userAgent); 778 return { 779 current: os.name, 780 version: version 781 }; 782 }); 783 }; 784 785 var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/; 786 var checkContains = function (target) { 787 return function (uastring) { 788 return contains$1(uastring, target); 789 }; 790 }; 791 var browsers = [ 792 { 793 name: 'Edge', 794 versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/], 795 search: function (uastring) { 796 return contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit'); 797 } 798 }, 799 { 800 name: 'Chrome', 801 brand: 'Chromium', 802 versionRegexes: [ 803 /.*?chrome\/([0-9]+)\.([0-9]+).*/, 804 normalVersionRegex 805 ], 806 search: function (uastring) { 807 return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe'); 808 } 809 }, 810 { 811 name: 'IE', 812 versionRegexes: [ 813 /.*?msie\ ?([0-9]+)\.([0-9]+).*/, 814 /.*?rv:([0-9]+)\.([0-9]+).*/ 815 ], 816 search: function (uastring) { 817 return contains$1(uastring, 'msie') || contains$1(uastring, 'trident'); 818 } 819 }, 820 { 821 name: 'Opera', 822 versionRegexes: [ 823 normalVersionRegex, 824 /.*?opera\/([0-9]+)\.([0-9]+).*/ 825 ], 826 search: checkContains('opera') 827 }, 828 { 829 name: 'Firefox', 830 versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/], 831 search: checkContains('firefox') 832 }, 833 { 834 name: 'Safari', 835 versionRegexes: [ 836 normalVersionRegex, 837 /.*?cpu os ([0-9]+)_([0-9]+).*/ 838 ], 839 search: function (uastring) { 840 return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit'); 841 } 842 } 843 ]; 844 var oses = [ 845 { 846 name: 'Windows', 847 search: checkContains('win'), 848 versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/] 849 }, 850 { 851 name: 'iOS', 852 search: function (uastring) { 853 return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad'); 854 }, 855 versionRegexes: [ 856 /.*?version\/\ ?([0-9]+)\.([0-9]+).*/, 857 /.*cpu os ([0-9]+)_([0-9]+).*/, 858 /.*cpu iphone os ([0-9]+)_([0-9]+).*/ 859 ] 860 }, 861 { 862 name: 'Android', 863 search: checkContains('android'), 864 versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/] 865 }, 866 { 867 name: 'OSX', 868 search: checkContains('mac os x'), 869 versionRegexes: [/.*?mac\ os\ x\ ?([0-9]+)_([0-9]+).*/] 870 }, 871 { 872 name: 'Linux', 873 search: checkContains('linux'), 874 versionRegexes: [] 875 }, 876 { 877 name: 'Solaris', 878 search: checkContains('sunos'), 879 versionRegexes: [] 880 }, 881 { 882 name: 'FreeBSD', 883 search: checkContains('freebsd'), 884 versionRegexes: [] 885 }, 886 { 887 name: 'ChromeOS', 888 search: checkContains('cros'), 889 versionRegexes: [/.*?chrome\/([0-9]+)\.([0-9]+).*/] 890 } 891 ]; 892 var PlatformInfo = { 893 browsers: constant$1(browsers), 894 oses: constant$1(oses) 895 }; 896 897 var edge = 'Edge'; 898 var chrome = 'Chrome'; 899 var ie = 'IE'; 900 var opera = 'Opera'; 901 var firefox = 'Firefox'; 902 var safari = 'Safari'; 903 var unknown$2 = function () { 904 return nu$c({ 905 current: undefined, 906 version: Version.unknown() 907 }); 908 }; 909 var nu$c = function (info) { 910 var current = info.current; 911 var version = info.version; 912 var isBrowser = function (name) { 913 return function () { 914 return current === name; 915 }; 916 }; 917 return { 918 current: current, 919 version: version, 920 isEdge: isBrowser(edge), 921 isChrome: isBrowser(chrome), 922 isIE: isBrowser(ie), 923 isOpera: isBrowser(opera), 924 isFirefox: isBrowser(firefox), 925 isSafari: isBrowser(safari) 926 }; 927 }; 928 var Browser = { 929 unknown: unknown$2, 930 nu: nu$c, 931 edge: constant$1(edge), 932 chrome: constant$1(chrome), 933 ie: constant$1(ie), 934 opera: constant$1(opera), 935 firefox: constant$1(firefox), 936 safari: constant$1(safari) 937 }; 938 939 var windows = 'Windows'; 940 var ios = 'iOS'; 941 var android = 'Android'; 942 var linux = 'Linux'; 943 var osx = 'OSX'; 944 var solaris = 'Solaris'; 945 var freebsd = 'FreeBSD'; 946 var chromeos = 'ChromeOS'; 947 var unknown$1 = function () { 948 return nu$b({ 949 current: undefined, 950 version: Version.unknown() 951 }); 952 }; 953 var nu$b = function (info) { 954 var current = info.current; 955 var version = info.version; 956 var isOS = function (name) { 957 return function () { 958 return current === name; 959 }; 960 }; 961 return { 962 current: current, 963 version: version, 964 isWindows: isOS(windows), 965 isiOS: isOS(ios), 966 isAndroid: isOS(android), 967 isOSX: isOS(osx), 968 isLinux: isOS(linux), 969 isSolaris: isOS(solaris), 970 isFreeBSD: isOS(freebsd), 971 isChromeOS: isOS(chromeos) 972 }; 973 }; 974 var OperatingSystem = { 975 unknown: unknown$1, 976 nu: nu$b, 977 windows: constant$1(windows), 978 ios: constant$1(ios), 979 android: constant$1(android), 980 linux: constant$1(linux), 981 osx: constant$1(osx), 982 solaris: constant$1(solaris), 983 freebsd: constant$1(freebsd), 984 chromeos: constant$1(chromeos) 985 }; 986 987 var detect$2 = function (userAgent, userAgentDataOpt, mediaMatch) { 988 var browsers = PlatformInfo.browsers(); 989 var oses = PlatformInfo.oses(); 990 var browser = userAgentDataOpt.bind(function (userAgentData) { 991 return detectBrowser$1(browsers, userAgentData); 992 }).orThunk(function () { 993 return detectBrowser(browsers, userAgent); 994 }).fold(Browser.unknown, Browser.nu); 995 var os = detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu); 996 var deviceType = DeviceType(os, browser, userAgent, mediaMatch); 997 return { 998 browser: browser, 999 os: os, 1000 deviceType: deviceType 1001 }; 1002 }; 1003 var PlatformDetection = { detect: detect$2 }; 1004 1005 var mediaMatch = function (query) { 1006 return window.matchMedia(query).matches; 1007 }; 1008 var platform = cached(function () { 1009 return PlatformDetection.detect(navigator.userAgent, Optional.from(navigator.userAgentData), mediaMatch); 1010 }); 1011 var detect$1 = function () { 1012 return platform(); 1013 }; 1014 1015 var compareDocumentPosition = function (a, b, match) { 1016 return (a.compareDocumentPosition(b) & match) !== 0; 1017 }; 1018 var documentPositionContainedBy = function (a, b) { 1019 return compareDocumentPosition(a, b, Node.DOCUMENT_POSITION_CONTAINED_BY); 1020 }; 1021 1022 var is = function (element, selector) { 1023 var dom = element.dom; 1024 if (dom.nodeType !== ELEMENT) { 1025 return false; 1026 } else { 1027 var elem = dom; 1028 if (elem.matches !== undefined) { 1029 return elem.matches(selector); 1030 } else if (elem.msMatchesSelector !== undefined) { 1031 return elem.msMatchesSelector(selector); 1032 } else if (elem.webkitMatchesSelector !== undefined) { 1033 return elem.webkitMatchesSelector(selector); 1034 } else if (elem.mozMatchesSelector !== undefined) { 1035 return elem.mozMatchesSelector(selector); 1036 } else { 1037 throw new Error('Browser lacks native selectors'); 1038 } 1039 } 1040 }; 1041 var bypassSelector = function (dom) { 1042 return dom.nodeType !== ELEMENT && dom.nodeType !== DOCUMENT && dom.nodeType !== DOCUMENT_FRAGMENT || dom.childElementCount === 0; 1043 }; 1044 var all$3 = function (selector, scope) { 1045 var base = scope === undefined ? document : scope.dom; 1046 return bypassSelector(base) ? [] : map$2(base.querySelectorAll(selector), SugarElement.fromDom); 1047 }; 1048 var one = function (selector, scope) { 1049 var base = scope === undefined ? document : scope.dom; 1050 return bypassSelector(base) ? Optional.none() : Optional.from(base.querySelector(selector)).map(SugarElement.fromDom); 1051 }; 1052 1053 var eq = function (e1, e2) { 1054 return e1.dom === e2.dom; 1055 }; 1056 var regularContains = function (e1, e2) { 1057 var d1 = e1.dom; 1058 var d2 = e2.dom; 1059 return d1 === d2 ? false : d1.contains(d2); 1060 }; 1061 var ieContains = function (e1, e2) { 1062 return documentPositionContainedBy(e1.dom, e2.dom); 1063 }; 1064 var contains = function (e1, e2) { 1065 return detect$1().browser.isIE() ? ieContains(e1, e2) : regularContains(e1, e2); 1066 }; 1067 1068 var owner$4 = function (element) { 1069 return SugarElement.fromDom(element.dom.ownerDocument); 1070 }; 1071 var documentOrOwner = function (dos) { 1072 return isDocument(dos) ? dos : owner$4(dos); 1073 }; 1074 var documentElement = function (element) { 1075 return SugarElement.fromDom(documentOrOwner(element).dom.documentElement); 1076 }; 1077 var defaultView = function (element) { 1078 return SugarElement.fromDom(documentOrOwner(element).dom.defaultView); 1079 }; 1080 var parent = function (element) { 1081 return Optional.from(element.dom.parentNode).map(SugarElement.fromDom); 1082 }; 1083 var parentNode = function (element) { 1084 return parent(element); 1085 }; 1086 var offsetParent = function (element) { 1087 return Optional.from(element.dom.offsetParent).map(SugarElement.fromDom); 1088 }; 1089 var nextSibling = function (element) { 1090 return Optional.from(element.dom.nextSibling).map(SugarElement.fromDom); 1091 }; 1092 var children = function (element) { 1093 return map$2(element.dom.childNodes, SugarElement.fromDom); 1094 }; 1095 var child$2 = function (element, index) { 1096 var cs = element.dom.childNodes; 1097 return Optional.from(cs[index]).map(SugarElement.fromDom); 1098 }; 1099 var firstChild = function (element) { 1100 return child$2(element, 0); 1101 }; 1102 var spot = function (element, offset) { 1103 return { 1104 element: element, 1105 offset: offset 1106 }; 1107 }; 1108 var leaf = function (element, offset) { 1109 var cs = children(element); 1110 return cs.length > 0 && offset < cs.length ? spot(cs[offset], 0) : spot(element, offset); 1111 }; 1112 1113 var isShadowRoot = function (dos) { 1114 return isDocumentFragment(dos) && isNonNullable(dos.dom.host); 1115 }; 1116 var supported = isFunction(Element.prototype.attachShadow) && isFunction(Node.prototype.getRootNode); 1117 var isSupported = constant$1(supported); 1118 var getRootNode = supported ? function (e) { 1119 return SugarElement.fromDom(e.dom.getRootNode()); 1120 } : documentOrOwner; 1121 var getContentContainer = function (dos) { 1122 return isShadowRoot(dos) ? dos : SugarElement.fromDom(documentOrOwner(dos).dom.body); 1123 }; 1124 var isInShadowRoot = function (e) { 1125 return getShadowRoot(e).isSome(); 1126 }; 1127 var getShadowRoot = function (e) { 1128 var r = getRootNode(e); 1129 return isShadowRoot(r) ? Optional.some(r) : Optional.none(); 1130 }; 1131 var getShadowHost = function (e) { 1132 return SugarElement.fromDom(e.dom.host); 1133 }; 1134 var getOriginalEventTarget = function (event) { 1135 if (isSupported() && isNonNullable(event.target)) { 1136 var el = SugarElement.fromDom(event.target); 1137 if (isElement$2(el) && isOpenShadowHost(el)) { 1138 if (event.composed && event.composedPath) { 1139 var composedPath = event.composedPath(); 1140 if (composedPath) { 1141 return head(composedPath); 1142 } 1143 } 1144 } 1145 } 1146 return Optional.from(event.target); 1147 }; 1148 var isOpenShadowHost = function (element) { 1149 return isNonNullable(element.dom.shadowRoot); 1150 }; 1151 1152 var inBody = function (element) { 1153 var dom = isText$1(element) ? element.dom.parentNode : element.dom; 1154 if (dom === undefined || dom === null || dom.ownerDocument === null) { 1155 return false; 1156 } 1157 var doc = dom.ownerDocument; 1158 return getShadowRoot(SugarElement.fromDom(dom)).fold(function () { 1159 return doc.body.contains(dom); 1160 }, compose1(inBody, getShadowHost)); 1161 }; 1162 var body = function () { 1163 return getBody(SugarElement.fromDom(document)); 1164 }; 1165 var getBody = function (doc) { 1166 var b = doc.dom.body; 1167 if (b === null || b === undefined) { 1168 throw new Error('Body is not available yet'); 1169 } 1170 return SugarElement.fromDom(b); 1171 }; 1172 1173 var rawSet = function (dom, key, value) { 1174 if (isString(value) || isBoolean(value) || isNumber(value)) { 1175 dom.setAttribute(key, value + ''); 1176 } else { 1177 console.error('Invalid call to Attribute.set. Key ', key, ':: Value ', value, ':: Element ', dom); 1178 throw new Error('Attribute value was not simple'); 1179 } 1180 }; 1181 var set$8 = function (element, key, value) { 1182 rawSet(element.dom, key, value); 1183 }; 1184 var setAll$1 = function (element, attrs) { 1185 var dom = element.dom; 1186 each(attrs, function (v, k) { 1187 rawSet(dom, k, v); 1188 }); 1189 }; 1190 var get$d = function (element, key) { 1191 var v = element.dom.getAttribute(key); 1192 return v === null ? undefined : v; 1193 }; 1194 var getOpt = function (element, key) { 1195 return Optional.from(get$d(element, key)); 1196 }; 1197 var has$1 = function (element, key) { 1198 var dom = element.dom; 1199 return dom && dom.hasAttribute ? dom.hasAttribute(key) : false; 1200 }; 1201 var remove$7 = function (element, key) { 1202 element.dom.removeAttribute(key); 1203 }; 1204 1205 var internalSet = function (dom, property, value) { 1206 if (!isString(value)) { 1207 console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value, ':: Element ', dom); 1208 throw new Error('CSS value must be a string: ' + value); 1209 } 1210 if (isSupported$1(dom)) { 1211 dom.style.setProperty(property, value); 1212 } 1213 }; 1214 var internalRemove = function (dom, property) { 1215 if (isSupported$1(dom)) { 1216 dom.style.removeProperty(property); 1217 } 1218 }; 1219 var set$7 = function (element, property, value) { 1220 var dom = element.dom; 1221 internalSet(dom, property, value); 1222 }; 1223 var setAll = function (element, css) { 1224 var dom = element.dom; 1225 each(css, function (v, k) { 1226 internalSet(dom, k, v); 1227 }); 1228 }; 1229 var setOptions = function (element, css) { 1230 var dom = element.dom; 1231 each(css, function (v, k) { 1232 v.fold(function () { 1233 internalRemove(dom, k); 1234 }, function (value) { 1235 internalSet(dom, k, value); 1236 }); 1237 }); 1238 }; 1239 var get$c = function (element, property) { 1240 var dom = element.dom; 1241 var styles = window.getComputedStyle(dom); 1242 var r = styles.getPropertyValue(property); 1243 return r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r; 1244 }; 1245 var getUnsafeProperty = function (dom, property) { 1246 return isSupported$1(dom) ? dom.style.getPropertyValue(property) : ''; 1247 }; 1248 var getRaw = function (element, property) { 1249 var dom = element.dom; 1250 var raw = getUnsafeProperty(dom, property); 1251 return Optional.from(raw).filter(function (r) { 1252 return r.length > 0; 1253 }); 1254 }; 1255 var getAllRaw = function (element) { 1256 var css = {}; 1257 var dom = element.dom; 1258 if (isSupported$1(dom)) { 1259 for (var i = 0; i < dom.style.length; i++) { 1260 var ruleName = dom.style.item(i); 1261 css[ruleName] = dom.style[ruleName]; 1262 } 1263 } 1264 return css; 1265 }; 1266 var isValidValue = function (tag, property, value) { 1267 var element = SugarElement.fromTag(tag); 1268 set$7(element, property, value); 1269 var style = getRaw(element, property); 1270 return style.isSome(); 1271 }; 1272 var remove$6 = function (element, property) { 1273 var dom = element.dom; 1274 internalRemove(dom, property); 1275 if (is$1(getOpt(element, 'style').map(trim$1), '')) { 1276 remove$7(element, 'style'); 1277 } 1278 }; 1279 var reflow = function (e) { 1280 return e.dom.offsetWidth; 1281 }; 1282 1283 var Dimension = function (name, getOffset) { 1284 var set = function (element, h) { 1285 if (!isNumber(h) && !h.match(/^[0-9]+$/)) { 1286 throw new Error(name + '.set accepts only positive integer values. Value was ' + h); 1287 } 1288 var dom = element.dom; 1289 if (isSupported$1(dom)) { 1290 dom.style[name] = h + 'px'; 1291 } 1292 }; 1293 var get = function (element) { 1294 var r = getOffset(element); 1295 if (r <= 0 || r === null) { 1296 var css = get$c(element, name); 1297 return parseFloat(css) || 0; 1298 } 1299 return r; 1300 }; 1301 var getOuter = get; 1302 var aggregate = function (element, properties) { 1303 return foldl(properties, function (acc, property) { 1304 var val = get$c(element, property); 1305 var value = val === undefined ? 0 : parseInt(val, 10); 1306 return isNaN(value) ? acc : acc + value; 1307 }, 0); 1308 }; 1309 var max = function (element, value, properties) { 1310 var cumulativeInclusions = aggregate(element, properties); 1311 var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0; 1312 return absoluteMax; 1313 }; 1314 return { 1315 set: set, 1316 get: get, 1317 getOuter: getOuter, 1318 aggregate: aggregate, 1319 max: max 1320 }; 1321 }; 1322 1323 var api$3 = Dimension('height', function (element) { 1324 var dom = element.dom; 1325 return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight; 1326 }); 1327 var get$b = function (element) { 1328 return api$3.get(element); 1329 }; 1330 var getOuter$2 = function (element) { 1331 return api$3.getOuter(element); 1332 }; 1333 var setMax$1 = function (element, value) { 1334 var inclusions = [ 1335 'margin-top', 1336 'border-top-width', 1337 'padding-top', 1338 'padding-bottom', 1339 'border-bottom-width', 1340 'margin-bottom' 1341 ]; 1342 var absMax = api$3.max(element, value, inclusions); 1343 set$7(element, 'max-height', absMax + 'px'); 1344 }; 1345 1346 var r$1 = function (left, top) { 1347 var translate = function (x, y) { 1348 return r$1(left + x, top + y); 1349 }; 1350 return { 1351 left: left, 1352 top: top, 1353 translate: translate 1354 }; 1355 }; 1356 var SugarPosition = r$1; 1357 1358 var boxPosition = function (dom) { 1359 var box = dom.getBoundingClientRect(); 1360 return SugarPosition(box.left, box.top); 1361 }; 1362 var firstDefinedOrZero = function (a, b) { 1363 if (a !== undefined) { 1364 return a; 1365 } else { 1366 return b !== undefined ? b : 0; 1367 } 1368 }; 1369 var absolute$3 = function (element) { 1370 var doc = element.dom.ownerDocument; 1371 var body = doc.body; 1372 var win = doc.defaultView; 1373 var html = doc.documentElement; 1374 if (body === element.dom) { 1375 return SugarPosition(body.offsetLeft, body.offsetTop); 1376 } 1377 var scrollTop = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageYOffset, html.scrollTop); 1378 var scrollLeft = firstDefinedOrZero(win === null || win === void 0 ? void 0 : win.pageXOffset, html.scrollLeft); 1379 var clientTop = firstDefinedOrZero(html.clientTop, body.clientTop); 1380 var clientLeft = firstDefinedOrZero(html.clientLeft, body.clientLeft); 1381 return viewport$1(element).translate(scrollLeft - clientLeft, scrollTop - clientTop); 1382 }; 1383 var viewport$1 = function (element) { 1384 var dom = element.dom; 1385 var doc = dom.ownerDocument; 1386 var body = doc.body; 1387 if (body === dom) { 1388 return SugarPosition(body.offsetLeft, body.offsetTop); 1389 } 1390 if (!inBody(element)) { 1391 return SugarPosition(0, 0); 1392 } 1393 return boxPosition(dom); 1394 }; 1395 1396 var api$2 = Dimension('width', function (element) { 1397 return element.dom.offsetWidth; 1398 }); 1399 var set$6 = function (element, h) { 1400 return api$2.set(element, h); 1401 }; 1402 var get$a = function (element) { 1403 return api$2.get(element); 1404 }; 1405 var getOuter$1 = function (element) { 1406 return api$2.getOuter(element); 1407 }; 1408 var setMax = function (element, value) { 1409 var inclusions = [ 1410 'margin-left', 1411 'border-left-width', 1412 'padding-left', 1413 'padding-right', 1414 'border-right-width', 1415 'margin-right' 1416 ]; 1417 var absMax = api$2.max(element, value, inclusions); 1418 set$7(element, 'max-width', absMax + 'px'); 1419 }; 1420 1421 var mkEvent = function (target, x, y, stop, prevent, kill, raw) { 1422 return { 1423 target: target, 1424 x: x, 1425 y: y, 1426 stop: stop, 1427 prevent: prevent, 1428 kill: kill, 1429 raw: raw 1430 }; 1431 }; 1432 var fromRawEvent$1 = function (rawEvent) { 1433 var target = SugarElement.fromDom(getOriginalEventTarget(rawEvent).getOr(rawEvent.target)); 1434 var stop = function () { 1435 return rawEvent.stopPropagation(); 1436 }; 1437 var prevent = function () { 1438 return rawEvent.preventDefault(); 1439 }; 1440 var kill = compose(prevent, stop); 1441 return mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent); 1442 }; 1443 var handle = function (filter, handler) { 1444 return function (rawEvent) { 1445 if (filter(rawEvent)) { 1446 handler(fromRawEvent$1(rawEvent)); 1447 } 1448 }; 1449 }; 1450 var binder = function (element, event, filter, handler, useCapture) { 1451 var wrapped = handle(filter, handler); 1452 element.dom.addEventListener(event, wrapped, useCapture); 1453 return { unbind: curry(unbind, element, event, wrapped, useCapture) }; 1454 }; 1455 var bind$2 = function (element, event, filter, handler) { 1456 return binder(element, event, filter, handler, false); 1457 }; 1458 var capture$1 = function (element, event, filter, handler) { 1459 return binder(element, event, filter, handler, true); 1460 }; 1461 var unbind = function (element, event, handler, useCapture) { 1462 element.dom.removeEventListener(event, handler, useCapture); 1463 }; 1464 1465 var before$2 = function (marker, element) { 1466 var parent$1 = parent(marker); 1467 parent$1.each(function (v) { 1468 v.dom.insertBefore(element.dom, marker.dom); 1469 }); 1470 }; 1471 var after$2 = function (marker, element) { 1472 var sibling = nextSibling(marker); 1473 sibling.fold(function () { 1474 var parent$1 = parent(marker); 1475 parent$1.each(function (v) { 1476 append$2(v, element); 1477 }); 1478 }, function (v) { 1479 before$2(v, element); 1480 }); 1481 }; 1482 var prepend$1 = function (parent, element) { 1483 var firstChild$1 = firstChild(parent); 1484 firstChild$1.fold(function () { 1485 append$2(parent, element); 1486 }, function (v) { 1487 parent.dom.insertBefore(element.dom, v.dom); 1488 }); 1489 }; 1490 var append$2 = function (parent, element) { 1491 parent.dom.appendChild(element.dom); 1492 }; 1493 var appendAt = function (parent, element, index) { 1494 child$2(parent, index).fold(function () { 1495 append$2(parent, element); 1496 }, function (v) { 1497 before$2(v, element); 1498 }); 1499 }; 1500 1501 var before$1 = function (marker, elements) { 1502 each$1(elements, function (x) { 1503 before$2(marker, x); 1504 }); 1505 }; 1506 var append$1 = function (parent, elements) { 1507 each$1(elements, function (x) { 1508 append$2(parent, x); 1509 }); 1510 }; 1511 1512 var empty = function (element) { 1513 element.dom.textContent = ''; 1514 each$1(children(element), function (rogue) { 1515 remove$5(rogue); 1516 }); 1517 }; 1518 var remove$5 = function (element) { 1519 var dom = element.dom; 1520 if (dom.parentNode !== null) { 1521 dom.parentNode.removeChild(dom); 1522 } 1523 }; 1524 var unwrap = function (wrapper) { 1525 var children$1 = children(wrapper); 1526 if (children$1.length > 0) { 1527 before$1(wrapper, children$1); 1528 } 1529 remove$5(wrapper); 1530 }; 1531 1532 var get$9 = function (_DOC) { 1533 var doc = _DOC !== undefined ? _DOC.dom : document; 1534 var x = doc.body.scrollLeft || doc.documentElement.scrollLeft; 1535 var y = doc.body.scrollTop || doc.documentElement.scrollTop; 1536 return SugarPosition(x, y); 1537 }; 1538 var to = function (x, y, _DOC) { 1539 var doc = _DOC !== undefined ? _DOC.dom : document; 1540 var win = doc.defaultView; 1541 if (win) { 1542 win.scrollTo(x, y); 1543 } 1544 }; 1545 1546 var get$8 = function (_win) { 1547 var win = _win === undefined ? window : _win; 1548 if (detect$1().browser.isFirefox()) { 1549 return Optional.none(); 1550 } else { 1551 return Optional.from(win['visualViewport']); 1552 } 1553 }; 1554 var bounds$1 = function (x, y, width, height) { 1555 return { 1556 x: x, 1557 y: y, 1558 width: width, 1559 height: height, 1560 right: x + width, 1561 bottom: y + height 1562 }; 1563 }; 1564 var getBounds$3 = function (_win) { 1565 var win = _win === undefined ? window : _win; 1566 var doc = win.document; 1567 var scroll = get$9(SugarElement.fromDom(doc)); 1568 return get$8(win).fold(function () { 1569 var html = win.document.documentElement; 1570 var width = html.clientWidth; 1571 var height = html.clientHeight; 1572 return bounds$1(scroll.left, scroll.top, width, height); 1573 }, function (visualViewport) { 1574 return bounds$1(Math.max(visualViewport.pageLeft, scroll.left), Math.max(visualViewport.pageTop, scroll.top), visualViewport.width, visualViewport.height); 1575 }); 1576 }; 1577 1578 var walkUp = function (navigation, doc) { 1579 var frame = navigation.view(doc); 1580 return frame.fold(constant$1([]), function (f) { 1581 var parent = navigation.owner(f); 1582 var rest = walkUp(navigation, parent); 1583 return [f].concat(rest); 1584 }); 1585 }; 1586 var pathTo = function (element, navigation) { 1587 var d = navigation.owner(element); 1588 var paths = walkUp(navigation, d); 1589 return Optional.some(paths); 1590 }; 1591 1592 var view = function (doc) { 1593 var _a; 1594 var element = doc.dom === document ? Optional.none() : Optional.from((_a = doc.dom.defaultView) === null || _a === void 0 ? void 0 : _a.frameElement); 1595 return element.map(SugarElement.fromDom); 1596 }; 1597 var owner$3 = function (element) { 1598 return owner$4(element); 1599 }; 1600 1601 var Navigation = /*#__PURE__*/Object.freeze({ 1602 __proto__: null, 1603 view: view, 1604 owner: owner$3 1605 }); 1606 1607 var find$2 = function (element) { 1608 var doc = SugarElement.fromDom(document); 1609 var scroll = get$9(doc); 1610 var path = pathTo(element, Navigation); 1611 return path.fold(curry(absolute$3, element), function (frames) { 1612 var offset = viewport$1(element); 1613 var r = foldr(frames, function (b, a) { 1614 var loc = viewport$1(a); 1615 return { 1616 left: b.left + loc.left, 1617 top: b.top + loc.top 1618 }; 1619 }, { 1620 left: 0, 1621 top: 0 1622 }); 1623 return SugarPosition(r.left + offset.left + scroll.left, r.top + offset.top + scroll.top); 1624 }); 1625 }; 1626 1627 var pointed = function (point, width, height) { 1628 return { 1629 point: point, 1630 width: width, 1631 height: height 1632 }; 1633 }; 1634 var rect = function (x, y, width, height) { 1635 return { 1636 x: x, 1637 y: y, 1638 width: width, 1639 height: height 1640 }; 1641 }; 1642 var bounds = function (x, y, width, height) { 1643 return { 1644 x: x, 1645 y: y, 1646 width: width, 1647 height: height, 1648 right: x + width, 1649 bottom: y + height 1650 }; 1651 }; 1652 var box$1 = function (element) { 1653 var xy = absolute$3(element); 1654 var w = getOuter$1(element); 1655 var h = getOuter$2(element); 1656 return bounds(xy.left, xy.top, w, h); 1657 }; 1658 var absolute$2 = function (element) { 1659 var position = find$2(element); 1660 var width = getOuter$1(element); 1661 var height = getOuter$2(element); 1662 return bounds(position.left, position.top, width, height); 1663 }; 1664 var win = function () { 1665 return getBounds$3(window); 1666 }; 1667 1668 var value$3 = function (o) { 1669 var or = function (_opt) { 1670 return value$3(o); 1671 }; 1672 var orThunk = function (_f) { 1673 return value$3(o); 1674 }; 1675 var map = function (f) { 1676 return value$3(f(o)); 1677 }; 1678 var mapError = function (_f) { 1679 return value$3(o); 1680 }; 1681 var each = function (f) { 1682 f(o); 1683 }; 1684 var bind = function (f) { 1685 return f(o); 1686 }; 1687 var fold = function (_, onValue) { 1688 return onValue(o); 1689 }; 1690 var exists = function (f) { 1691 return f(o); 1692 }; 1693 var forall = function (f) { 1694 return f(o); 1695 }; 1696 var toOptional = function () { 1697 return Optional.some(o); 1698 }; 1699 return { 1700 isValue: always, 1701 isError: never, 1702 getOr: constant$1(o), 1703 getOrThunk: constant$1(o), 1704 getOrDie: constant$1(o), 1705 or: or, 1706 orThunk: orThunk, 1707 fold: fold, 1708 map: map, 1709 mapError: mapError, 1710 each: each, 1711 bind: bind, 1712 exists: exists, 1713 forall: forall, 1714 toOptional: toOptional 1715 }; 1716 }; 1717 var error$1 = function (message) { 1718 var getOrThunk = function (f) { 1719 return f(); 1720 }; 1721 var getOrDie = function () { 1722 return die(String(message))(); 1723 }; 1724 var or = identity$1; 1725 var orThunk = function (f) { 1726 return f(); 1727 }; 1728 var map = function (_f) { 1729 return error$1(message); 1730 }; 1731 var mapError = function (f) { 1732 return error$1(f(message)); 1733 }; 1734 var bind = function (_f) { 1735 return error$1(message); 1736 }; 1737 var fold = function (onError, _) { 1738 return onError(message); 1739 }; 1740 return { 1741 isValue: never, 1742 isError: always, 1743 getOr: identity$1, 1744 getOrThunk: getOrThunk, 1745 getOrDie: getOrDie, 1746 or: or, 1747 orThunk: orThunk, 1748 fold: fold, 1749 map: map, 1750 mapError: mapError, 1751 each: noop, 1752 bind: bind, 1753 exists: never, 1754 forall: always, 1755 toOptional: Optional.none 1756 }; 1757 }; 1758 var fromOption = function (opt, err) { 1759 return opt.fold(function () { 1760 return error$1(err); 1761 }, value$3); 1762 }; 1763 var Result = { 1764 value: value$3, 1765 error: error$1, 1766 fromOption: fromOption 1767 }; 1768 1769 var SimpleResultType; 1770 (function (SimpleResultType) { 1771 SimpleResultType[SimpleResultType['Error'] = 0] = 'Error'; 1772 SimpleResultType[SimpleResultType['Value'] = 1] = 'Value'; 1773 }(SimpleResultType || (SimpleResultType = {}))); 1774 var fold$1 = function (res, onError, onValue) { 1775 return res.stype === SimpleResultType.Error ? onError(res.serror) : onValue(res.svalue); 1776 }; 1777 var partition$2 = function (results) { 1778 var values = []; 1779 var errors = []; 1780 each$1(results, function (obj) { 1781 fold$1(obj, function (err) { 1782 return errors.push(err); 1783 }, function (val) { 1784 return values.push(val); 1785 }); 1786 }); 1787 return { 1788 values: values, 1789 errors: errors 1790 }; 1791 }; 1792 var mapError = function (res, f) { 1793 if (res.stype === SimpleResultType.Error) { 1794 return { 1795 stype: SimpleResultType.Error, 1796 serror: f(res.serror) 1797 }; 1798 } else { 1799 return res; 1800 } 1801 }; 1802 var map = function (res, f) { 1803 if (res.stype === SimpleResultType.Value) { 1804 return { 1805 stype: SimpleResultType.Value, 1806 svalue: f(res.svalue) 1807 }; 1808 } else { 1809 return res; 1810 } 1811 }; 1812 var bind$1 = function (res, f) { 1813 if (res.stype === SimpleResultType.Value) { 1814 return f(res.svalue); 1815 } else { 1816 return res; 1817 } 1818 }; 1819 var bindError = function (res, f) { 1820 if (res.stype === SimpleResultType.Error) { 1821 return f(res.serror); 1822 } else { 1823 return res; 1824 } 1825 }; 1826 var svalue = function (v) { 1827 return { 1828 stype: SimpleResultType.Value, 1829 svalue: v 1830 }; 1831 }; 1832 var serror = function (e) { 1833 return { 1834 stype: SimpleResultType.Error, 1835 serror: e 1836 }; 1837 }; 1838 var toResult$1 = function (res) { 1839 return fold$1(res, Result.error, Result.value); 1840 }; 1841 var fromResult$1 = function (res) { 1842 return res.fold(serror, svalue); 1843 }; 1844 var SimpleResult = { 1845 fromResult: fromResult$1, 1846 toResult: toResult$1, 1847 svalue: svalue, 1848 partition: partition$2, 1849 serror: serror, 1850 bind: bind$1, 1851 bindError: bindError, 1852 map: map, 1853 mapError: mapError, 1854 fold: fold$1 1855 }; 1856 1857 var field$2 = function (key, newKey, presence, prop) { 1858 return { 1859 tag: 'field', 1860 key: key, 1861 newKey: newKey, 1862 presence: presence, 1863 prop: prop 1864 }; 1865 }; 1866 var customField$1 = function (newKey, instantiator) { 1867 return { 1868 tag: 'custom', 1869 newKey: newKey, 1870 instantiator: instantiator 1871 }; 1872 }; 1873 var fold = function (value, ifField, ifCustom) { 1874 switch (value.tag) { 1875 case 'field': 1876 return ifField(value.key, value.newKey, value.presence, value.prop); 1877 case 'custom': 1878 return ifCustom(value.newKey, value.instantiator); 1879 } 1880 }; 1881 1882 var shallow$1 = function (old, nu) { 1883 return nu; 1884 }; 1885 var deep = function (old, nu) { 1886 var bothObjects = isObject(old) && isObject(nu); 1887 return bothObjects ? deepMerge(old, nu) : nu; 1888 }; 1889 var baseMerge = function (merger) { 1890 return function () { 1891 var objects = []; 1892 for (var _i = 0; _i < arguments.length; _i++) { 1893 objects[_i] = arguments[_i]; 1894 } 1895 if (objects.length === 0) { 1896 throw new Error('Can\'t merge zero objects'); 1897 } 1898 var ret = {}; 1899 for (var j = 0; j < objects.length; j++) { 1900 var curObject = objects[j]; 1901 for (var key in curObject) { 1902 if (has$2(curObject, key)) { 1903 ret[key] = merger(ret[key], curObject[key]); 1904 } 1905 } 1906 } 1907 return ret; 1908 }; 1909 }; 1910 var deepMerge = baseMerge(deep); 1911 var merge$1 = baseMerge(shallow$1); 1912 1913 var required$2 = function () { 1914 return { 1915 tag: 'required', 1916 process: {} 1917 }; 1918 }; 1919 var defaultedThunk = function (fallbackThunk) { 1920 return { 1921 tag: 'defaultedThunk', 1922 process: fallbackThunk 1923 }; 1924 }; 1925 var defaulted$1 = function (fallback) { 1926 return defaultedThunk(constant$1(fallback)); 1927 }; 1928 var asOption = function () { 1929 return { 1930 tag: 'option', 1931 process: {} 1932 }; 1933 }; 1934 var mergeWithThunk = function (baseThunk) { 1935 return { 1936 tag: 'mergeWithThunk', 1937 process: baseThunk 1938 }; 1939 }; 1940 var mergeWith = function (base) { 1941 return mergeWithThunk(constant$1(base)); 1942 }; 1943 1944 var mergeValues$1 = function (values, base) { 1945 return values.length > 0 ? SimpleResult.svalue(deepMerge(base, merge$1.apply(undefined, values))) : SimpleResult.svalue(base); 1946 }; 1947 var mergeErrors$1 = function (errors) { 1948 return compose(SimpleResult.serror, flatten)(errors); 1949 }; 1950 var consolidateObj = function (objects, base) { 1951 var partition = SimpleResult.partition(objects); 1952 return partition.errors.length > 0 ? mergeErrors$1(partition.errors) : mergeValues$1(partition.values, base); 1953 }; 1954 var consolidateArr = function (objects) { 1955 var partitions = SimpleResult.partition(objects); 1956 return partitions.errors.length > 0 ? mergeErrors$1(partitions.errors) : SimpleResult.svalue(partitions.values); 1957 }; 1958 var ResultCombine = { 1959 consolidateObj: consolidateObj, 1960 consolidateArr: consolidateArr 1961 }; 1962 1963 var formatObj = function (input) { 1964 return isObject(input) && keys(input).length > 100 ? ' removed due to size' : JSON.stringify(input, null, 2); 1965 }; 1966 var formatErrors = function (errors) { 1967 var es = errors.length > 10 ? errors.slice(0, 10).concat([{ 1968 path: [], 1969 getErrorInfo: constant$1('... (only showing first ten failures)') 1970 }]) : errors; 1971 return map$2(es, function (e) { 1972 return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo(); 1973 }); 1974 }; 1975 1976 var nu$a = function (path, getErrorInfo) { 1977 return SimpleResult.serror([{ 1978 path: path, 1979 getErrorInfo: getErrorInfo 1980 }]); 1981 }; 1982 var missingRequired = function (path, key, obj) { 1983 return nu$a(path, function () { 1984 return 'Could not find valid *required* value for "' + key + '" in ' + formatObj(obj); 1985 }); 1986 }; 1987 var missingKey = function (path, key) { 1988 return nu$a(path, function () { 1989 return 'Choice schema did not contain choice key: "' + key + '"'; 1990 }); 1991 }; 1992 var missingBranch = function (path, branches, branch) { 1993 return nu$a(path, function () { 1994 return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches); 1995 }); 1996 }; 1997 var unsupportedFields = function (path, unsupported) { 1998 return nu$a(path, function () { 1999 return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified'; 2000 }); 2001 }; 2002 var custom = function (path, err) { 2003 return nu$a(path, constant$1(err)); 2004 }; 2005 2006 var value$2 = function (validator) { 2007 var extract = function (path, val) { 2008 return SimpleResult.bindError(validator(val), function (err) { 2009 return custom(path, err); 2010 }); 2011 }; 2012 var toString = constant$1('val'); 2013 return { 2014 extract: extract, 2015 toString: toString 2016 }; 2017 }; 2018 var anyValue$1 = value$2(SimpleResult.svalue); 2019 2020 var requiredAccess = function (path, obj, key, bundle) { 2021 return get$e(obj, key).fold(function () { 2022 return missingRequired(path, key, obj); 2023 }, bundle); 2024 }; 2025 var fallbackAccess = function (obj, key, fallback, bundle) { 2026 var v = get$e(obj, key).getOrThunk(function () { 2027 return fallback(obj); 2028 }); 2029 return bundle(v); 2030 }; 2031 var optionAccess = function (obj, key, bundle) { 2032 return bundle(get$e(obj, key)); 2033 }; 2034 var optionDefaultedAccess = function (obj, key, fallback, bundle) { 2035 var opt = get$e(obj, key).map(function (val) { 2036 return val === true ? fallback(obj) : val; 2037 }); 2038 return bundle(opt); 2039 }; 2040 var extractField = function (field, path, obj, key, prop) { 2041 var bundle = function (av) { 2042 return prop.extract(path.concat([key]), av); 2043 }; 2044 var bundleAsOption = function (optValue) { 2045 return optValue.fold(function () { 2046 return SimpleResult.svalue(Optional.none()); 2047 }, function (ov) { 2048 var result = prop.extract(path.concat([key]), ov); 2049 return SimpleResult.map(result, Optional.some); 2050 }); 2051 }; 2052 switch (field.tag) { 2053 case 'required': 2054 return requiredAccess(path, obj, key, bundle); 2055 case 'defaultedThunk': 2056 return fallbackAccess(obj, key, field.process, bundle); 2057 case 'option': 2058 return optionAccess(obj, key, bundleAsOption); 2059 case 'defaultedOptionThunk': 2060 return optionDefaultedAccess(obj, key, field.process, bundleAsOption); 2061 case 'mergeWithThunk': { 2062 return fallbackAccess(obj, key, constant$1({}), function (v) { 2063 var result = deepMerge(field.process(obj), v); 2064 return bundle(result); 2065 }); 2066 } 2067 } 2068 }; 2069 var extractFields = function (path, obj, fields) { 2070 var success = {}; 2071 var errors = []; 2072 for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) { 2073 var field = fields_1[_i]; 2074 fold(field, function (key, newKey, presence, prop) { 2075 var result = extractField(presence, path, obj, key, prop); 2076 SimpleResult.fold(result, function (err) { 2077 errors.push.apply(errors, err); 2078 }, function (res) { 2079 success[newKey] = res; 2080 }); 2081 }, function (newKey, instantiator) { 2082 success[newKey] = instantiator(obj); 2083 }); 2084 } 2085 return errors.length > 0 ? SimpleResult.serror(errors) : SimpleResult.svalue(success); 2086 }; 2087 var valueThunk = function (getDelegate) { 2088 var extract = function (path, val) { 2089 return getDelegate().extract(path, val); 2090 }; 2091 var toString = function () { 2092 return getDelegate().toString(); 2093 }; 2094 return { 2095 extract: extract, 2096 toString: toString 2097 }; 2098 }; 2099 var getSetKeys = function (obj) { 2100 return keys(filter$1(obj, isNonNullable)); 2101 }; 2102 var objOfOnly = function (fields) { 2103 var delegate = objOf(fields); 2104 var fieldNames = foldr(fields, function (acc, value) { 2105 return fold(value, function (key) { 2106 var _a; 2107 return deepMerge(acc, (_a = {}, _a[key] = true, _a)); 2108 }, constant$1(acc)); 2109 }, {}); 2110 var extract = function (path, o) { 2111 var keys = isBoolean(o) ? [] : getSetKeys(o); 2112 var extra = filter$2(keys, function (k) { 2113 return !hasNonNullableKey(fieldNames, k); 2114 }); 2115 return extra.length === 0 ? delegate.extract(path, o) : unsupportedFields(path, extra); 2116 }; 2117 return { 2118 extract: extract, 2119 toString: delegate.toString 2120 }; 2121 }; 2122 var objOf = function (values) { 2123 var extract = function (path, o) { 2124 return extractFields(path, o, values); 2125 }; 2126 var toString = function () { 2127 var fieldStrings = map$2(values, function (value) { 2128 return fold(value, function (key, _okey, _presence, prop) { 2129 return key + ' -> ' + prop.toString(); 2130 }, function (newKey, _instantiator) { 2131 return 'state(' + newKey + ')'; 2132 }); 2133 }); 2134 return 'obj{\n' + fieldStrings.join('\n') + '}'; 2135 }; 2136 return { 2137 extract: extract, 2138 toString: toString 2139 }; 2140 }; 2141 var arrOf = function (prop) { 2142 var extract = function (path, array) { 2143 var results = map$2(array, function (a, i) { 2144 return prop.extract(path.concat(['[' + i + ']']), a); 2145 }); 2146 return ResultCombine.consolidateArr(results); 2147 }; 2148 var toString = function () { 2149 return 'array(' + prop.toString() + ')'; 2150 }; 2151 return { 2152 extract: extract, 2153 toString: toString 2154 }; 2155 }; 2156 var oneOf = function (props) { 2157 var extract = function (path, val) { 2158 var errors = []; 2159 for (var _i = 0, props_1 = props; _i < props_1.length; _i++) { 2160 var prop = props_1[_i]; 2161 var res = prop.extract(path, val); 2162 if (res.stype === SimpleResultType.Value) { 2163 return res; 2164 } 2165 errors.push(res); 2166 } 2167 return ResultCombine.consolidateArr(errors); 2168 }; 2169 var toString = function () { 2170 return 'oneOf(' + map$2(props, function (prop) { 2171 return prop.toString(); 2172 }).join(', ') + ')'; 2173 }; 2174 return { 2175 extract: extract, 2176 toString: toString 2177 }; 2178 }; 2179 var setOf$1 = function (validator, prop) { 2180 var validateKeys = function (path, keys) { 2181 return arrOf(value$2(validator)).extract(path, keys); 2182 }; 2183 var extract = function (path, o) { 2184 var keys$1 = keys(o); 2185 var validatedKeys = validateKeys(path, keys$1); 2186 return SimpleResult.bind(validatedKeys, function (validKeys) { 2187 var schema = map$2(validKeys, function (vk) { 2188 return field$2(vk, vk, required$2(), prop); 2189 }); 2190 return objOf(schema).extract(path, o); 2191 }); 2192 }; 2193 var toString = function () { 2194 return 'setOf(' + prop.toString() + ')'; 2195 }; 2196 return { 2197 extract: extract, 2198 toString: toString 2199 }; 2200 }; 2201 var thunk = function (_desc, processor) { 2202 var getP = cached(processor); 2203 var extract = function (path, val) { 2204 return getP().extract(path, val); 2205 }; 2206 var toString = function () { 2207 return getP().toString(); 2208 }; 2209 return { 2210 extract: extract, 2211 toString: toString 2212 }; 2213 }; 2214 var arrOfObj = compose(arrOf, objOf); 2215 2216 var anyValue = constant$1(anyValue$1); 2217 var typedValue = function (validator, expectedType) { 2218 return value$2(function (a) { 2219 var actualType = typeof a; 2220 return validator(a) ? SimpleResult.svalue(a) : SimpleResult.serror('Expected type: ' + expectedType + ' but got: ' + actualType); 2221 }); 2222 }; 2223 var number = typedValue(isNumber, 'number'); 2224 var string = typedValue(isString, 'string'); 2225 var boolean = typedValue(isBoolean, 'boolean'); 2226 var functionProcessor = typedValue(isFunction, 'function'); 2227 var isPostMessageable = function (val) { 2228 if (Object(val) !== val) { 2229 return true; 2230 } 2231 switch ({}.toString.call(val).slice(8, -1)) { 2232 case 'Boolean': 2233 case 'Number': 2234 case 'String': 2235 case 'Date': 2236 case 'RegExp': 2237 case 'Blob': 2238 case 'FileList': 2239 case 'ImageData': 2240 case 'ImageBitmap': 2241 case 'ArrayBuffer': 2242 return true; 2243 case 'Array': 2244 case 'Object': 2245 return Object.keys(val).every(function (prop) { 2246 return isPostMessageable(val[prop]); 2247 }); 2248 default: 2249 return false; 2250 } 2251 }; 2252 var postMessageable = value$2(function (a) { 2253 if (isPostMessageable(a)) { 2254 return SimpleResult.svalue(a); 2255 } else { 2256 return SimpleResult.serror('Expected value to be acceptable for sending via postMessage'); 2257 } 2258 }); 2259 2260 var chooseFrom = function (path, input, branches, ch) { 2261 var fields = get$e(branches, ch); 2262 return fields.fold(function () { 2263 return missingBranch(path, branches, ch); 2264 }, function (vp) { 2265 return vp.extract(path.concat(['branch: ' + ch]), input); 2266 }); 2267 }; 2268 var choose$2 = function (key, branches) { 2269 var extract = function (path, input) { 2270 var choice = get$e(input, key); 2271 return choice.fold(function () { 2272 return missingKey(path, key); 2273 }, function (chosen) { 2274 return chooseFrom(path, input, branches, chosen); 2275 }); 2276 }; 2277 var toString = function () { 2278 return 'chooseOn(' + key + '). Possible values: ' + keys(branches); 2279 }; 2280 return { 2281 extract: extract, 2282 toString: toString 2283 }; 2284 }; 2285 2286 var arrOfVal = function () { 2287 return arrOf(anyValue$1); 2288 }; 2289 var valueOf = function (validator) { 2290 return value$2(function (v) { 2291 return validator(v).fold(SimpleResult.serror, SimpleResult.svalue); 2292 }); 2293 }; 2294 var setOf = function (validator, prop) { 2295 return setOf$1(function (v) { 2296 return SimpleResult.fromResult(validator(v)); 2297 }, prop); 2298 }; 2299 var extractValue = function (label, prop, obj) { 2300 var res = prop.extract([label], obj); 2301 return SimpleResult.mapError(res, function (errs) { 2302 return { 2303 input: obj, 2304 errors: errs 2305 }; 2306 }); 2307 }; 2308 var asRaw = function (label, prop, obj) { 2309 return SimpleResult.toResult(extractValue(label, prop, obj)); 2310 }; 2311 var getOrDie = function (extraction) { 2312 return extraction.fold(function (errInfo) { 2313 throw new Error(formatError(errInfo)); 2314 }, identity$1); 2315 }; 2316 var asRawOrDie$1 = function (label, prop, obj) { 2317 return getOrDie(asRaw(label, prop, obj)); 2318 }; 2319 var formatError = function (errInfo) { 2320 return 'Errors: \n' + formatErrors(errInfo.errors).join('\n') + '\n\nInput object: ' + formatObj(errInfo.input); 2321 }; 2322 var choose$1 = function (key, branches) { 2323 return choose$2(key, map$1(branches, objOf)); 2324 }; 2325 var thunkOf = function (desc, schema) { 2326 return thunk(desc, schema); 2327 }; 2328 2329 var field$1 = field$2; 2330 var customField = customField$1; 2331 var validateEnum = function (values) { 2332 return valueOf(function (value) { 2333 return contains$2(values, value) ? Result.value(value) : Result.error('Unsupported value: "' + value + '", choose one of "' + values.join(', ') + '".'); 2334 }); 2335 }; 2336 var required$1 = function (key) { 2337 return field$1(key, key, required$2(), anyValue()); 2338 }; 2339 var requiredOf = function (key, schema) { 2340 return field$1(key, key, required$2(), schema); 2341 }; 2342 var requiredNumber = function (key) { 2343 return requiredOf(key, number); 2344 }; 2345 var requiredString = function (key) { 2346 return requiredOf(key, string); 2347 }; 2348 var requiredStringEnum = function (key, values) { 2349 return field$1(key, key, required$2(), validateEnum(values)); 2350 }; 2351 var requiredBoolean = function (key) { 2352 return requiredOf(key, boolean); 2353 }; 2354 var requiredFunction = function (key) { 2355 return requiredOf(key, functionProcessor); 2356 }; 2357 var forbid = function (key, message) { 2358 return field$1(key, key, asOption(), value$2(function (_v) { 2359 return SimpleResult.serror('The field: ' + key + ' is forbidden. ' + message); 2360 })); 2361 }; 2362 var requiredObjOf = function (key, objSchema) { 2363 return field$1(key, key, required$2(), objOf(objSchema)); 2364 }; 2365 var requiredArrayOfObj = function (key, objFields) { 2366 return field$1(key, key, required$2(), arrOfObj(objFields)); 2367 }; 2368 var requiredArrayOf = function (key, schema) { 2369 return field$1(key, key, required$2(), arrOf(schema)); 2370 }; 2371 var option = function (key) { 2372 return field$1(key, key, asOption(), anyValue()); 2373 }; 2374 var optionOf = function (key, schema) { 2375 return field$1(key, key, asOption(), schema); 2376 }; 2377 var optionNumber = function (key) { 2378 return optionOf(key, number); 2379 }; 2380 var optionString = function (key) { 2381 return optionOf(key, string); 2382 }; 2383 var optionFunction = function (key) { 2384 return optionOf(key, functionProcessor); 2385 }; 2386 var optionArrayOf = function (key, schema) { 2387 return optionOf(key, arrOf(schema)); 2388 }; 2389 var optionObjOf = function (key, objSchema) { 2390 return optionOf(key, objOf(objSchema)); 2391 }; 2392 var optionObjOfOnly = function (key, objSchema) { 2393 return optionOf(key, objOfOnly(objSchema)); 2394 }; 2395 var defaulted = function (key, fallback) { 2396 return field$1(key, key, defaulted$1(fallback), anyValue()); 2397 }; 2398 var defaultedOf = function (key, fallback, schema) { 2399 return field$1(key, key, defaulted$1(fallback), schema); 2400 }; 2401 var defaultedNumber = function (key, fallback) { 2402 return defaultedOf(key, fallback, number); 2403 }; 2404 var defaultedString = function (key, fallback) { 2405 return defaultedOf(key, fallback, string); 2406 }; 2407 var defaultedStringEnum = function (key, fallback, values) { 2408 return defaultedOf(key, fallback, validateEnum(values)); 2409 }; 2410 var defaultedBoolean = function (key, fallback) { 2411 return defaultedOf(key, fallback, boolean); 2412 }; 2413 var defaultedFunction = function (key, fallback) { 2414 return defaultedOf(key, fallback, functionProcessor); 2415 }; 2416 var defaultedPostMsg = function (key, fallback) { 2417 return defaultedOf(key, fallback, postMessageable); 2418 }; 2419 var defaultedArrayOf = function (key, fallback, schema) { 2420 return defaultedOf(key, fallback, arrOf(schema)); 2421 }; 2422 var defaultedObjOf = function (key, fallback, objSchema) { 2423 return defaultedOf(key, fallback, objOf(objSchema)); 2424 }; 2425 2426 var Cell = function (initial) { 2427 var value = initial; 2428 var get = function () { 2429 return value; 2430 }; 2431 var set = function (v) { 2432 value = v; 2433 }; 2434 return { 2435 get: get, 2436 set: set 2437 }; 2438 }; 2439 2440 var generate$7 = function (cases) { 2441 if (!isArray(cases)) { 2442 throw new Error('cases must be an array'); 2443 } 2444 if (cases.length === 0) { 2445 throw new Error('there must be at least one case'); 2446 } 2447 var constructors = []; 2448 var adt = {}; 2449 each$1(cases, function (acase, count) { 2450 var keys$1 = keys(acase); 2451 if (keys$1.length !== 1) { 2452 throw new Error('one and only one name per case'); 2453 } 2454 var key = keys$1[0]; 2455 var value = acase[key]; 2456 if (adt[key] !== undefined) { 2457 throw new Error('duplicate key detected:' + key); 2458 } else if (key === 'cata') { 2459 throw new Error('cannot have a case named cata (sorry)'); 2460 } else if (!isArray(value)) { 2461 throw new Error('case arguments must be an array'); 2462 } 2463 constructors.push(key); 2464 adt[key] = function () { 2465 var args = []; 2466 for (var _i = 0; _i < arguments.length; _i++) { 2467 args[_i] = arguments[_i]; 2468 } 2469 var argLength = args.length; 2470 if (argLength !== value.length) { 2471 throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength); 2472 } 2473 var match = function (branches) { 2474 var branchKeys = keys(branches); 2475 if (constructors.length !== branchKeys.length) { 2476 throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(',')); 2477 } 2478 var allReqd = forall(constructors, function (reqKey) { 2479 return contains$2(branchKeys, reqKey); 2480 }); 2481 if (!allReqd) { 2482 throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', ')); 2483 } 2484 return branches[key].apply(null, args); 2485 }; 2486 return { 2487 fold: function () { 2488 var foldArgs = []; 2489 for (var _i = 0; _i < arguments.length; _i++) { 2490 foldArgs[_i] = arguments[_i]; 2491 } 2492 if (foldArgs.length !== cases.length) { 2493 throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + foldArgs.length); 2494 } 2495 var target = foldArgs[count]; 2496 return target.apply(null, args); 2497 }, 2498 match: match, 2499 log: function (label) { 2500 console.log(label, { 2501 constructors: constructors, 2502 constructor: key, 2503 params: args 2504 }); 2505 } 2506 }; 2507 }; 2508 }); 2509 return adt; 2510 }; 2511 var Adt = { generate: generate$7 }; 2512 2513 Adt.generate([ 2514 { 2515 bothErrors: [ 2516 'error1', 2517 'error2' 2518 ] 2519 }, 2520 { 2521 firstError: [ 2522 'error1', 2523 'value2' 2524 ] 2525 }, 2526 { 2527 secondError: [ 2528 'value1', 2529 'error2' 2530 ] 2531 }, 2532 { 2533 bothValues: [ 2534 'value1', 2535 'value2' 2536 ] 2537 } 2538 ]); 2539 var partition$1 = function (results) { 2540 var errors = []; 2541 var values = []; 2542 each$1(results, function (result) { 2543 result.fold(function (err) { 2544 errors.push(err); 2545 }, function (value) { 2546 values.push(value); 2547 }); 2548 }); 2549 return { 2550 errors: errors, 2551 values: values 2552 }; 2553 }; 2554 2555 var exclude$1 = function (obj, fields) { 2556 var r = {}; 2557 each(obj, function (v, k) { 2558 if (!contains$2(fields, k)) { 2559 r[k] = v; 2560 } 2561 }); 2562 return r; 2563 }; 2564 2565 var wrap$2 = function (key, value) { 2566 var _a; 2567 return _a = {}, _a[key] = value, _a; 2568 }; 2569 var wrapAll$1 = function (keyvalues) { 2570 var r = {}; 2571 each$1(keyvalues, function (kv) { 2572 r[kv.key] = kv.value; 2573 }); 2574 return r; 2575 }; 2576 2577 var exclude = function (obj, fields) { 2578 return exclude$1(obj, fields); 2579 }; 2580 var wrap$1 = function (key, value) { 2581 return wrap$2(key, value); 2582 }; 2583 var wrapAll = function (keyvalues) { 2584 return wrapAll$1(keyvalues); 2585 }; 2586 var mergeValues = function (values, base) { 2587 return values.length === 0 ? Result.value(base) : Result.value(deepMerge(base, merge$1.apply(undefined, values))); 2588 }; 2589 var mergeErrors = function (errors) { 2590 return Result.error(flatten(errors)); 2591 }; 2592 var consolidate = function (objs, base) { 2593 var partitions = partition$1(objs); 2594 return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base); 2595 }; 2596 2597 var ensureIsRoot = function (isRoot) { 2598 return isFunction(isRoot) ? isRoot : never; 2599 }; 2600 var ancestor$2 = function (scope, transform, isRoot) { 2601 var element = scope.dom; 2602 var stop = ensureIsRoot(isRoot); 2603 while (element.parentNode) { 2604 element = element.parentNode; 2605 var el = SugarElement.fromDom(element); 2606 var transformed = transform(el); 2607 if (transformed.isSome()) { 2608 return transformed; 2609 } else if (stop(el)) { 2610 break; 2611 } 2612 } 2613 return Optional.none(); 2614 }; 2615 var closest$4 = function (scope, transform, isRoot) { 2616 var current = transform(scope); 2617 var stop = ensureIsRoot(isRoot); 2618 return current.orThunk(function () { 2619 return stop(scope) ? Optional.none() : ancestor$2(scope, transform, stop); 2620 }); 2621 }; 2622 2623 var isSource = function (component, simulatedEvent) { 2624 return eq(component.element, simulatedEvent.event.target); 2625 }; 2626 2627 var defaultEventHandler = { 2628 can: always, 2629 abort: never, 2630 run: noop 2631 }; 2632 var nu$9 = function (parts) { 2633 if (!hasNonNullableKey(parts, 'can') && !hasNonNullableKey(parts, 'abort') && !hasNonNullableKey(parts, 'run')) { 2634 throw new Error('EventHandler defined by: ' + JSON.stringify(parts, null, 2) + ' does not have can, abort, or run!'); 2635 } 2636 return __assign(__assign({}, defaultEventHandler), parts); 2637 }; 2638 var all$2 = function (handlers, f) { 2639 return function () { 2640 var args = []; 2641 for (var _i = 0; _i < arguments.length; _i++) { 2642 args[_i] = arguments[_i]; 2643 } 2644 return foldl(handlers, function (acc, handler) { 2645 return acc && f(handler).apply(undefined, args); 2646 }, true); 2647 }; 2648 }; 2649 var any = function (handlers, f) { 2650 return function () { 2651 var args = []; 2652 for (var _i = 0; _i < arguments.length; _i++) { 2653 args[_i] = arguments[_i]; 2654 } 2655 return foldl(handlers, function (acc, handler) { 2656 return acc || f(handler).apply(undefined, args); 2657 }, false); 2658 }; 2659 }; 2660 var read$2 = function (handler) { 2661 return isFunction(handler) ? { 2662 can: always, 2663 abort: never, 2664 run: handler 2665 } : handler; 2666 }; 2667 var fuse$1 = function (handlers) { 2668 var can = all$2(handlers, function (handler) { 2669 return handler.can; 2670 }); 2671 var abort = any(handlers, function (handler) { 2672 return handler.abort; 2673 }); 2674 var run = function () { 2675 var args = []; 2676 for (var _i = 0; _i < arguments.length; _i++) { 2677 args[_i] = arguments[_i]; 2678 } 2679 each$1(handlers, function (handler) { 2680 handler.run.apply(undefined, args); 2681 }); 2682 }; 2683 return { 2684 can: can, 2685 abort: abort, 2686 run: run 2687 }; 2688 }; 2689 2690 var constant = constant$1; 2691 var touchstart = constant('touchstart'); 2692 var touchmove = constant('touchmove'); 2693 var touchend = constant('touchend'); 2694 var touchcancel = constant('touchcancel'); 2695 var mousedown = constant('mousedown'); 2696 var mousemove = constant('mousemove'); 2697 var mouseout = constant('mouseout'); 2698 var mouseup = constant('mouseup'); 2699 var mouseover = constant('mouseover'); 2700 var focusin = constant('focusin'); 2701 var focusout = constant('focusout'); 2702 var keydown = constant('keydown'); 2703 var keyup = constant('keyup'); 2704 var input = constant('input'); 2705 var change = constant('change'); 2706 var click = constant('click'); 2707 var transitioncancel = constant('transitioncancel'); 2708 var transitionend = constant('transitionend'); 2709 var transitionstart = constant('transitionstart'); 2710 var selectstart = constant('selectstart'); 2711 2712 var prefixName = function (name) { 2713 return constant$1('alloy.' + name); 2714 }; 2715 var alloy = { tap: prefixName('tap') }; 2716 var focus$4 = prefixName('focus'); 2717 var postBlur = prefixName('blur.post'); 2718 var postPaste = prefixName('paste.post'); 2719 var receive = prefixName('receive'); 2720 var execute$5 = prefixName('execute'); 2721 var focusItem = prefixName('focus.item'); 2722 var tap = alloy.tap; 2723 var longpress = prefixName('longpress'); 2724 var sandboxClose = prefixName('sandbox.close'); 2725 var typeaheadCancel = prefixName('typeahead.cancel'); 2726 var systemInit = prefixName('system.init'); 2727 var documentTouchmove = prefixName('system.touchmove'); 2728 var documentTouchend = prefixName('system.touchend'); 2729 var windowScroll = prefixName('system.scroll'); 2730 var windowResize = prefixName('system.resize'); 2731 var attachedToDom = prefixName('system.attached'); 2732 var detachedFromDom = prefixName('system.detached'); 2733 var dismissRequested = prefixName('system.dismissRequested'); 2734 var repositionRequested = prefixName('system.repositionRequested'); 2735 var focusShifted = prefixName('focusmanager.shifted'); 2736 var slotVisibility = prefixName('slotcontainer.visibility'); 2737 var changeTab = prefixName('change.tab'); 2738 var dismissTab = prefixName('dismiss.tab'); 2739 var highlight$1 = prefixName('highlight'); 2740 var dehighlight$1 = prefixName('dehighlight'); 2741 2742 var emit = function (component, event) { 2743 dispatchWith(component, component.element, event, {}); 2744 }; 2745 var emitWith = function (component, event, properties) { 2746 dispatchWith(component, component.element, event, properties); 2747 }; 2748 var emitExecute = function (component) { 2749 emit(component, execute$5()); 2750 }; 2751 var dispatch = function (component, target, event) { 2752 dispatchWith(component, target, event, {}); 2753 }; 2754 var dispatchWith = function (component, target, event, properties) { 2755 var data = __assign({ target: target }, properties); 2756 component.getSystem().triggerEvent(event, target, data); 2757 }; 2758 var dispatchEvent = function (component, target, event, simulatedEvent) { 2759 component.getSystem().triggerEvent(event, target, simulatedEvent.event); 2760 }; 2761 2762 var derive$2 = function (configs) { 2763 return wrapAll(configs); 2764 }; 2765 var abort = function (name, predicate) { 2766 return { 2767 key: name, 2768 value: nu$9({ abort: predicate }) 2769 }; 2770 }; 2771 var can = function (name, predicate) { 2772 return { 2773 key: name, 2774 value: nu$9({ can: predicate }) 2775 }; 2776 }; 2777 var preventDefault = function (name) { 2778 return { 2779 key: name, 2780 value: nu$9({ 2781 run: function (component, simulatedEvent) { 2782 simulatedEvent.event.prevent(); 2783 } 2784 }) 2785 }; 2786 }; 2787 var run$1 = function (name, handler) { 2788 return { 2789 key: name, 2790 value: nu$9({ run: handler }) 2791 }; 2792 }; 2793 var runActionExtra = function (name, action, extra) { 2794 return { 2795 key: name, 2796 value: nu$9({ 2797 run: function (component, simulatedEvent) { 2798 action.apply(undefined, [ 2799 component, 2800 simulatedEvent 2801 ].concat(extra)); 2802 } 2803 }) 2804 }; 2805 }; 2806 var runOnName = function (name) { 2807 return function (handler) { 2808 return run$1(name, handler); 2809 }; 2810 }; 2811 var runOnSourceName = function (name) { 2812 return function (handler) { 2813 return { 2814 key: name, 2815 value: nu$9({ 2816 run: function (component, simulatedEvent) { 2817 if (isSource(component, simulatedEvent)) { 2818 handler(component, simulatedEvent); 2819 } 2820 } 2821 }) 2822 }; 2823 }; 2824 }; 2825 var redirectToUid = function (name, uid) { 2826 return run$1(name, function (component, simulatedEvent) { 2827 component.getSystem().getByUid(uid).each(function (redirectee) { 2828 dispatchEvent(redirectee, redirectee.element, name, simulatedEvent); 2829 }); 2830 }); 2831 }; 2832 var redirectToPart = function (name, detail, partName) { 2833 var uid = detail.partUids[partName]; 2834 return redirectToUid(name, uid); 2835 }; 2836 var runWithTarget = function (name, f) { 2837 return run$1(name, function (component, simulatedEvent) { 2838 var ev = simulatedEvent.event; 2839 var target = component.getSystem().getByDom(ev.target).getOrThunk(function () { 2840 var closest = closest$4(ev.target, function (el) { 2841 return component.getSystem().getByDom(el).toOptional(); 2842 }, never); 2843 return closest.getOr(component); 2844 }); 2845 f(component, target, simulatedEvent); 2846 }); 2847 }; 2848 var cutter = function (name) { 2849 return run$1(name, function (component, simulatedEvent) { 2850 simulatedEvent.cut(); 2851 }); 2852 }; 2853 var stopper = function (name) { 2854 return run$1(name, function (component, simulatedEvent) { 2855 simulatedEvent.stop(); 2856 }); 2857 }; 2858 var runOnSource = function (name, f) { 2859 return runOnSourceName(name)(f); 2860 }; 2861 var runOnAttached = runOnSourceName(attachedToDom()); 2862 var runOnDetached = runOnSourceName(detachedFromDom()); 2863 var runOnInit = runOnSourceName(systemInit()); 2864 var runOnExecute$1 = runOnName(execute$5()); 2865 2866 var fromHtml$1 = function (html, scope) { 2867 var doc = scope || document; 2868 var div = doc.createElement('div'); 2869 div.innerHTML = html; 2870 return children(SugarElement.fromDom(div)); 2871 }; 2872 2873 var get$7 = function (element) { 2874 return element.dom.innerHTML; 2875 }; 2876 var set$5 = function (element, content) { 2877 var owner = owner$4(element); 2878 var docDom = owner.dom; 2879 var fragment = SugarElement.fromDom(docDom.createDocumentFragment()); 2880 var contentElements = fromHtml$1(content, docDom); 2881 append$1(fragment, contentElements); 2882 empty(element); 2883 append$2(element, fragment); 2884 }; 2885 var getOuter = function (element) { 2886 var container = SugarElement.fromTag('div'); 2887 var clone = SugarElement.fromDom(element.dom.cloneNode(true)); 2888 append$2(container, clone); 2889 return get$7(container); 2890 }; 2891 2892 var clone$1 = function (original, isDeep) { 2893 return SugarElement.fromDom(original.dom.cloneNode(isDeep)); 2894 }; 2895 var shallow = function (original) { 2896 return clone$1(original, false); 2897 }; 2898 2899 var getHtml = function (element) { 2900 if (isShadowRoot(element)) { 2901 return '#shadow-root'; 2902 } else { 2903 var clone = shallow(element); 2904 return getOuter(clone); 2905 } 2906 }; 2907 2908 var element = function (elem) { 2909 return getHtml(elem); 2910 }; 2911 2912 var isRecursive = function (component, originator, target) { 2913 return eq(originator, component.element) && !eq(originator, target); 2914 }; 2915 var events$i = derive$2([can(focus$4(), function (component, simulatedEvent) { 2916 var event = simulatedEvent.event; 2917 var originator = event.originator; 2918 var target = event.target; 2919 if (isRecursive(component, originator, target)) { 2920 console.warn(focus$4() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$4() + ' event handlers'); 2921 return false; 2922 } else { 2923 return true; 2924 } 2925 })]); 2926 2927 var DefaultEvents = /*#__PURE__*/Object.freeze({ 2928 __proto__: null, 2929 events: events$i 2930 }); 2931 2932 var unique = 0; 2933 var generate$6 = function (prefix) { 2934 var date = new Date(); 2935 var time = date.getTime(); 2936 var random = Math.floor(Math.random() * 1000000000); 2937 unique++; 2938 return prefix + '_' + random + unique + String(time); 2939 }; 2940 2941 var prefix$1 = constant$1('alloy-id-'); 2942 var idAttr$1 = constant$1('data-alloy-id'); 2943 2944 var prefix = prefix$1(); 2945 var idAttr = idAttr$1(); 2946 var write = function (label, elem) { 2947 var id = generate$6(prefix + label); 2948 writeOnly(elem, id); 2949 return id; 2950 }; 2951 var writeOnly = function (elem, uid) { 2952 Object.defineProperty(elem.dom, idAttr, { 2953 value: uid, 2954 writable: true 2955 }); 2956 }; 2957 var read$1 = function (elem) { 2958 var id = isElement$2(elem) ? elem.dom[idAttr] : null; 2959 return Optional.from(id); 2960 }; 2961 var generate$5 = function (prefix) { 2962 return generate$6(prefix); 2963 }; 2964 2965 var make$8 = identity$1; 2966 2967 var NoContextApi = function (getComp) { 2968 var getMessage = function (event) { 2969 return 'The component must be in a context to execute: ' + event + (getComp ? '\n' + element(getComp().element) + ' is not in context.' : ''); 2970 }; 2971 var fail = function (event) { 2972 return function () { 2973 throw new Error(getMessage(event)); 2974 }; 2975 }; 2976 var warn = function (event) { 2977 return function () { 2978 console.warn(getMessage(event)); 2979 }; 2980 }; 2981 return { 2982 debugInfo: constant$1('fake'), 2983 triggerEvent: warn('triggerEvent'), 2984 triggerFocus: warn('triggerFocus'), 2985 triggerEscape: warn('triggerEscape'), 2986 broadcast: warn('broadcast'), 2987 broadcastOn: warn('broadcastOn'), 2988 broadcastEvent: warn('broadcastEvent'), 2989 build: fail('build'), 2990 addToWorld: fail('addToWorld'), 2991 removeFromWorld: fail('removeFromWorld'), 2992 addToGui: fail('addToGui'), 2993 removeFromGui: fail('removeFromGui'), 2994 getByUid: fail('getByUid'), 2995 getByDom: fail('getByDom'), 2996 isConnected: never 2997 }; 2998 }; 2999 var singleton$1 = NoContextApi(); 3000 3001 var markAsBehaviourApi = function (f, apiName, apiFunction) { 3002 var delegate = apiFunction.toString(); 3003 var endIndex = delegate.indexOf(')') + 1; 3004 var openBracketIndex = delegate.indexOf('('); 3005 var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); 3006 f.toFunctionAnnotation = function () { 3007 return { 3008 name: apiName, 3009 parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3))) 3010 }; 3011 }; 3012 return f; 3013 }; 3014 var cleanParameters = function (parameters) { 3015 return map$2(parameters, function (p) { 3016 return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p; 3017 }); 3018 }; 3019 var markAsExtraApi = function (f, extraName) { 3020 var delegate = f.toString(); 3021 var endIndex = delegate.indexOf(')') + 1; 3022 var openBracketIndex = delegate.indexOf('('); 3023 var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); 3024 f.toFunctionAnnotation = function () { 3025 return { 3026 name: extraName, 3027 parameters: cleanParameters(parameters) 3028 }; 3029 }; 3030 return f; 3031 }; 3032 var markAsSketchApi = function (f, apiFunction) { 3033 var delegate = apiFunction.toString(); 3034 var endIndex = delegate.indexOf(')') + 1; 3035 var openBracketIndex = delegate.indexOf('('); 3036 var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/); 3037 f.toFunctionAnnotation = function () { 3038 return { 3039 name: 'OVERRIDE', 3040 parameters: cleanParameters(parameters.slice(1)) 3041 }; 3042 }; 3043 return f; 3044 }; 3045 3046 var premadeTag = generate$6('alloy-premade'); 3047 var premade$1 = function (comp) { 3048 return wrap$1(premadeTag, comp); 3049 }; 3050 var getPremade = function (spec) { 3051 return get$e(spec, premadeTag); 3052 }; 3053 var makeApi = function (f) { 3054 return markAsSketchApi(function (component) { 3055 var rest = []; 3056 for (var _i = 1; _i < arguments.length; _i++) { 3057 rest[_i - 1] = arguments[_i]; 3058 } 3059 return f.apply(void 0, __spreadArray([ 3060 component.getApis(), 3061 component 3062 ], rest, false)); 3063 }, f); 3064 }; 3065 3066 var NoState = { 3067 init: function () { 3068 return nu$8({ readState: constant$1('No State required') }); 3069 } 3070 }; 3071 var nu$8 = function (spec) { 3072 return spec; 3073 }; 3074 3075 var generateFrom$1 = function (spec, all) { 3076 var schema = map$2(all, function (a) { 3077 return optionObjOf(a.name(), [ 3078 required$1('config'), 3079 defaulted('state', NoState) 3080 ]); 3081 }); 3082 var validated = asRaw('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) { 3083 throw new Error(formatError(errInfo) + '\nComplete spec:\n' + JSON.stringify(spec, null, 2)); 3084 }, identity$1); 3085 return { 3086 list: all, 3087 data: map$1(validated, function (optBlobThunk) { 3088 var output = optBlobThunk.map(function (blob) { 3089 return { 3090 config: blob.config, 3091 state: blob.state.init(blob.config) 3092 }; 3093 }); 3094 return constant$1(output); 3095 }) 3096 }; 3097 }; 3098 var getBehaviours$3 = function (bData) { 3099 return bData.list; 3100 }; 3101 var getData$2 = function (bData) { 3102 return bData.data; 3103 }; 3104 3105 var byInnerKey = function (data, tuple) { 3106 var r = {}; 3107 each(data, function (detail, key) { 3108 each(detail, function (value, indexKey) { 3109 var chain = get$e(r, indexKey).getOr([]); 3110 r[indexKey] = chain.concat([tuple(key, value)]); 3111 }); 3112 }); 3113 return r; 3114 }; 3115 3116 var nu$7 = function (s) { 3117 return { 3118 classes: isUndefined(s.classes) ? [] : s.classes, 3119 attributes: isUndefined(s.attributes) ? {} : s.attributes, 3120 styles: isUndefined(s.styles) ? {} : s.styles 3121 }; 3122 }; 3123 var merge = function (defnA, mod) { 3124 return __assign(__assign({}, defnA), { 3125 attributes: __assign(__assign({}, defnA.attributes), mod.attributes), 3126 styles: __assign(__assign({}, defnA.styles), mod.styles), 3127 classes: defnA.classes.concat(mod.classes) 3128 }); 3129 }; 3130 3131 var combine$2 = function (info, baseMod, behaviours, base) { 3132 var modsByBehaviour = __assign({}, baseMod); 3133 each$1(behaviours, function (behaviour) { 3134 modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base); 3135 }); 3136 var byAspect = byInnerKey(modsByBehaviour, function (name, modification) { 3137 return { 3138 name: name, 3139 modification: modification 3140 }; 3141 }); 3142 var combineObjects = function (objects) { 3143 return foldr(objects, function (b, a) { 3144 return __assign(__assign({}, a.modification), b); 3145 }, {}); 3146 }; 3147 var combinedClasses = foldr(byAspect.classes, function (b, a) { 3148 return a.modification.concat(b); 3149 }, []); 3150 var combinedAttributes = combineObjects(byAspect.attributes); 3151 var combinedStyles = combineObjects(byAspect.styles); 3152 return nu$7({ 3153 classes: combinedClasses, 3154 attributes: combinedAttributes, 3155 styles: combinedStyles 3156 }); 3157 }; 3158 3159 var sortKeys = function (label, keyName, array, order) { 3160 try { 3161 var sorted = sort(array, function (a, b) { 3162 var aKey = a[keyName]; 3163 var bKey = b[keyName]; 3164 var aIndex = order.indexOf(aKey); 3165 var bIndex = order.indexOf(bKey); 3166 if (aIndex === -1) { 3167 throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2)); 3168 } 3169 if (bIndex === -1) { 3170 throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + JSON.stringify(order, null, 2)); 3171 } 3172 if (aIndex < bIndex) { 3173 return -1; 3174 } else if (bIndex < aIndex) { 3175 return 1; 3176 } else { 3177 return 0; 3178 } 3179 }); 3180 return Result.value(sorted); 3181 } catch (err) { 3182 return Result.error([err]); 3183 } 3184 }; 3185 3186 var uncurried = function (handler, purpose) { 3187 return { 3188 handler: handler, 3189 purpose: purpose 3190 }; 3191 }; 3192 var curried = function (handler, purpose) { 3193 return { 3194 cHandler: handler, 3195 purpose: purpose 3196 }; 3197 }; 3198 var curryArgs = function (descHandler, extraArgs) { 3199 return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose); 3200 }; 3201 var getCurried = function (descHandler) { 3202 return descHandler.cHandler; 3203 }; 3204 3205 var behaviourTuple = function (name, handler) { 3206 return { 3207 name: name, 3208 handler: handler 3209 }; 3210 }; 3211 var nameToHandlers = function (behaviours, info) { 3212 var r = {}; 3213 each$1(behaviours, function (behaviour) { 3214 r[behaviour.name()] = behaviour.handlers(info); 3215 }); 3216 return r; 3217 }; 3218 var groupByEvents = function (info, behaviours, base) { 3219 var behaviourEvents = __assign(__assign({}, base), nameToHandlers(behaviours, info)); 3220 return byInnerKey(behaviourEvents, behaviourTuple); 3221 }; 3222 var combine$1 = function (info, eventOrder, behaviours, base) { 3223 var byEventName = groupByEvents(info, behaviours, base); 3224 return combineGroups(byEventName, eventOrder); 3225 }; 3226 var assemble = function (rawHandler) { 3227 var handler = read$2(rawHandler); 3228 return function (component, simulatedEvent) { 3229 var rest = []; 3230 for (var _i = 2; _i < arguments.length; _i++) { 3231 rest[_i - 2] = arguments[_i]; 3232 } 3233 var args = [ 3234 component, 3235 simulatedEvent 3236 ].concat(rest); 3237 if (handler.abort.apply(undefined, args)) { 3238 simulatedEvent.stop(); 3239 } else if (handler.can.apply(undefined, args)) { 3240 handler.run.apply(undefined, args); 3241 } 3242 }; 3243 }; 3244 var missingOrderError = function (eventName, tuples) { 3245 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) { 3246 return c.name; 3247 }), null, 2)]); 3248 }; 3249 var fuse = function (tuples, eventOrder, eventName) { 3250 var order = eventOrder[eventName]; 3251 if (!order) { 3252 return missingOrderError(eventName, tuples); 3253 } else { 3254 return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) { 3255 var handlers = map$2(sortedTuples, function (tuple) { 3256 return tuple.handler; 3257 }); 3258 return fuse$1(handlers); 3259 }); 3260 } 3261 }; 3262 var combineGroups = function (byEventName, eventOrder) { 3263 var r = mapToArray(byEventName, function (tuples, eventName) { 3264 var combined = tuples.length === 1 ? Result.value(tuples[0].handler) : fuse(tuples, eventOrder, eventName); 3265 return combined.map(function (handler) { 3266 var assembled = assemble(handler); 3267 var purpose = tuples.length > 1 ? filter$2(eventOrder[eventName], function (o) { 3268 return exists(tuples, function (t) { 3269 return t.name === o; 3270 }); 3271 }).join(' > ') : tuples[0].name; 3272 return wrap$1(eventName, uncurried(assembled, purpose)); 3273 }); 3274 }); 3275 return consolidate(r, {}); 3276 }; 3277 3278 var _a$2; 3279 var baseBehaviour = 'alloy.base.behaviour'; 3280 var schema$z = objOf([ 3281 field$1('dom', 'dom', required$2(), objOf([ 3282 required$1('tag'), 3283 defaulted('styles', {}), 3284 defaulted('classes', []), 3285 defaulted('attributes', {}), 3286 option('value'), 3287 option('innerHtml') 3288 ])), 3289 required$1('components'), 3290 required$1('uid'), 3291 defaulted('events', {}), 3292 defaulted('apis', {}), 3293 field$1('eventOrder', 'eventOrder', mergeWith((_a$2 = {}, _a$2[execute$5()] = [ 3294 'disabling', 3295 baseBehaviour, 3296 'toggling', 3297 'typeaheadevents' 3298 ], _a$2[focus$4()] = [ 3299 baseBehaviour, 3300 'focusing', 3301 'keying' 3302 ], _a$2[systemInit()] = [ 3303 baseBehaviour, 3304 'disabling', 3305 'toggling', 3306 'representing' 3307 ], _a$2[input()] = [ 3308 baseBehaviour, 3309 'representing', 3310 'streaming', 3311 'invalidating' 3312 ], _a$2[detachedFromDom()] = [ 3313 baseBehaviour, 3314 'representing', 3315 'item-events', 3316 'tooltipping' 3317 ], _a$2[mousedown()] = [ 3318 'focusing', 3319 baseBehaviour, 3320 'item-type-events' 3321 ], _a$2[touchstart()] = [ 3322 'focusing', 3323 baseBehaviour, 3324 'item-type-events' 3325 ], _a$2[mouseover()] = [ 3326 'item-type-events', 3327 'tooltipping' 3328 ], _a$2[receive()] = [ 3329 'receiving', 3330 'reflecting', 3331 'tooltipping' 3332 ], _a$2)), anyValue()), 3333 option('domModification') 3334 ]); 3335 var toInfo = function (spec) { 3336 return asRaw('custom.definition', schema$z, spec); 3337 }; 3338 var toDefinition = function (detail) { 3339 return __assign(__assign({}, detail.dom), { 3340 uid: detail.uid, 3341 domChildren: map$2(detail.components, function (comp) { 3342 return comp.element; 3343 }) 3344 }); 3345 }; 3346 var toModification = function (detail) { 3347 return detail.domModification.fold(function () { 3348 return nu$7({}); 3349 }, nu$7); 3350 }; 3351 var toEvents = function (info) { 3352 return info.events; 3353 }; 3354 3355 var read = function (element, attr) { 3356 var value = get$d(element, attr); 3357 return value === undefined || value === '' ? [] : value.split(' '); 3358 }; 3359 var add$4 = function (element, attr, id) { 3360 var old = read(element, attr); 3361 var nu = old.concat([id]); 3362 set$8(element, attr, nu.join(' ')); 3363 return true; 3364 }; 3365 var remove$4 = function (element, attr, id) { 3366 var nu = filter$2(read(element, attr), function (v) { 3367 return v !== id; 3368 }); 3369 if (nu.length > 0) { 3370 set$8(element, attr, nu.join(' ')); 3371 } else { 3372 remove$7(element, attr); 3373 } 3374 return false; 3375 }; 3376 3377 var supports = function (element) { 3378 return element.dom.classList !== undefined; 3379 }; 3380 var get$6 = function (element) { 3381 return read(element, 'class'); 3382 }; 3383 var add$3 = function (element, clazz) { 3384 return add$4(element, 'class', clazz); 3385 }; 3386 var remove$3 = function (element, clazz) { 3387 return remove$4(element, 'class', clazz); 3388 }; 3389 3390 var add$2 = function (element, clazz) { 3391 if (supports(element)) { 3392 element.dom.classList.add(clazz); 3393 } else { 3394 add$3(element, clazz); 3395 } 3396 }; 3397 var cleanClass = function (element) { 3398 var classList = supports(element) ? element.dom.classList : get$6(element); 3399 if (classList.length === 0) { 3400 remove$7(element, 'class'); 3401 } 3402 }; 3403 var remove$2 = function (element, clazz) { 3404 if (supports(element)) { 3405 var classList = element.dom.classList; 3406 classList.remove(clazz); 3407 } else { 3408 remove$3(element, clazz); 3409 } 3410 cleanClass(element); 3411 }; 3412 var has = function (element, clazz) { 3413 return supports(element) && element.dom.classList.contains(clazz); 3414 }; 3415 3416 var add$1 = function (element, classes) { 3417 each$1(classes, function (x) { 3418 add$2(element, x); 3419 }); 3420 }; 3421 var remove$1 = function (element, classes) { 3422 each$1(classes, function (x) { 3423 remove$2(element, x); 3424 }); 3425 }; 3426 var hasAll = function (element, classes) { 3427 return forall(classes, function (clazz) { 3428 return has(element, clazz); 3429 }); 3430 }; 3431 3432 var get$5 = function (element) { 3433 return element.dom.value; 3434 }; 3435 var set$4 = function (element, value) { 3436 if (value === undefined) { 3437 throw new Error('Value.set was undefined'); 3438 } 3439 element.dom.value = value; 3440 }; 3441 3442 var renderToDom = function (definition) { 3443 var subject = SugarElement.fromTag(definition.tag); 3444 setAll$1(subject, definition.attributes); 3445 add$1(subject, definition.classes); 3446 setAll(subject, definition.styles); 3447 definition.innerHtml.each(function (html) { 3448 return set$5(subject, html); 3449 }); 3450 var children = definition.domChildren; 3451 append$1(subject, children); 3452 definition.value.each(function (value) { 3453 set$4(subject, value); 3454 }); 3455 if (!definition.uid) { 3456 debugger; 3457 } 3458 writeOnly(subject, definition.uid); 3459 return subject; 3460 }; 3461 3462 var getBehaviours$2 = function (spec) { 3463 var behaviours = get$e(spec, 'behaviours').getOr({}); 3464 return bind$3(keys(behaviours), function (name) { 3465 var behaviour = behaviours[name]; 3466 return isNonNullable(behaviour) ? [behaviour.me] : []; 3467 }); 3468 }; 3469 var generateFrom = function (spec, all) { 3470 return generateFrom$1(spec, all); 3471 }; 3472 var generate$4 = function (spec) { 3473 var all = getBehaviours$2(spec); 3474 return generateFrom(spec, all); 3475 }; 3476 3477 var getDomDefinition = function (info, bList, bData) { 3478 var definition = toDefinition(info); 3479 var infoModification = toModification(info); 3480 var baseModification = { 'alloy.base.modification': infoModification }; 3481 var modification = bList.length > 0 ? combine$2(bData, baseModification, bList, definition) : infoModification; 3482 return merge(definition, modification); 3483 }; 3484 var getEvents = function (info, bList, bData) { 3485 var baseEvents = { 'alloy.base.behaviour': toEvents(info) }; 3486 return combine$1(bData, info.eventOrder, bList, baseEvents).getOrDie(); 3487 }; 3488 var build$2 = function (spec) { 3489 var getMe = function () { 3490 return me; 3491 }; 3492 var systemApi = Cell(singleton$1); 3493 var info = getOrDie(toInfo(spec)); 3494 var bBlob = generate$4(spec); 3495 var bList = getBehaviours$3(bBlob); 3496 var bData = getData$2(bBlob); 3497 var modDefinition = getDomDefinition(info, bList, bData); 3498 var item = renderToDom(modDefinition); 3499 var events = getEvents(info, bList, bData); 3500 var subcomponents = Cell(info.components); 3501 var connect = function (newApi) { 3502 systemApi.set(newApi); 3503 }; 3504 var disconnect = function () { 3505 systemApi.set(NoContextApi(getMe)); 3506 }; 3507 var syncComponents = function () { 3508 var children$1 = children(item); 3509 var subs = bind$3(children$1, function (child) { 3510 return systemApi.get().getByDom(child).fold(function () { 3511 return []; 3512 }, pure$2); 3513 }); 3514 subcomponents.set(subs); 3515 }; 3516 var config = function (behaviour) { 3517 var b = bData; 3518 var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () { 3519 throw new Error('Could not find ' + behaviour.name() + ' in ' + JSON.stringify(spec, null, 2)); 3520 }; 3521 return f(); 3522 }; 3523 var hasConfigured = function (behaviour) { 3524 return isFunction(bData[behaviour.name()]); 3525 }; 3526 var getApis = function () { 3527 return info.apis; 3528 }; 3529 var readState = function (behaviourName) { 3530 return bData[behaviourName]().map(function (b) { 3531 return b.state.readState(); 3532 }).getOr('not enabled'); 3533 }; 3534 var me = { 3535 uid: spec.uid, 3536 getSystem: systemApi.get, 3537 config: config, 3538 hasConfigured: hasConfigured, 3539 spec: spec, 3540 readState: readState, 3541 getApis: getApis, 3542 connect: connect, 3543 disconnect: disconnect, 3544 element: item, 3545 syncComponents: syncComponents, 3546 components: subcomponents.get, 3547 events: events 3548 }; 3549 return me; 3550 }; 3551 3552 var buildSubcomponents = function (spec) { 3553 var components = get$e(spec, 'components').getOr([]); 3554 return map$2(components, build$1); 3555 }; 3556 var buildFromSpec = function (userSpec) { 3557 var _a = make$8(userSpec), specEvents = _a.events, spec = __rest(_a, ['events']); 3558 var components = buildSubcomponents(spec); 3559 var completeSpec = __assign(__assign({}, spec), { 3560 events: __assign(__assign({}, DefaultEvents), specEvents), 3561 components: components 3562 }); 3563 return Result.value(build$2(completeSpec)); 3564 }; 3565 var text = function (textContent) { 3566 var element = SugarElement.fromText(textContent); 3567 return external$2({ element: element }); 3568 }; 3569 var external$2 = function (spec) { 3570 var extSpec = asRawOrDie$1('external.component', objOfOnly([ 3571 required$1('element'), 3572 option('uid') 3573 ]), spec); 3574 var systemApi = Cell(NoContextApi()); 3575 var connect = function (newApi) { 3576 systemApi.set(newApi); 3577 }; 3578 var disconnect = function () { 3579 systemApi.set(NoContextApi(function () { 3580 return me; 3581 })); 3582 }; 3583 var uid = extSpec.uid.getOrThunk(function () { 3584 return generate$5('external'); 3585 }); 3586 writeOnly(extSpec.element, uid); 3587 var me = { 3588 uid: uid, 3589 getSystem: systemApi.get, 3590 config: Optional.none, 3591 hasConfigured: never, 3592 connect: connect, 3593 disconnect: disconnect, 3594 getApis: function () { 3595 return {}; 3596 }, 3597 element: extSpec.element, 3598 spec: spec, 3599 readState: constant$1('No state'), 3600 syncComponents: noop, 3601 components: constant$1([]), 3602 events: {} 3603 }; 3604 return premade$1(me); 3605 }; 3606 var uids = generate$5; 3607 var isSketchSpec$1 = function (spec) { 3608 return has$2(spec, 'uid'); 3609 }; 3610 var build$1 = function (spec) { 3611 return getPremade(spec).getOrThunk(function () { 3612 var userSpecWithUid = isSketchSpec$1(spec) ? spec : __assign({ uid: uids('') }, spec); 3613 return buildFromSpec(userSpecWithUid).getOrDie(); 3614 }); 3615 }; 3616 var premade = premade$1; 3617 3618 function ClosestOrAncestor (is, ancestor, scope, a, isRoot) { 3619 if (is(scope, a)) { 3620 return Optional.some(scope); 3621 } else if (isFunction(isRoot) && isRoot(scope)) { 3622 return Optional.none(); 3623 } else { 3624 return ancestor(scope, a, isRoot); 3625 } 3626 } 3627 3628 var ancestor$1 = function (scope, predicate, isRoot) { 3629 var element = scope.dom; 3630 var stop = isFunction(isRoot) ? isRoot : never; 3631 while (element.parentNode) { 3632 element = element.parentNode; 3633 var el = SugarElement.fromDom(element); 3634 if (predicate(el)) { 3635 return Optional.some(el); 3636 } else if (stop(el)) { 3637 break; 3638 } 3639 } 3640 return Optional.none(); 3641 }; 3642 var closest$3 = function (scope, predicate, isRoot) { 3643 var is = function (s, test) { 3644 return test(s); 3645 }; 3646 return ClosestOrAncestor(is, ancestor$1, scope, predicate, isRoot); 3647 }; 3648 var child$1 = function (scope, predicate) { 3649 var pred = function (node) { 3650 return predicate(SugarElement.fromDom(node)); 3651 }; 3652 var result = find$5(scope.dom.childNodes, pred); 3653 return result.map(SugarElement.fromDom); 3654 }; 3655 var descendant$1 = function (scope, predicate) { 3656 var descend = function (node) { 3657 for (var i = 0; i < node.childNodes.length; i++) { 3658 var child_1 = SugarElement.fromDom(node.childNodes[i]); 3659 if (predicate(child_1)) { 3660 return Optional.some(child_1); 3661 } 3662 var res = descend(node.childNodes[i]); 3663 if (res.isSome()) { 3664 return res; 3665 } 3666 } 3667 return Optional.none(); 3668 }; 3669 return descend(scope.dom); 3670 }; 3671 3672 var closest$2 = function (scope, predicate, isRoot) { 3673 return closest$3(scope, predicate, isRoot).isSome(); 3674 }; 3675 3676 var ancestor = function (scope, selector, isRoot) { 3677 return ancestor$1(scope, function (e) { 3678 return is(e, selector); 3679 }, isRoot); 3680 }; 3681 var child = function (scope, selector) { 3682 return child$1(scope, function (e) { 3683 return is(e, selector); 3684 }); 3685 }; 3686 var descendant = function (scope, selector) { 3687 return one(selector, scope); 3688 }; 3689 var closest$1 = function (scope, selector, isRoot) { 3690 var is$1 = function (element, selector) { 3691 return is(element, selector); 3692 }; 3693 return ClosestOrAncestor(is$1, ancestor, scope, selector, isRoot); 3694 }; 3695 3696 var find$1 = function (queryElem) { 3697 var dependent = closest$3(queryElem, function (elem) { 3698 if (!isElement$2(elem)) { 3699 return false; 3700 } 3701 var id = get$d(elem, 'id'); 3702 return id !== undefined && id.indexOf('aria-owns') > -1; 3703 }); 3704 return dependent.bind(function (dep) { 3705 var id = get$d(dep, 'id'); 3706 var dos = getRootNode(dep); 3707 return descendant(dos, '[aria-owns="' + id + '"]'); 3708 }); 3709 }; 3710 var manager = function () { 3711 var ariaId = generate$6('aria-owns'); 3712 var link = function (elem) { 3713 set$8(elem, 'aria-owns', ariaId); 3714 }; 3715 var unlink = function (elem) { 3716 remove$7(elem, 'aria-owns'); 3717 }; 3718 return { 3719 id: ariaId, 3720 link: link, 3721 unlink: unlink 3722 }; 3723 }; 3724 3725 var isAriaPartOf = function (component, queryElem) { 3726 return find$1(queryElem).exists(function (owner) { 3727 return isPartOf$1(component, owner); 3728 }); 3729 }; 3730 var isPartOf$1 = function (component, queryElem) { 3731 return closest$2(queryElem, function (el) { 3732 return eq(el, component.element); 3733 }, never) || isAriaPartOf(component, queryElem); 3734 }; 3735 3736 var unknown = 'unknown'; 3737 var EventConfiguration; 3738 (function (EventConfiguration) { 3739 EventConfiguration[EventConfiguration['STOP'] = 0] = 'STOP'; 3740 EventConfiguration[EventConfiguration['NORMAL'] = 1] = 'NORMAL'; 3741 EventConfiguration[EventConfiguration['LOGGING'] = 2] = 'LOGGING'; 3742 }(EventConfiguration || (EventConfiguration = {}))); 3743 var eventConfig = Cell({}); 3744 var makeEventLogger = function (eventName, initialTarget) { 3745 var sequence = []; 3746 var startTime = new Date().getTime(); 3747 return { 3748 logEventCut: function (_name, target, purpose) { 3749 sequence.push({ 3750 outcome: 'cut', 3751 target: target, 3752 purpose: purpose 3753 }); 3754 }, 3755 logEventStopped: function (_name, target, purpose) { 3756 sequence.push({ 3757 outcome: 'stopped', 3758 target: target, 3759 purpose: purpose 3760 }); 3761 }, 3762 logNoParent: function (_name, target, purpose) { 3763 sequence.push({ 3764 outcome: 'no-parent', 3765 target: target, 3766 purpose: purpose 3767 }); 3768 }, 3769 logEventNoHandlers: function (_name, target) { 3770 sequence.push({ 3771 outcome: 'no-handlers-left', 3772 target: target 3773 }); 3774 }, 3775 logEventResponse: function (_name, target, purpose) { 3776 sequence.push({ 3777 outcome: 'response', 3778 purpose: purpose, 3779 target: target 3780 }); 3781 }, 3782 write: function () { 3783 var finishTime = new Date().getTime(); 3784 if (contains$2([ 3785 'mousemove', 3786 'mouseover', 3787 'mouseout', 3788 systemInit() 3789 ], eventName)) { 3790 return; 3791 } 3792 console.log(eventName, { 3793 event: eventName, 3794 time: finishTime - startTime, 3795 target: initialTarget.dom, 3796 sequence: map$2(sequence, function (s) { 3797 if (!contains$2([ 3798 'cut', 3799 'stopped', 3800 'response' 3801 ], s.outcome)) { 3802 return s.outcome; 3803 } else { 3804 return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')'; 3805 } 3806 }) 3807 }); 3808 } 3809 }; 3810 }; 3811 var processEvent = function (eventName, initialTarget, f) { 3812 var status = get$e(eventConfig.get(), eventName).orThunk(function () { 3813 var patterns = keys(eventConfig.get()); 3814 return findMap(patterns, function (p) { 3815 return eventName.indexOf(p) > -1 ? Optional.some(eventConfig.get()[p]) : Optional.none(); 3816 }); 3817 }).getOr(EventConfiguration.NORMAL); 3818 switch (status) { 3819 case EventConfiguration.NORMAL: 3820 return f(noLogger()); 3821 case EventConfiguration.LOGGING: { 3822 var logger = makeEventLogger(eventName, initialTarget); 3823 var output = f(logger); 3824 logger.write(); 3825 return output; 3826 } 3827 case EventConfiguration.STOP: 3828 return true; 3829 } 3830 }; 3831 var path = [ 3832 'alloy/data/Fields', 3833 'alloy/debugging/Debugging' 3834 ]; 3835 var getTrace = function () { 3836 var err = new Error(); 3837 if (err.stack !== undefined) { 3838 var lines = err.stack.split('\n'); 3839 return find$5(lines, function (line) { 3840 return line.indexOf('alloy') > 0 && !exists(path, function (p) { 3841 return line.indexOf(p) > -1; 3842 }); 3843 }).getOr(unknown); 3844 } else { 3845 return unknown; 3846 } 3847 }; 3848 var ignoreEvent = { 3849 logEventCut: noop, 3850 logEventStopped: noop, 3851 logNoParent: noop, 3852 logEventNoHandlers: noop, 3853 logEventResponse: noop, 3854 write: noop 3855 }; 3856 var monitorEvent = function (eventName, initialTarget, f) { 3857 return processEvent(eventName, initialTarget, f); 3858 }; 3859 var noLogger = constant$1(ignoreEvent); 3860 3861 var menuFields = constant$1([ 3862 required$1('menu'), 3863 required$1('selectedMenu') 3864 ]); 3865 var itemFields = constant$1([ 3866 required$1('item'), 3867 required$1('selectedItem') 3868 ]); 3869 constant$1(objOf(itemFields().concat(menuFields()))); 3870 var itemSchema$3 = constant$1(objOf(itemFields())); 3871 3872 var _initSize = requiredObjOf('initSize', [ 3873 required$1('numColumns'), 3874 required$1('numRows') 3875 ]); 3876 var itemMarkers = function () { 3877 return requiredOf('markers', itemSchema$3()); 3878 }; 3879 var tieredMenuMarkers = function () { 3880 return requiredObjOf('markers', [required$1('backgroundMenu')].concat(menuFields()).concat(itemFields())); 3881 }; 3882 var markers$1 = function (required) { 3883 return requiredObjOf('markers', map$2(required, required$1)); 3884 }; 3885 var onPresenceHandler = function (label, fieldName, presence) { 3886 getTrace(); 3887 return field$1(fieldName, fieldName, presence, valueOf(function (f) { 3888 return Result.value(function () { 3889 var args = []; 3890 for (var _i = 0; _i < arguments.length; _i++) { 3891 args[_i] = arguments[_i]; 3892 } 3893 return f.apply(undefined, args); 3894 }); 3895 })); 3896 }; 3897 var onHandler = function (fieldName) { 3898 return onPresenceHandler('onHandler', fieldName, defaulted$1(noop)); 3899 }; 3900 var onKeyboardHandler = function (fieldName) { 3901 return onPresenceHandler('onKeyboardHandler', fieldName, defaulted$1(Optional.none)); 3902 }; 3903 var onStrictHandler = function (fieldName) { 3904 return onPresenceHandler('onHandler', fieldName, required$2()); 3905 }; 3906 var onStrictKeyboardHandler = function (fieldName) { 3907 return onPresenceHandler('onKeyboardHandler', fieldName, required$2()); 3908 }; 3909 var output$1 = function (name, value) { 3910 return customField(name, constant$1(value)); 3911 }; 3912 var snapshot = function (name) { 3913 return customField(name, identity$1); 3914 }; 3915 var initSize = constant$1(_initSize); 3916 3917 var nu$6 = function (x, y, bubble, direction, placement, boundsRestriction, labelPrefix, alwaysFit) { 3918 if (alwaysFit === void 0) { 3919 alwaysFit = false; 3920 } 3921 return { 3922 x: x, 3923 y: y, 3924 bubble: bubble, 3925 direction: direction, 3926 placement: placement, 3927 restriction: boundsRestriction, 3928 label: labelPrefix + '-' + placement, 3929 alwaysFit: alwaysFit 3930 }; 3931 }; 3932 3933 var adt$a = Adt.generate([ 3934 { southeast: [] }, 3935 { southwest: [] }, 3936 { northeast: [] }, 3937 { northwest: [] }, 3938 { south: [] }, 3939 { north: [] }, 3940 { east: [] }, 3941 { west: [] } 3942 ]); 3943 var cata$2 = function (subject, southeast, southwest, northeast, northwest, south, north, east, west) { 3944 return subject.fold(southeast, southwest, northeast, northwest, south, north, east, west); 3945 }; 3946 var cataVertical = function (subject, south, middle, north) { 3947 return subject.fold(south, south, north, north, south, north, middle, middle); 3948 }; 3949 var cataHorizontal = function (subject, east, middle, west) { 3950 return subject.fold(east, west, east, west, middle, middle, east, west); 3951 }; 3952 var southeast$3 = adt$a.southeast; 3953 var southwest$3 = adt$a.southwest; 3954 var northeast$3 = adt$a.northeast; 3955 var northwest$3 = adt$a.northwest; 3956 var south$3 = adt$a.south; 3957 var north$3 = adt$a.north; 3958 var east$3 = adt$a.east; 3959 var west$3 = adt$a.west; 3960 3961 var cycleBy = function (value, delta, min, max) { 3962 var r = value + delta; 3963 if (r > max) { 3964 return min; 3965 } else if (r < min) { 3966 return max; 3967 } else { 3968 return r; 3969 } 3970 }; 3971 var clamp$1 = function (value, min, max) { 3972 return Math.min(Math.max(value, min), max); 3973 }; 3974 3975 var getRestriction = function (anchor, restriction) { 3976 switch (restriction) { 3977 case 1: 3978 return anchor.x; 3979 case 0: 3980 return anchor.x + anchor.width; 3981 case 2: 3982 return anchor.y; 3983 case 3: 3984 return anchor.y + anchor.height; 3985 } 3986 }; 3987 var boundsRestriction = function (anchor, restrictions) { 3988 return mapToObject([ 3989 'left', 3990 'right', 3991 'top', 3992 'bottom' 3993 ], function (dir) { 3994 return get$e(restrictions, dir).map(function (restriction) { 3995 return getRestriction(anchor, restriction); 3996 }); 3997 }); 3998 }; 3999 var adjustBounds = function (bounds$1, restriction, bubbleOffset) { 4000 var applyRestriction = function (dir, current) { 4001 return restriction[dir].map(function (pos) { 4002 var isVerticalAxis = dir === 'top' || dir === 'bottom'; 4003 var offset = isVerticalAxis ? bubbleOffset.top : bubbleOffset.left; 4004 var comparator = dir === 'left' || dir === 'top' ? Math.max : Math.min; 4005 var newPos = comparator(pos, current) + offset; 4006 return isVerticalAxis ? clamp$1(newPos, bounds$1.y, bounds$1.bottom) : clamp$1(newPos, bounds$1.x, bounds$1.right); 4007 }).getOr(current); 4008 }; 4009 var adjustedLeft = applyRestriction('left', bounds$1.x); 4010 var adjustedTop = applyRestriction('top', bounds$1.y); 4011 var adjustedRight = applyRestriction('right', bounds$1.right); 4012 var adjustedBottom = applyRestriction('bottom', bounds$1.bottom); 4013 return bounds(adjustedLeft, adjustedTop, adjustedRight - adjustedLeft, adjustedBottom - adjustedTop); 4014 }; 4015 4016 var labelPrefix$2 = 'layout'; 4017 var eastX$1 = function (anchor) { 4018 return anchor.x; 4019 }; 4020 var middleX$1 = function (anchor, element) { 4021 return anchor.x + anchor.width / 2 - element.width / 2; 4022 }; 4023 var westX$1 = function (anchor, element) { 4024 return anchor.x + anchor.width - element.width; 4025 }; 4026 var northY$2 = function (anchor, element) { 4027 return anchor.y - element.height; 4028 }; 4029 var southY$2 = function (anchor) { 4030 return anchor.y + anchor.height; 4031 }; 4032 var centreY$1 = function (anchor, element) { 4033 return anchor.y + anchor.height / 2 - element.height / 2; 4034 }; 4035 var eastEdgeX$1 = function (anchor) { 4036 return anchor.x + anchor.width; 4037 }; 4038 var westEdgeX$1 = function (anchor, element) { 4039 return anchor.x - element.width; 4040 }; 4041 var southeast$2 = function (anchor, element, bubbles) { 4042 return nu$6(eastX$1(anchor), southY$2(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, { 4043 left: 1, 4044 top: 3 4045 }), labelPrefix$2); 4046 }; 4047 var southwest$2 = function (anchor, element, bubbles) { 4048 return nu$6(westX$1(anchor, element), southY$2(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, { 4049 right: 0, 4050 top: 3 4051 }), labelPrefix$2); 4052 }; 4053 var northeast$2 = function (anchor, element, bubbles) { 4054 return nu$6(eastX$1(anchor), northY$2(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, { 4055 left: 1, 4056 bottom: 2 4057 }), labelPrefix$2); 4058 }; 4059 var northwest$2 = function (anchor, element, bubbles) { 4060 return nu$6(westX$1(anchor, element), northY$2(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, { 4061 right: 0, 4062 bottom: 2 4063 }), labelPrefix$2); 4064 }; 4065 var north$2 = function (anchor, element, bubbles) { 4066 return nu$6(middleX$1(anchor, element), northY$2(anchor, element), bubbles.north(), north$3(), 'north', boundsRestriction(anchor, { bottom: 2 }), labelPrefix$2); 4067 }; 4068 var south$2 = function (anchor, element, bubbles) { 4069 return nu$6(middleX$1(anchor, element), southY$2(anchor), bubbles.south(), south$3(), 'south', boundsRestriction(anchor, { top: 3 }), labelPrefix$2); 4070 }; 4071 var east$2 = function (anchor, element, bubbles) { 4072 return nu$6(eastEdgeX$1(anchor), centreY$1(anchor, element), bubbles.east(), east$3(), 'east', boundsRestriction(anchor, { left: 0 }), labelPrefix$2); 4073 }; 4074 var west$2 = function (anchor, element, bubbles) { 4075 return nu$6(westEdgeX$1(anchor, element), centreY$1(anchor, element), bubbles.west(), west$3(), 'west', boundsRestriction(anchor, { right: 1 }), labelPrefix$2); 4076 }; 4077 var all$1 = function () { 4078 return [ 4079 southeast$2, 4080 southwest$2, 4081 northeast$2, 4082 northwest$2, 4083 south$2, 4084 north$2, 4085 east$2, 4086 west$2 4087 ]; 4088 }; 4089 var allRtl$1 = function () { 4090 return [ 4091 southwest$2, 4092 southeast$2, 4093 northwest$2, 4094 northeast$2, 4095 south$2, 4096 north$2, 4097 east$2, 4098 west$2 4099 ]; 4100 }; 4101 var aboveOrBelow = function () { 4102 return [ 4103 northeast$2, 4104 northwest$2, 4105 southeast$2, 4106 southwest$2, 4107 north$2, 4108 south$2 4109 ]; 4110 }; 4111 var aboveOrBelowRtl = function () { 4112 return [ 4113 northwest$2, 4114 northeast$2, 4115 southwest$2, 4116 southeast$2, 4117 north$2, 4118 south$2 4119 ]; 4120 }; 4121 var belowOrAbove = function () { 4122 return [ 4123 southeast$2, 4124 southwest$2, 4125 northeast$2, 4126 northwest$2, 4127 south$2, 4128 north$2 4129 ]; 4130 }; 4131 var belowOrAboveRtl = function () { 4132 return [ 4133 southwest$2, 4134 southeast$2, 4135 northwest$2, 4136 northeast$2, 4137 south$2, 4138 north$2 4139 ]; 4140 }; 4141 4142 var chooseChannels = function (channels, message) { 4143 return message.universal ? channels : filter$2(channels, function (ch) { 4144 return contains$2(message.channels, ch); 4145 }); 4146 }; 4147 var events$h = function (receiveConfig) { 4148 return derive$2([run$1(receive(), function (component, message) { 4149 var channelMap = receiveConfig.channels; 4150 var channels = keys(channelMap); 4151 var receivingData = message; 4152 var targetChannels = chooseChannels(channels, receivingData); 4153 each$1(targetChannels, function (ch) { 4154 var channelInfo = channelMap[ch]; 4155 var channelSchema = channelInfo.schema; 4156 var data = asRawOrDie$1('channel[' + ch + '] data\nReceiver: ' + element(component.element), channelSchema, receivingData.data); 4157 channelInfo.onReceive(component, data); 4158 }); 4159 })]); 4160 }; 4161 4162 var ActiveReceiving = /*#__PURE__*/Object.freeze({ 4163 __proto__: null, 4164 events: events$h 4165 }); 4166 4167 var ReceivingSchema = [requiredOf('channels', setOf(Result.value, objOfOnly([ 4168 onStrictHandler('onReceive'), 4169 defaulted('schema', anyValue()) 4170 ])))]; 4171 4172 var executeEvent = function (bConfig, bState, executor) { 4173 return runOnExecute$1(function (component) { 4174 executor(component, bConfig, bState); 4175 }); 4176 }; 4177 var loadEvent = function (bConfig, bState, f) { 4178 return runOnInit(function (component, _simulatedEvent) { 4179 f(component, bConfig, bState); 4180 }); 4181 }; 4182 var create$8 = function (schema, name, active, apis, extra, state) { 4183 var configSchema = objOfOnly(schema); 4184 var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]); 4185 return doCreate(configSchema, schemaSchema, name, active, apis, extra, state); 4186 }; 4187 var createModes$1 = function (modes, name, active, apis, extra, state) { 4188 var configSchema = modes; 4189 var schemaSchema = optionObjOf(name, [optionOf('config', modes)]); 4190 return doCreate(configSchema, schemaSchema, name, active, apis, extra, state); 4191 }; 4192 var wrapApi = function (bName, apiFunction, apiName) { 4193 var f = function (component) { 4194 var rest = []; 4195 for (var _i = 1; _i < arguments.length; _i++) { 4196 rest[_i - 1] = arguments[_i]; 4197 } 4198 var args = [component].concat(rest); 4199 return component.config({ name: constant$1(bName) }).fold(function () { 4200 throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName); 4201 }, function (info) { 4202 var rest = Array.prototype.slice.call(args, 1); 4203 return apiFunction.apply(undefined, [ 4204 component, 4205 info.config, 4206 info.state 4207 ].concat(rest)); 4208 }); 4209 }; 4210 return markAsBehaviourApi(f, apiName, apiFunction); 4211 }; 4212 var revokeBehaviour = function (name) { 4213 return { 4214 key: name, 4215 value: undefined 4216 }; 4217 }; 4218 var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) { 4219 var getConfig = function (info) { 4220 return hasNonNullableKey(info, name) ? info[name]() : Optional.none(); 4221 }; 4222 var wrappedApis = map$1(apis, function (apiF, apiName) { 4223 return wrapApi(name, apiF, apiName); 4224 }); 4225 var wrappedExtra = map$1(extra, function (extraF, extraName) { 4226 return markAsExtraApi(extraF, extraName); 4227 }); 4228 var me = __assign(__assign(__assign({}, wrappedExtra), wrappedApis), { 4229 revoke: curry(revokeBehaviour, name), 4230 config: function (spec) { 4231 var prepared = asRawOrDie$1(name + '-config', configSchema, spec); 4232 return { 4233 key: name, 4234 value: { 4235 config: prepared, 4236 me: me, 4237 configAsRaw: cached(function () { 4238 return asRawOrDie$1(name + '-config', configSchema, spec); 4239 }), 4240 initialConfig: spec, 4241 state: state 4242 } 4243 }; 4244 }, 4245 schema: constant$1(schemaSchema), 4246 exhibit: function (info, base) { 4247 return lift2(getConfig(info), get$e(active, 'exhibit'), function (behaviourInfo, exhibitor) { 4248 return exhibitor(base, behaviourInfo.config, behaviourInfo.state); 4249 }).getOrThunk(function () { 4250 return nu$7({}); 4251 }); 4252 }, 4253 name: constant$1(name), 4254 handlers: function (info) { 4255 return getConfig(info).map(function (behaviourInfo) { 4256 var getEvents = get$e(active, 'events').getOr(function () { 4257 return {}; 4258 }); 4259 return getEvents(behaviourInfo.config, behaviourInfo.state); 4260 }).getOr({}); 4261 } 4262 }); 4263 return me; 4264 }; 4265 4266 var derive$1 = function (capabilities) { 4267 return wrapAll(capabilities); 4268 }; 4269 var simpleSchema = objOfOnly([ 4270 required$1('fields'), 4271 required$1('name'), 4272 defaulted('active', {}), 4273 defaulted('apis', {}), 4274 defaulted('state', NoState), 4275 defaulted('extra', {}) 4276 ]); 4277 var create$7 = function (data) { 4278 var value = asRawOrDie$1('Creating behaviour: ' + data.name, simpleSchema, data); 4279 return create$8(value.fields, value.name, value.active, value.apis, value.extra, value.state); 4280 }; 4281 var modeSchema = objOfOnly([ 4282 required$1('branchKey'), 4283 required$1('branches'), 4284 required$1('name'), 4285 defaulted('active', {}), 4286 defaulted('apis', {}), 4287 defaulted('state', NoState), 4288 defaulted('extra', {}) 4289 ]); 4290 var createModes = function (data) { 4291 var value = asRawOrDie$1('Creating behaviour: ' + data.name, modeSchema, data); 4292 return createModes$1(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state); 4293 }; 4294 var revoke = constant$1(undefined); 4295 4296 var Receiving = create$7({ 4297 fields: ReceivingSchema, 4298 name: 'receiving', 4299 active: ActiveReceiving 4300 }); 4301 4302 var exhibit$6 = function (base, posConfig) { 4303 return nu$7({ 4304 classes: [], 4305 styles: posConfig.useFixed() ? {} : { position: 'relative' } 4306 }); 4307 }; 4308 4309 var ActivePosition = /*#__PURE__*/Object.freeze({ 4310 __proto__: null, 4311 exhibit: exhibit$6 4312 }); 4313 4314 var getDocument = function () { 4315 return SugarElement.fromDom(document); 4316 }; 4317 4318 var focus$3 = function (element) { 4319 return element.dom.focus(); 4320 }; 4321 var blur$1 = function (element) { 4322 return element.dom.blur(); 4323 }; 4324 var hasFocus = function (element) { 4325 var root = getRootNode(element).dom; 4326 return element.dom === root.activeElement; 4327 }; 4328 var active = function (root) { 4329 if (root === void 0) { 4330 root = getDocument(); 4331 } 4332 return Optional.from(root.dom.activeElement).map(SugarElement.fromDom); 4333 }; 4334 var search = function (element) { 4335 return active(getRootNode(element)).filter(function (e) { 4336 return element.dom.contains(e.dom); 4337 }); 4338 }; 4339 4340 var preserve$1 = function (f, container) { 4341 var dos = getRootNode(container); 4342 var refocus = active(dos).bind(function (focused) { 4343 var hasFocus = function (elem) { 4344 return eq(focused, elem); 4345 }; 4346 return hasFocus(container) ? Optional.some(container) : descendant$1(container, hasFocus); 4347 }); 4348 var result = f(container); 4349 refocus.each(function (oldFocus) { 4350 active(dos).filter(function (newFocus) { 4351 return eq(newFocus, oldFocus); 4352 }).fold(function () { 4353 focus$3(oldFocus); 4354 }, noop); 4355 }); 4356 return result; 4357 }; 4358 4359 var NuPositionCss = function (position, left, top, right, bottom) { 4360 var toPx = function (num) { 4361 return num + 'px'; 4362 }; 4363 return { 4364 position: position, 4365 left: left.map(toPx), 4366 top: top.map(toPx), 4367 right: right.map(toPx), 4368 bottom: bottom.map(toPx) 4369 }; 4370 }; 4371 var toOptions = function (position) { 4372 return __assign(__assign({}, position), { position: Optional.some(position.position) }); 4373 }; 4374 var applyPositionCss = function (element, position) { 4375 setOptions(element, toOptions(position)); 4376 }; 4377 4378 var adt$9 = Adt.generate([ 4379 { none: [] }, 4380 { 4381 relative: [ 4382 'x', 4383 'y', 4384 'width', 4385 'height' 4386 ] 4387 }, 4388 { 4389 fixed: [ 4390 'x', 4391 'y', 4392 'width', 4393 'height' 4394 ] 4395 } 4396 ]); 4397 var positionWithDirection = function (posName, decision, x, y, width, height) { 4398 var decisionRect = decision.rect; 4399 var decisionX = decisionRect.x - x; 4400 var decisionY = decisionRect.y - y; 4401 var decisionWidth = decisionRect.width; 4402 var decisionHeight = decisionRect.height; 4403 var decisionRight = width - (decisionX + decisionWidth); 4404 var decisionBottom = height - (decisionY + decisionHeight); 4405 var left = Optional.some(decisionX); 4406 var top = Optional.some(decisionY); 4407 var right = Optional.some(decisionRight); 4408 var bottom = Optional.some(decisionBottom); 4409 var none = Optional.none(); 4410 return cata$2(decision.direction, function () { 4411 return NuPositionCss(posName, left, top, none, none); 4412 }, function () { 4413 return NuPositionCss(posName, none, top, right, none); 4414 }, function () { 4415 return NuPositionCss(posName, left, none, none, bottom); 4416 }, function () { 4417 return NuPositionCss(posName, none, none, right, bottom); 4418 }, function () { 4419 return NuPositionCss(posName, left, top, none, none); 4420 }, function () { 4421 return NuPositionCss(posName, left, none, none, bottom); 4422 }, function () { 4423 return NuPositionCss(posName, left, top, none, none); 4424 }, function () { 4425 return NuPositionCss(posName, none, top, right, none); 4426 }); 4427 }; 4428 var reposition = function (origin, decision) { 4429 return origin.fold(function () { 4430 var decisionRect = decision.rect; 4431 return NuPositionCss('absolute', Optional.some(decisionRect.x), Optional.some(decisionRect.y), Optional.none(), Optional.none()); 4432 }, function (x, y, width, height) { 4433 return positionWithDirection('absolute', decision, x, y, width, height); 4434 }, function (x, y, width, height) { 4435 return positionWithDirection('fixed', decision, x, y, width, height); 4436 }); 4437 }; 4438 var toBox = function (origin, element) { 4439 var rel = curry(find$2, element); 4440 var position = origin.fold(rel, rel, function () { 4441 var scroll = get$9(); 4442 return find$2(element).translate(-scroll.left, -scroll.top); 4443 }); 4444 var width = getOuter$1(element); 4445 var height = getOuter$2(element); 4446 return bounds(position.left, position.top, width, height); 4447 }; 4448 var viewport = function (origin, getBounds) { 4449 return getBounds.fold(function () { 4450 return origin.fold(win, win, bounds); 4451 }, function (b) { 4452 return origin.fold(b, b, function () { 4453 var bounds$1 = b(); 4454 var pos = translate$2(origin, bounds$1.x, bounds$1.y); 4455 return bounds(pos.left, pos.top, bounds$1.width, bounds$1.height); 4456 }); 4457 }); 4458 }; 4459 var translate$2 = function (origin, x, y) { 4460 var pos = SugarPosition(x, y); 4461 var removeScroll = function () { 4462 var outerScroll = get$9(); 4463 return pos.translate(-outerScroll.left, -outerScroll.top); 4464 }; 4465 return origin.fold(constant$1(pos), constant$1(pos), removeScroll); 4466 }; 4467 var cata$1 = function (subject, onNone, onRelative, onFixed) { 4468 return subject.fold(onNone, onRelative, onFixed); 4469 }; 4470 adt$9.none; 4471 var relative$1 = adt$9.relative; 4472 var fixed$1 = adt$9.fixed; 4473 4474 var anchor = function (anchorBox, origin) { 4475 return { 4476 anchorBox: anchorBox, 4477 origin: origin 4478 }; 4479 }; 4480 var box = function (anchorBox, origin) { 4481 return anchor(anchorBox, origin); 4482 }; 4483 4484 var placementAttribute = 'data-alloy-placement'; 4485 var setPlacement$1 = function (element, placement) { 4486 set$8(element, placementAttribute, placement); 4487 }; 4488 var getPlacement = function (element) { 4489 return getOpt(element, placementAttribute); 4490 }; 4491 var reset$2 = function (element) { 4492 return remove$7(element, placementAttribute); 4493 }; 4494 4495 var adt$8 = Adt.generate([ 4496 { fit: ['reposition'] }, 4497 { 4498 nofit: [ 4499 'reposition', 4500 'visibleW', 4501 'visibleH', 4502 'isVisible' 4503 ] 4504 } 4505 ]); 4506 var determinePosition = function (box, bounds) { 4507 var boundsX = bounds.x, boundsY = bounds.y, boundsRight = bounds.right, boundsBottom = bounds.bottom; 4508 var x = box.x, y = box.y, right = box.right, bottom = box.bottom, width = box.width, height = box.height; 4509 var xInBounds = x >= boundsX && x <= boundsRight; 4510 var yInBounds = y >= boundsY && y <= boundsBottom; 4511 var originInBounds = xInBounds && yInBounds; 4512 var rightInBounds = right <= boundsRight && right >= boundsX; 4513 var bottomInBounds = bottom <= boundsBottom && bottom >= boundsY; 4514 var sizeInBounds = rightInBounds && bottomInBounds; 4515 var visibleW = Math.min(width, x >= boundsX ? boundsRight - x : right - boundsX); 4516 var visibleH = Math.min(height, y >= boundsY ? boundsBottom - y : bottom - boundsY); 4517 return { 4518 originInBounds: originInBounds, 4519 sizeInBounds: sizeInBounds, 4520 visibleW: visibleW, 4521 visibleH: visibleH 4522 }; 4523 }; 4524 var calcReposition = function (box, bounds$1) { 4525 var boundsX = bounds$1.x, boundsY = bounds$1.y, boundsRight = bounds$1.right, boundsBottom = bounds$1.bottom; 4526 var x = box.x, y = box.y, width = box.width, height = box.height; 4527 var maxX = Math.max(boundsX, boundsRight - width); 4528 var maxY = Math.max(boundsY, boundsBottom - height); 4529 var restrictedX = clamp$1(x, boundsX, maxX); 4530 var restrictedY = clamp$1(y, boundsY, maxY); 4531 var restrictedWidth = Math.min(restrictedX + width, boundsRight) - restrictedX; 4532 var restrictedHeight = Math.min(restrictedY + height, boundsBottom) - restrictedY; 4533 return bounds(restrictedX, restrictedY, restrictedWidth, restrictedHeight); 4534 }; 4535 var calcMaxSizes = function (direction, box, bounds) { 4536 var upAvailable = constant$1(box.bottom - bounds.y); 4537 var downAvailable = constant$1(bounds.bottom - box.y); 4538 var maxHeight = cataVertical(direction, downAvailable, downAvailable, upAvailable); 4539 var westAvailable = constant$1(box.right - bounds.x); 4540 var eastAvailable = constant$1(bounds.right - box.x); 4541 var maxWidth = cataHorizontal(direction, eastAvailable, eastAvailable, westAvailable); 4542 return { 4543 maxWidth: maxWidth, 4544 maxHeight: maxHeight 4545 }; 4546 }; 4547 var attempt = function (candidate, width, height, bounds$1) { 4548 var bubble = candidate.bubble; 4549 var bubbleOffset = bubble.offset; 4550 var adjustedBounds = adjustBounds(bounds$1, candidate.restriction, bubbleOffset); 4551 var newX = candidate.x + bubbleOffset.left; 4552 var newY = candidate.y + bubbleOffset.top; 4553 var box = bounds(newX, newY, width, height); 4554 var _a = determinePosition(box, adjustedBounds), originInBounds = _a.originInBounds, sizeInBounds = _a.sizeInBounds, visibleW = _a.visibleW, visibleH = _a.visibleH; 4555 var fits = originInBounds && sizeInBounds; 4556 var fittedBox = fits ? box : calcReposition(box, adjustedBounds); 4557 var isPartlyVisible = fittedBox.width > 0 && fittedBox.height > 0; 4558 var _b = calcMaxSizes(candidate.direction, fittedBox, bounds$1), maxWidth = _b.maxWidth, maxHeight = _b.maxHeight; 4559 var reposition = { 4560 rect: fittedBox, 4561 maxHeight: maxHeight, 4562 maxWidth: maxWidth, 4563 direction: candidate.direction, 4564 placement: candidate.placement, 4565 classes: { 4566 on: bubble.classesOn, 4567 off: bubble.classesOff 4568 }, 4569 layout: candidate.label, 4570 testY: newY 4571 }; 4572 return fits || candidate.alwaysFit ? adt$8.fit(reposition) : adt$8.nofit(reposition, visibleW, visibleH, isPartlyVisible); 4573 }; 4574 var attempts = function (element, candidates, anchorBox, elementBox, bubbles, bounds) { 4575 var panelWidth = elementBox.width; 4576 var panelHeight = elementBox.height; 4577 var attemptBestFit = function (layout, reposition, visibleW, visibleH, isVisible) { 4578 var next = layout(anchorBox, elementBox, bubbles, element, bounds); 4579 var attemptLayout = attempt(next, panelWidth, panelHeight, bounds); 4580 return attemptLayout.fold(constant$1(attemptLayout), function (newReposition, newVisibleW, newVisibleH, newIsVisible) { 4581 var improved = isVisible === newIsVisible ? newVisibleH > visibleH || newVisibleW > visibleW : !isVisible && newIsVisible; 4582 return improved ? attemptLayout : adt$8.nofit(reposition, visibleW, visibleH, isVisible); 4583 }); 4584 }; 4585 var abc = foldl(candidates, function (b, a) { 4586 var bestNext = curry(attemptBestFit, a); 4587 return b.fold(constant$1(b), bestNext); 4588 }, adt$8.nofit({ 4589 rect: anchorBox, 4590 maxHeight: elementBox.height, 4591 maxWidth: elementBox.width, 4592 direction: southeast$3(), 4593 placement: 'southeast', 4594 classes: { 4595 on: [], 4596 off: [] 4597 }, 4598 layout: 'none', 4599 testY: anchorBox.y 4600 }, -1, -1, false)); 4601 return abc.fold(identity$1, identity$1); 4602 }; 4603 4604 var singleton = function (doRevoke) { 4605 var subject = Cell(Optional.none()); 4606 var revoke = function () { 4607 return subject.get().each(doRevoke); 4608 }; 4609 var clear = function () { 4610 revoke(); 4611 subject.set(Optional.none()); 4612 }; 4613 var isSet = function () { 4614 return subject.get().isSome(); 4615 }; 4616 var get = function () { 4617 return subject.get(); 4618 }; 4619 var set = function (s) { 4620 revoke(); 4621 subject.set(Optional.some(s)); 4622 }; 4623 return { 4624 clear: clear, 4625 isSet: isSet, 4626 get: get, 4627 set: set 4628 }; 4629 }; 4630 var destroyable = function () { 4631 return singleton(function (s) { 4632 return s.destroy(); 4633 }); 4634 }; 4635 var unbindable = function () { 4636 return singleton(function (s) { 4637 return s.unbind(); 4638 }); 4639 }; 4640 var api$1 = function () { 4641 var subject = destroyable(); 4642 var run = function (f) { 4643 return subject.get().each(f); 4644 }; 4645 return __assign(__assign({}, subject), { run: run }); 4646 }; 4647 var value$1 = function () { 4648 var subject = singleton(noop); 4649 var on = function (f) { 4650 return subject.get().each(f); 4651 }; 4652 return __assign(__assign({}, subject), { on: on }); 4653 }; 4654 4655 var filter = always; 4656 var bind = function (element, event, handler) { 4657 return bind$2(element, event, filter, handler); 4658 }; 4659 var capture = function (element, event, handler) { 4660 return capture$1(element, event, filter, handler); 4661 }; 4662 var fromRawEvent = fromRawEvent$1; 4663 4664 var properties = [ 4665 'top', 4666 'bottom', 4667 'right', 4668 'left' 4669 ]; 4670 var timerAttr = 'data-alloy-transition-timer'; 4671 var isTransitioning$1 = function (element, transition) { 4672 return hasAll(element, transition.classes); 4673 }; 4674 var shouldApplyTransitionCss = function (transition, decision, lastPlacement) { 4675 return lastPlacement.exists(function (placer) { 4676 var mode = transition.mode; 4677 return mode === 'all' ? true : placer[mode] !== decision[mode]; 4678 }); 4679 }; 4680 var hasChanges = function (position, intermediate) { 4681 var round = function (value) { 4682 return parseFloat(value).toFixed(3); 4683 }; 4684 return find$4(intermediate, function (value, key) { 4685 var newValue = position[key].map(round); 4686 var val = value.map(round); 4687 return !equals(newValue, val); 4688 }).isSome(); 4689 }; 4690 var getTransitionDuration = function (element) { 4691 var get = function (name) { 4692 var style = get$c(element, name); 4693 var times = isString(style) ? style.split(/\s*,\s*/) : []; 4694 return filter$2(times, isNotEmpty); 4695 }; 4696 var parse = function (value) { 4697 if (isString(value) && /^[\d.]+/.test(value)) { 4698 var num = parseFloat(value); 4699 return endsWith(value, 'ms') ? num : num * 1000; 4700 } else { 4701 return 0; 4702 } 4703 }; 4704 var delay = get('transition-delay'); 4705 var duration = get('transition-duration'); 4706 return foldl(duration, function (acc, dur, i) { 4707 var time = parse(delay[i]) + parse(dur); 4708 return Math.max(acc, time); 4709 }, 0); 4710 }; 4711 var setupTransitionListeners = function (element, transition) { 4712 var transitionEnd = unbindable(); 4713 var transitionCancel = unbindable(); 4714 var timer; 4715 var isSourceTransition = function (e) { 4716 var _a; 4717 var pseudoElement = (_a = e.raw.pseudoElement) !== null && _a !== void 0 ? _a : ''; 4718 return eq(e.target, element) && isEmpty(pseudoElement) && contains$2(properties, e.raw.propertyName); 4719 }; 4720 var transitionDone = function (e) { 4721 if (isNullable(e) || isSourceTransition(e)) { 4722 transitionEnd.clear(); 4723 transitionCancel.clear(); 4724 var type = e === null || e === void 0 ? void 0 : e.raw.type; 4725 if (isNullable(type) || type === transitionend()) { 4726 clearTimeout(timer); 4727 remove$7(element, timerAttr); 4728 remove$1(element, transition.classes); 4729 } 4730 } 4731 }; 4732 var transitionStarted = function () { 4733 transitionEnd.set(bind(element, transitionend(), transitionDone)); 4734 transitionCancel.set(bind(element, transitioncancel(), transitionDone)); 4735 }; 4736 if ('ontransitionstart' in element.dom) { 4737 var transitionStart_1 = bind(element, transitionstart(), function (e) { 4738 if (isSourceTransition(e)) { 4739 transitionStart_1.unbind(); 4740 transitionStarted(); 4741 } 4742 }); 4743 } else { 4744 transitionStarted(); 4745 } 4746 var duration = getTransitionDuration(element); 4747 requestAnimationFrame(function () { 4748 timer = setTimeout(transitionDone, duration + 17); 4749 set$8(element, timerAttr, timer); 4750 }); 4751 }; 4752 var startTransitioning = function (element, transition) { 4753 add$1(element, transition.classes); 4754 getOpt(element, timerAttr).each(function (timerId) { 4755 clearTimeout(parseInt(timerId, 10)); 4756 remove$7(element, timerAttr); 4757 }); 4758 setupTransitionListeners(element, transition); 4759 }; 4760 var applyTransitionCss = function (element, origin, position, transition, decision, lastPlacement) { 4761 var shouldTransition = shouldApplyTransitionCss(transition, decision, lastPlacement); 4762 if (shouldTransition || isTransitioning$1(element, transition)) { 4763 set$7(element, 'position', position.position); 4764 var rect = toBox(origin, element); 4765 var intermediatePosition_1 = reposition(origin, __assign(__assign({}, decision), { rect: rect })); 4766 var intermediateCssOptions = mapToObject(properties, function (prop) { 4767 return intermediatePosition_1[prop]; 4768 }); 4769 if (hasChanges(position, intermediateCssOptions)) { 4770 setOptions(element, intermediateCssOptions); 4771 if (shouldTransition) { 4772 startTransitioning(element, transition); 4773 } 4774 reflow(element); 4775 } 4776 } else { 4777 remove$1(element, transition.classes); 4778 } 4779 }; 4780 4781 var elementSize = function (p) { 4782 return { 4783 width: getOuter$1(p), 4784 height: getOuter$2(p) 4785 }; 4786 }; 4787 var layout = function (anchorBox, element, bubbles, options) { 4788 remove$6(element, 'max-height'); 4789 remove$6(element, 'max-width'); 4790 var elementBox = elementSize(element); 4791 return attempts(element, options.preference, anchorBox, elementBox, bubbles, options.bounds); 4792 }; 4793 var setClasses = function (element, decision) { 4794 var classInfo = decision.classes; 4795 remove$1(element, classInfo.off); 4796 add$1(element, classInfo.on); 4797 }; 4798 var setHeight = function (element, decision, options) { 4799 var maxHeightFunction = options.maxHeightFunction; 4800 maxHeightFunction(element, decision.maxHeight); 4801 }; 4802 var setWidth = function (element, decision, options) { 4803 var maxWidthFunction = options.maxWidthFunction; 4804 maxWidthFunction(element, decision.maxWidth); 4805 }; 4806 var position$2 = function (element, decision, options) { 4807 var positionCss = reposition(options.origin, decision); 4808 options.transition.each(function (transition) { 4809 applyTransitionCss(element, options.origin, positionCss, transition, decision, options.lastPlacement); 4810 }); 4811 applyPositionCss(element, positionCss); 4812 }; 4813 var setPlacement = function (element, decision) { 4814 setPlacement$1(element, decision.placement); 4815 }; 4816 4817 var setMaxHeight = function (element, maxHeight) { 4818 setMax$1(element, Math.floor(maxHeight)); 4819 }; 4820 var anchored = constant$1(function (element, available) { 4821 setMaxHeight(element, available); 4822 setAll(element, { 4823 'overflow-x': 'hidden', 4824 'overflow-y': 'auto' 4825 }); 4826 }); 4827 var expandable$1 = constant$1(function (element, available) { 4828 setMaxHeight(element, available); 4829 }); 4830 4831 var defaultOr = function (options, key, dephault) { 4832 return options[key] === undefined ? dephault : options[key]; 4833 }; 4834 var simple = function (anchor, element, bubble, layouts, lastPlacement, getBounds, overrideOptions, transition) { 4835 var maxHeightFunction = defaultOr(overrideOptions, 'maxHeightFunction', anchored()); 4836 var maxWidthFunction = defaultOr(overrideOptions, 'maxWidthFunction', noop); 4837 var anchorBox = anchor.anchorBox; 4838 var origin = anchor.origin; 4839 var options = { 4840 bounds: viewport(origin, getBounds), 4841 origin: origin, 4842 preference: layouts, 4843 maxHeightFunction: maxHeightFunction, 4844 maxWidthFunction: maxWidthFunction, 4845 lastPlacement: lastPlacement, 4846 transition: transition 4847 }; 4848 return go(anchorBox, element, bubble, options); 4849 }; 4850 var go = function (anchorBox, element, bubble, options) { 4851 var decision = layout(anchorBox, element, bubble, options); 4852 position$2(element, decision, options); 4853 setPlacement(element, decision); 4854 setClasses(element, decision); 4855 setHeight(element, decision, options); 4856 setWidth(element, decision, options); 4857 return { 4858 layout: decision.layout, 4859 placement: decision.placement 4860 }; 4861 }; 4862 4863 var allAlignments = [ 4864 'valignCentre', 4865 'alignLeft', 4866 'alignRight', 4867 'alignCentre', 4868 'top', 4869 'bottom', 4870 'left', 4871 'right', 4872 'inset' 4873 ]; 4874 var nu$5 = function (xOffset, yOffset, classes, insetModifier) { 4875 if (insetModifier === void 0) { 4876 insetModifier = 1; 4877 } 4878 var insetXOffset = xOffset * insetModifier; 4879 var insetYOffset = yOffset * insetModifier; 4880 var getClasses = function (prop) { 4881 return get$e(classes, prop).getOr([]); 4882 }; 4883 var make = function (xDelta, yDelta, alignmentsOn) { 4884 var alignmentsOff = difference(allAlignments, alignmentsOn); 4885 return { 4886 offset: SugarPosition(xDelta, yDelta), 4887 classesOn: bind$3(alignmentsOn, getClasses), 4888 classesOff: bind$3(alignmentsOff, getClasses) 4889 }; 4890 }; 4891 return { 4892 southeast: function () { 4893 return make(-xOffset, yOffset, [ 4894 'top', 4895 'alignLeft' 4896 ]); 4897 }, 4898 southwest: function () { 4899 return make(xOffset, yOffset, [ 4900 'top', 4901 'alignRight' 4902 ]); 4903 }, 4904 south: function () { 4905 return make(-xOffset / 2, yOffset, [ 4906 'top', 4907 'alignCentre' 4908 ]); 4909 }, 4910 northeast: function () { 4911 return make(-xOffset, -yOffset, [ 4912 'bottom', 4913 'alignLeft' 4914 ]); 4915 }, 4916 northwest: function () { 4917 return make(xOffset, -yOffset, [ 4918 'bottom', 4919 'alignRight' 4920 ]); 4921 }, 4922 north: function () { 4923 return make(-xOffset / 2, -yOffset, [ 4924 'bottom', 4925 'alignCentre' 4926 ]); 4927 }, 4928 east: function () { 4929 return make(xOffset, -yOffset / 2, [ 4930 'valignCentre', 4931 'left' 4932 ]); 4933 }, 4934 west: function () { 4935 return make(-xOffset, -yOffset / 2, [ 4936 'valignCentre', 4937 'right' 4938 ]); 4939 }, 4940 insetNortheast: function () { 4941 return make(insetXOffset, insetYOffset, [ 4942 'top', 4943 'alignLeft', 4944 'inset' 4945 ]); 4946 }, 4947 insetNorthwest: function () { 4948 return make(-insetXOffset, insetYOffset, [ 4949 'top', 4950 'alignRight', 4951 'inset' 4952 ]); 4953 }, 4954 insetNorth: function () { 4955 return make(-insetXOffset / 2, insetYOffset, [ 4956 'top', 4957 'alignCentre', 4958 'inset' 4959 ]); 4960 }, 4961 insetSoutheast: function () { 4962 return make(insetXOffset, -insetYOffset, [ 4963 'bottom', 4964 'alignLeft', 4965 'inset' 4966 ]); 4967 }, 4968 insetSouthwest: function () { 4969 return make(-insetXOffset, -insetYOffset, [ 4970 'bottom', 4971 'alignRight', 4972 'inset' 4973 ]); 4974 }, 4975 insetSouth: function () { 4976 return make(-insetXOffset / 2, -insetYOffset, [ 4977 'bottom', 4978 'alignCentre', 4979 'inset' 4980 ]); 4981 }, 4982 insetEast: function () { 4983 return make(-insetXOffset, -insetYOffset / 2, [ 4984 'valignCentre', 4985 'right', 4986 'inset' 4987 ]); 4988 }, 4989 insetWest: function () { 4990 return make(insetXOffset, -insetYOffset / 2, [ 4991 'valignCentre', 4992 'left', 4993 'inset' 4994 ]); 4995 } 4996 }; 4997 }; 4998 var fallback = function () { 4999 return nu$5(0, 0, {}); 5000 }; 5001 5002 var nu$4 = identity$1; 5003 5004 var onDirection = function (isLtr, isRtl) { 5005 return function (element) { 5006 return getDirection(element) === 'rtl' ? isRtl : isLtr; 5007 }; 5008 }; 5009 var getDirection = function (element) { 5010 return get$c(element, 'direction') === 'rtl' ? 'rtl' : 'ltr'; 5011 }; 5012 5013 var AttributeValue; 5014 (function (AttributeValue) { 5015 AttributeValue['TopToBottom'] = 'toptobottom'; 5016 AttributeValue['BottomToTop'] = 'bottomtotop'; 5017 }(AttributeValue || (AttributeValue = {}))); 5018 var Attribute = 'data-alloy-vertical-dir'; 5019 var isBottomToTopDir = function (el) { 5020 return closest$2(el, function (current) { 5021 return isElement$2(current) && get$d(current, 'data-alloy-vertical-dir') === AttributeValue.BottomToTop; 5022 }); 5023 }; 5024 5025 var schema$y = function () { 5026 return optionObjOf('layouts', [ 5027 required$1('onLtr'), 5028 required$1('onRtl'), 5029 option('onBottomLtr'), 5030 option('onBottomRtl') 5031 ]); 5032 }; 5033 var get$4 = function (elem, info, defaultLtr, defaultRtl, defaultBottomLtr, defaultBottomRtl, dirElement) { 5034 var isBottomToTop = dirElement.map(isBottomToTopDir).getOr(false); 5035 var customLtr = info.layouts.map(function (ls) { 5036 return ls.onLtr(elem); 5037 }); 5038 var customRtl = info.layouts.map(function (ls) { 5039 return ls.onRtl(elem); 5040 }); 5041 var ltr = isBottomToTop ? info.layouts.bind(function (ls) { 5042 return ls.onBottomLtr.map(function (f) { 5043 return f(elem); 5044 }); 5045 }).or(customLtr).getOr(defaultBottomLtr) : customLtr.getOr(defaultLtr); 5046 var rtl = isBottomToTop ? info.layouts.bind(function (ls) { 5047 return ls.onBottomRtl.map(function (f) { 5048 return f(elem); 5049 }); 5050 }).or(customRtl).getOr(defaultBottomRtl) : customRtl.getOr(defaultRtl); 5051 var f = onDirection(ltr, rtl); 5052 return f(elem); 5053 }; 5054 5055 var placement$4 = function (component, anchorInfo, origin) { 5056 var hotspot = anchorInfo.hotspot; 5057 var anchorBox = toBox(origin, hotspot.element); 5058 var layouts = get$4(component.element, anchorInfo, belowOrAbove(), belowOrAboveRtl(), aboveOrBelow(), aboveOrBelowRtl(), Optional.some(anchorInfo.hotspot.element)); 5059 return Optional.some(nu$4({ 5060 anchorBox: anchorBox, 5061 bubble: anchorInfo.bubble.getOr(fallback()), 5062 overrides: anchorInfo.overrides, 5063 layouts: layouts, 5064 placer: Optional.none() 5065 })); 5066 }; 5067 var HotspotAnchor = [ 5068 required$1('hotspot'), 5069 option('bubble'), 5070 defaulted('overrides', {}), 5071 schema$y(), 5072 output$1('placement', placement$4) 5073 ]; 5074 5075 var placement$3 = function (component, anchorInfo, origin) { 5076 var pos = translate$2(origin, anchorInfo.x, anchorInfo.y); 5077 var anchorBox = bounds(pos.left, pos.top, anchorInfo.width, anchorInfo.height); 5078 var layouts = get$4(component.element, anchorInfo, all$1(), allRtl$1(), all$1(), allRtl$1(), Optional.none()); 5079 return Optional.some(nu$4({ 5080 anchorBox: anchorBox, 5081 bubble: anchorInfo.bubble, 5082 overrides: anchorInfo.overrides, 5083 layouts: layouts, 5084 placer: Optional.none() 5085 })); 5086 }; 5087 var MakeshiftAnchor = [ 5088 required$1('x'), 5089 required$1('y'), 5090 defaulted('height', 0), 5091 defaulted('width', 0), 5092 defaulted('bubble', fallback()), 5093 defaulted('overrides', {}), 5094 schema$y(), 5095 output$1('placement', placement$3) 5096 ]; 5097 5098 var adt$7 = Adt.generate([ 5099 { screen: ['point'] }, 5100 { 5101 absolute: [ 5102 'point', 5103 'scrollLeft', 5104 'scrollTop' 5105 ] 5106 } 5107 ]); 5108 var toFixed = function (pos) { 5109 return pos.fold(identity$1, function (point, scrollLeft, scrollTop) { 5110 return point.translate(-scrollLeft, -scrollTop); 5111 }); 5112 }; 5113 var toAbsolute = function (pos) { 5114 return pos.fold(identity$1, identity$1); 5115 }; 5116 var sum = function (points) { 5117 return foldl(points, function (b, a) { 5118 return b.translate(a.left, a.top); 5119 }, SugarPosition(0, 0)); 5120 }; 5121 var sumAsFixed = function (positions) { 5122 var points = map$2(positions, toFixed); 5123 return sum(points); 5124 }; 5125 var sumAsAbsolute = function (positions) { 5126 var points = map$2(positions, toAbsolute); 5127 return sum(points); 5128 }; 5129 var screen = adt$7.screen; 5130 var absolute$1 = adt$7.absolute; 5131 5132 var getOffset = function (component, origin, anchorInfo) { 5133 var win = defaultView(anchorInfo.root).dom; 5134 var hasSameOwner = function (frame) { 5135 var frameOwner = owner$4(frame); 5136 var compOwner = owner$4(component.element); 5137 return eq(frameOwner, compOwner); 5138 }; 5139 return Optional.from(win.frameElement).map(SugarElement.fromDom).filter(hasSameOwner).map(absolute$3); 5140 }; 5141 var getRootPoint = function (component, origin, anchorInfo) { 5142 var doc = owner$4(component.element); 5143 var outerScroll = get$9(doc); 5144 var offset = getOffset(component, origin, anchorInfo).getOr(outerScroll); 5145 return absolute$1(offset, outerScroll.left, outerScroll.top); 5146 }; 5147 5148 var getBox = function (left, top, width, height) { 5149 var point = screen(SugarPosition(left, top)); 5150 return Optional.some(pointed(point, width, height)); 5151 }; 5152 var calcNewAnchor = function (optBox, rootPoint, anchorInfo, origin, elem) { 5153 return optBox.map(function (box) { 5154 var points = [ 5155 rootPoint, 5156 box.point 5157 ]; 5158 var topLeft = cata$1(origin, function () { 5159 return sumAsAbsolute(points); 5160 }, function () { 5161 return sumAsAbsolute(points); 5162 }, function () { 5163 return sumAsFixed(points); 5164 }); 5165 var anchorBox = rect(topLeft.left, topLeft.top, box.width, box.height); 5166 var layoutsLtr = anchorInfo.showAbove ? aboveOrBelow() : belowOrAbove(); 5167 var layoutsRtl = anchorInfo.showAbove ? aboveOrBelowRtl() : belowOrAboveRtl(); 5168 var layouts = get$4(elem, anchorInfo, layoutsLtr, layoutsRtl, layoutsLtr, layoutsRtl, Optional.none()); 5169 return nu$4({ 5170 anchorBox: anchorBox, 5171 bubble: anchorInfo.bubble.getOr(fallback()), 5172 overrides: anchorInfo.overrides, 5173 layouts: layouts, 5174 placer: Optional.none() 5175 }); 5176 }); 5177 }; 5178 5179 var placement$2 = function (component, anchorInfo, origin) { 5180 var rootPoint = getRootPoint(component, origin, anchorInfo); 5181 return anchorInfo.node.filter(inBody).bind(function (target) { 5182 var rect = target.dom.getBoundingClientRect(); 5183 var nodeBox = getBox(rect.left, rect.top, rect.width, rect.height); 5184 var elem = anchorInfo.node.getOr(component.element); 5185 return calcNewAnchor(nodeBox, rootPoint, anchorInfo, origin, elem); 5186 }); 5187 }; 5188 var NodeAnchor = [ 5189 required$1('node'), 5190 required$1('root'), 5191 option('bubble'), 5192 schema$y(), 5193 defaulted('overrides', {}), 5194 defaulted('showAbove', false), 5195 output$1('placement', placement$2) 5196 ]; 5197 5198 var zeroWidth = '\uFEFF'; 5199 var nbsp = '\xA0'; 5200 5201 var create$6 = function (start, soffset, finish, foffset) { 5202 return { 5203 start: start, 5204 soffset: soffset, 5205 finish: finish, 5206 foffset: foffset 5207 }; 5208 }; 5209 var SimRange = { create: create$6 }; 5210 5211 var adt$6 = Adt.generate([ 5212 { before: ['element'] }, 5213 { 5214 on: [ 5215 'element', 5216 'offset' 5217 ] 5218 }, 5219 { after: ['element'] } 5220 ]); 5221 var cata = function (subject, onBefore, onOn, onAfter) { 5222 return subject.fold(onBefore, onOn, onAfter); 5223 }; 5224 var getStart$1 = function (situ) { 5225 return situ.fold(identity$1, identity$1, identity$1); 5226 }; 5227 var before = adt$6.before; 5228 var on$1 = adt$6.on; 5229 var after$1 = adt$6.after; 5230 var Situ = { 5231 before: before, 5232 on: on$1, 5233 after: after$1, 5234 cata: cata, 5235 getStart: getStart$1 5236 }; 5237 5238 var adt$5 = Adt.generate([ 5239 { domRange: ['rng'] }, 5240 { 5241 relative: [ 5242 'startSitu', 5243 'finishSitu' 5244 ] 5245 }, 5246 { 5247 exact: [ 5248 'start', 5249 'soffset', 5250 'finish', 5251 'foffset' 5252 ] 5253 } 5254 ]); 5255 var exactFromRange = function (simRange) { 5256 return adt$5.exact(simRange.start, simRange.soffset, simRange.finish, simRange.foffset); 5257 }; 5258 var getStart = function (selection) { 5259 return selection.match({ 5260 domRange: function (rng) { 5261 return SugarElement.fromDom(rng.startContainer); 5262 }, 5263 relative: function (startSitu, _finishSitu) { 5264 return Situ.getStart(startSitu); 5265 }, 5266 exact: function (start, _soffset, _finish, _foffset) { 5267 return start; 5268 } 5269 }); 5270 }; 5271 var domRange = adt$5.domRange; 5272 var relative = adt$5.relative; 5273 var exact = adt$5.exact; 5274 var getWin = function (selection) { 5275 var start = getStart(selection); 5276 return defaultView(start); 5277 }; 5278 var range$1 = SimRange.create; 5279 var SimSelection = { 5280 domRange: domRange, 5281 relative: relative, 5282 exact: exact, 5283 exactFromRange: exactFromRange, 5284 getWin: getWin, 5285 range: range$1 5286 }; 5287 5288 var setStart = function (rng, situ) { 5289 situ.fold(function (e) { 5290 rng.setStartBefore(e.dom); 5291 }, function (e, o) { 5292 rng.setStart(e.dom, o); 5293 }, function (e) { 5294 rng.setStartAfter(e.dom); 5295 }); 5296 }; 5297 var setFinish = function (rng, situ) { 5298 situ.fold(function (e) { 5299 rng.setEndBefore(e.dom); 5300 }, function (e, o) { 5301 rng.setEnd(e.dom, o); 5302 }, function (e) { 5303 rng.setEndAfter(e.dom); 5304 }); 5305 }; 5306 var relativeToNative = function (win, startSitu, finishSitu) { 5307 var range = win.document.createRange(); 5308 setStart(range, startSitu); 5309 setFinish(range, finishSitu); 5310 return range; 5311 }; 5312 var exactToNative = function (win, start, soffset, finish, foffset) { 5313 var rng = win.document.createRange(); 5314 rng.setStart(start.dom, soffset); 5315 rng.setEnd(finish.dom, foffset); 5316 return rng; 5317 }; 5318 var toRect = function (rect) { 5319 return { 5320 left: rect.left, 5321 top: rect.top, 5322 right: rect.right, 5323 bottom: rect.bottom, 5324 width: rect.width, 5325 height: rect.height 5326 }; 5327 }; 5328 var getFirstRect$1 = function (rng) { 5329 var rects = rng.getClientRects(); 5330 var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect(); 5331 return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none(); 5332 }; 5333 var getBounds$2 = function (rng) { 5334 var rect = rng.getBoundingClientRect(); 5335 return rect.width > 0 || rect.height > 0 ? Optional.some(rect).map(toRect) : Optional.none(); 5336 }; 5337 5338 var adt$4 = Adt.generate([ 5339 { 5340 ltr: [ 5341 'start', 5342 'soffset', 5343 'finish', 5344 'foffset' 5345 ] 5346 }, 5347 { 5348 rtl: [ 5349 'start', 5350 'soffset', 5351 'finish', 5352 'foffset' 5353 ] 5354 } 5355 ]); 5356 var fromRange = function (win, type, range) { 5357 return type(SugarElement.fromDom(range.startContainer), range.startOffset, SugarElement.fromDom(range.endContainer), range.endOffset); 5358 }; 5359 var getRanges = function (win, selection) { 5360 return selection.match({ 5361 domRange: function (rng) { 5362 return { 5363 ltr: constant$1(rng), 5364 rtl: Optional.none 5365 }; 5366 }, 5367 relative: function (startSitu, finishSitu) { 5368 return { 5369 ltr: cached(function () { 5370 return relativeToNative(win, startSitu, finishSitu); 5371 }), 5372 rtl: cached(function () { 5373 return Optional.some(relativeToNative(win, finishSitu, startSitu)); 5374 }) 5375 }; 5376 }, 5377 exact: function (start, soffset, finish, foffset) { 5378 return { 5379 ltr: cached(function () { 5380 return exactToNative(win, start, soffset, finish, foffset); 5381 }), 5382 rtl: cached(function () { 5383 return Optional.some(exactToNative(win, finish, foffset, start, soffset)); 5384 }) 5385 }; 5386 } 5387 }); 5388 }; 5389 var doDiagnose = function (win, ranges) { 5390 var rng = ranges.ltr(); 5391 if (rng.collapsed) { 5392 var reversed = ranges.rtl().filter(function (rev) { 5393 return rev.collapsed === false; 5394 }); 5395 return reversed.map(function (rev) { 5396 return adt$4.rtl(SugarElement.fromDom(rev.endContainer), rev.endOffset, SugarElement.fromDom(rev.startContainer), rev.startOffset); 5397 }).getOrThunk(function () { 5398 return fromRange(win, adt$4.ltr, rng); 5399 }); 5400 } else { 5401 return fromRange(win, adt$4.ltr, rng); 5402 } 5403 }; 5404 var diagnose = function (win, selection) { 5405 var ranges = getRanges(win, selection); 5406 return doDiagnose(win, ranges); 5407 }; 5408 var asLtrRange = function (win, selection) { 5409 var diagnosis = diagnose(win, selection); 5410 return diagnosis.match({ 5411 ltr: function (start, soffset, finish, foffset) { 5412 var rng = win.document.createRange(); 5413 rng.setStart(start.dom, soffset); 5414 rng.setEnd(finish.dom, foffset); 5415 return rng; 5416 }, 5417 rtl: function (start, soffset, finish, foffset) { 5418 var rng = win.document.createRange(); 5419 rng.setStart(finish.dom, foffset); 5420 rng.setEnd(start.dom, soffset); 5421 return rng; 5422 } 5423 }); 5424 }; 5425 adt$4.ltr; 5426 adt$4.rtl; 5427 5428 var NodeValue = function (is, name) { 5429 var get = function (element) { 5430 if (!is(element)) { 5431 throw new Error('Can only get ' + name + ' value of a ' + name + ' node'); 5432 } 5433 return getOption(element).getOr(''); 5434 }; 5435 var getOption = function (element) { 5436 return is(element) ? Optional.from(element.dom.nodeValue) : Optional.none(); 5437 }; 5438 var set = function (element, value) { 5439 if (!is(element)) { 5440 throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node'); 5441 } 5442 element.dom.nodeValue = value; 5443 }; 5444 return { 5445 get: get, 5446 getOption: getOption, 5447 set: set 5448 }; 5449 }; 5450 5451 var api = NodeValue(isText$1, 'text'); 5452 var get$3 = function (element) { 5453 return api.get(element); 5454 }; 5455 var getOption = function (element) { 5456 return api.getOption(element); 5457 }; 5458 5459 var getEnd = function (element) { 5460 return name$2(element) === 'img' ? 1 : getOption(element).fold(function () { 5461 return children(element).length; 5462 }, function (v) { 5463 return v.length; 5464 }); 5465 }; 5466 var isTextNodeWithCursorPosition = function (el) { 5467 return getOption(el).filter(function (text) { 5468 return text.trim().length !== 0 || text.indexOf(nbsp) > -1; 5469 }).isSome(); 5470 }; 5471 var elementsWithCursorPosition = [ 5472 'img', 5473 'br' 5474 ]; 5475 var isCursorPosition = function (elem) { 5476 var hasCursorPosition = isTextNodeWithCursorPosition(elem); 5477 return hasCursorPosition || contains$2(elementsWithCursorPosition, name$2(elem)); 5478 }; 5479 5480 var last$1 = function (element) { 5481 return descendantRtl(element, isCursorPosition); 5482 }; 5483 var descendantRtl = function (scope, predicate) { 5484 var descend = function (element) { 5485 var children$1 = children(element); 5486 for (var i = children$1.length - 1; i >= 0; i--) { 5487 var child = children$1[i]; 5488 if (predicate(child)) { 5489 return Optional.some(child); 5490 } 5491 var res = descend(child); 5492 if (res.isSome()) { 5493 return res; 5494 } 5495 } 5496 return Optional.none(); 5497 }; 5498 return descend(scope); 5499 }; 5500 5501 var descendants = function (scope, selector) { 5502 return all$3(selector, scope); 5503 }; 5504 5505 var makeRange = function (start, soffset, finish, foffset) { 5506 var doc = owner$4(start); 5507 var rng = doc.dom.createRange(); 5508 rng.setStart(start.dom, soffset); 5509 rng.setEnd(finish.dom, foffset); 5510 return rng; 5511 }; 5512 var after = function (start, soffset, finish, foffset) { 5513 var r = makeRange(start, soffset, finish, foffset); 5514 var same = eq(start, finish) && soffset === foffset; 5515 return r.collapsed && !same; 5516 }; 5517 5518 var getNativeSelection = function (win) { 5519 return Optional.from(win.getSelection()); 5520 }; 5521 var readRange = function (selection) { 5522 if (selection.rangeCount > 0) { 5523 var firstRng = selection.getRangeAt(0); 5524 var lastRng = selection.getRangeAt(selection.rangeCount - 1); 5525 return Optional.some(SimRange.create(SugarElement.fromDom(firstRng.startContainer), firstRng.startOffset, SugarElement.fromDom(lastRng.endContainer), lastRng.endOffset)); 5526 } else { 5527 return Optional.none(); 5528 } 5529 }; 5530 var doGetExact = function (selection) { 5531 if (selection.anchorNode === null || selection.focusNode === null) { 5532 return readRange(selection); 5533 } else { 5534 var anchor = SugarElement.fromDom(selection.anchorNode); 5535 var focus_1 = SugarElement.fromDom(selection.focusNode); 5536 return after(anchor, selection.anchorOffset, focus_1, selection.focusOffset) ? Optional.some(SimRange.create(anchor, selection.anchorOffset, focus_1, selection.focusOffset)) : readRange(selection); 5537 } 5538 }; 5539 var getExact = function (win) { 5540 return getNativeSelection(win).filter(function (sel) { 5541 return sel.rangeCount > 0; 5542 }).bind(doGetExact); 5543 }; 5544 var getFirstRect = function (win, selection) { 5545 var rng = asLtrRange(win, selection); 5546 return getFirstRect$1(rng); 5547 }; 5548 var getBounds$1 = function (win, selection) { 5549 var rng = asLtrRange(win, selection); 5550 return getBounds$2(rng); 5551 }; 5552 5553 var point$1 = function (element, offset) { 5554 return { 5555 element: element, 5556 offset: offset 5557 }; 5558 }; 5559 var descendOnce$1 = function (element, offset) { 5560 var children$1 = children(element); 5561 if (children$1.length === 0) { 5562 return point$1(element, offset); 5563 } else if (offset < children$1.length) { 5564 return point$1(children$1[offset], 0); 5565 } else { 5566 var last = children$1[children$1.length - 1]; 5567 var len = isText$1(last) ? get$3(last).length : children(last).length; 5568 return point$1(last, len); 5569 } 5570 }; 5571 5572 var descendOnce = function (element, offset) { 5573 return isText$1(element) ? point$1(element, offset) : descendOnce$1(element, offset); 5574 }; 5575 var getAnchorSelection = function (win, anchorInfo) { 5576 var getSelection = anchorInfo.getSelection.getOrThunk(function () { 5577 return function () { 5578 return getExact(win); 5579 }; 5580 }); 5581 return getSelection().map(function (sel) { 5582 var modStart = descendOnce(sel.start, sel.soffset); 5583 var modFinish = descendOnce(sel.finish, sel.foffset); 5584 return SimSelection.range(modStart.element, modStart.offset, modFinish.element, modFinish.offset); 5585 }); 5586 }; 5587 var placement$1 = function (component, anchorInfo, origin) { 5588 var win = defaultView(anchorInfo.root).dom; 5589 var rootPoint = getRootPoint(component, origin, anchorInfo); 5590 var selectionBox = getAnchorSelection(win, anchorInfo).bind(function (sel) { 5591 var optRect = getBounds$1(win, SimSelection.exactFromRange(sel)).orThunk(function () { 5592 var x = SugarElement.fromText(zeroWidth); 5593 before$2(sel.start, x); 5594 var rect = getFirstRect(win, SimSelection.exact(x, 0, x, 1)); 5595 remove$5(x); 5596 return rect; 5597 }); 5598 return optRect.bind(function (rawRect) { 5599 return getBox(rawRect.left, rawRect.top, rawRect.width, rawRect.height); 5600 }); 5601 }); 5602 var targetElement = getAnchorSelection(win, anchorInfo).bind(function (sel) { 5603 return isElement$2(sel.start) ? Optional.some(sel.start) : parentNode(sel.start); 5604 }); 5605 var elem = targetElement.getOr(component.element); 5606 return calcNewAnchor(selectionBox, rootPoint, anchorInfo, origin, elem); 5607 }; 5608 var SelectionAnchor = [ 5609 option('getSelection'), 5610 required$1('root'), 5611 option('bubble'), 5612 schema$y(), 5613 defaulted('overrides', {}), 5614 defaulted('showAbove', false), 5615 output$1('placement', placement$1) 5616 ]; 5617 5618 var labelPrefix$1 = 'link-layout'; 5619 var eastX = function (anchor) { 5620 return anchor.x + anchor.width; 5621 }; 5622 var westX = function (anchor, element) { 5623 return anchor.x - element.width; 5624 }; 5625 var northY$1 = function (anchor, element) { 5626 return anchor.y - element.height + anchor.height; 5627 }; 5628 var southY$1 = function (anchor) { 5629 return anchor.y; 5630 }; 5631 var southeast$1 = function (anchor, element, bubbles) { 5632 return nu$6(eastX(anchor), southY$1(anchor), bubbles.southeast(), southeast$3(), 'southeast', boundsRestriction(anchor, { 5633 left: 0, 5634 top: 2 5635 }), labelPrefix$1); 5636 }; 5637 var southwest$1 = function (anchor, element, bubbles) { 5638 return nu$6(westX(anchor, element), southY$1(anchor), bubbles.southwest(), southwest$3(), 'southwest', boundsRestriction(anchor, { 5639 right: 1, 5640 top: 2 5641 }), labelPrefix$1); 5642 }; 5643 var northeast$1 = function (anchor, element, bubbles) { 5644 return nu$6(eastX(anchor), northY$1(anchor, element), bubbles.northeast(), northeast$3(), 'northeast', boundsRestriction(anchor, { 5645 left: 0, 5646 bottom: 3 5647 }), labelPrefix$1); 5648 }; 5649 var northwest$1 = function (anchor, element, bubbles) { 5650 return nu$6(westX(anchor, element), northY$1(anchor, element), bubbles.northwest(), northwest$3(), 'northwest', boundsRestriction(anchor, { 5651 right: 1, 5652 bottom: 3 5653 }), labelPrefix$1); 5654 }; 5655 var all = function () { 5656 return [ 5657 southeast$1, 5658 southwest$1, 5659 northeast$1, 5660 northwest$1 5661 ]; 5662 }; 5663 var allRtl = function () { 5664 return [ 5665 southwest$1, 5666 southeast$1, 5667 northwest$1, 5668 northeast$1 5669 ]; 5670 }; 5671 5672 var placement = function (component, submenuInfo, origin) { 5673 var anchorBox = toBox(origin, submenuInfo.item.element); 5674 var layouts = get$4(component.element, submenuInfo, all(), allRtl(), all(), allRtl(), Optional.none()); 5675 return Optional.some(nu$4({ 5676 anchorBox: anchorBox, 5677 bubble: fallback(), 5678 overrides: submenuInfo.overrides, 5679 layouts: layouts, 5680 placer: Optional.none() 5681 })); 5682 }; 5683 var SubmenuAnchor = [ 5684 required$1('item'), 5685 schema$y(), 5686 defaulted('overrides', {}), 5687 output$1('placement', placement) 5688 ]; 5689 5690 var AnchorSchema = choose$1('type', { 5691 selection: SelectionAnchor, 5692 node: NodeAnchor, 5693 hotspot: HotspotAnchor, 5694 submenu: SubmenuAnchor, 5695 makeshift: MakeshiftAnchor 5696 }); 5697 5698 var TransitionSchema = [ 5699 requiredArrayOf('classes', string), 5700 defaultedStringEnum('mode', 'all', [ 5701 'all', 5702 'layout', 5703 'placement' 5704 ]) 5705 ]; 5706 var PositionSchema = [ 5707 defaulted('useFixed', never), 5708 option('getBounds') 5709 ]; 5710 var PlacementSchema = [ 5711 requiredOf('anchor', AnchorSchema), 5712 optionObjOf('transition', TransitionSchema) 5713 ]; 5714 5715 var getFixedOrigin = function () { 5716 var html = document.documentElement; 5717 return fixed$1(0, 0, html.clientWidth, html.clientHeight); 5718 }; 5719 var getRelativeOrigin = function (component) { 5720 var position = absolute$3(component.element); 5721 var bounds = component.element.dom.getBoundingClientRect(); 5722 return relative$1(position.left, position.top, bounds.width, bounds.height); 5723 }; 5724 var place = function (component, origin, anchoring, getBounds, placee, lastPlace, transition) { 5725 var anchor = box(anchoring.anchorBox, origin); 5726 return simple(anchor, placee.element, anchoring.bubble, anchoring.layouts, lastPlace, getBounds, anchoring.overrides, transition); 5727 }; 5728 var position$1 = function (component, posConfig, posState, placee, placementSpec) { 5729 positionWithin(component, posConfig, posState, placee, placementSpec, Optional.none()); 5730 }; 5731 var positionWithin = function (component, posConfig, posState, placee, placementSpec, boxElement) { 5732 var boundsBox = boxElement.map(box$1); 5733 return positionWithinBounds(component, posConfig, posState, placee, placementSpec, boundsBox); 5734 }; 5735 var positionWithinBounds = function (component, posConfig, posState, placee, placementSpec, bounds) { 5736 var placeeDetail = asRawOrDie$1('placement.info', objOf(PlacementSchema), placementSpec); 5737 var anchorage = placeeDetail.anchor; 5738 var element = placee.element; 5739 var placeeState = posState.get(placee.uid); 5740 preserve$1(function () { 5741 set$7(element, 'position', 'fixed'); 5742 var oldVisibility = getRaw(element, 'visibility'); 5743 set$7(element, 'visibility', 'hidden'); 5744 var origin = posConfig.useFixed() ? getFixedOrigin() : getRelativeOrigin(component); 5745 var placer = anchorage.placement; 5746 var getBounds = bounds.map(constant$1).or(posConfig.getBounds); 5747 placer(component, anchorage, origin).each(function (anchoring) { 5748 var doPlace = anchoring.placer.getOr(place); 5749 var newState = doPlace(component, origin, anchoring, getBounds, placee, placeeState, placeeDetail.transition); 5750 posState.set(placee.uid, newState); 5751 }); 5752 oldVisibility.fold(function () { 5753 remove$6(element, 'visibility'); 5754 }, function (vis) { 5755 set$7(element, 'visibility', vis); 5756 }); 5757 if (getRaw(element, 'left').isNone() && getRaw(element, 'top').isNone() && getRaw(element, 'right').isNone() && getRaw(element, 'bottom').isNone() && is$1(getRaw(element, 'position'), 'fixed')) { 5758 remove$6(element, 'position'); 5759 } 5760 }, element); 5761 }; 5762 var getMode = function (component, pConfig, _pState) { 5763 return pConfig.useFixed() ? 'fixed' : 'absolute'; 5764 }; 5765 var reset$1 = function (component, pConfig, posState, placee) { 5766 var element = placee.element; 5767 each$1([ 5768 'position', 5769 'left', 5770 'right', 5771 'top', 5772 'bottom' 5773 ], function (prop) { 5774 return remove$6(element, prop); 5775 }); 5776 reset$2(element); 5777 posState.clear(placee.uid); 5778 }; 5779 5780 var PositionApis = /*#__PURE__*/Object.freeze({ 5781 __proto__: null, 5782 position: position$1, 5783 positionWithin: positionWithin, 5784 positionWithinBounds: positionWithinBounds, 5785 getMode: getMode, 5786 reset: reset$1 5787 }); 5788 5789 var init$g = function () { 5790 var state = {}; 5791 var set = function (id, data) { 5792 state[id] = data; 5793 }; 5794 var get = function (id) { 5795 return get$e(state, id); 5796 }; 5797 var clear = function (id) { 5798 if (isNonNullable(id)) { 5799 delete state[id]; 5800 } else { 5801 state = {}; 5802 } 5803 }; 5804 return nu$8({ 5805 readState: function () { 5806 return state; 5807 }, 5808 clear: clear, 5809 set: set, 5810 get: get 5811 }); 5812 }; 5813 5814 var PositioningState = /*#__PURE__*/Object.freeze({ 5815 __proto__: null, 5816 init: init$g 5817 }); 5818 5819 var Positioning = create$7({ 5820 fields: PositionSchema, 5821 name: 'positioning', 5822 active: ActivePosition, 5823 apis: PositionApis, 5824 state: PositioningState 5825 }); 5826 5827 var fireDetaching = function (component) { 5828 emit(component, detachedFromDom()); 5829 var children = component.components(); 5830 each$1(children, fireDetaching); 5831 }; 5832 var fireAttaching = function (component) { 5833 var children = component.components(); 5834 each$1(children, fireAttaching); 5835 emit(component, attachedToDom()); 5836 }; 5837 var attach$1 = function (parent, child) { 5838 append$2(parent.element, child.element); 5839 }; 5840 var detachChildren$1 = function (component) { 5841 each$1(component.components(), function (childComp) { 5842 return remove$5(childComp.element); 5843 }); 5844 empty(component.element); 5845 component.syncComponents(); 5846 }; 5847 var replaceChildren = function (component, newChildren) { 5848 var subs = component.components(); 5849 detachChildren$1(component); 5850 var deleted = difference(subs, newChildren); 5851 each$1(deleted, function (comp) { 5852 fireDetaching(comp); 5853 component.getSystem().removeFromWorld(comp); 5854 }); 5855 each$1(newChildren, function (childComp) { 5856 if (!childComp.getSystem().isConnected()) { 5857 component.getSystem().addToWorld(childComp); 5858 attach$1(component, childComp); 5859 if (inBody(component.element)) { 5860 fireAttaching(childComp); 5861 } 5862 } else { 5863 attach$1(component, childComp); 5864 } 5865 component.syncComponents(); 5866 }); 5867 }; 5868 5869 var attach = function (parent, child) { 5870 attachWith(parent, child, append$2); 5871 }; 5872 var attachWith = function (parent, child, insertion) { 5873 parent.getSystem().addToWorld(child); 5874 insertion(parent.element, child.element); 5875 if (inBody(parent.element)) { 5876 fireAttaching(child); 5877 } 5878 parent.syncComponents(); 5879 }; 5880 var doDetach = function (component) { 5881 fireDetaching(component); 5882 remove$5(component.element); 5883 component.getSystem().removeFromWorld(component); 5884 }; 5885 var detach = function (component) { 5886 var parent$1 = parent(component.element).bind(function (p) { 5887 return component.getSystem().getByDom(p).toOptional(); 5888 }); 5889 doDetach(component); 5890 parent$1.each(function (p) { 5891 p.syncComponents(); 5892 }); 5893 }; 5894 var detachChildren = function (component) { 5895 var subs = component.components(); 5896 each$1(subs, doDetach); 5897 empty(component.element); 5898 component.syncComponents(); 5899 }; 5900 var attachSystem = function (element, guiSystem) { 5901 attachSystemWith(element, guiSystem, append$2); 5902 }; 5903 var attachSystemAfter = function (element, guiSystem) { 5904 attachSystemWith(element, guiSystem, after$2); 5905 }; 5906 var attachSystemWith = function (element, guiSystem, inserter) { 5907 inserter(element, guiSystem.element); 5908 var children$1 = children(guiSystem.element); 5909 each$1(children$1, function (child) { 5910 guiSystem.getByDom(child).each(fireAttaching); 5911 }); 5912 }; 5913 var detachSystem = function (guiSystem) { 5914 var children$1 = children(guiSystem.element); 5915 each$1(children$1, function (child) { 5916 guiSystem.getByDom(child).each(fireDetaching); 5917 }); 5918 remove$5(guiSystem.element); 5919 }; 5920 5921 var rebuild = function (sandbox, sConfig, sState, data) { 5922 sState.get().each(function (_data) { 5923 detachChildren(sandbox); 5924 }); 5925 var point = sConfig.getAttachPoint(sandbox); 5926 attach(point, sandbox); 5927 var built = sandbox.getSystem().build(data); 5928 attach(sandbox, built); 5929 sState.set(built); 5930 return built; 5931 }; 5932 var open$1 = function (sandbox, sConfig, sState, data) { 5933 var newState = rebuild(sandbox, sConfig, sState, data); 5934 sConfig.onOpen(sandbox, newState); 5935 return newState; 5936 }; 5937 var setContent = function (sandbox, sConfig, sState, data) { 5938 return sState.get().map(function () { 5939 return rebuild(sandbox, sConfig, sState, data); 5940 }); 5941 }; 5942 var openWhileCloaked = function (sandbox, sConfig, sState, data, transaction) { 5943 cloak(sandbox, sConfig); 5944 open$1(sandbox, sConfig, sState, data); 5945 transaction(); 5946 decloak(sandbox, sConfig); 5947 }; 5948 var close$1 = function (sandbox, sConfig, sState) { 5949 sState.get().each(function (data) { 5950 detachChildren(sandbox); 5951 detach(sandbox); 5952 sConfig.onClose(sandbox, data); 5953 sState.clear(); 5954 }); 5955 }; 5956 var isOpen$1 = function (_sandbox, _sConfig, sState) { 5957 return sState.isOpen(); 5958 }; 5959 var isPartOf = function (sandbox, sConfig, sState, queryElem) { 5960 return isOpen$1(sandbox, sConfig, sState) && sState.get().exists(function (data) { 5961 return sConfig.isPartOf(sandbox, data, queryElem); 5962 }); 5963 }; 5964 var getState$2 = function (_sandbox, _sConfig, sState) { 5965 return sState.get(); 5966 }; 5967 var store = function (sandbox, cssKey, attr, newValue) { 5968 getRaw(sandbox.element, cssKey).fold(function () { 5969 remove$7(sandbox.element, attr); 5970 }, function (v) { 5971 set$8(sandbox.element, attr, v); 5972 }); 5973 set$7(sandbox.element, cssKey, newValue); 5974 }; 5975 var restore = function (sandbox, cssKey, attr) { 5976 getOpt(sandbox.element, attr).fold(function () { 5977 return remove$6(sandbox.element, cssKey); 5978 }, function (oldValue) { 5979 return set$7(sandbox.element, cssKey, oldValue); 5980 }); 5981 }; 5982 var cloak = function (sandbox, sConfig, _sState) { 5983 var sink = sConfig.getAttachPoint(sandbox); 5984 set$7(sandbox.element, 'position', Positioning.getMode(sink)); 5985 store(sandbox, 'visibility', sConfig.cloakVisibilityAttr, 'hidden'); 5986 }; 5987 var hasPosition = function (element) { 5988 return exists([ 5989 'top', 5990 'left', 5991 'right', 5992 'bottom' 5993 ], function (pos) { 5994 return getRaw(element, pos).isSome(); 5995 }); 5996 }; 5997 var decloak = function (sandbox, sConfig, _sState) { 5998 if (!hasPosition(sandbox.element)) { 5999 remove$6(sandbox.element, 'position'); 6000 } 6001 restore(sandbox, 'visibility', sConfig.cloakVisibilityAttr); 6002 }; 6003 6004 var SandboxApis = /*#__PURE__*/Object.freeze({ 6005 __proto__: null, 6006 cloak: cloak, 6007 decloak: decloak, 6008 open: open$1, 6009 openWhileCloaked: openWhileCloaked, 6010 close: close$1, 6011 isOpen: isOpen$1, 6012 isPartOf: isPartOf, 6013 getState: getState$2, 6014 setContent: setContent 6015 }); 6016 6017 var events$g = function (sandboxConfig, sandboxState) { 6018 return derive$2([run$1(sandboxClose(), function (sandbox, _simulatedEvent) { 6019 close$1(sandbox, sandboxConfig, sandboxState); 6020 })]); 6021 }; 6022 6023 var ActiveSandbox = /*#__PURE__*/Object.freeze({ 6024 __proto__: null, 6025 events: events$g 6026 }); 6027 6028 var SandboxSchema = [ 6029 onHandler('onOpen'), 6030 onHandler('onClose'), 6031 required$1('isPartOf'), 6032 required$1('getAttachPoint'), 6033 defaulted('cloakVisibilityAttr', 'data-precloak-visibility') 6034 ]; 6035 6036 var init$f = function () { 6037 var contents = value$1(); 6038 var readState = constant$1('not-implemented'); 6039 return nu$8({ 6040 readState: readState, 6041 isOpen: contents.isSet, 6042 clear: contents.clear, 6043 set: contents.set, 6044 get: contents.get 6045 }); 6046 }; 6047 6048 var SandboxState = /*#__PURE__*/Object.freeze({ 6049 __proto__: null, 6050 init: init$f 6051 }); 6052 6053 var Sandboxing = create$7({ 6054 fields: SandboxSchema, 6055 name: 'sandboxing', 6056 active: ActiveSandbox, 6057 apis: SandboxApis, 6058 state: SandboxState 6059 }); 6060 6061 var dismissPopups = constant$1('dismiss.popups'); 6062 var repositionPopups = constant$1('reposition.popups'); 6063 var mouseReleased = constant$1('mouse.released'); 6064 6065 var schema$x = objOfOnly([ 6066 defaulted('isExtraPart', never), 6067 optionObjOf('fireEventInstead', [defaulted('event', dismissRequested())]) 6068 ]); 6069 var receivingChannel$1 = function (rawSpec) { 6070 var _a; 6071 var detail = asRawOrDie$1('Dismissal', schema$x, rawSpec); 6072 return _a = {}, _a[dismissPopups()] = { 6073 schema: objOfOnly([required$1('target')]), 6074 onReceive: function (sandbox, data) { 6075 if (Sandboxing.isOpen(sandbox)) { 6076 var isPart = Sandboxing.isPartOf(sandbox, data.target) || detail.isExtraPart(sandbox, data.target); 6077 if (!isPart) { 6078 detail.fireEventInstead.fold(function () { 6079 return Sandboxing.close(sandbox); 6080 }, function (fe) { 6081 return emit(sandbox, fe.event); 6082 }); 6083 } 6084 } 6085 } 6086 }, _a; 6087 }; 6088 6089 var schema$w = objOfOnly([ 6090 optionObjOf('fireEventInstead', [defaulted('event', repositionRequested())]), 6091 requiredFunction('doReposition') 6092 ]); 6093 var receivingChannel = function (rawSpec) { 6094 var _a; 6095 var detail = asRawOrDie$1('Reposition', schema$w, rawSpec); 6096 return _a = {}, _a[repositionPopups()] = { 6097 onReceive: function (sandbox) { 6098 if (Sandboxing.isOpen(sandbox)) { 6099 detail.fireEventInstead.fold(function () { 6100 return detail.doReposition(sandbox); 6101 }, function (fe) { 6102 return emit(sandbox, fe.event); 6103 }); 6104 } 6105 } 6106 }, _a; 6107 }; 6108 6109 var onLoad$5 = function (component, repConfig, repState) { 6110 repConfig.store.manager.onLoad(component, repConfig, repState); 6111 }; 6112 var onUnload$2 = function (component, repConfig, repState) { 6113 repConfig.store.manager.onUnload(component, repConfig, repState); 6114 }; 6115 var setValue$3 = function (component, repConfig, repState, data) { 6116 repConfig.store.manager.setValue(component, repConfig, repState, data); 6117 }; 6118 var getValue$3 = function (component, repConfig, repState) { 6119 return repConfig.store.manager.getValue(component, repConfig, repState); 6120 }; 6121 var getState$1 = function (component, repConfig, repState) { 6122 return repState; 6123 }; 6124 6125 var RepresentApis = /*#__PURE__*/Object.freeze({ 6126 __proto__: null, 6127 onLoad: onLoad$5, 6128 onUnload: onUnload$2, 6129 setValue: setValue$3, 6130 getValue: getValue$3, 6131 getState: getState$1 6132 }); 6133 6134 var events$f = function (repConfig, repState) { 6135 var es = repConfig.resetOnDom ? [ 6136 runOnAttached(function (comp, _se) { 6137 onLoad$5(comp, repConfig, repState); 6138 }), 6139 runOnDetached(function (comp, _se) { 6140 onUnload$2(comp, repConfig, repState); 6141 }) 6142 ] : [loadEvent(repConfig, repState, onLoad$5)]; 6143 return derive$2(es); 6144 }; 6145 6146 var ActiveRepresenting = /*#__PURE__*/Object.freeze({ 6147 __proto__: null, 6148 events: events$f 6149 }); 6150 6151 var memory$1 = function () { 6152 var data = Cell(null); 6153 var readState = function () { 6154 return { 6155 mode: 'memory', 6156 value: data.get() 6157 }; 6158 }; 6159 var isNotSet = function () { 6160 return data.get() === null; 6161 }; 6162 var clear = function () { 6163 data.set(null); 6164 }; 6165 return nu$8({ 6166 set: data.set, 6167 get: data.get, 6168 isNotSet: isNotSet, 6169 clear: clear, 6170 readState: readState 6171 }); 6172 }; 6173 var manual = function () { 6174 var readState = noop; 6175 return nu$8({ readState: readState }); 6176 }; 6177 var dataset = function () { 6178 var dataByValue = Cell({}); 6179 var dataByText = Cell({}); 6180 var readState = function () { 6181 return { 6182 mode: 'dataset', 6183 dataByValue: dataByValue.get(), 6184 dataByText: dataByText.get() 6185 }; 6186 }; 6187 var clear = function () { 6188 dataByValue.set({}); 6189 dataByText.set({}); 6190 }; 6191 var lookup = function (itemString) { 6192 return get$e(dataByValue.get(), itemString).orThunk(function () { 6193 return get$e(dataByText.get(), itemString); 6194 }); 6195 }; 6196 var update = function (items) { 6197 var currentDataByValue = dataByValue.get(); 6198 var currentDataByText = dataByText.get(); 6199 var newDataByValue = {}; 6200 var newDataByText = {}; 6201 each$1(items, function (item) { 6202 newDataByValue[item.value] = item; 6203 get$e(item, 'meta').each(function (meta) { 6204 get$e(meta, 'text').each(function (text) { 6205 newDataByText[text] = item; 6206 }); 6207 }); 6208 }); 6209 dataByValue.set(__assign(__assign({}, currentDataByValue), newDataByValue)); 6210 dataByText.set(__assign(__assign({}, currentDataByText), newDataByText)); 6211 }; 6212 return nu$8({ 6213 readState: readState, 6214 lookup: lookup, 6215 update: update, 6216 clear: clear 6217 }); 6218 }; 6219 var init$e = function (spec) { 6220 return spec.store.manager.state(spec); 6221 }; 6222 6223 var RepresentState = /*#__PURE__*/Object.freeze({ 6224 __proto__: null, 6225 memory: memory$1, 6226 dataset: dataset, 6227 manual: manual, 6228 init: init$e 6229 }); 6230 6231 var setValue$2 = function (component, repConfig, repState, data) { 6232 var store = repConfig.store; 6233 repState.update([data]); 6234 store.setValue(component, data); 6235 repConfig.onSetValue(component, data); 6236 }; 6237 var getValue$2 = function (component, repConfig, repState) { 6238 var store = repConfig.store; 6239 var key = store.getDataKey(component); 6240 return repState.lookup(key).getOrThunk(function () { 6241 return store.getFallbackEntry(key); 6242 }); 6243 }; 6244 var onLoad$4 = function (component, repConfig, repState) { 6245 var store = repConfig.store; 6246 store.initialValue.each(function (data) { 6247 setValue$2(component, repConfig, repState, data); 6248 }); 6249 }; 6250 var onUnload$1 = function (component, repConfig, repState) { 6251 repState.clear(); 6252 }; 6253 var DatasetStore = [ 6254 option('initialValue'), 6255 required$1('getFallbackEntry'), 6256 required$1('getDataKey'), 6257 required$1('setValue'), 6258 output$1('manager', { 6259 setValue: setValue$2, 6260 getValue: getValue$2, 6261 onLoad: onLoad$4, 6262 onUnload: onUnload$1, 6263 state: dataset 6264 }) 6265 ]; 6266 6267 var getValue$1 = function (component, repConfig, _repState) { 6268 return repConfig.store.getValue(component); 6269 }; 6270 var setValue$1 = function (component, repConfig, _repState, data) { 6271 repConfig.store.setValue(component, data); 6272 repConfig.onSetValue(component, data); 6273 }; 6274 var onLoad$3 = function (component, repConfig, _repState) { 6275 repConfig.store.initialValue.each(function (data) { 6276 repConfig.store.setValue(component, data); 6277 }); 6278 }; 6279 var ManualStore = [ 6280 required$1('getValue'), 6281 defaulted('setValue', noop), 6282 option('initialValue'), 6283 output$1('manager', { 6284 setValue: setValue$1, 6285 getValue: getValue$1, 6286 onLoad: onLoad$3, 6287 onUnload: noop, 6288 state: NoState.init 6289 }) 6290 ]; 6291 6292 var setValue = function (component, repConfig, repState, data) { 6293 repState.set(data); 6294 repConfig.onSetValue(component, data); 6295 }; 6296 var getValue = function (component, repConfig, repState) { 6297 return repState.get(); 6298 }; 6299 var onLoad$2 = function (component, repConfig, repState) { 6300 repConfig.store.initialValue.each(function (initVal) { 6301 if (repState.isNotSet()) { 6302 repState.set(initVal); 6303 } 6304 }); 6305 }; 6306 var onUnload = function (component, repConfig, repState) { 6307 repState.clear(); 6308 }; 6309 var MemoryStore = [ 6310 option('initialValue'), 6311 output$1('manager', { 6312 setValue: setValue, 6313 getValue: getValue, 6314 onLoad: onLoad$2, 6315 onUnload: onUnload, 6316 state: memory$1 6317 }) 6318 ]; 6319 6320 var RepresentSchema = [ 6321 defaultedOf('store', { mode: 'memory' }, choose$1('mode', { 6322 memory: MemoryStore, 6323 manual: ManualStore, 6324 dataset: DatasetStore 6325 })), 6326 onHandler('onSetValue'), 6327 defaulted('resetOnDom', false) 6328 ]; 6329 6330 var Representing = create$7({ 6331 fields: RepresentSchema, 6332 name: 'representing', 6333 active: ActiveRepresenting, 6334 apis: RepresentApis, 6335 extra: { 6336 setValueFrom: function (component, source) { 6337 var value = Representing.getValue(source); 6338 Representing.setValue(component, value); 6339 } 6340 }, 6341 state: RepresentState 6342 }); 6343 6344 var field = function (name, forbidden) { 6345 return defaultedObjOf(name, {}, map$2(forbidden, function (f) { 6346 return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name); 6347 }).concat([customField('dump', identity$1)])); 6348 }; 6349 var get$2 = function (data) { 6350 return data.dump; 6351 }; 6352 var augment = function (data, original) { 6353 return __assign(__assign({}, derive$1(original)), data.dump); 6354 }; 6355 var SketchBehaviours = { 6356 field: field, 6357 augment: augment, 6358 get: get$2 6359 }; 6360 6361 var _placeholder = 'placeholder'; 6362 var adt$3 = Adt.generate([ 6363 { 6364 single: [ 6365 'required', 6366 'valueThunk' 6367 ] 6368 }, 6369 { 6370 multiple: [ 6371 'required', 6372 'valueThunks' 6373 ] 6374 } 6375 ]); 6376 var isSubstituted = function (spec) { 6377 return has$2(spec, 'uiType'); 6378 }; 6379 var subPlaceholder = function (owner, detail, compSpec, placeholders) { 6380 if (owner.exists(function (o) { 6381 return o !== compSpec.owner; 6382 })) { 6383 return adt$3.single(true, constant$1(compSpec)); 6384 } 6385 return get$e(placeholders, compSpec.name).fold(function () { 6386 throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + JSON.stringify(compSpec, null, 2)); 6387 }, function (newSpec) { 6388 return newSpec.replace(); 6389 }); 6390 }; 6391 var scan = function (owner, detail, compSpec, placeholders) { 6392 if (isSubstituted(compSpec) && compSpec.uiType === _placeholder) { 6393 return subPlaceholder(owner, detail, compSpec, placeholders); 6394 } else { 6395 return adt$3.single(false, constant$1(compSpec)); 6396 } 6397 }; 6398 var substitute = function (owner, detail, compSpec, placeholders) { 6399 var base = scan(owner, detail, compSpec, placeholders); 6400 return base.fold(function (req, valueThunk) { 6401 var value = isSubstituted(compSpec) ? valueThunk(detail, compSpec.config, compSpec.validated) : valueThunk(detail); 6402 var childSpecs = get$e(value, 'components').getOr([]); 6403 var substituted = bind$3(childSpecs, function (c) { 6404 return substitute(owner, detail, c, placeholders); 6405 }); 6406 return [__assign(__assign({}, value), { components: substituted })]; 6407 }, function (req, valuesThunk) { 6408 if (isSubstituted(compSpec)) { 6409 var values = valuesThunk(detail, compSpec.config, compSpec.validated); 6410 var preprocessor = compSpec.validated.preprocess.getOr(identity$1); 6411 return preprocessor(values); 6412 } else { 6413 return valuesThunk(detail); 6414 } 6415 }); 6416 }; 6417 var substituteAll = function (owner, detail, components, placeholders) { 6418 return bind$3(components, function (c) { 6419 return substitute(owner, detail, c, placeholders); 6420 }); 6421 }; 6422 var oneReplace = function (label, replacements) { 6423 var called = false; 6424 var used = function () { 6425 return called; 6426 }; 6427 var replace = function () { 6428 if (called) { 6429 throw new Error('Trying to use the same placeholder more than once: ' + label); 6430 } 6431 called = true; 6432 return replacements; 6433 }; 6434 var required = function () { 6435 return replacements.fold(function (req, _) { 6436 return req; 6437 }, function (req, _) { 6438 return req; 6439 }); 6440 }; 6441 return { 6442 name: constant$1(label), 6443 required: required, 6444 used: used, 6445 replace: replace 6446 }; 6447 }; 6448 var substitutePlaces = function (owner, detail, components, placeholders) { 6449 var ps = map$1(placeholders, function (ph, name) { 6450 return oneReplace(name, ph); 6451 }); 6452 var outcome = substituteAll(owner, detail, components, ps); 6453 each(ps, function (p) { 6454 if (p.used() === false && p.required()) { 6455 throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + JSON.stringify(detail.components, null, 2)); 6456 } 6457 }); 6458 return outcome; 6459 }; 6460 var single$2 = adt$3.single; 6461 var multiple = adt$3.multiple; 6462 var placeholder = constant$1(_placeholder); 6463 6464 var adt$2 = Adt.generate([ 6465 { required: ['data'] }, 6466 { external: ['data'] }, 6467 { optional: ['data'] }, 6468 { group: ['data'] } 6469 ]); 6470 var fFactory = defaulted('factory', { sketch: identity$1 }); 6471 var fSchema = defaulted('schema', []); 6472 var fName = required$1('name'); 6473 var fPname = field$1('pname', 'pname', defaultedThunk(function (typeSpec) { 6474 return '<alloy.' + generate$6(typeSpec.name) + '>'; 6475 }), anyValue()); 6476 var fGroupSchema = customField('schema', function () { 6477 return [option('preprocess')]; 6478 }); 6479 var fDefaults = defaulted('defaults', constant$1({})); 6480 var fOverrides = defaulted('overrides', constant$1({})); 6481 var requiredSpec = objOf([ 6482 fFactory, 6483 fSchema, 6484 fName, 6485 fPname, 6486 fDefaults, 6487 fOverrides 6488 ]); 6489 var externalSpec = objOf([ 6490 fFactory, 6491 fSchema, 6492 fName, 6493 fDefaults, 6494 fOverrides 6495 ]); 6496 var optionalSpec = objOf([ 6497 fFactory, 6498 fSchema, 6499 fName, 6500 fPname, 6501 fDefaults, 6502 fOverrides 6503 ]); 6504 var groupSpec = objOf([ 6505 fFactory, 6506 fGroupSchema, 6507 fName, 6508 required$1('unit'), 6509 fPname, 6510 fDefaults, 6511 fOverrides 6512 ]); 6513 var asNamedPart = function (part) { 6514 return part.fold(Optional.some, Optional.none, Optional.some, Optional.some); 6515 }; 6516 var name$1 = function (part) { 6517 var get = function (data) { 6518 return data.name; 6519 }; 6520 return part.fold(get, get, get, get); 6521 }; 6522 var asCommon = function (part) { 6523 return part.fold(identity$1, identity$1, identity$1, identity$1); 6524 }; 6525 var convert = function (adtConstructor, partSchema) { 6526 return function (spec) { 6527 var data = asRawOrDie$1('Converting part type', partSchema, spec); 6528 return adtConstructor(data); 6529 }; 6530 }; 6531 var required = convert(adt$2.required, requiredSpec); 6532 var external$1 = convert(adt$2.external, externalSpec); 6533 var optional = convert(adt$2.optional, optionalSpec); 6534 var group = convert(adt$2.group, groupSpec); 6535 var original = constant$1('entirety'); 6536 6537 var PartType = /*#__PURE__*/Object.freeze({ 6538 __proto__: null, 6539 required: required, 6540 external: external$1, 6541 optional: optional, 6542 group: group, 6543 asNamedPart: asNamedPart, 6544 name: name$1, 6545 asCommon: asCommon, 6546 original: original 6547 }); 6548 6549 var combine = function (detail, data, partSpec, partValidated) { 6550 return deepMerge(data.defaults(detail, partSpec, partValidated), partSpec, { uid: detail.partUids[data.name] }, data.overrides(detail, partSpec, partValidated)); 6551 }; 6552 var subs = function (owner, detail, parts) { 6553 var internals = {}; 6554 var externals = {}; 6555 each$1(parts, function (part) { 6556 part.fold(function (data) { 6557 internals[data.pname] = single$2(true, function (detail, partSpec, partValidated) { 6558 return data.factory.sketch(combine(detail, data, partSpec, partValidated)); 6559 }); 6560 }, function (data) { 6561 var partSpec = detail.parts[data.name]; 6562 externals[data.name] = constant$1(data.factory.sketch(combine(detail, data, partSpec[original()]), partSpec)); 6563 }, function (data) { 6564 internals[data.pname] = single$2(false, function (detail, partSpec, partValidated) { 6565 return data.factory.sketch(combine(detail, data, partSpec, partValidated)); 6566 }); 6567 }, function (data) { 6568 internals[data.pname] = multiple(true, function (detail, _partSpec, _partValidated) { 6569 var units = detail[data.name]; 6570 return map$2(units, function (u) { 6571 return data.factory.sketch(deepMerge(data.defaults(detail, u, _partValidated), u, data.overrides(detail, u))); 6572 }); 6573 }); 6574 }); 6575 }); 6576 return { 6577 internals: constant$1(internals), 6578 externals: constant$1(externals) 6579 }; 6580 }; 6581 6582 var generate$3 = function (owner, parts) { 6583 var r = {}; 6584 each$1(parts, function (part) { 6585 asNamedPart(part).each(function (np) { 6586 var g = doGenerateOne(owner, np.pname); 6587 r[np.name] = function (config) { 6588 var validated = asRawOrDie$1('Part: ' + np.name + ' in ' + owner, objOf(np.schema), config); 6589 return __assign(__assign({}, g), { 6590 config: config, 6591 validated: validated 6592 }); 6593 }; 6594 }); 6595 }); 6596 return r; 6597 }; 6598 var doGenerateOne = function (owner, pname) { 6599 return { 6600 uiType: placeholder(), 6601 owner: owner, 6602 name: pname 6603 }; 6604 }; 6605 var generateOne$1 = function (owner, pname, config) { 6606 return { 6607 uiType: placeholder(), 6608 owner: owner, 6609 name: pname, 6610 config: config, 6611 validated: {} 6612 }; 6613 }; 6614 var schemas = function (parts) { 6615 return bind$3(parts, function (part) { 6616 return part.fold(Optional.none, Optional.some, Optional.none, Optional.none).map(function (data) { 6617 return requiredObjOf(data.name, data.schema.concat([snapshot(original())])); 6618 }).toArray(); 6619 }); 6620 }; 6621 var names = function (parts) { 6622 return map$2(parts, name$1); 6623 }; 6624 var substitutes = function (owner, detail, parts) { 6625 return subs(owner, detail, parts); 6626 }; 6627 var components$1 = function (owner, detail, internals) { 6628 return substitutePlaces(Optional.some(owner), detail, detail.components, internals); 6629 }; 6630 var getPart = function (component, detail, partKey) { 6631 var uid = detail.partUids[partKey]; 6632 return component.getSystem().getByUid(uid).toOptional(); 6633 }; 6634 var getPartOrDie = function (component, detail, partKey) { 6635 return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey); 6636 }; 6637 var getParts = function (component, detail, partKeys) { 6638 var r = {}; 6639 var uids = detail.partUids; 6640 var system = component.getSystem(); 6641 each$1(partKeys, function (pk) { 6642 r[pk] = constant$1(system.getByUid(uids[pk])); 6643 }); 6644 return r; 6645 }; 6646 var getAllParts = function (component, detail) { 6647 var system = component.getSystem(); 6648 return map$1(detail.partUids, function (pUid, _k) { 6649 return constant$1(system.getByUid(pUid)); 6650 }); 6651 }; 6652 var getAllPartNames = function (detail) { 6653 return keys(detail.partUids); 6654 }; 6655 var getPartsOrDie = function (component, detail, partKeys) { 6656 var r = {}; 6657 var uids = detail.partUids; 6658 var system = component.getSystem(); 6659 each$1(partKeys, function (pk) { 6660 r[pk] = constant$1(system.getByUid(uids[pk]).getOrDie()); 6661 }); 6662 return r; 6663 }; 6664 var defaultUids = function (baseUid, partTypes) { 6665 var partNames = names(partTypes); 6666 return wrapAll(map$2(partNames, function (pn) { 6667 return { 6668 key: pn, 6669 value: baseUid + '-' + pn 6670 }; 6671 })); 6672 }; 6673 var defaultUidsSchema = function (partTypes) { 6674 return field$1('partUids', 'partUids', mergeWithThunk(function (spec) { 6675 return defaultUids(spec.uid, partTypes); 6676 }), anyValue()); 6677 }; 6678 6679 var AlloyParts = /*#__PURE__*/Object.freeze({ 6680 __proto__: null, 6681 generate: generate$3, 6682 generateOne: generateOne$1, 6683 schemas: schemas, 6684 names: names, 6685 substitutes: substitutes, 6686 components: components$1, 6687 defaultUids: defaultUids, 6688 defaultUidsSchema: defaultUidsSchema, 6689 getAllParts: getAllParts, 6690 getAllPartNames: getAllPartNames, 6691 getPart: getPart, 6692 getPartOrDie: getPartOrDie, 6693 getParts: getParts, 6694 getPartsOrDie: getPartsOrDie 6695 }); 6696 6697 var base = function (partSchemas, partUidsSchemas) { 6698 var ps = partSchemas.length > 0 ? [requiredObjOf('parts', partSchemas)] : []; 6699 return ps.concat([ 6700 required$1('uid'), 6701 defaulted('dom', {}), 6702 defaulted('components', []), 6703 snapshot('originalSpec'), 6704 defaulted('debug.sketcher', {}) 6705 ]).concat(partUidsSchemas); 6706 }; 6707 var asRawOrDie = function (label, schema, spec, partSchemas, partUidsSchemas) { 6708 var baseS = base(partSchemas, partUidsSchemas); 6709 return asRawOrDie$1(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec); 6710 }; 6711 6712 var single$1 = function (owner, schema, factory, spec) { 6713 var specWithUid = supplyUid(spec); 6714 var detail = asRawOrDie(owner, schema, specWithUid, [], []); 6715 return factory(detail, specWithUid); 6716 }; 6717 var composite$1 = function (owner, schema, partTypes, factory, spec) { 6718 var specWithUid = supplyUid(spec); 6719 var partSchemas = schemas(partTypes); 6720 var partUidsSchema = defaultUidsSchema(partTypes); 6721 var detail = asRawOrDie(owner, schema, specWithUid, partSchemas, [partUidsSchema]); 6722 var subs = substitutes(owner, detail, partTypes); 6723 var components = components$1(owner, detail, subs.internals()); 6724 return factory(detail, components, specWithUid, subs.externals()); 6725 }; 6726 var hasUid = function (spec) { 6727 return has$2(spec, 'uid'); 6728 }; 6729 var supplyUid = function (spec) { 6730 return hasUid(spec) ? spec : __assign(__assign({}, spec), { uid: generate$5('uid') }); 6731 }; 6732 6733 var isSketchSpec = function (spec) { 6734 return spec.uid !== undefined; 6735 }; 6736 var singleSchema = objOfOnly([ 6737 required$1('name'), 6738 required$1('factory'), 6739 required$1('configFields'), 6740 defaulted('apis', {}), 6741 defaulted('extraApis', {}) 6742 ]); 6743 var compositeSchema = objOfOnly([ 6744 required$1('name'), 6745 required$1('factory'), 6746 required$1('configFields'), 6747 required$1('partFields'), 6748 defaulted('apis', {}), 6749 defaulted('extraApis', {}) 6750 ]); 6751 var single = function (rawConfig) { 6752 var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, singleSchema, rawConfig); 6753 var sketch = function (spec) { 6754 return single$1(config.name, config.configFields, config.factory, spec); 6755 }; 6756 var apis = map$1(config.apis, makeApi); 6757 var extraApis = map$1(config.extraApis, function (f, k) { 6758 return markAsExtraApi(f, k); 6759 }); 6760 return __assign(__assign({ 6761 name: config.name, 6762 configFields: config.configFields, 6763 sketch: sketch 6764 }, apis), extraApis); 6765 }; 6766 var composite = function (rawConfig) { 6767 var config = asRawOrDie$1('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig); 6768 var sketch = function (spec) { 6769 return composite$1(config.name, config.configFields, config.partFields, config.factory, spec); 6770 }; 6771 var parts = generate$3(config.name, config.partFields); 6772 var apis = map$1(config.apis, makeApi); 6773 var extraApis = map$1(config.extraApis, function (f, k) { 6774 return markAsExtraApi(f, k); 6775 }); 6776 return __assign(__assign({ 6777 name: config.name, 6778 partFields: config.partFields, 6779 configFields: config.configFields, 6780 sketch: sketch, 6781 parts: parts 6782 }, apis), extraApis); 6783 }; 6784 6785 var inside = function (target) { 6786 return name$2(target) === 'input' && get$d(target, 'type') !== 'radio' || name$2(target) === 'textarea'; 6787 }; 6788 6789 var getCurrent = function (component, composeConfig, _composeState) { 6790 return composeConfig.find(component); 6791 }; 6792 6793 var ComposeApis = /*#__PURE__*/Object.freeze({ 6794 __proto__: null, 6795 getCurrent: getCurrent 6796 }); 6797 6798 var ComposeSchema = [required$1('find')]; 6799 6800 var Composing = create$7({ 6801 fields: ComposeSchema, 6802 name: 'composing', 6803 apis: ComposeApis 6804 }); 6805 6806 var nativeDisabled = [ 6807 'input', 6808 'button', 6809 'textarea', 6810 'select' 6811 ]; 6812 var onLoad$1 = function (component, disableConfig, disableState) { 6813 var f = disableConfig.disabled() ? disable$1 : enable$1; 6814 f(component, disableConfig); 6815 }; 6816 var hasNative = function (component, config) { 6817 return config.useNative === true && contains$2(nativeDisabled, name$2(component.element)); 6818 }; 6819 var nativeIsDisabled = function (component) { 6820 return has$1(component.element, 'disabled'); 6821 }; 6822 var nativeDisable = function (component) { 6823 set$8(component.element, 'disabled', 'disabled'); 6824 }; 6825 var nativeEnable = function (component) { 6826 remove$7(component.element, 'disabled'); 6827 }; 6828 var ariaIsDisabled = function (component) { 6829 return get$d(component.element, 'aria-disabled') === 'true'; 6830 }; 6831 var ariaDisable = function (component) { 6832 set$8(component.element, 'aria-disabled', 'true'); 6833 }; 6834 var ariaEnable = function (component) { 6835 set$8(component.element, 'aria-disabled', 'false'); 6836 }; 6837 var disable$1 = function (component, disableConfig, _disableState) { 6838 disableConfig.disableClass.each(function (disableClass) { 6839 add$2(component.element, disableClass); 6840 }); 6841 var f = hasNative(component, disableConfig) ? nativeDisable : ariaDisable; 6842 f(component); 6843 disableConfig.onDisabled(component); 6844 }; 6845 var enable$1 = function (component, disableConfig, _disableState) { 6846 disableConfig.disableClass.each(function (disableClass) { 6847 remove$2(component.element, disableClass); 6848 }); 6849 var f = hasNative(component, disableConfig) ? nativeEnable : ariaEnable; 6850 f(component); 6851 disableConfig.onEnabled(component); 6852 }; 6853 var isDisabled = function (component, disableConfig) { 6854 return hasNative(component, disableConfig) ? nativeIsDisabled(component) : ariaIsDisabled(component); 6855 }; 6856 var set$3 = function (component, disableConfig, disableState, disabled) { 6857 var f = disabled ? disable$1 : enable$1; 6858 f(component, disableConfig); 6859 }; 6860 6861 var DisableApis = /*#__PURE__*/Object.freeze({ 6862 __proto__: null, 6863 enable: enable$1, 6864 disable: disable$1, 6865 isDisabled: isDisabled, 6866 onLoad: onLoad$1, 6867 set: set$3 6868 }); 6869 6870 var exhibit$5 = function (base, disableConfig) { 6871 return nu$7({ classes: disableConfig.disabled() ? disableConfig.disableClass.toArray() : [] }); 6872 }; 6873 var events$e = function (disableConfig, disableState) { 6874 return derive$2([ 6875 abort(execute$5(), function (component, _simulatedEvent) { 6876 return isDisabled(component, disableConfig); 6877 }), 6878 loadEvent(disableConfig, disableState, onLoad$1) 6879 ]); 6880 }; 6881 6882 var ActiveDisable = /*#__PURE__*/Object.freeze({ 6883 __proto__: null, 6884 exhibit: exhibit$5, 6885 events: events$e 6886 }); 6887 6888 var DisableSchema = [ 6889 defaultedFunction('disabled', never), 6890 defaulted('useNative', true), 6891 option('disableClass'), 6892 onHandler('onDisabled'), 6893 onHandler('onEnabled') 6894 ]; 6895 6896 var Disabling = create$7({ 6897 fields: DisableSchema, 6898 name: 'disabling', 6899 active: ActiveDisable, 6900 apis: DisableApis 6901 }); 6902 6903 var dehighlightAllExcept = function (component, hConfig, hState, skip) { 6904 var highlighted = descendants(component.element, '.' + hConfig.highlightClass); 6905 each$1(highlighted, function (h) { 6906 if (!exists(skip, function (skipComp) { 6907 return skipComp.element === h; 6908 })) { 6909 remove$2(h, hConfig.highlightClass); 6910 component.getSystem().getByDom(h).each(function (target) { 6911 hConfig.onDehighlight(component, target); 6912 emit(target, dehighlight$1()); 6913 }); 6914 } 6915 }); 6916 }; 6917 var dehighlightAll = function (component, hConfig, hState) { 6918 return dehighlightAllExcept(component, hConfig, hState, []); 6919 }; 6920 var dehighlight = function (component, hConfig, hState, target) { 6921 if (isHighlighted(component, hConfig, hState, target)) { 6922 remove$2(target.element, hConfig.highlightClass); 6923 hConfig.onDehighlight(component, target); 6924 emit(target, dehighlight$1()); 6925 } 6926 }; 6927 var highlight = function (component, hConfig, hState, target) { 6928 dehighlightAllExcept(component, hConfig, hState, [target]); 6929 if (!isHighlighted(component, hConfig, hState, target)) { 6930 add$2(target.element, hConfig.highlightClass); 6931 hConfig.onHighlight(component, target); 6932 emit(target, highlight$1()); 6933 } 6934 }; 6935 var highlightFirst = function (component, hConfig, hState) { 6936 getFirst(component, hConfig).each(function (firstComp) { 6937 highlight(component, hConfig, hState, firstComp); 6938 }); 6939 }; 6940 var highlightLast = function (component, hConfig, hState) { 6941 getLast(component, hConfig).each(function (lastComp) { 6942 highlight(component, hConfig, hState, lastComp); 6943 }); 6944 }; 6945 var highlightAt = function (component, hConfig, hState, index) { 6946 getByIndex(component, hConfig, hState, index).fold(function (err) { 6947 throw err; 6948 }, function (firstComp) { 6949 highlight(component, hConfig, hState, firstComp); 6950 }); 6951 }; 6952 var highlightBy = function (component, hConfig, hState, predicate) { 6953 var candidates = getCandidates(component, hConfig); 6954 var targetComp = find$5(candidates, predicate); 6955 targetComp.each(function (c) { 6956 highlight(component, hConfig, hState, c); 6957 }); 6958 }; 6959 var isHighlighted = function (component, hConfig, hState, queryTarget) { 6960 return has(queryTarget.element, hConfig.highlightClass); 6961 }; 6962 var getHighlighted = function (component, hConfig, _hState) { 6963 return descendant(component.element, '.' + hConfig.highlightClass).bind(function (e) { 6964 return component.getSystem().getByDom(e).toOptional(); 6965 }); 6966 }; 6967 var getByIndex = function (component, hConfig, hState, index) { 6968 var items = descendants(component.element, '.' + hConfig.itemClass); 6969 return Optional.from(items[index]).fold(function () { 6970 return Result.error(new Error('No element found with index ' + index)); 6971 }, component.getSystem().getByDom); 6972 }; 6973 var getFirst = function (component, hConfig, _hState) { 6974 return descendant(component.element, '.' + hConfig.itemClass).bind(function (e) { 6975 return component.getSystem().getByDom(e).toOptional(); 6976 }); 6977 }; 6978 var getLast = function (component, hConfig, _hState) { 6979 var items = descendants(component.element, '.' + hConfig.itemClass); 6980 var last = items.length > 0 ? Optional.some(items[items.length - 1]) : Optional.none(); 6981 return last.bind(function (c) { 6982 return component.getSystem().getByDom(c).toOptional(); 6983 }); 6984 }; 6985 var getDelta$2 = function (component, hConfig, hState, delta) { 6986 var items = descendants(component.element, '.' + hConfig.itemClass); 6987 var current = findIndex$1(items, function (item) { 6988 return has(item, hConfig.highlightClass); 6989 }); 6990 return current.bind(function (selected) { 6991 var dest = cycleBy(selected, delta, 0, items.length - 1); 6992 return component.getSystem().getByDom(items[dest]).toOptional(); 6993 }); 6994 }; 6995 var getPrevious = function (component, hConfig, hState) { 6996 return getDelta$2(component, hConfig, hState, -1); 6997 }; 6998 var getNext = function (component, hConfig, hState) { 6999 return getDelta$2(component, hConfig, hState, +1); 7000 }; 7001 var getCandidates = function (component, hConfig, _hState) { 7002 var items = descendants(component.element, '.' + hConfig.itemClass); 7003 return cat(map$2(items, function (i) { 7004 return component.getSystem().getByDom(i).toOptional(); 7005 })); 7006 }; 7007 7008 var HighlightApis = /*#__PURE__*/Object.freeze({ 7009 __proto__: null, 7010 dehighlightAll: dehighlightAll, 7011 dehighlight: dehighlight, 7012 highlight: highlight, 7013 highlightFirst: highlightFirst, 7014 highlightLast: highlightLast, 7015 highlightAt: highlightAt, 7016 highlightBy: highlightBy, 7017 isHighlighted: isHighlighted, 7018 getHighlighted: getHighlighted, 7019 getFirst: getFirst, 7020 getLast: getLast, 7021 getPrevious: getPrevious, 7022 getNext: getNext, 7023 getCandidates: getCandidates 7024 }); 7025 7026 var HighlightSchema = [ 7027 required$1('highlightClass'), 7028 required$1('itemClass'), 7029 onHandler('onHighlight'), 7030 onHandler('onDehighlight') 7031 ]; 7032 7033 var Highlighting = create$7({ 7034 fields: HighlightSchema, 7035 name: 'highlighting', 7036 apis: HighlightApis 7037 }); 7038 7039 var BACKSPACE = [8]; 7040 var TAB = [9]; 7041 var ENTER = [13]; 7042 var ESCAPE = [27]; 7043 var SPACE = [32]; 7044 var LEFT = [37]; 7045 var UP = [38]; 7046 var RIGHT = [39]; 7047 var DOWN = [40]; 7048 7049 var cyclePrev = function (values, index, predicate) { 7050 var before = reverse(values.slice(0, index)); 7051 var after = reverse(values.slice(index + 1)); 7052 return find$5(before.concat(after), predicate); 7053 }; 7054 var tryPrev = function (values, index, predicate) { 7055 var before = reverse(values.slice(0, index)); 7056 return find$5(before, predicate); 7057 }; 7058 var cycleNext = function (values, index, predicate) { 7059 var before = values.slice(0, index); 7060 var after = values.slice(index + 1); 7061 return find$5(after.concat(before), predicate); 7062 }; 7063 var tryNext = function (values, index, predicate) { 7064 var after = values.slice(index + 1); 7065 return find$5(after, predicate); 7066 }; 7067 7068 var inSet = function (keys) { 7069 return function (event) { 7070 var raw = event.raw; 7071 return contains$2(keys, raw.which); 7072 }; 7073 }; 7074 var and = function (preds) { 7075 return function (event) { 7076 return forall(preds, function (pred) { 7077 return pred(event); 7078 }); 7079 }; 7080 }; 7081 var isShift = function (event) { 7082 var raw = event.raw; 7083 return raw.shiftKey === true; 7084 }; 7085 var isControl = function (event) { 7086 var raw = event.raw; 7087 return raw.ctrlKey === true; 7088 }; 7089 var isNotShift = not(isShift); 7090 7091 var rule = function (matches, action) { 7092 return { 7093 matches: matches, 7094 classification: action 7095 }; 7096 }; 7097 var choose = function (transitions, event) { 7098 var transition = find$5(transitions, function (t) { 7099 return t.matches(event); 7100 }); 7101 return transition.map(function (t) { 7102 return t.classification; 7103 }); 7104 }; 7105 7106 var reportFocusShifting = function (component, prevFocus, newFocus) { 7107 var noChange = prevFocus.exists(function (p) { 7108 return newFocus.exists(function (n) { 7109 return eq(n, p); 7110 }); 7111 }); 7112 if (!noChange) { 7113 emitWith(component, focusShifted(), { 7114 prevFocus: prevFocus, 7115 newFocus: newFocus 7116 }); 7117 } 7118 }; 7119 var dom$2 = function () { 7120 var get = function (component) { 7121 return search(component.element); 7122 }; 7123 var set = function (component, focusee) { 7124 var prevFocus = get(component); 7125 component.getSystem().triggerFocus(focusee, component.element); 7126 var newFocus = get(component); 7127 reportFocusShifting(component, prevFocus, newFocus); 7128 }; 7129 return { 7130 get: get, 7131 set: set 7132 }; 7133 }; 7134 var highlights = function () { 7135 var get = function (component) { 7136 return Highlighting.getHighlighted(component).map(function (item) { 7137 return item.element; 7138 }); 7139 }; 7140 var set = function (component, element) { 7141 var prevFocus = get(component); 7142 component.getSystem().getByDom(element).fold(noop, function (item) { 7143 Highlighting.highlight(component, item); 7144 }); 7145 var newFocus = get(component); 7146 reportFocusShifting(component, prevFocus, newFocus); 7147 }; 7148 return { 7149 get: get, 7150 set: set 7151 }; 7152 }; 7153 7154 var FocusInsideModes; 7155 (function (FocusInsideModes) { 7156 FocusInsideModes['OnFocusMode'] = 'onFocus'; 7157 FocusInsideModes['OnEnterOrSpaceMode'] = 'onEnterOrSpace'; 7158 FocusInsideModes['OnApiMode'] = 'onApi'; 7159 }(FocusInsideModes || (FocusInsideModes = {}))); 7160 7161 var typical = function (infoSchema, stateInit, getKeydownRules, getKeyupRules, optFocusIn) { 7162 var schema = function () { 7163 return infoSchema.concat([ 7164 defaulted('focusManager', dom$2()), 7165 defaultedOf('focusInside', 'onFocus', valueOf(function (val) { 7166 return contains$2([ 7167 'onFocus', 7168 'onEnterOrSpace', 7169 'onApi' 7170 ], val) ? Result.value(val) : Result.error('Invalid value for focusInside'); 7171 })), 7172 output$1('handler', me), 7173 output$1('state', stateInit), 7174 output$1('sendFocusIn', optFocusIn) 7175 ]); 7176 }; 7177 var processKey = function (component, simulatedEvent, getRules, keyingConfig, keyingState) { 7178 var rules = getRules(component, simulatedEvent, keyingConfig, keyingState); 7179 return choose(rules, simulatedEvent.event).bind(function (rule) { 7180 return rule(component, simulatedEvent, keyingConfig, keyingState); 7181 }); 7182 }; 7183 var toEvents = function (keyingConfig, keyingState) { 7184 var onFocusHandler = keyingConfig.focusInside !== FocusInsideModes.OnFocusMode ? Optional.none() : optFocusIn(keyingConfig).map(function (focusIn) { 7185 return run$1(focus$4(), function (component, simulatedEvent) { 7186 focusIn(component, keyingConfig, keyingState); 7187 simulatedEvent.stop(); 7188 }); 7189 }); 7190 var tryGoInsideComponent = function (component, simulatedEvent) { 7191 var isEnterOrSpace = inSet(SPACE.concat(ENTER))(simulatedEvent.event); 7192 if (keyingConfig.focusInside === FocusInsideModes.OnEnterOrSpaceMode && isEnterOrSpace && isSource(component, simulatedEvent)) { 7193 optFocusIn(keyingConfig).each(function (focusIn) { 7194 focusIn(component, keyingConfig, keyingState); 7195 simulatedEvent.stop(); 7196 }); 7197 } 7198 }; 7199 var keyboardEvents = [ 7200 run$1(keydown(), function (component, simulatedEvent) { 7201 processKey(component, simulatedEvent, getKeydownRules, keyingConfig, keyingState).fold(function () { 7202 tryGoInsideComponent(component, simulatedEvent); 7203 }, function (_) { 7204 simulatedEvent.stop(); 7205 }); 7206 }), 7207 run$1(keyup(), function (component, simulatedEvent) { 7208 processKey(component, simulatedEvent, getKeyupRules, keyingConfig, keyingState).each(function (_) { 7209 simulatedEvent.stop(); 7210 }); 7211 }) 7212 ]; 7213 return derive$2(onFocusHandler.toArray().concat(keyboardEvents)); 7214 }; 7215 var me = { 7216 schema: schema, 7217 processKey: processKey, 7218 toEvents: toEvents 7219 }; 7220 return me; 7221 }; 7222 7223 var create$5 = function (cyclicField) { 7224 var schema = [ 7225 option('onEscape'), 7226 option('onEnter'), 7227 defaulted('selector', '[data-alloy-tabstop="true"]:not(:disabled)'), 7228 defaulted('firstTabstop', 0), 7229 defaulted('useTabstopAt', always), 7230 option('visibilitySelector') 7231 ].concat([cyclicField]); 7232 var isVisible = function (tabbingConfig, element) { 7233 var target = tabbingConfig.visibilitySelector.bind(function (sel) { 7234 return closest$1(element, sel); 7235 }).getOr(element); 7236 return get$b(target) > 0; 7237 }; 7238 var findInitial = function (component, tabbingConfig) { 7239 var tabstops = descendants(component.element, tabbingConfig.selector); 7240 var visibles = filter$2(tabstops, function (elem) { 7241 return isVisible(tabbingConfig, elem); 7242 }); 7243 return Optional.from(visibles[tabbingConfig.firstTabstop]); 7244 }; 7245 var findCurrent = function (component, tabbingConfig) { 7246 return tabbingConfig.focusManager.get(component).bind(function (elem) { 7247 return closest$1(elem, tabbingConfig.selector); 7248 }); 7249 }; 7250 var isTabstop = function (tabbingConfig, element) { 7251 return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt(element); 7252 }; 7253 var focusIn = function (component, tabbingConfig, _tabbingState) { 7254 findInitial(component, tabbingConfig).each(function (target) { 7255 tabbingConfig.focusManager.set(component, target); 7256 }); 7257 }; 7258 var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) { 7259 return cycle(tabstops, stopIndex, function (elem) { 7260 return isTabstop(tabbingConfig, elem); 7261 }).fold(function () { 7262 return tabbingConfig.cyclic ? Optional.some(true) : Optional.none(); 7263 }, function (target) { 7264 tabbingConfig.focusManager.set(component, target); 7265 return Optional.some(true); 7266 }); 7267 }; 7268 var go = function (component, _simulatedEvent, tabbingConfig, cycle) { 7269 var tabstops = descendants(component.element, tabbingConfig.selector); 7270 return findCurrent(component, tabbingConfig).bind(function (tabstop) { 7271 var optStopIndex = findIndex$1(tabstops, curry(eq, tabstop)); 7272 return optStopIndex.bind(function (stopIndex) { 7273 return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle); 7274 }); 7275 }); 7276 }; 7277 var goBackwards = function (component, simulatedEvent, tabbingConfig) { 7278 var navigate = tabbingConfig.cyclic ? cyclePrev : tryPrev; 7279 return go(component, simulatedEvent, tabbingConfig, navigate); 7280 }; 7281 var goForwards = function (component, simulatedEvent, tabbingConfig) { 7282 var navigate = tabbingConfig.cyclic ? cycleNext : tryNext; 7283 return go(component, simulatedEvent, tabbingConfig, navigate); 7284 }; 7285 var execute = function (component, simulatedEvent, tabbingConfig) { 7286 return tabbingConfig.onEnter.bind(function (f) { 7287 return f(component, simulatedEvent); 7288 }); 7289 }; 7290 var exit = function (component, simulatedEvent, tabbingConfig) { 7291 return tabbingConfig.onEscape.bind(function (f) { 7292 return f(component, simulatedEvent); 7293 }); 7294 }; 7295 var getKeydownRules = constant$1([ 7296 rule(and([ 7297 isShift, 7298 inSet(TAB) 7299 ]), goBackwards), 7300 rule(inSet(TAB), goForwards), 7301 rule(inSet(ESCAPE), exit), 7302 rule(and([ 7303 isNotShift, 7304 inSet(ENTER) 7305 ]), execute) 7306 ]); 7307 var getKeyupRules = constant$1([]); 7308 return typical(schema, NoState.init, getKeydownRules, getKeyupRules, function () { 7309 return Optional.some(focusIn); 7310 }); 7311 }; 7312 7313 var AcyclicType = create$5(customField('cyclic', never)); 7314 7315 var CyclicType = create$5(customField('cyclic', always)); 7316 7317 var doDefaultExecute = function (component, _simulatedEvent, focused) { 7318 dispatch(component, focused, execute$5()); 7319 return Optional.some(true); 7320 }; 7321 var defaultExecute = function (component, simulatedEvent, focused) { 7322 var isComplex = inside(focused) && inSet(SPACE)(simulatedEvent.event); 7323 return isComplex ? Optional.none() : doDefaultExecute(component, simulatedEvent, focused); 7324 }; 7325 var stopEventForFirefox = function (_component, _simulatedEvent) { 7326 return Optional.some(true); 7327 }; 7328 7329 var schema$v = [ 7330 defaulted('execute', defaultExecute), 7331 defaulted('useSpace', false), 7332 defaulted('useEnter', true), 7333 defaulted('useControlEnter', false), 7334 defaulted('useDown', false) 7335 ]; 7336 var execute$4 = function (component, simulatedEvent, executeConfig) { 7337 return executeConfig.execute(component, simulatedEvent, component.element); 7338 }; 7339 var getKeydownRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) { 7340 var spaceExec = executeConfig.useSpace && !inside(component.element) ? SPACE : []; 7341 var enterExec = executeConfig.useEnter ? ENTER : []; 7342 var downExec = executeConfig.useDown ? DOWN : []; 7343 var execKeys = spaceExec.concat(enterExec).concat(downExec); 7344 return [rule(inSet(execKeys), execute$4)].concat(executeConfig.useControlEnter ? [rule(and([ 7345 isControl, 7346 inSet(ENTER) 7347 ]), execute$4)] : []); 7348 }; 7349 var getKeyupRules$5 = function (component, _simulatedEvent, executeConfig, _executeState) { 7350 return executeConfig.useSpace && !inside(component.element) ? [rule(inSet(SPACE), stopEventForFirefox)] : []; 7351 }; 7352 var ExecutionType = typical(schema$v, NoState.init, getKeydownRules$5, getKeyupRules$5, function () { 7353 return Optional.none(); 7354 }); 7355 7356 var flatgrid$1 = function () { 7357 var dimensions = value$1(); 7358 var setGridSize = function (numRows, numColumns) { 7359 dimensions.set({ 7360 numRows: numRows, 7361 numColumns: numColumns 7362 }); 7363 }; 7364 var getNumRows = function () { 7365 return dimensions.get().map(function (d) { 7366 return d.numRows; 7367 }); 7368 }; 7369 var getNumColumns = function () { 7370 return dimensions.get().map(function (d) { 7371 return d.numColumns; 7372 }); 7373 }; 7374 return nu$8({ 7375 readState: function () { 7376 return dimensions.get().map(function (d) { 7377 return { 7378 numRows: String(d.numRows), 7379 numColumns: String(d.numColumns) 7380 }; 7381 }).getOr({ 7382 numRows: '?', 7383 numColumns: '?' 7384 }); 7385 }, 7386 setGridSize: setGridSize, 7387 getNumRows: getNumRows, 7388 getNumColumns: getNumColumns 7389 }); 7390 }; 7391 var init$d = function (spec) { 7392 return spec.state(spec); 7393 }; 7394 7395 var KeyingState = /*#__PURE__*/Object.freeze({ 7396 __proto__: null, 7397 flatgrid: flatgrid$1, 7398 init: init$d 7399 }); 7400 7401 var useH = function (movement) { 7402 return function (component, simulatedEvent, config, state) { 7403 var move = movement(component.element); 7404 return use(move, component, simulatedEvent, config, state); 7405 }; 7406 }; 7407 var west$1 = function (moveLeft, moveRight) { 7408 var movement = onDirection(moveLeft, moveRight); 7409 return useH(movement); 7410 }; 7411 var east$1 = function (moveLeft, moveRight) { 7412 var movement = onDirection(moveRight, moveLeft); 7413 return useH(movement); 7414 }; 7415 var useV = function (move) { 7416 return function (component, simulatedEvent, config, state) { 7417 return use(move, component, simulatedEvent, config, state); 7418 }; 7419 }; 7420 var use = function (move, component, simulatedEvent, config, state) { 7421 var outcome = config.focusManager.get(component).bind(function (focused) { 7422 return move(component.element, focused, config, state); 7423 }); 7424 return outcome.map(function (newFocus) { 7425 config.focusManager.set(component, newFocus); 7426 return true; 7427 }); 7428 }; 7429 var north$1 = useV; 7430 var south$1 = useV; 7431 var move$1 = useV; 7432 7433 var isHidden$1 = function (dom) { 7434 return dom.offsetWidth <= 0 && dom.offsetHeight <= 0; 7435 }; 7436 var isVisible = function (element) { 7437 return !isHidden$1(element.dom); 7438 }; 7439 7440 var locate = function (candidates, predicate) { 7441 return findIndex$1(candidates, predicate).map(function (index) { 7442 return { 7443 index: index, 7444 candidates: candidates 7445 }; 7446 }); 7447 }; 7448 7449 var locateVisible = function (container, current, selector) { 7450 var predicate = function (x) { 7451 return eq(x, current); 7452 }; 7453 var candidates = descendants(container, selector); 7454 var visible = filter$2(candidates, isVisible); 7455 return locate(visible, predicate); 7456 }; 7457 var findIndex = function (elements, target) { 7458 return findIndex$1(elements, function (elem) { 7459 return eq(target, elem); 7460 }); 7461 }; 7462 7463 var withGrid = function (values, index, numCols, f) { 7464 var oldRow = Math.floor(index / numCols); 7465 var oldColumn = index % numCols; 7466 return f(oldRow, oldColumn).bind(function (address) { 7467 var newIndex = address.row * numCols + address.column; 7468 return newIndex >= 0 && newIndex < values.length ? Optional.some(values[newIndex]) : Optional.none(); 7469 }); 7470 }; 7471 var cycleHorizontal$1 = function (values, index, numRows, numCols, delta) { 7472 return withGrid(values, index, numCols, function (oldRow, oldColumn) { 7473 var onLastRow = oldRow === numRows - 1; 7474 var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols; 7475 var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1); 7476 return Optional.some({ 7477 row: oldRow, 7478 column: newColumn 7479 }); 7480 }); 7481 }; 7482 var cycleVertical$1 = function (values, index, numRows, numCols, delta) { 7483 return withGrid(values, index, numCols, function (oldRow, oldColumn) { 7484 var newRow = cycleBy(oldRow, delta, 0, numRows - 1); 7485 var onLastRow = newRow === numRows - 1; 7486 var colsInRow = onLastRow ? values.length - newRow * numCols : numCols; 7487 var newCol = clamp$1(oldColumn, 0, colsInRow - 1); 7488 return Optional.some({ 7489 row: newRow, 7490 column: newCol 7491 }); 7492 }); 7493 }; 7494 var cycleRight$1 = function (values, index, numRows, numCols) { 7495 return cycleHorizontal$1(values, index, numRows, numCols, +1); 7496 }; 7497 var cycleLeft$1 = function (values, index, numRows, numCols) { 7498 return cycleHorizontal$1(values, index, numRows, numCols, -1); 7499 }; 7500 var cycleUp$1 = function (values, index, numRows, numCols) { 7501 return cycleVertical$1(values, index, numRows, numCols, -1); 7502 }; 7503 var cycleDown$1 = function (values, index, numRows, numCols) { 7504 return cycleVertical$1(values, index, numRows, numCols, +1); 7505 }; 7506 7507 var schema$u = [ 7508 required$1('selector'), 7509 defaulted('execute', defaultExecute), 7510 onKeyboardHandler('onEscape'), 7511 defaulted('captureTab', false), 7512 initSize() 7513 ]; 7514 var focusIn$3 = function (component, gridConfig, _gridState) { 7515 descendant(component.element, gridConfig.selector).each(function (first) { 7516 gridConfig.focusManager.set(component, first); 7517 }); 7518 }; 7519 var findCurrent$1 = function (component, gridConfig) { 7520 return gridConfig.focusManager.get(component).bind(function (elem) { 7521 return closest$1(elem, gridConfig.selector); 7522 }); 7523 }; 7524 var execute$3 = function (component, simulatedEvent, gridConfig, _gridState) { 7525 return findCurrent$1(component, gridConfig).bind(function (focused) { 7526 return gridConfig.execute(component, simulatedEvent, focused); 7527 }); 7528 }; 7529 var doMove$2 = function (cycle) { 7530 return function (element, focused, gridConfig, gridState) { 7531 return locateVisible(element, focused, gridConfig.selector).bind(function (identified) { 7532 return cycle(identified.candidates, identified.index, gridState.getNumRows().getOr(gridConfig.initSize.numRows), gridState.getNumColumns().getOr(gridConfig.initSize.numColumns)); 7533 }); 7534 }; 7535 }; 7536 var handleTab = function (_component, _simulatedEvent, gridConfig) { 7537 return gridConfig.captureTab ? Optional.some(true) : Optional.none(); 7538 }; 7539 var doEscape$1 = function (component, simulatedEvent, gridConfig) { 7540 return gridConfig.onEscape(component, simulatedEvent); 7541 }; 7542 var moveLeft$3 = doMove$2(cycleLeft$1); 7543 var moveRight$3 = doMove$2(cycleRight$1); 7544 var moveNorth$1 = doMove$2(cycleUp$1); 7545 var moveSouth$1 = doMove$2(cycleDown$1); 7546 var getKeydownRules$4 = constant$1([ 7547 rule(inSet(LEFT), west$1(moveLeft$3, moveRight$3)), 7548 rule(inSet(RIGHT), east$1(moveLeft$3, moveRight$3)), 7549 rule(inSet(UP), north$1(moveNorth$1)), 7550 rule(inSet(DOWN), south$1(moveSouth$1)), 7551 rule(and([ 7552 isShift, 7553 inSet(TAB) 7554 ]), handleTab), 7555 rule(and([ 7556 isNotShift, 7557 inSet(TAB) 7558 ]), handleTab), 7559 rule(inSet(ESCAPE), doEscape$1), 7560 rule(inSet(SPACE.concat(ENTER)), execute$3) 7561 ]); 7562 var getKeyupRules$4 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 7563 var FlatgridType = typical(schema$u, flatgrid$1, getKeydownRules$4, getKeyupRules$4, function () { 7564 return Optional.some(focusIn$3); 7565 }); 7566 7567 var horizontal = function (container, selector, current, delta) { 7568 var isDisabledButton = function (candidate) { 7569 return name$2(candidate) === 'button' && get$d(candidate, 'disabled') === 'disabled'; 7570 }; 7571 var tryCycle = function (initial, index, candidates) { 7572 var newIndex = cycleBy(index, delta, 0, candidates.length - 1); 7573 if (newIndex === initial) { 7574 return Optional.none(); 7575 } else { 7576 return isDisabledButton(candidates[newIndex]) ? tryCycle(initial, newIndex, candidates) : Optional.from(candidates[newIndex]); 7577 } 7578 }; 7579 return locateVisible(container, current, selector).bind(function (identified) { 7580 var index = identified.index; 7581 var candidates = identified.candidates; 7582 return tryCycle(index, index, candidates); 7583 }); 7584 }; 7585 7586 var schema$t = [ 7587 required$1('selector'), 7588 defaulted('getInitial', Optional.none), 7589 defaulted('execute', defaultExecute), 7590 onKeyboardHandler('onEscape'), 7591 defaulted('executeOnMove', false), 7592 defaulted('allowVertical', true) 7593 ]; 7594 var findCurrent = function (component, flowConfig) { 7595 return flowConfig.focusManager.get(component).bind(function (elem) { 7596 return closest$1(elem, flowConfig.selector); 7597 }); 7598 }; 7599 var execute$2 = function (component, simulatedEvent, flowConfig) { 7600 return findCurrent(component, flowConfig).bind(function (focused) { 7601 return flowConfig.execute(component, simulatedEvent, focused); 7602 }); 7603 }; 7604 var focusIn$2 = function (component, flowConfig, _state) { 7605 flowConfig.getInitial(component).orThunk(function () { 7606 return descendant(component.element, flowConfig.selector); 7607 }).each(function (first) { 7608 flowConfig.focusManager.set(component, first); 7609 }); 7610 }; 7611 var moveLeft$2 = function (element, focused, info) { 7612 return horizontal(element, info.selector, focused, -1); 7613 }; 7614 var moveRight$2 = function (element, focused, info) { 7615 return horizontal(element, info.selector, focused, +1); 7616 }; 7617 var doMove$1 = function (movement) { 7618 return function (component, simulatedEvent, flowConfig, flowState) { 7619 return movement(component, simulatedEvent, flowConfig, flowState).bind(function () { 7620 return flowConfig.executeOnMove ? execute$2(component, simulatedEvent, flowConfig) : Optional.some(true); 7621 }); 7622 }; 7623 }; 7624 var doEscape = function (component, simulatedEvent, flowConfig) { 7625 return flowConfig.onEscape(component, simulatedEvent); 7626 }; 7627 var getKeydownRules$3 = function (_component, _se, flowConfig, _flowState) { 7628 var westMovers = LEFT.concat(flowConfig.allowVertical ? UP : []); 7629 var eastMovers = RIGHT.concat(flowConfig.allowVertical ? DOWN : []); 7630 return [ 7631 rule(inSet(westMovers), doMove$1(west$1(moveLeft$2, moveRight$2))), 7632 rule(inSet(eastMovers), doMove$1(east$1(moveLeft$2, moveRight$2))), 7633 rule(inSet(ENTER), execute$2), 7634 rule(inSet(SPACE), execute$2), 7635 rule(inSet(ESCAPE), doEscape) 7636 ]; 7637 }; 7638 var getKeyupRules$3 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 7639 var FlowType = typical(schema$t, NoState.init, getKeydownRules$3, getKeyupRules$3, function () { 7640 return Optional.some(focusIn$2); 7641 }); 7642 7643 var toCell = function (matrix, rowIndex, columnIndex) { 7644 return Optional.from(matrix[rowIndex]).bind(function (row) { 7645 return Optional.from(row[columnIndex]).map(function (cell) { 7646 return { 7647 rowIndex: rowIndex, 7648 columnIndex: columnIndex, 7649 cell: cell 7650 }; 7651 }); 7652 }); 7653 }; 7654 var cycleHorizontal = function (matrix, rowIndex, startCol, deltaCol) { 7655 var row = matrix[rowIndex]; 7656 var colsInRow = row.length; 7657 var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1); 7658 return toCell(matrix, rowIndex, newColIndex); 7659 }; 7660 var cycleVertical = function (matrix, colIndex, startRow, deltaRow) { 7661 var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1); 7662 var colsInNextRow = matrix[nextRowIndex].length; 7663 var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1); 7664 return toCell(matrix, nextRowIndex, nextColIndex); 7665 }; 7666 var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) { 7667 var row = matrix[rowIndex]; 7668 var colsInRow = row.length; 7669 var newColIndex = clamp$1(startCol + deltaCol, 0, colsInRow - 1); 7670 return toCell(matrix, rowIndex, newColIndex); 7671 }; 7672 var moveVertical = function (matrix, colIndex, startRow, deltaRow) { 7673 var nextRowIndex = clamp$1(startRow + deltaRow, 0, matrix.length - 1); 7674 var colsInNextRow = matrix[nextRowIndex].length; 7675 var nextColIndex = clamp$1(colIndex, 0, colsInNextRow - 1); 7676 return toCell(matrix, nextRowIndex, nextColIndex); 7677 }; 7678 var cycleRight = function (matrix, startRow, startCol) { 7679 return cycleHorizontal(matrix, startRow, startCol, +1); 7680 }; 7681 var cycleLeft = function (matrix, startRow, startCol) { 7682 return cycleHorizontal(matrix, startRow, startCol, -1); 7683 }; 7684 var cycleUp = function (matrix, startRow, startCol) { 7685 return cycleVertical(matrix, startCol, startRow, -1); 7686 }; 7687 var cycleDown = function (matrix, startRow, startCol) { 7688 return cycleVertical(matrix, startCol, startRow, +1); 7689 }; 7690 var moveLeft$1 = function (matrix, startRow, startCol) { 7691 return moveHorizontal(matrix, startRow, startCol, -1); 7692 }; 7693 var moveRight$1 = function (matrix, startRow, startCol) { 7694 return moveHorizontal(matrix, startRow, startCol, +1); 7695 }; 7696 var moveUp$1 = function (matrix, startRow, startCol) { 7697 return moveVertical(matrix, startCol, startRow, -1); 7698 }; 7699 var moveDown$1 = function (matrix, startRow, startCol) { 7700 return moveVertical(matrix, startCol, startRow, +1); 7701 }; 7702 7703 var schema$s = [ 7704 requiredObjOf('selectors', [ 7705 required$1('row'), 7706 required$1('cell') 7707 ]), 7708 defaulted('cycles', true), 7709 defaulted('previousSelector', Optional.none), 7710 defaulted('execute', defaultExecute) 7711 ]; 7712 var focusIn$1 = function (component, matrixConfig, _state) { 7713 var focused = matrixConfig.previousSelector(component).orThunk(function () { 7714 var selectors = matrixConfig.selectors; 7715 return descendant(component.element, selectors.cell); 7716 }); 7717 focused.each(function (cell) { 7718 matrixConfig.focusManager.set(component, cell); 7719 }); 7720 }; 7721 var execute$1 = function (component, simulatedEvent, matrixConfig) { 7722 return search(component.element).bind(function (focused) { 7723 return matrixConfig.execute(component, simulatedEvent, focused); 7724 }); 7725 }; 7726 var toMatrix = function (rows, matrixConfig) { 7727 return map$2(rows, function (row) { 7728 return descendants(row, matrixConfig.selectors.cell); 7729 }); 7730 }; 7731 var doMove = function (ifCycle, ifMove) { 7732 return function (element, focused, matrixConfig) { 7733 var move = matrixConfig.cycles ? ifCycle : ifMove; 7734 return closest$1(focused, matrixConfig.selectors.row).bind(function (inRow) { 7735 var cellsInRow = descendants(inRow, matrixConfig.selectors.cell); 7736 return findIndex(cellsInRow, focused).bind(function (colIndex) { 7737 var allRows = descendants(element, matrixConfig.selectors.row); 7738 return findIndex(allRows, inRow).bind(function (rowIndex) { 7739 var matrix = toMatrix(allRows, matrixConfig); 7740 return move(matrix, rowIndex, colIndex).map(function (next) { 7741 return next.cell; 7742 }); 7743 }); 7744 }); 7745 }); 7746 }; 7747 }; 7748 var moveLeft = doMove(cycleLeft, moveLeft$1); 7749 var moveRight = doMove(cycleRight, moveRight$1); 7750 var moveNorth = doMove(cycleUp, moveUp$1); 7751 var moveSouth = doMove(cycleDown, moveDown$1); 7752 var getKeydownRules$2 = constant$1([ 7753 rule(inSet(LEFT), west$1(moveLeft, moveRight)), 7754 rule(inSet(RIGHT), east$1(moveLeft, moveRight)), 7755 rule(inSet(UP), north$1(moveNorth)), 7756 rule(inSet(DOWN), south$1(moveSouth)), 7757 rule(inSet(SPACE.concat(ENTER)), execute$1) 7758 ]); 7759 var getKeyupRules$2 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 7760 var MatrixType = typical(schema$s, NoState.init, getKeydownRules$2, getKeyupRules$2, function () { 7761 return Optional.some(focusIn$1); 7762 }); 7763 7764 var schema$r = [ 7765 required$1('selector'), 7766 defaulted('execute', defaultExecute), 7767 defaulted('moveOnTab', false) 7768 ]; 7769 var execute = function (component, simulatedEvent, menuConfig) { 7770 return menuConfig.focusManager.get(component).bind(function (focused) { 7771 return menuConfig.execute(component, simulatedEvent, focused); 7772 }); 7773 }; 7774 var focusIn = function (component, menuConfig, _state) { 7775 descendant(component.element, menuConfig.selector).each(function (first) { 7776 menuConfig.focusManager.set(component, first); 7777 }); 7778 }; 7779 var moveUp = function (element, focused, info) { 7780 return horizontal(element, info.selector, focused, -1); 7781 }; 7782 var moveDown = function (element, focused, info) { 7783 return horizontal(element, info.selector, focused, +1); 7784 }; 7785 var fireShiftTab = function (component, simulatedEvent, menuConfig, menuState) { 7786 return menuConfig.moveOnTab ? move$1(moveUp)(component, simulatedEvent, menuConfig, menuState) : Optional.none(); 7787 }; 7788 var fireTab = function (component, simulatedEvent, menuConfig, menuState) { 7789 return menuConfig.moveOnTab ? move$1(moveDown)(component, simulatedEvent, menuConfig, menuState) : Optional.none(); 7790 }; 7791 var getKeydownRules$1 = constant$1([ 7792 rule(inSet(UP), move$1(moveUp)), 7793 rule(inSet(DOWN), move$1(moveDown)), 7794 rule(and([ 7795 isShift, 7796 inSet(TAB) 7797 ]), fireShiftTab), 7798 rule(and([ 7799 isNotShift, 7800 inSet(TAB) 7801 ]), fireTab), 7802 rule(inSet(ENTER), execute), 7803 rule(inSet(SPACE), execute) 7804 ]); 7805 var getKeyupRules$1 = constant$1([rule(inSet(SPACE), stopEventForFirefox)]); 7806 var MenuType = typical(schema$r, NoState.init, getKeydownRules$1, getKeyupRules$1, function () { 7807 return Optional.some(focusIn); 7808 }); 7809 7810 var schema$q = [ 7811 onKeyboardHandler('onSpace'), 7812 onKeyboardHandler('onEnter'), 7813 onKeyboardHandler('onShiftEnter'), 7814 onKeyboardHandler('onLeft'), 7815 onKeyboardHandler('onRight'), 7816 onKeyboardHandler('onTab'), 7817 onKeyboardHandler('onShiftTab'), 7818 onKeyboardHandler('onUp'), 7819 onKeyboardHandler('onDown'), 7820 onKeyboardHandler('onEscape'), 7821 defaulted('stopSpaceKeyup', false), 7822 option('focusIn') 7823 ]; 7824 var getKeydownRules = function (component, simulatedEvent, specialInfo) { 7825 return [ 7826 rule(inSet(SPACE), specialInfo.onSpace), 7827 rule(and([ 7828 isNotShift, 7829 inSet(ENTER) 7830 ]), specialInfo.onEnter), 7831 rule(and([ 7832 isShift, 7833 inSet(ENTER) 7834 ]), specialInfo.onShiftEnter), 7835 rule(and([ 7836 isShift, 7837 inSet(TAB) 7838 ]), specialInfo.onShiftTab), 7839 rule(and([ 7840 isNotShift, 7841 inSet(TAB) 7842 ]), specialInfo.onTab), 7843 rule(inSet(UP), specialInfo.onUp), 7844 rule(inSet(DOWN), specialInfo.onDown), 7845 rule(inSet(LEFT), specialInfo.onLeft), 7846 rule(inSet(RIGHT), specialInfo.onRight), 7847 rule(inSet(SPACE), specialInfo.onSpace), 7848 rule(inSet(ESCAPE), specialInfo.onEscape) 7849 ]; 7850 }; 7851 var getKeyupRules = function (component, simulatedEvent, specialInfo) { 7852 return specialInfo.stopSpaceKeyup ? [rule(inSet(SPACE), stopEventForFirefox)] : []; 7853 }; 7854 var SpecialType = typical(schema$q, NoState.init, getKeydownRules, getKeyupRules, function (specialInfo) { 7855 return specialInfo.focusIn; 7856 }); 7857 7858 var acyclic = AcyclicType.schema(); 7859 var cyclic = CyclicType.schema(); 7860 var flow = FlowType.schema(); 7861 var flatgrid = FlatgridType.schema(); 7862 var matrix = MatrixType.schema(); 7863 var execution = ExecutionType.schema(); 7864 var menu = MenuType.schema(); 7865 var special = SpecialType.schema(); 7866 7867 var KeyboardBranches = /*#__PURE__*/Object.freeze({ 7868 __proto__: null, 7869 acyclic: acyclic, 7870 cyclic: cyclic, 7871 flow: flow, 7872 flatgrid: flatgrid, 7873 matrix: matrix, 7874 execution: execution, 7875 menu: menu, 7876 special: special 7877 }); 7878 7879 var isFlatgridState = function (keyState) { 7880 return hasNonNullableKey(keyState, 'setGridSize'); 7881 }; 7882 var Keying = createModes({ 7883 branchKey: 'mode', 7884 branches: KeyboardBranches, 7885 name: 'keying', 7886 active: { 7887 events: function (keyingConfig, keyingState) { 7888 var handler = keyingConfig.handler; 7889 return handler.toEvents(keyingConfig, keyingState); 7890 } 7891 }, 7892 apis: { 7893 focusIn: function (component, keyConfig, keyState) { 7894 keyConfig.sendFocusIn(keyConfig).fold(function () { 7895 component.getSystem().triggerFocus(component.element, component.element); 7896 }, function (sendFocusIn) { 7897 sendFocusIn(component, keyConfig, keyState); 7898 }); 7899 }, 7900 setGridSize: function (component, keyConfig, keyState, numRows, numColumns) { 7901 if (!isFlatgridState(keyState)) { 7902 console.error('Layout does not support setGridSize'); 7903 } else { 7904 keyState.setGridSize(numRows, numColumns); 7905 } 7906 } 7907 }, 7908 state: KeyingState 7909 }); 7910 7911 var set$2 = function (component, replaceConfig, replaceState, data) { 7912 preserve$1(function () { 7913 var newChildren = map$2(data, component.getSystem().build); 7914 replaceChildren(component, newChildren); 7915 }, component.element); 7916 }; 7917 var insert = function (component, replaceConfig, insertion, childSpec) { 7918 var child = component.getSystem().build(childSpec); 7919 attachWith(component, child, insertion); 7920 }; 7921 var append = function (component, replaceConfig, replaceState, appendee) { 7922 insert(component, replaceConfig, append$2, appendee); 7923 }; 7924 var prepend = function (component, replaceConfig, replaceState, prependee) { 7925 insert(component, replaceConfig, prepend$1, prependee); 7926 }; 7927 var remove = function (component, replaceConfig, replaceState, removee) { 7928 var children = contents(component); 7929 var foundChild = find$5(children, function (child) { 7930 return eq(removee.element, child.element); 7931 }); 7932 foundChild.each(detach); 7933 }; 7934 var contents = function (component, _replaceConfig) { 7935 return component.components(); 7936 }; 7937 var replaceAt = function (component, replaceConfig, replaceState, replaceeIndex, replacer) { 7938 var children = contents(component); 7939 return Optional.from(children[replaceeIndex]).map(function (replacee) { 7940 remove(component, replaceConfig, replaceState, replacee); 7941 replacer.each(function (r) { 7942 insert(component, replaceConfig, function (p, c) { 7943 appendAt(p, c, replaceeIndex); 7944 }, r); 7945 }); 7946 return replacee; 7947 }); 7948 }; 7949 var replaceBy = function (component, replaceConfig, replaceState, replaceePred, replacer) { 7950 var children = contents(component); 7951 return findIndex$1(children, replaceePred).bind(function (replaceeIndex) { 7952 return replaceAt(component, replaceConfig, replaceState, replaceeIndex, replacer); 7953 }); 7954 }; 7955 7956 var ReplaceApis = /*#__PURE__*/Object.freeze({ 7957 __proto__: null, 7958 append: append, 7959 prepend: prepend, 7960 remove: remove, 7961 replaceAt: replaceAt, 7962 replaceBy: replaceBy, 7963 set: set$2, 7964 contents: contents 7965 }); 7966 7967 var Replacing = create$7({ 7968 fields: [], 7969 name: 'replacing', 7970 apis: ReplaceApis 7971 }); 7972 7973 var events$d = function (name, eventHandlers) { 7974 var events = derive$2(eventHandlers); 7975 return create$7({ 7976 fields: [required$1('enabled')], 7977 name: name, 7978 active: { events: constant$1(events) } 7979 }); 7980 }; 7981 var config = function (name, eventHandlers) { 7982 var me = events$d(name, eventHandlers); 7983 return { 7984 key: name, 7985 value: { 7986 config: {}, 7987 me: me, 7988 configAsRaw: constant$1({}), 7989 initialConfig: {}, 7990 state: NoState 7991 } 7992 }; 7993 }; 7994 7995 var focus$2 = function (component, focusConfig) { 7996 if (!focusConfig.ignore) { 7997 focus$3(component.element); 7998 focusConfig.onFocus(component); 7999 } 8000 }; 8001 var blur = function (component, focusConfig) { 8002 if (!focusConfig.ignore) { 8003 blur$1(component.element); 8004 } 8005 }; 8006 var isFocused = function (component) { 8007 return hasFocus(component.element); 8008 }; 8009 8010 var FocusApis = /*#__PURE__*/Object.freeze({ 8011 __proto__: null, 8012 focus: focus$2, 8013 blur: blur, 8014 isFocused: isFocused 8015 }); 8016 8017 var exhibit$4 = function (base, focusConfig) { 8018 var mod = focusConfig.ignore ? {} : { attributes: { tabindex: '-1' } }; 8019 return nu$7(mod); 8020 }; 8021 var events$c = function (focusConfig) { 8022 return derive$2([run$1(focus$4(), function (component, simulatedEvent) { 8023 focus$2(component, focusConfig); 8024 simulatedEvent.stop(); 8025 })].concat(focusConfig.stopMousedown ? [run$1(mousedown(), function (_, simulatedEvent) { 8026 simulatedEvent.event.prevent(); 8027 })] : [])); 8028 }; 8029 8030 var ActiveFocus = /*#__PURE__*/Object.freeze({ 8031 __proto__: null, 8032 exhibit: exhibit$4, 8033 events: events$c 8034 }); 8035 8036 var FocusSchema = [ 8037 onHandler('onFocus'), 8038 defaulted('stopMousedown', false), 8039 defaulted('ignore', false) 8040 ]; 8041 8042 var Focusing = create$7({ 8043 fields: FocusSchema, 8044 name: 'focusing', 8045 active: ActiveFocus, 8046 apis: FocusApis 8047 }); 8048 8049 var SetupBehaviourCellState = function (initialState) { 8050 var init = function () { 8051 var cell = Cell(initialState); 8052 var get = function () { 8053 return cell.get(); 8054 }; 8055 var set = function (newState) { 8056 return cell.set(newState); 8057 }; 8058 var clear = function () { 8059 return cell.set(initialState); 8060 }; 8061 var readState = function () { 8062 return cell.get(); 8063 }; 8064 return { 8065 get: get, 8066 set: set, 8067 clear: clear, 8068 readState: readState 8069 }; 8070 }; 8071 return { init: init }; 8072 }; 8073 8074 var updateAriaState = function (component, toggleConfig, toggleState) { 8075 var ariaInfo = toggleConfig.aria; 8076 ariaInfo.update(component, ariaInfo, toggleState.get()); 8077 }; 8078 var updateClass = function (component, toggleConfig, toggleState) { 8079 toggleConfig.toggleClass.each(function (toggleClass) { 8080 if (toggleState.get()) { 8081 add$2(component.element, toggleClass); 8082 } else { 8083 remove$2(component.element, toggleClass); 8084 } 8085 }); 8086 }; 8087 var toggle$2 = function (component, toggleConfig, toggleState) { 8088 set$1(component, toggleConfig, toggleState, !toggleState.get()); 8089 }; 8090 var on = function (component, toggleConfig, toggleState) { 8091 toggleState.set(true); 8092 updateClass(component, toggleConfig, toggleState); 8093 updateAriaState(component, toggleConfig, toggleState); 8094 }; 8095 var off = function (component, toggleConfig, toggleState) { 8096 toggleState.set(false); 8097 updateClass(component, toggleConfig, toggleState); 8098 updateAriaState(component, toggleConfig, toggleState); 8099 }; 8100 var set$1 = function (component, toggleConfig, toggleState, state) { 8101 var action = state ? on : off; 8102 action(component, toggleConfig, toggleState); 8103 }; 8104 var isOn = function (component, toggleConfig, toggleState) { 8105 return toggleState.get(); 8106 }; 8107 var onLoad = function (component, toggleConfig, toggleState) { 8108 set$1(component, toggleConfig, toggleState, toggleConfig.selected); 8109 }; 8110 8111 var ToggleApis = /*#__PURE__*/Object.freeze({ 8112 __proto__: null, 8113 onLoad: onLoad, 8114 toggle: toggle$2, 8115 isOn: isOn, 8116 on: on, 8117 off: off, 8118 set: set$1 8119 }); 8120 8121 var exhibit$3 = function () { 8122 return nu$7({}); 8123 }; 8124 var events$b = function (toggleConfig, toggleState) { 8125 var execute = executeEvent(toggleConfig, toggleState, toggle$2); 8126 var load = loadEvent(toggleConfig, toggleState, onLoad); 8127 return derive$2(flatten([ 8128 toggleConfig.toggleOnExecute ? [execute] : [], 8129 [load] 8130 ])); 8131 }; 8132 8133 var ActiveToggle = /*#__PURE__*/Object.freeze({ 8134 __proto__: null, 8135 exhibit: exhibit$3, 8136 events: events$b 8137 }); 8138 8139 var updatePressed = function (component, ariaInfo, status) { 8140 set$8(component.element, 'aria-pressed', status); 8141 if (ariaInfo.syncWithExpanded) { 8142 updateExpanded(component, ariaInfo, status); 8143 } 8144 }; 8145 var updateSelected = function (component, ariaInfo, status) { 8146 set$8(component.element, 'aria-selected', status); 8147 }; 8148 var updateChecked = function (component, ariaInfo, status) { 8149 set$8(component.element, 'aria-checked', status); 8150 }; 8151 var updateExpanded = function (component, ariaInfo, status) { 8152 set$8(component.element, 'aria-expanded', status); 8153 }; 8154 8155 var ToggleSchema = [ 8156 defaulted('selected', false), 8157 option('toggleClass'), 8158 defaulted('toggleOnExecute', true), 8159 defaultedOf('aria', { mode: 'none' }, choose$1('mode', { 8160 pressed: [ 8161 defaulted('syncWithExpanded', false), 8162 output$1('update', updatePressed) 8163 ], 8164 checked: [output$1('update', updateChecked)], 8165 expanded: [output$1('update', updateExpanded)], 8166 selected: [output$1('update', updateSelected)], 8167 none: [output$1('update', noop)] 8168 })) 8169 ]; 8170 8171 var Toggling = create$7({ 8172 fields: ToggleSchema, 8173 name: 'toggling', 8174 active: ActiveToggle, 8175 apis: ToggleApis, 8176 state: SetupBehaviourCellState(false) 8177 }); 8178 8179 var pointerEvents = function () { 8180 var onClick = function (component, simulatedEvent) { 8181 simulatedEvent.stop(); 8182 emitExecute(component); 8183 }; 8184 return [ 8185 run$1(click(), onClick), 8186 run$1(tap(), onClick), 8187 cutter(touchstart()), 8188 cutter(mousedown()) 8189 ]; 8190 }; 8191 var events$a = function (optAction) { 8192 var executeHandler = function (action) { 8193 return runOnExecute$1(function (component, simulatedEvent) { 8194 action(component); 8195 simulatedEvent.stop(); 8196 }); 8197 }; 8198 return derive$2(flatten([ 8199 optAction.map(executeHandler).toArray(), 8200 pointerEvents() 8201 ])); 8202 }; 8203 8204 var hoverEvent = 'alloy.item-hover'; 8205 var focusEvent = 'alloy.item-focus'; 8206 var onHover = function (item) { 8207 if (search(item.element).isNone() || Focusing.isFocused(item)) { 8208 if (!Focusing.isFocused(item)) { 8209 Focusing.focus(item); 8210 } 8211 emitWith(item, hoverEvent, { item: item }); 8212 } 8213 }; 8214 var onFocus$1 = function (item) { 8215 emitWith(item, focusEvent, { item: item }); 8216 }; 8217 var hover = constant$1(hoverEvent); 8218 var focus$1 = constant$1(focusEvent); 8219 8220 var builder$2 = function (detail) { 8221 return { 8222 dom: detail.dom, 8223 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 } : {}) }), 8224 behaviours: SketchBehaviours.augment(detail.itemBehaviours, [ 8225 detail.toggling.fold(Toggling.revoke, function (tConfig) { 8226 return Toggling.config(__assign({ aria: { mode: 'checked' } }, tConfig)); 8227 }), 8228 Focusing.config({ 8229 ignore: detail.ignoreFocus, 8230 stopMousedown: detail.ignoreFocus, 8231 onFocus: function (component) { 8232 onFocus$1(component); 8233 } 8234 }), 8235 Keying.config({ mode: 'execution' }), 8236 Representing.config({ 8237 store: { 8238 mode: 'memory', 8239 initialValue: detail.data 8240 } 8241 }), 8242 config('item-type-events', __spreadArray(__spreadArray([], pointerEvents(), true), [ 8243 run$1(mouseover(), onHover), 8244 run$1(focusItem(), Focusing.focus) 8245 ], false)) 8246 ]), 8247 components: detail.components, 8248 eventOrder: detail.eventOrder 8249 }; 8250 }; 8251 var schema$p = [ 8252 required$1('data'), 8253 required$1('components'), 8254 required$1('dom'), 8255 defaulted('hasSubmenu', false), 8256 option('toggling'), 8257 SketchBehaviours.field('itemBehaviours', [ 8258 Toggling, 8259 Focusing, 8260 Keying, 8261 Representing 8262 ]), 8263 defaulted('ignoreFocus', false), 8264 defaulted('domModification', {}), 8265 output$1('builder', builder$2), 8266 defaulted('eventOrder', {}) 8267 ]; 8268 8269 var builder$1 = function (detail) { 8270 return { 8271 dom: detail.dom, 8272 components: detail.components, 8273 events: derive$2([stopper(focusItem())]) 8274 }; 8275 }; 8276 var schema$o = [ 8277 required$1('dom'), 8278 required$1('components'), 8279 output$1('builder', builder$1) 8280 ]; 8281 8282 var owner$2 = constant$1('item-widget'); 8283 var parts$h = constant$1([required({ 8284 name: 'widget', 8285 overrides: function (detail) { 8286 return { 8287 behaviours: derive$1([Representing.config({ 8288 store: { 8289 mode: 'manual', 8290 getValue: function (_component) { 8291 return detail.data; 8292 }, 8293 setValue: noop 8294 } 8295 })]) 8296 }; 8297 } 8298 })]); 8299 8300 var builder = function (detail) { 8301 var subs = substitutes(owner$2(), detail, parts$h()); 8302 var components = components$1(owner$2(), detail, subs.internals()); 8303 var focusWidget = function (component) { 8304 return getPart(component, detail, 'widget').map(function (widget) { 8305 Keying.focusIn(widget); 8306 return widget; 8307 }); 8308 }; 8309 var onHorizontalArrow = function (component, simulatedEvent) { 8310 return inside(simulatedEvent.event.target) ? Optional.none() : function () { 8311 if (detail.autofocus) { 8312 simulatedEvent.setSource(component.element); 8313 return Optional.none(); 8314 } else { 8315 return Optional.none(); 8316 } 8317 }(); 8318 }; 8319 return { 8320 dom: detail.dom, 8321 components: components, 8322 domModification: detail.domModification, 8323 events: derive$2([ 8324 runOnExecute$1(function (component, simulatedEvent) { 8325 focusWidget(component).each(function (_widget) { 8326 simulatedEvent.stop(); 8327 }); 8328 }), 8329 run$1(mouseover(), onHover), 8330 run$1(focusItem(), function (component, _simulatedEvent) { 8331 if (detail.autofocus) { 8332 focusWidget(component); 8333 } else { 8334 Focusing.focus(component); 8335 } 8336 }) 8337 ]), 8338 behaviours: SketchBehaviours.augment(detail.widgetBehaviours, [ 8339 Representing.config({ 8340 store: { 8341 mode: 'memory', 8342 initialValue: detail.data 8343 } 8344 }), 8345 Focusing.config({ 8346 ignore: detail.ignoreFocus, 8347 onFocus: function (component) { 8348 onFocus$1(component); 8349 } 8350 }), 8351 Keying.config({ 8352 mode: 'special', 8353 focusIn: detail.autofocus ? function (component) { 8354 focusWidget(component); 8355 } : revoke(), 8356 onLeft: onHorizontalArrow, 8357 onRight: onHorizontalArrow, 8358 onEscape: function (component, simulatedEvent) { 8359 if (!Focusing.isFocused(component) && !detail.autofocus) { 8360 Focusing.focus(component); 8361 return Optional.some(true); 8362 } else if (detail.autofocus) { 8363 simulatedEvent.setSource(component.element); 8364 return Optional.none(); 8365 } else { 8366 return Optional.none(); 8367 } 8368 } 8369 }) 8370 ]) 8371 }; 8372 }; 8373 var schema$n = [ 8374 required$1('uid'), 8375 required$1('data'), 8376 required$1('components'), 8377 required$1('dom'), 8378 defaulted('autofocus', false), 8379 defaulted('ignoreFocus', false), 8380 SketchBehaviours.field('widgetBehaviours', [ 8381 Representing, 8382 Focusing, 8383 Keying 8384 ]), 8385 defaulted('domModification', {}), 8386 defaultUidsSchema(parts$h()), 8387 output$1('builder', builder) 8388 ]; 8389 8390 var itemSchema$2 = choose$1('type', { 8391 widget: schema$n, 8392 item: schema$p, 8393 separator: schema$o 8394 }); 8395 var configureGrid = function (detail, movementInfo) { 8396 return { 8397 mode: 'flatgrid', 8398 selector: '.' + detail.markers.item, 8399 initSize: { 8400 numColumns: movementInfo.initSize.numColumns, 8401 numRows: movementInfo.initSize.numRows 8402 }, 8403 focusManager: detail.focusManager 8404 }; 8405 }; 8406 var configureMatrix = function (detail, movementInfo) { 8407 return { 8408 mode: 'matrix', 8409 selectors: { 8410 row: movementInfo.rowSelector, 8411 cell: '.' + detail.markers.item 8412 }, 8413 focusManager: detail.focusManager 8414 }; 8415 }; 8416 var configureMenu = function (detail, movementInfo) { 8417 return { 8418 mode: 'menu', 8419 selector: '.' + detail.markers.item, 8420 moveOnTab: movementInfo.moveOnTab, 8421 focusManager: detail.focusManager 8422 }; 8423 }; 8424 var parts$g = constant$1([group({ 8425 factory: { 8426 sketch: function (spec) { 8427 var itemInfo = asRawOrDie$1('menu.spec item', itemSchema$2, spec); 8428 return itemInfo.builder(itemInfo); 8429 } 8430 }, 8431 name: 'items', 8432 unit: 'item', 8433 defaults: function (detail, u) { 8434 return has$2(u, 'uid') ? u : __assign(__assign({}, u), { uid: generate$5('item') }); 8435 }, 8436 overrides: function (detail, u) { 8437 return { 8438 type: u.type, 8439 ignoreFocus: detail.fakeFocus, 8440 domModification: { classes: [detail.markers.item] } 8441 }; 8442 } 8443 })]); 8444 var schema$m = constant$1([ 8445 required$1('value'), 8446 required$1('items'), 8447 required$1('dom'), 8448 required$1('components'), 8449 defaulted('eventOrder', {}), 8450 field('menuBehaviours', [ 8451 Highlighting, 8452 Representing, 8453 Composing, 8454 Keying 8455 ]), 8456 defaultedOf('movement', { 8457 mode: 'menu', 8458 moveOnTab: true 8459 }, choose$1('mode', { 8460 grid: [ 8461 initSize(), 8462 output$1('config', configureGrid) 8463 ], 8464 matrix: [ 8465 output$1('config', configureMatrix), 8466 required$1('rowSelector') 8467 ], 8468 menu: [ 8469 defaulted('moveOnTab', true), 8470 output$1('config', configureMenu) 8471 ] 8472 })), 8473 itemMarkers(), 8474 defaulted('fakeFocus', false), 8475 defaulted('focusManager', dom$2()), 8476 onHandler('onHighlight') 8477 ]); 8478 8479 var focus = constant$1('alloy.menu-focus'); 8480 8481 var make$7 = function (detail, components, _spec, _externals) { 8482 return { 8483 uid: detail.uid, 8484 dom: detail.dom, 8485 markers: detail.markers, 8486 behaviours: augment(detail.menuBehaviours, [ 8487 Highlighting.config({ 8488 highlightClass: detail.markers.selectedItem, 8489 itemClass: detail.markers.item, 8490 onHighlight: detail.onHighlight 8491 }), 8492 Representing.config({ 8493 store: { 8494 mode: 'memory', 8495 initialValue: detail.value 8496 } 8497 }), 8498 Composing.config({ find: Optional.some }), 8499 Keying.config(detail.movement.config(detail, detail.movement)) 8500 ]), 8501 events: derive$2([ 8502 run$1(focus$1(), function (menu, simulatedEvent) { 8503 var event = simulatedEvent.event; 8504 menu.getSystem().getByDom(event.target).each(function (item) { 8505 Highlighting.highlight(menu, item); 8506 simulatedEvent.stop(); 8507 emitWith(menu, focus(), { 8508 menu: menu, 8509 item: item 8510 }); 8511 }); 8512 }), 8513 run$1(hover(), function (menu, simulatedEvent) { 8514 var item = simulatedEvent.event.item; 8515 Highlighting.highlight(menu, item); 8516 }) 8517 ]), 8518 components: components, 8519 eventOrder: detail.eventOrder, 8520 domModification: { attributes: { role: 'menu' } } 8521 }; 8522 }; 8523 8524 var Menu = composite({ 8525 name: 'Menu', 8526 configFields: schema$m(), 8527 partFields: parts$g(), 8528 factory: make$7 8529 }); 8530 8531 var transpose$1 = function (obj) { 8532 return tupleMap(obj, function (v, k) { 8533 return { 8534 k: v, 8535 v: k 8536 }; 8537 }); 8538 }; 8539 var trace = function (items, byItem, byMenu, finish) { 8540 return get$e(byMenu, finish).bind(function (triggerItem) { 8541 return get$e(items, triggerItem).bind(function (triggerMenu) { 8542 var rest = trace(items, byItem, byMenu, triggerMenu); 8543 return Optional.some([triggerMenu].concat(rest)); 8544 }); 8545 }).getOr([]); 8546 }; 8547 var generate$2 = function (menus, expansions) { 8548 var items = {}; 8549 each(menus, function (menuItems, menu) { 8550 each$1(menuItems, function (item) { 8551 items[item] = menu; 8552 }); 8553 }); 8554 var byItem = expansions; 8555 var byMenu = transpose$1(expansions); 8556 var menuPaths = map$1(byMenu, function (_triggerItem, submenu) { 8557 return [submenu].concat(trace(items, byItem, byMenu, submenu)); 8558 }); 8559 return map$1(items, function (menu) { 8560 return get$e(menuPaths, menu).getOr([menu]); 8561 }); 8562 }; 8563 8564 var init$c = function () { 8565 var expansions = Cell({}); 8566 var menus = Cell({}); 8567 var paths = Cell({}); 8568 var primary = value$1(); 8569 var directory = Cell({}); 8570 var clear = function () { 8571 expansions.set({}); 8572 menus.set({}); 8573 paths.set({}); 8574 primary.clear(); 8575 }; 8576 var isClear = function () { 8577 return primary.get().isNone(); 8578 }; 8579 var setMenuBuilt = function (menuName, built) { 8580 var _a; 8581 menus.set(__assign(__assign({}, menus.get()), (_a = {}, _a[menuName] = { 8582 type: 'prepared', 8583 menu: built 8584 }, _a))); 8585 }; 8586 var setContents = function (sPrimary, sMenus, sExpansions, dir) { 8587 primary.set(sPrimary); 8588 expansions.set(sExpansions); 8589 menus.set(sMenus); 8590 directory.set(dir); 8591 var sPaths = generate$2(dir, sExpansions); 8592 paths.set(sPaths); 8593 }; 8594 var getTriggeringItem = function (menuValue) { 8595 return find$4(expansions.get(), function (v, _k) { 8596 return v === menuValue; 8597 }); 8598 }; 8599 var getTriggerData = function (menuValue, getItemByValue, path) { 8600 return getPreparedMenu(menuValue).bind(function (menu) { 8601 return getTriggeringItem(menuValue).bind(function (triggeringItemValue) { 8602 return getItemByValue(triggeringItemValue).map(function (triggeredItem) { 8603 return { 8604 triggeredMenu: menu, 8605 triggeringItem: triggeredItem, 8606 triggeringPath: path 8607 }; 8608 }); 8609 }); 8610 }); 8611 }; 8612 var getTriggeringPath = function (itemValue, getItemByValue) { 8613 var extraPath = filter$2(lookupItem(itemValue).toArray(), function (menuValue) { 8614 return getPreparedMenu(menuValue).isSome(); 8615 }); 8616 return get$e(paths.get(), itemValue).bind(function (path) { 8617 var revPath = reverse(extraPath.concat(path)); 8618 var triggers = bind$3(revPath, function (menuValue, menuIndex) { 8619 return getTriggerData(menuValue, getItemByValue, revPath.slice(0, menuIndex + 1)).fold(function () { 8620 return is$1(primary.get(), menuValue) ? [] : [Optional.none()]; 8621 }, function (data) { 8622 return [Optional.some(data)]; 8623 }); 8624 }); 8625 return sequence(triggers); 8626 }); 8627 }; 8628 var expand = function (itemValue) { 8629 return get$e(expansions.get(), itemValue).map(function (menu) { 8630 var current = get$e(paths.get(), itemValue).getOr([]); 8631 return [menu].concat(current); 8632 }); 8633 }; 8634 var collapse = function (itemValue) { 8635 return get$e(paths.get(), itemValue).bind(function (path) { 8636 return path.length > 1 ? Optional.some(path.slice(1)) : Optional.none(); 8637 }); 8638 }; 8639 var refresh = function (itemValue) { 8640 return get$e(paths.get(), itemValue); 8641 }; 8642 var getPreparedMenu = function (menuValue) { 8643 return lookupMenu(menuValue).bind(extractPreparedMenu); 8644 }; 8645 var lookupMenu = function (menuValue) { 8646 return get$e(menus.get(), menuValue); 8647 }; 8648 var lookupItem = function (itemValue) { 8649 return get$e(expansions.get(), itemValue); 8650 }; 8651 var otherMenus = function (path) { 8652 var menuValues = directory.get(); 8653 return difference(keys(menuValues), path); 8654 }; 8655 var getPrimary = function () { 8656 return primary.get().bind(getPreparedMenu); 8657 }; 8658 var getMenus = function () { 8659 return menus.get(); 8660 }; 8661 return { 8662 setMenuBuilt: setMenuBuilt, 8663 setContents: setContents, 8664 expand: expand, 8665 refresh: refresh, 8666 collapse: collapse, 8667 lookupMenu: lookupMenu, 8668 lookupItem: lookupItem, 8669 otherMenus: otherMenus, 8670 getPrimary: getPrimary, 8671 getMenus: getMenus, 8672 clear: clear, 8673 isClear: isClear, 8674 getTriggeringPath: getTriggeringPath 8675 }; 8676 }; 8677 var extractPreparedMenu = function (prep) { 8678 return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none(); 8679 }; 8680 var LayeredState = { 8681 init: init$c, 8682 extractPreparedMenu: extractPreparedMenu 8683 }; 8684 8685 var make$6 = function (detail, _rawUiSpec) { 8686 var submenuParentItems = value$1(); 8687 var buildMenus = function (container, primaryName, menus) { 8688 return map$1(menus, function (spec, name) { 8689 var makeSketch = function () { 8690 return Menu.sketch(__assign(__assign({}, spec), { 8691 value: name, 8692 markers: detail.markers, 8693 fakeFocus: detail.fakeFocus, 8694 onHighlight: detail.onHighlight, 8695 focusManager: detail.fakeFocus ? highlights() : dom$2() 8696 })); 8697 }; 8698 return name === primaryName ? { 8699 type: 'prepared', 8700 menu: container.getSystem().build(makeSketch()) 8701 } : { 8702 type: 'notbuilt', 8703 nbMenu: makeSketch 8704 }; 8705 }); 8706 }; 8707 var layeredState = LayeredState.init(); 8708 var setup = function (container) { 8709 var componentMap = buildMenus(container, detail.data.primary, detail.data.menus); 8710 var directory = toDirectory(); 8711 layeredState.setContents(detail.data.primary, componentMap, detail.data.expansions, directory); 8712 return layeredState.getPrimary(); 8713 }; 8714 var getItemValue = function (item) { 8715 return Representing.getValue(item).value; 8716 }; 8717 var getItemByValue = function (_container, menus, itemValue) { 8718 return findMap(menus, function (menu) { 8719 if (!menu.getSystem().isConnected()) { 8720 return Optional.none(); 8721 } 8722 var candidates = Highlighting.getCandidates(menu); 8723 return find$5(candidates, function (c) { 8724 return getItemValue(c) === itemValue; 8725 }); 8726 }); 8727 }; 8728 var toDirectory = function (_container) { 8729 return map$1(detail.data.menus, function (data, _menuName) { 8730 return bind$3(data.items, function (item) { 8731 return item.type === 'separator' ? [] : [item.data.value]; 8732 }); 8733 }); 8734 }; 8735 var setActiveMenu = function (container, menu) { 8736 Highlighting.highlight(container, menu); 8737 Highlighting.getHighlighted(menu).orThunk(function () { 8738 return Highlighting.getFirst(menu); 8739 }).each(function (item) { 8740 dispatch(container, item.element, focusItem()); 8741 }); 8742 }; 8743 var getMenus = function (state, menuValues) { 8744 return cat(map$2(menuValues, function (mv) { 8745 return state.lookupMenu(mv).bind(function (prep) { 8746 return prep.type === 'prepared' ? Optional.some(prep.menu) : Optional.none(); 8747 }); 8748 })); 8749 }; 8750 var closeOthers = function (container, state, path) { 8751 var others = getMenus(state, state.otherMenus(path)); 8752 each$1(others, function (o) { 8753 remove$1(o.element, [detail.markers.backgroundMenu]); 8754 if (!detail.stayInDom) { 8755 Replacing.remove(container, o); 8756 } 8757 }); 8758 }; 8759 var getSubmenuParents = function (container) { 8760 return submenuParentItems.get().getOrThunk(function () { 8761 var r = {}; 8762 var items = descendants(container.element, '.' + detail.markers.item); 8763 var parentItems = filter$2(items, function (i) { 8764 return get$d(i, 'aria-haspopup') === 'true'; 8765 }); 8766 each$1(parentItems, function (i) { 8767 container.getSystem().getByDom(i).each(function (itemComp) { 8768 var key = getItemValue(itemComp); 8769 r[key] = itemComp; 8770 }); 8771 }); 8772 submenuParentItems.set(r); 8773 return r; 8774 }); 8775 }; 8776 var updateAriaExpansions = function (container, path) { 8777 var parentItems = getSubmenuParents(container); 8778 each(parentItems, function (v, k) { 8779 var expanded = contains$2(path, k); 8780 set$8(v.element, 'aria-expanded', expanded); 8781 }); 8782 }; 8783 var updateMenuPath = function (container, state, path) { 8784 return Optional.from(path[0]).bind(function (latestMenuName) { 8785 return state.lookupMenu(latestMenuName).bind(function (menuPrep) { 8786 if (menuPrep.type === 'notbuilt') { 8787 return Optional.none(); 8788 } else { 8789 var activeMenu = menuPrep.menu; 8790 var rest = getMenus(state, path.slice(1)); 8791 each$1(rest, function (r) { 8792 add$2(r.element, detail.markers.backgroundMenu); 8793 }); 8794 if (!inBody(activeMenu.element)) { 8795 Replacing.append(container, premade(activeMenu)); 8796 } 8797 remove$1(activeMenu.element, [detail.markers.backgroundMenu]); 8798 setActiveMenu(container, activeMenu); 8799 closeOthers(container, state, path); 8800 return Optional.some(activeMenu); 8801 } 8802 }); 8803 }); 8804 }; 8805 var ExpandHighlightDecision; 8806 (function (ExpandHighlightDecision) { 8807 ExpandHighlightDecision[ExpandHighlightDecision['HighlightSubmenu'] = 0] = 'HighlightSubmenu'; 8808 ExpandHighlightDecision[ExpandHighlightDecision['HighlightParent'] = 1] = 'HighlightParent'; 8809 }(ExpandHighlightDecision || (ExpandHighlightDecision = {}))); 8810 var buildIfRequired = function (container, menuName, menuPrep) { 8811 if (menuPrep.type === 'notbuilt') { 8812 var menu = container.getSystem().build(menuPrep.nbMenu()); 8813 layeredState.setMenuBuilt(menuName, menu); 8814 return menu; 8815 } else { 8816 return menuPrep.menu; 8817 } 8818 }; 8819 var expandRight = function (container, item, decision) { 8820 if (decision === void 0) { 8821 decision = ExpandHighlightDecision.HighlightSubmenu; 8822 } 8823 if (item.hasConfigured(Disabling) && Disabling.isDisabled(item)) { 8824 return Optional.some(item); 8825 } else { 8826 var value = getItemValue(item); 8827 return layeredState.expand(value).bind(function (path) { 8828 updateAriaExpansions(container, path); 8829 return Optional.from(path[0]).bind(function (menuName) { 8830 return layeredState.lookupMenu(menuName).bind(function (activeMenuPrep) { 8831 var activeMenu = buildIfRequired(container, menuName, activeMenuPrep); 8832 if (!inBody(activeMenu.element)) { 8833 Replacing.append(container, premade(activeMenu)); 8834 } 8835 detail.onOpenSubmenu(container, item, activeMenu, reverse(path)); 8836 if (decision === ExpandHighlightDecision.HighlightSubmenu) { 8837 Highlighting.highlightFirst(activeMenu); 8838 return updateMenuPath(container, layeredState, path); 8839 } else { 8840 Highlighting.dehighlightAll(activeMenu); 8841 return Optional.some(item); 8842 } 8843 }); 8844 }); 8845 }); 8846 } 8847 }; 8848 var collapseLeft = function (container, item) { 8849 var value = getItemValue(item); 8850 return layeredState.collapse(value).bind(function (path) { 8851 updateAriaExpansions(container, path); 8852 return updateMenuPath(container, layeredState, path).map(function (activeMenu) { 8853 detail.onCollapseMenu(container, item, activeMenu); 8854 return activeMenu; 8855 }); 8856 }); 8857 }; 8858 var updateView = function (container, item) { 8859 var value = getItemValue(item); 8860 return layeredState.refresh(value).bind(function (path) { 8861 updateAriaExpansions(container, path); 8862 return updateMenuPath(container, layeredState, path); 8863 }); 8864 }; 8865 var onRight = function (container, item) { 8866 return inside(item.element) ? Optional.none() : expandRight(container, item, ExpandHighlightDecision.HighlightSubmenu); 8867 }; 8868 var onLeft = function (container, item) { 8869 return inside(item.element) ? Optional.none() : collapseLeft(container, item); 8870 }; 8871 var onEscape = function (container, item) { 8872 return collapseLeft(container, item).orThunk(function () { 8873 return detail.onEscape(container, item).map(function () { 8874 return container; 8875 }); 8876 }); 8877 }; 8878 var keyOnItem = function (f) { 8879 return function (container, simulatedEvent) { 8880 return closest$1(simulatedEvent.getSource(), '.' + detail.markers.item).bind(function (target) { 8881 return container.getSystem().getByDom(target).toOptional().bind(function (item) { 8882 return f(container, item).map(always); 8883 }); 8884 }); 8885 }; 8886 }; 8887 var events = derive$2([ 8888 run$1(focus(), function (sandbox, simulatedEvent) { 8889 var item = simulatedEvent.event.item; 8890 layeredState.lookupItem(getItemValue(item)).each(function () { 8891 var menu = simulatedEvent.event.menu; 8892 Highlighting.highlight(sandbox, menu); 8893 var value = getItemValue(simulatedEvent.event.item); 8894 layeredState.refresh(value).each(function (path) { 8895 return closeOthers(sandbox, layeredState, path); 8896 }); 8897 }); 8898 }), 8899 runOnExecute$1(function (component, simulatedEvent) { 8900 var target = simulatedEvent.event.target; 8901 component.getSystem().getByDom(target).each(function (item) { 8902 var itemValue = getItemValue(item); 8903 if (itemValue.indexOf('collapse-item') === 0) { 8904 collapseLeft(component, item); 8905 } 8906 expandRight(component, item, ExpandHighlightDecision.HighlightSubmenu).fold(function () { 8907 detail.onExecute(component, item); 8908 }, noop); 8909 }); 8910 }), 8911 runOnAttached(function (container, _simulatedEvent) { 8912 setup(container).each(function (primary) { 8913 Replacing.append(container, premade(primary)); 8914 detail.onOpenMenu(container, primary); 8915 if (detail.highlightImmediately) { 8916 setActiveMenu(container, primary); 8917 } 8918 }); 8919 }) 8920 ].concat(detail.navigateOnHover ? [run$1(hover(), function (sandbox, simulatedEvent) { 8921 var item = simulatedEvent.event.item; 8922 updateView(sandbox, item); 8923 expandRight(sandbox, item, ExpandHighlightDecision.HighlightParent); 8924 detail.onHover(sandbox, item); 8925 })] : [])); 8926 var getActiveItem = function (container) { 8927 return Highlighting.getHighlighted(container).bind(Highlighting.getHighlighted); 8928 }; 8929 var collapseMenuApi = function (container) { 8930 getActiveItem(container).each(function (currentItem) { 8931 collapseLeft(container, currentItem); 8932 }); 8933 }; 8934 var highlightPrimary = function (container) { 8935 layeredState.getPrimary().each(function (primary) { 8936 setActiveMenu(container, primary); 8937 }); 8938 }; 8939 var extractMenuFromContainer = function (container) { 8940 return Optional.from(container.components()[0]).filter(function (comp) { 8941 return get$d(comp.element, 'role') === 'menu'; 8942 }); 8943 }; 8944 var repositionMenus = function (container) { 8945 var maybeActivePrimary = layeredState.getPrimary().bind(function (primary) { 8946 return getActiveItem(container).bind(function (currentItem) { 8947 var itemValue = getItemValue(currentItem); 8948 var allMenus = values(layeredState.getMenus()); 8949 var preparedMenus = cat(map$2(allMenus, LayeredState.extractPreparedMenu)); 8950 return layeredState.getTriggeringPath(itemValue, function (v) { 8951 return getItemByValue(container, preparedMenus, v); 8952 }); 8953 }).map(function (triggeringPath) { 8954 return { 8955 primary: primary, 8956 triggeringPath: triggeringPath 8957 }; 8958 }); 8959 }); 8960 maybeActivePrimary.fold(function () { 8961 extractMenuFromContainer(container).each(function (primaryMenu) { 8962 detail.onRepositionMenu(container, primaryMenu, []); 8963 }); 8964 }, function (_a) { 8965 var primary = _a.primary, triggeringPath = _a.triggeringPath; 8966 detail.onRepositionMenu(container, primary, triggeringPath); 8967 }); 8968 }; 8969 var apis = { 8970 collapseMenu: collapseMenuApi, 8971 highlightPrimary: highlightPrimary, 8972 repositionMenus: repositionMenus 8973 }; 8974 return { 8975 uid: detail.uid, 8976 dom: detail.dom, 8977 markers: detail.markers, 8978 behaviours: augment(detail.tmenuBehaviours, [ 8979 Keying.config({ 8980 mode: 'special', 8981 onRight: keyOnItem(onRight), 8982 onLeft: keyOnItem(onLeft), 8983 onEscape: keyOnItem(onEscape), 8984 focusIn: function (container, _keyInfo) { 8985 layeredState.getPrimary().each(function (primary) { 8986 dispatch(container, primary.element, focusItem()); 8987 }); 8988 } 8989 }), 8990 Highlighting.config({ 8991 highlightClass: detail.markers.selectedMenu, 8992 itemClass: detail.markers.menu 8993 }), 8994 Composing.config({ 8995 find: function (container) { 8996 return Highlighting.getHighlighted(container); 8997 } 8998 }), 8999 Replacing.config({}) 9000 ]), 9001 eventOrder: detail.eventOrder, 9002 apis: apis, 9003 events: events 9004 }; 9005 }; 9006 var collapseItem$1 = constant$1('collapse-item'); 9007 9008 var tieredData = function (primary, menus, expansions) { 9009 return { 9010 primary: primary, 9011 menus: menus, 9012 expansions: expansions 9013 }; 9014 }; 9015 var singleData = function (name, menu) { 9016 return { 9017 primary: name, 9018 menus: wrap$1(name, menu), 9019 expansions: {} 9020 }; 9021 }; 9022 var collapseItem = function (text) { 9023 return { 9024 value: generate$6(collapseItem$1()), 9025 meta: { text: text } 9026 }; 9027 }; 9028 var tieredMenu = single({ 9029 name: 'TieredMenu', 9030 configFields: [ 9031 onStrictKeyboardHandler('onExecute'), 9032 onStrictKeyboardHandler('onEscape'), 9033 onStrictHandler('onOpenMenu'), 9034 onStrictHandler('onOpenSubmenu'), 9035 onHandler('onRepositionMenu'), 9036 onHandler('onCollapseMenu'), 9037 defaulted('highlightImmediately', true), 9038 requiredObjOf('data', [ 9039 required$1('primary'), 9040 required$1('menus'), 9041 required$1('expansions') 9042 ]), 9043 defaulted('fakeFocus', false), 9044 onHandler('onHighlight'), 9045 onHandler('onHover'), 9046 tieredMenuMarkers(), 9047 required$1('dom'), 9048 defaulted('navigateOnHover', true), 9049 defaulted('stayInDom', false), 9050 field('tmenuBehaviours', [ 9051 Keying, 9052 Highlighting, 9053 Composing, 9054 Replacing 9055 ]), 9056 defaulted('eventOrder', {}) 9057 ], 9058 apis: { 9059 collapseMenu: function (apis, tmenu) { 9060 apis.collapseMenu(tmenu); 9061 }, 9062 highlightPrimary: function (apis, tmenu) { 9063 apis.highlightPrimary(tmenu); 9064 }, 9065 repositionMenus: function (apis, tmenu) { 9066 apis.repositionMenus(tmenu); 9067 } 9068 }, 9069 factory: make$6, 9070 extraApis: { 9071 tieredData: tieredData, 9072 singleData: singleData, 9073 collapseItem: collapseItem 9074 } 9075 }); 9076 9077 var makeMenu = function (detail, menuSandbox, placementSpec, menuSpec, getBounds) { 9078 var lazySink = function () { 9079 return detail.lazySink(menuSandbox); 9080 }; 9081 var layouts = menuSpec.type === 'horizontal' ? { 9082 layouts: { 9083 onLtr: function () { 9084 return belowOrAbove(); 9085 }, 9086 onRtl: function () { 9087 return belowOrAboveRtl(); 9088 } 9089 } 9090 } : {}; 9091 var isFirstTierSubmenu = function (triggeringPaths) { 9092 return triggeringPaths.length === 2; 9093 }; 9094 var getSubmenuLayouts = function (triggeringPaths) { 9095 return isFirstTierSubmenu(triggeringPaths) ? layouts : {}; 9096 }; 9097 return tieredMenu.sketch({ 9098 dom: { tag: 'div' }, 9099 data: menuSpec.data, 9100 markers: menuSpec.menu.markers, 9101 highlightImmediately: menuSpec.menu.highlightImmediately, 9102 onEscape: function () { 9103 Sandboxing.close(menuSandbox); 9104 detail.onEscape.map(function (handler) { 9105 return handler(menuSandbox); 9106 }); 9107 return Optional.some(true); 9108 }, 9109 onExecute: function () { 9110 return Optional.some(true); 9111 }, 9112 onOpenMenu: function (tmenu, menu) { 9113 Positioning.positionWithinBounds(lazySink().getOrDie(), menu, placementSpec, getBounds()); 9114 }, 9115 onOpenSubmenu: function (tmenu, item, submenu, triggeringPaths) { 9116 var sink = lazySink().getOrDie(); 9117 Positioning.position(sink, submenu, { 9118 anchor: __assign({ 9119 type: 'submenu', 9120 item: item 9121 }, getSubmenuLayouts(triggeringPaths)) 9122 }); 9123 }, 9124 onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) { 9125 var sink = lazySink().getOrDie(); 9126 Positioning.positionWithinBounds(sink, primaryMenu, placementSpec, getBounds()); 9127 each$1(submenuTriggers, function (st) { 9128 var submenuLayouts = getSubmenuLayouts(st.triggeringPath); 9129 Positioning.position(sink, st.triggeredMenu, { 9130 anchor: __assign({ 9131 type: 'submenu', 9132 item: st.triggeringItem 9133 }, submenuLayouts) 9134 }); 9135 }); 9136 } 9137 }); 9138 }; 9139 var factory$m = function (detail, spec) { 9140 var isPartOfRelated = function (sandbox, queryElem) { 9141 var related = detail.getRelated(sandbox); 9142 return related.exists(function (rel) { 9143 return isPartOf$1(rel, queryElem); 9144 }); 9145 }; 9146 var setContent = function (sandbox, thing) { 9147 Sandboxing.setContent(sandbox, thing); 9148 }; 9149 var showAt = function (sandbox, thing, placementSpec) { 9150 showWithin(sandbox, thing, placementSpec, Optional.none()); 9151 }; 9152 var showWithin = function (sandbox, thing, placementSpec, boxElement) { 9153 showWithinBounds(sandbox, thing, placementSpec, function () { 9154 return boxElement.map(function (elem) { 9155 return box$1(elem); 9156 }); 9157 }); 9158 }; 9159 var showWithinBounds = function (sandbox, thing, placementSpec, getBounds) { 9160 var sink = detail.lazySink(sandbox).getOrDie(); 9161 Sandboxing.openWhileCloaked(sandbox, thing, function () { 9162 return Positioning.positionWithinBounds(sink, sandbox, placementSpec, getBounds()); 9163 }); 9164 Representing.setValue(sandbox, Optional.some({ 9165 mode: 'position', 9166 config: placementSpec, 9167 getBounds: getBounds 9168 })); 9169 }; 9170 var showMenuAt = function (sandbox, placementSpec, menuSpec) { 9171 showMenuWithinBounds(sandbox, placementSpec, menuSpec, Optional.none); 9172 }; 9173 var showMenuWithinBounds = function (sandbox, placementSpec, menuSpec, getBounds) { 9174 var menu = makeMenu(detail, sandbox, placementSpec, menuSpec, getBounds); 9175 Sandboxing.open(sandbox, menu); 9176 Representing.setValue(sandbox, Optional.some({ 9177 mode: 'menu', 9178 menu: menu 9179 })); 9180 }; 9181 var hide = function (sandbox) { 9182 if (Sandboxing.isOpen(sandbox)) { 9183 Representing.setValue(sandbox, Optional.none()); 9184 Sandboxing.close(sandbox); 9185 } 9186 }; 9187 var getContent = function (sandbox) { 9188 return Sandboxing.getState(sandbox); 9189 }; 9190 var reposition = function (sandbox) { 9191 if (Sandboxing.isOpen(sandbox)) { 9192 Representing.getValue(sandbox).each(function (state) { 9193 switch (state.mode) { 9194 case 'menu': 9195 Sandboxing.getState(sandbox).each(tieredMenu.repositionMenus); 9196 break; 9197 case 'position': 9198 var sink = detail.lazySink(sandbox).getOrDie(); 9199 Positioning.positionWithinBounds(sink, sandbox, state.config, state.getBounds()); 9200 break; 9201 } 9202 }); 9203 } 9204 }; 9205 var apis = { 9206 setContent: setContent, 9207 showAt: showAt, 9208 showWithin: showWithin, 9209 showWithinBounds: showWithinBounds, 9210 showMenuAt: showMenuAt, 9211 showMenuWithinBounds: showMenuWithinBounds, 9212 hide: hide, 9213 getContent: getContent, 9214 reposition: reposition, 9215 isOpen: Sandboxing.isOpen 9216 }; 9217 return { 9218 uid: detail.uid, 9219 dom: detail.dom, 9220 behaviours: augment(detail.inlineBehaviours, [ 9221 Sandboxing.config({ 9222 isPartOf: function (sandbox, data, queryElem) { 9223 return isPartOf$1(data, queryElem) || isPartOfRelated(sandbox, queryElem); 9224 }, 9225 getAttachPoint: function (sandbox) { 9226 return detail.lazySink(sandbox).getOrDie(); 9227 }, 9228 onOpen: function (sandbox) { 9229 detail.onShow(sandbox); 9230 }, 9231 onClose: function (sandbox) { 9232 detail.onHide(sandbox); 9233 } 9234 }), 9235 Representing.config({ 9236 store: { 9237 mode: 'memory', 9238 initialValue: Optional.none() 9239 } 9240 }), 9241 Receiving.config({ 9242 channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: spec.isExtraPart }, detail.fireDismissalEventInstead.map(function (fe) { 9243 return { fireEventInstead: { event: fe.event } }; 9244 }).getOr({})))), receivingChannel(__assign(__assign({}, detail.fireRepositionEventInstead.map(function (fe) { 9245 return { fireEventInstead: { event: fe.event } }; 9246 }).getOr({})), { doReposition: reposition }))) 9247 }) 9248 ]), 9249 eventOrder: detail.eventOrder, 9250 apis: apis 9251 }; 9252 }; 9253 var InlineView = single({ 9254 name: 'InlineView', 9255 configFields: [ 9256 required$1('lazySink'), 9257 onHandler('onShow'), 9258 onHandler('onHide'), 9259 optionFunction('onEscape'), 9260 field('inlineBehaviours', [ 9261 Sandboxing, 9262 Representing, 9263 Receiving 9264 ]), 9265 optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]), 9266 optionObjOf('fireRepositionEventInstead', [defaulted('event', repositionRequested())]), 9267 defaulted('getRelated', Optional.none), 9268 defaulted('isExtraPart', never), 9269 defaulted('eventOrder', Optional.none) 9270 ], 9271 factory: factory$m, 9272 apis: { 9273 showAt: function (apis, component, anchor, thing) { 9274 apis.showAt(component, anchor, thing); 9275 }, 9276 showWithin: function (apis, component, anchor, thing, boxElement) { 9277 apis.showWithin(component, anchor, thing, boxElement); 9278 }, 9279 showWithinBounds: function (apis, component, anchor, thing, bounds) { 9280 apis.showWithinBounds(component, anchor, thing, bounds); 9281 }, 9282 showMenuAt: function (apis, component, anchor, menuSpec) { 9283 apis.showMenuAt(component, anchor, menuSpec); 9284 }, 9285 showMenuWithinBounds: function (apis, component, anchor, menuSpec, bounds) { 9286 apis.showMenuWithinBounds(component, anchor, menuSpec, bounds); 9287 }, 9288 hide: function (apis, component) { 9289 apis.hide(component); 9290 }, 9291 isOpen: function (apis, component) { 9292 return apis.isOpen(component); 9293 }, 9294 getContent: function (apis, component) { 9295 return apis.getContent(component); 9296 }, 9297 setContent: function (apis, component, thing) { 9298 apis.setContent(component, thing); 9299 }, 9300 reposition: function (apis, component) { 9301 apis.reposition(component); 9302 } 9303 } 9304 }); 9305 9306 var labelPrefix = 'layout-inset'; 9307 var westEdgeX = function (anchor) { 9308 return anchor.x; 9309 }; 9310 var middleX = function (anchor, element) { 9311 return anchor.x + anchor.width / 2 - element.width / 2; 9312 }; 9313 var eastEdgeX = function (anchor, element) { 9314 return anchor.x + anchor.width - element.width; 9315 }; 9316 var northY = function (anchor) { 9317 return anchor.y; 9318 }; 9319 var southY = function (anchor, element) { 9320 return anchor.y + anchor.height - element.height; 9321 }; 9322 var centreY = function (anchor, element) { 9323 return anchor.y + anchor.height / 2 - element.height / 2; 9324 }; 9325 var southwest = function (anchor, element, bubbles) { 9326 return nu$6(eastEdgeX(anchor, element), southY(anchor, element), bubbles.insetSouthwest(), northwest$3(), 'southwest', boundsRestriction(anchor, { 9327 right: 0, 9328 bottom: 3 9329 }), labelPrefix); 9330 }; 9331 var southeast = function (anchor, element, bubbles) { 9332 return nu$6(westEdgeX(anchor), southY(anchor, element), bubbles.insetSoutheast(), northeast$3(), 'southeast', boundsRestriction(anchor, { 9333 left: 1, 9334 bottom: 3 9335 }), labelPrefix); 9336 }; 9337 var northwest = function (anchor, element, bubbles) { 9338 return nu$6(eastEdgeX(anchor, element), northY(anchor), bubbles.insetNorthwest(), southwest$3(), 'northwest', boundsRestriction(anchor, { 9339 right: 0, 9340 top: 2 9341 }), labelPrefix); 9342 }; 9343 var northeast = function (anchor, element, bubbles) { 9344 return nu$6(westEdgeX(anchor), northY(anchor), bubbles.insetNortheast(), southeast$3(), 'northeast', boundsRestriction(anchor, { 9345 left: 1, 9346 top: 2 9347 }), labelPrefix); 9348 }; 9349 var north = function (anchor, element, bubbles) { 9350 return nu$6(middleX(anchor, element), northY(anchor), bubbles.insetNorth(), south$3(), 'north', boundsRestriction(anchor, { top: 2 }), labelPrefix); 9351 }; 9352 var south = function (anchor, element, bubbles) { 9353 return nu$6(middleX(anchor, element), southY(anchor, element), bubbles.insetSouth(), north$3(), 'south', boundsRestriction(anchor, { bottom: 3 }), labelPrefix); 9354 }; 9355 var east = function (anchor, element, bubbles) { 9356 return nu$6(eastEdgeX(anchor, element), centreY(anchor, element), bubbles.insetEast(), west$3(), 'east', boundsRestriction(anchor, { right: 0 }), labelPrefix); 9357 }; 9358 var west = function (anchor, element, bubbles) { 9359 return nu$6(westEdgeX(anchor), centreY(anchor, element), bubbles.insetWest(), east$3(), 'west', boundsRestriction(anchor, { left: 1 }), labelPrefix); 9360 }; 9361 var lookupPreserveLayout = function (lastPlacement) { 9362 switch (lastPlacement) { 9363 case 'north': 9364 return north; 9365 case 'northeast': 9366 return northeast; 9367 case 'northwest': 9368 return northwest; 9369 case 'south': 9370 return south; 9371 case 'southeast': 9372 return southeast; 9373 case 'southwest': 9374 return southwest; 9375 case 'east': 9376 return east; 9377 case 'west': 9378 return west; 9379 } 9380 }; 9381 var preserve = function (anchor, element, bubbles, placee, bounds) { 9382 var layout = getPlacement(placee).map(lookupPreserveLayout).getOr(north); 9383 return layout(anchor, element, bubbles, placee, bounds); 9384 }; 9385 var lookupFlippedLayout = function (lastPlacement) { 9386 switch (lastPlacement) { 9387 case 'north': 9388 return south; 9389 case 'northeast': 9390 return southeast; 9391 case 'northwest': 9392 return southwest; 9393 case 'south': 9394 return north; 9395 case 'southeast': 9396 return northeast; 9397 case 'southwest': 9398 return northwest; 9399 case 'east': 9400 return west; 9401 case 'west': 9402 return east; 9403 } 9404 }; 9405 var flip$2 = function (anchor, element, bubbles, placee, bounds) { 9406 var layout = getPlacement(placee).map(lookupFlippedLayout).getOr(north); 9407 return layout(anchor, element, bubbles, placee, bounds); 9408 }; 9409 9410 var global$f = tinymce.util.Tools.resolve('tinymce.util.Delay'); 9411 9412 var factory$l = function (detail) { 9413 var events = events$a(detail.action); 9414 var tag = detail.dom.tag; 9415 var lookupAttr = function (attr) { 9416 return get$e(detail.dom, 'attributes').bind(function (attrs) { 9417 return get$e(attrs, attr); 9418 }); 9419 }; 9420 var getModAttributes = function () { 9421 if (tag === 'button') { 9422 var type = lookupAttr('type').getOr('button'); 9423 var roleAttrs = lookupAttr('role').map(function (role) { 9424 return { role: role }; 9425 }).getOr({}); 9426 return __assign({ type: type }, roleAttrs); 9427 } else { 9428 var role = lookupAttr('role').getOr('button'); 9429 return { role: role }; 9430 } 9431 }; 9432 return { 9433 uid: detail.uid, 9434 dom: detail.dom, 9435 components: detail.components, 9436 events: events, 9437 behaviours: SketchBehaviours.augment(detail.buttonBehaviours, [ 9438 Focusing.config({}), 9439 Keying.config({ 9440 mode: 'execution', 9441 useSpace: true, 9442 useEnter: true 9443 }) 9444 ]), 9445 domModification: { attributes: getModAttributes() }, 9446 eventOrder: detail.eventOrder 9447 }; 9448 }; 9449 var Button = single({ 9450 name: 'Button', 9451 factory: factory$l, 9452 configFields: [ 9453 defaulted('uid', undefined), 9454 required$1('dom'), 9455 defaulted('components', []), 9456 SketchBehaviours.field('buttonBehaviours', [ 9457 Focusing, 9458 Keying 9459 ]), 9460 option('action'), 9461 option('role'), 9462 defaulted('eventOrder', {}) 9463 ] 9464 }); 9465 9466 var record = function (spec) { 9467 var uid = isSketchSpec(spec) && hasNonNullableKey(spec, 'uid') ? spec.uid : generate$5('memento'); 9468 var get = function (anyInSystem) { 9469 return anyInSystem.getSystem().getByUid(uid).getOrDie(); 9470 }; 9471 var getOpt = function (anyInSystem) { 9472 return anyInSystem.getSystem().getByUid(uid).toOptional(); 9473 }; 9474 var asSpec = function () { 9475 return __assign(__assign({}, spec), { uid: uid }); 9476 }; 9477 return { 9478 get: get, 9479 getOpt: getOpt, 9480 asSpec: asSpec 9481 }; 9482 }; 9483 9484 var global$e = tinymce.util.Tools.resolve('tinymce.util.I18n'); 9485 9486 var rtlTransform = { 9487 'indent': true, 9488 'outdent': true, 9489 'table-insert-column-after': true, 9490 'table-insert-column-before': true, 9491 'paste-column-after': true, 9492 'paste-column-before': true, 9493 'unordered-list': true, 9494 'list-bull-circle': true, 9495 'list-bull-default': true, 9496 'list-bull-square': true 9497 }; 9498 var defaultIconName = 'temporary-placeholder'; 9499 var defaultIcon = function (icons) { 9500 return function () { 9501 return get$e(icons, defaultIconName).getOr('!not found!'); 9502 }; 9503 }; 9504 var getIconName = function (name, icons) { 9505 var lcName = name.toLowerCase(); 9506 if (global$e.isRtl()) { 9507 var rtlName = ensureTrailing(lcName, '-rtl'); 9508 return has$2(icons, rtlName) ? rtlName : lcName; 9509 } else { 9510 return lcName; 9511 } 9512 }; 9513 var lookupIcon = function (name, icons) { 9514 return get$e(icons, getIconName(name, icons)); 9515 }; 9516 var get$1 = function (name, iconProvider) { 9517 var icons = iconProvider(); 9518 return lookupIcon(name, icons).getOrThunk(defaultIcon(icons)); 9519 }; 9520 var getOr = function (name, iconProvider, fallbackIcon) { 9521 var icons = iconProvider(); 9522 return lookupIcon(name, icons).or(fallbackIcon).getOrThunk(defaultIcon(icons)); 9523 }; 9524 var needsRtlTransform = function (iconName) { 9525 return global$e.isRtl() ? has$2(rtlTransform, iconName) : false; 9526 }; 9527 var addFocusableBehaviour = function () { 9528 return config('add-focusable', [runOnAttached(function (comp) { 9529 child(comp.element, 'svg').each(function (svg) { 9530 return set$8(svg, 'focusable', 'false'); 9531 }); 9532 })]); 9533 }; 9534 var renderIcon$2 = function (spec, iconName, icons, fallbackIcon) { 9535 var _a, _b; 9536 var rtlIconClasses = needsRtlTransform(iconName) ? ['tox-icon--flip'] : []; 9537 var iconHtml = get$e(icons, getIconName(iconName, icons)).or(fallbackIcon).getOrThunk(defaultIcon(icons)); 9538 return { 9539 dom: { 9540 tag: spec.tag, 9541 attributes: (_a = spec.attributes) !== null && _a !== void 0 ? _a : {}, 9542 classes: spec.classes.concat(rtlIconClasses), 9543 innerHtml: iconHtml 9544 }, 9545 behaviours: derive$1(__spreadArray(__spreadArray([], (_b = spec.behaviours) !== null && _b !== void 0 ? _b : [], true), [addFocusableBehaviour()], false)) 9546 }; 9547 }; 9548 var render$3 = function (iconName, spec, iconProvider, fallbackIcon) { 9549 if (fallbackIcon === void 0) { 9550 fallbackIcon = Optional.none(); 9551 } 9552 return renderIcon$2(spec, iconName, iconProvider(), fallbackIcon); 9553 }; 9554 var renderFirst = function (iconNames, spec, iconProvider) { 9555 var icons = iconProvider(); 9556 var iconName = find$5(iconNames, function (name) { 9557 return has$2(icons, getIconName(name, icons)); 9558 }); 9559 return renderIcon$2(spec, iconName.getOr(defaultIconName), icons, Optional.none()); 9560 }; 9561 9562 var notificationIconMap = { 9563 success: 'checkmark', 9564 error: 'warning', 9565 err: 'error', 9566 warning: 'warning', 9567 warn: 'warning', 9568 info: 'info' 9569 }; 9570 var factory$k = function (detail) { 9571 var memBannerText = record({ 9572 dom: { 9573 tag: 'p', 9574 innerHtml: detail.translationProvider(detail.text) 9575 }, 9576 behaviours: derive$1([Replacing.config({})]) 9577 }); 9578 var renderPercentBar = function (percent) { 9579 return { 9580 dom: { 9581 tag: 'div', 9582 classes: ['tox-bar'], 9583 attributes: { style: 'width: ' + percent + '%' } 9584 } 9585 }; 9586 }; 9587 var renderPercentText = function (percent) { 9588 return { 9589 dom: { 9590 tag: 'div', 9591 classes: ['tox-text'], 9592 innerHtml: percent + '%' 9593 } 9594 }; 9595 }; 9596 var memBannerProgress = record({ 9597 dom: { 9598 tag: 'div', 9599 classes: detail.progress ? [ 9600 'tox-progress-bar', 9601 'tox-progress-indicator' 9602 ] : ['tox-progress-bar'] 9603 }, 9604 components: [ 9605 { 9606 dom: { 9607 tag: 'div', 9608 classes: ['tox-bar-container'] 9609 }, 9610 components: [renderPercentBar(0)] 9611 }, 9612 renderPercentText(0) 9613 ], 9614 behaviours: derive$1([Replacing.config({})]) 9615 }); 9616 var updateProgress = function (comp, percent) { 9617 if (comp.getSystem().isConnected()) { 9618 memBannerProgress.getOpt(comp).each(function (progress) { 9619 Replacing.set(progress, [ 9620 { 9621 dom: { 9622 tag: 'div', 9623 classes: ['tox-bar-container'] 9624 }, 9625 components: [renderPercentBar(percent)] 9626 }, 9627 renderPercentText(percent) 9628 ]); 9629 }); 9630 } 9631 }; 9632 var updateText = function (comp, text$1) { 9633 if (comp.getSystem().isConnected()) { 9634 var banner = memBannerText.get(comp); 9635 Replacing.set(banner, [text(text$1)]); 9636 } 9637 }; 9638 var apis = { 9639 updateProgress: updateProgress, 9640 updateText: updateText 9641 }; 9642 var iconChoices = flatten([ 9643 detail.icon.toArray(), 9644 detail.level.toArray(), 9645 detail.level.bind(function (level) { 9646 return Optional.from(notificationIconMap[level]); 9647 }).toArray() 9648 ]); 9649 var memButton = record(Button.sketch({ 9650 dom: { 9651 tag: 'button', 9652 classes: [ 9653 'tox-notification__dismiss', 9654 'tox-button', 9655 'tox-button--naked', 9656 'tox-button--icon' 9657 ] 9658 }, 9659 components: [render$3('close', { 9660 tag: 'div', 9661 classes: ['tox-icon'], 9662 attributes: { 'aria-label': detail.translationProvider('Close') } 9663 }, detail.iconProvider)], 9664 action: function (comp) { 9665 detail.onAction(comp); 9666 } 9667 })); 9668 var notificationIconSpec = renderFirst(iconChoices, { 9669 tag: 'div', 9670 classes: ['tox-notification__icon'] 9671 }, detail.iconProvider); 9672 var notificationBodySpec = { 9673 dom: { 9674 tag: 'div', 9675 classes: ['tox-notification__body'] 9676 }, 9677 components: [memBannerText.asSpec()], 9678 behaviours: derive$1([Replacing.config({})]) 9679 }; 9680 var components = [ 9681 notificationIconSpec, 9682 notificationBodySpec 9683 ]; 9684 return { 9685 uid: detail.uid, 9686 dom: { 9687 tag: 'div', 9688 attributes: { role: 'alert' }, 9689 classes: detail.level.map(function (level) { 9690 return [ 9691 'tox-notification', 9692 'tox-notification--in', 9693 'tox-notification--' + level 9694 ]; 9695 }).getOr([ 9696 'tox-notification', 9697 'tox-notification--in' 9698 ]) 9699 }, 9700 behaviours: derive$1([ 9701 Focusing.config({}), 9702 config('notification-events', [run$1(focusin(), function (comp) { 9703 memButton.getOpt(comp).each(Focusing.focus); 9704 })]) 9705 ]), 9706 components: components.concat(detail.progress ? [memBannerProgress.asSpec()] : []).concat(!detail.closeButton ? [] : [memButton.asSpec()]), 9707 apis: apis 9708 }; 9709 }; 9710 var Notification = single({ 9711 name: 'Notification', 9712 factory: factory$k, 9713 configFields: [ 9714 option('level'), 9715 required$1('progress'), 9716 required$1('icon'), 9717 required$1('onAction'), 9718 required$1('text'), 9719 required$1('iconProvider'), 9720 required$1('translationProvider'), 9721 defaultedBoolean('closeButton', true) 9722 ], 9723 apis: { 9724 updateProgress: function (apis, comp, percent) { 9725 apis.updateProgress(comp, percent); 9726 }, 9727 updateText: function (apis, comp, text) { 9728 apis.updateText(comp, text); 9729 } 9730 } 9731 }); 9732 9733 function NotificationManagerImpl (editor, extras, uiMothership) { 9734 var sharedBackstage = extras.backstage.shared; 9735 var getLayoutDirection = function (rel) { 9736 switch (rel) { 9737 case 'bc-bc': 9738 return south; 9739 case 'tc-tc': 9740 return north; 9741 case 'tc-bc': 9742 return north$2; 9743 case 'bc-tc': 9744 default: 9745 return south$2; 9746 } 9747 }; 9748 var reposition = function (notifications) { 9749 if (notifications.length > 0) { 9750 each$1(notifications, function (notification, index) { 9751 if (index === 0) { 9752 notification.moveRel(null, 'banner'); 9753 } else { 9754 notification.moveRel(notifications[index - 1].getEl(), 'bc-tc'); 9755 } 9756 }); 9757 } 9758 }; 9759 var open = function (settings, closeCallback) { 9760 var hideCloseButton = !settings.closeButton && settings.timeout && (settings.timeout > 0 || settings.timeout < 0); 9761 var close = function () { 9762 closeCallback(); 9763 InlineView.hide(notificationWrapper); 9764 }; 9765 var notification = build$1(Notification.sketch({ 9766 text: settings.text, 9767 level: contains$2([ 9768 'success', 9769 'error', 9770 'warning', 9771 'warn', 9772 'info' 9773 ], settings.type) ? settings.type : undefined, 9774 progress: settings.progressBar === true, 9775 icon: Optional.from(settings.icon), 9776 closeButton: !hideCloseButton, 9777 onAction: close, 9778 iconProvider: sharedBackstage.providers.icons, 9779 translationProvider: sharedBackstage.providers.translate 9780 })); 9781 var notificationWrapper = build$1(InlineView.sketch(__assign({ 9782 dom: { 9783 tag: 'div', 9784 classes: ['tox-notifications-container'] 9785 }, 9786 lazySink: sharedBackstage.getSink, 9787 fireDismissalEventInstead: {} 9788 }, sharedBackstage.header.isPositionedAtTop() ? {} : { fireRepositionEventInstead: {} }))); 9789 uiMothership.add(notificationWrapper); 9790 if (settings.timeout > 0) { 9791 global$f.setTimeout(function () { 9792 close(); 9793 }, settings.timeout); 9794 } 9795 var getBounds = function () { 9796 var contentArea = box$1(SugarElement.fromDom(editor.getContentAreaContainer())); 9797 var win$1 = win(); 9798 var x = clamp$1(win$1.x, contentArea.x, contentArea.right); 9799 var y = clamp$1(win$1.y, contentArea.y, contentArea.bottom); 9800 var right = Math.max(contentArea.right, win$1.right); 9801 var bottom = Math.max(contentArea.bottom, win$1.bottom); 9802 return Optional.some(bounds(x, y, right - x, bottom - y)); 9803 }; 9804 return { 9805 close: close, 9806 moveTo: function (x, y) { 9807 InlineView.showAt(notificationWrapper, premade(notification), { 9808 anchor: { 9809 type: 'makeshift', 9810 x: x, 9811 y: y 9812 } 9813 }); 9814 }, 9815 moveRel: function (element, rel) { 9816 var notificationSpec = premade(notification); 9817 var anchorOverrides = { maxHeightFunction: expandable$1() }; 9818 if (rel !== 'banner' && isNonNullable(element)) { 9819 var layoutDirection_1 = getLayoutDirection(rel); 9820 var nodeAnchor = { 9821 type: 'node', 9822 root: body(), 9823 node: Optional.some(SugarElement.fromDom(element)), 9824 overrides: anchorOverrides, 9825 layouts: { 9826 onRtl: function () { 9827 return [layoutDirection_1]; 9828 }, 9829 onLtr: function () { 9830 return [layoutDirection_1]; 9831 } 9832 } 9833 }; 9834 InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: nodeAnchor }, getBounds); 9835 } else { 9836 var anchor = __assign(__assign({}, sharedBackstage.anchors.banner()), { overrides: anchorOverrides }); 9837 InlineView.showWithinBounds(notificationWrapper, notificationSpec, { anchor: anchor }, getBounds); 9838 } 9839 }, 9840 text: function (nuText) { 9841 Notification.updateText(notification, nuText); 9842 }, 9843 settings: settings, 9844 getEl: function () { 9845 return notification.element.dom; 9846 }, 9847 progressBar: { 9848 value: function (percent) { 9849 Notification.updateProgress(notification, percent); 9850 } 9851 } 9852 }; 9853 }; 9854 var close = function (notification) { 9855 notification.close(); 9856 }; 9857 var getArgs = function (notification) { 9858 return notification.settings; 9859 }; 9860 return { 9861 open: open, 9862 close: close, 9863 reposition: reposition, 9864 getArgs: getArgs 9865 }; 9866 } 9867 9868 var first = function (fn, rate) { 9869 var timer = null; 9870 var cancel = function () { 9871 if (!isNull(timer)) { 9872 clearTimeout(timer); 9873 timer = null; 9874 } 9875 }; 9876 var throttle = function () { 9877 var args = []; 9878 for (var _i = 0; _i < arguments.length; _i++) { 9879 args[_i] = arguments[_i]; 9880 } 9881 if (isNull(timer)) { 9882 timer = setTimeout(function () { 9883 timer = null; 9884 fn.apply(null, args); 9885 }, rate); 9886 } 9887 }; 9888 return { 9889 cancel: cancel, 9890 throttle: throttle 9891 }; 9892 }; 9893 var last = function (fn, rate) { 9894 var timer = null; 9895 var cancel = function () { 9896 if (!isNull(timer)) { 9897 clearTimeout(timer); 9898 timer = null; 9899 } 9900 }; 9901 var throttle = function () { 9902 var args = []; 9903 for (var _i = 0; _i < arguments.length; _i++) { 9904 args[_i] = arguments[_i]; 9905 } 9906 cancel(); 9907 timer = setTimeout(function () { 9908 timer = null; 9909 fn.apply(null, args); 9910 }, rate); 9911 }; 9912 return { 9913 cancel: cancel, 9914 throttle: throttle 9915 }; 9916 }; 9917 9918 var global$d = tinymce.util.Tools.resolve('tinymce.dom.TextSeeker'); 9919 9920 var isBoundary = function (dom, node) { 9921 return dom.isBlock(node) || contains$2([ 9922 'BR', 9923 'IMG', 9924 'HR', 9925 'INPUT' 9926 ], node.nodeName) || dom.getContentEditable(node) === 'false'; 9927 }; 9928 var repeatLeft = function (dom, node, offset, process, rootNode) { 9929 var search = global$d(dom, function (node) { 9930 return isBoundary(dom, node); 9931 }); 9932 return Optional.from(search.backwards(node, offset, process, rootNode)); 9933 }; 9934 9935 var autocompleteSelector = '[data-mce-autocompleter]'; 9936 var create$4 = function (editor, range) { 9937 return detect(SugarElement.fromDom(editor.selection.getNode())).getOrThunk(function () { 9938 var wrapper = SugarElement.fromHtml('<span data-mce-autocompleter="1" data-mce-bogus="1"></span>', editor.getDoc()); 9939 append$2(wrapper, SugarElement.fromDom(range.extractContents())); 9940 range.insertNode(wrapper.dom); 9941 parent(wrapper).each(function (elm) { 9942 return elm.dom.normalize(); 9943 }); 9944 last$1(wrapper).map(function (last) { 9945 editor.selection.setCursorLocation(last.dom, getEnd(last)); 9946 }); 9947 return wrapper; 9948 }); 9949 }; 9950 var detect = function (elm) { 9951 return closest$1(elm, autocompleteSelector); 9952 }; 9953 9954 var isValidTextRange = function (rng) { 9955 return rng.collapsed && rng.startContainer.nodeType === 3; 9956 }; 9957 var getText = function (rng) { 9958 return rng.toString().replace(/\u00A0/g, ' ').replace(/\uFEFF/g, ''); 9959 }; 9960 var isWhitespace = function (chr) { 9961 return chr !== '' && ' \xA0\f\n\r\t\x0B'.indexOf(chr) !== -1; 9962 }; 9963 9964 var stripTriggerChar = function (text, triggerCh) { 9965 return text.substring(triggerCh.length); 9966 }; 9967 var findChar = function (text, index, ch) { 9968 var i; 9969 for (i = index - 1; i >= 0; i--) { 9970 var char = text.charAt(i); 9971 if (isWhitespace(char)) { 9972 return Optional.none(); 9973 } 9974 if (char === ch) { 9975 break; 9976 } 9977 } 9978 return Optional.some(i); 9979 }; 9980 var findStart = function (dom, initRange, ch, minChars) { 9981 if (minChars === void 0) { 9982 minChars = 0; 9983 } 9984 if (!isValidTextRange(initRange)) { 9985 return Optional.none(); 9986 } 9987 var findTriggerChIndex = function (element, offset, text) { 9988 return findChar(text, offset, ch).getOr(offset); 9989 }; 9990 var root = dom.getParent(initRange.startContainer, dom.isBlock) || dom.getRoot(); 9991 return repeatLeft(dom, initRange.startContainer, initRange.startOffset, findTriggerChIndex, root).bind(function (spot) { 9992 var range = initRange.cloneRange(); 9993 range.setStart(spot.container, spot.offset); 9994 range.setEnd(initRange.endContainer, initRange.endOffset); 9995 if (range.collapsed) { 9996 return Optional.none(); 9997 } 9998 var text = getText(range); 9999 var triggerCharIndex = text.lastIndexOf(ch); 10000 if (triggerCharIndex !== 0 || stripTriggerChar(text, ch).length < minChars) { 10001 return Optional.none(); 10002 } else { 10003 return Optional.some({ 10004 text: stripTriggerChar(text, ch), 10005 range: range, 10006 triggerChar: ch 10007 }); 10008 } 10009 }); 10010 }; 10011 var getContext = function (dom, initRange, ch, minChars) { 10012 if (minChars === void 0) { 10013 minChars = 0; 10014 } 10015 return detect(SugarElement.fromDom(initRange.startContainer)).fold(function () { 10016 return findStart(dom, initRange, ch, minChars); 10017 }, function (elm) { 10018 var range = dom.createRng(); 10019 range.selectNode(elm.dom); 10020 var text = getText(range); 10021 return Optional.some({ 10022 range: range, 10023 text: stripTriggerChar(text, ch), 10024 triggerChar: ch 10025 }); 10026 }); 10027 }; 10028 10029 var setup$e = function (api, editor) { 10030 editor.on('keypress compositionend', api.onKeypress.throttle); 10031 editor.on('remove', api.onKeypress.cancel); 10032 var redirectKeyToItem = function (item, e) { 10033 emitWith(item, keydown(), { raw: e }); 10034 }; 10035 editor.on('keydown', function (e) { 10036 var getItem = function () { 10037 return api.getView().bind(Highlighting.getHighlighted); 10038 }; 10039 if (e.which === 8) { 10040 api.onKeypress.throttle(e); 10041 } 10042 if (api.isActive()) { 10043 if (e.which === 27) { 10044 api.cancelIfNecessary(); 10045 } 10046 if (api.isMenuOpen()) { 10047 if (e.which === 13) { 10048 getItem().each(emitExecute); 10049 e.preventDefault(); 10050 } else if (e.which === 40) { 10051 getItem().fold(function () { 10052 api.getView().each(Highlighting.highlightFirst); 10053 }, function (item) { 10054 redirectKeyToItem(item, e); 10055 }); 10056 e.preventDefault(); 10057 e.stopImmediatePropagation(); 10058 } else if (e.which === 37 || e.which === 38 || e.which === 39) { 10059 getItem().each(function (item) { 10060 redirectKeyToItem(item, e); 10061 e.preventDefault(); 10062 e.stopImmediatePropagation(); 10063 }); 10064 } 10065 } else { 10066 if (e.which === 13 || e.which === 38 || e.which === 40) { 10067 api.cancelIfNecessary(); 10068 } 10069 } 10070 } 10071 }); 10072 editor.on('NodeChange', function (e) { 10073 if (api.isActive() && !api.isProcessingAction() && detect(SugarElement.fromDom(e.element)).isNone()) { 10074 api.cancelIfNecessary(); 10075 } 10076 }); 10077 }; 10078 var AutocompleterEditorEvents = { setup: setup$e }; 10079 10080 var global$c = tinymce.util.Tools.resolve('tinymce.util.Promise'); 10081 10082 var point = function (container, offset) { 10083 return { 10084 container: container, 10085 offset: offset 10086 }; 10087 }; 10088 10089 var isText = function (node) { 10090 return node.nodeType === TEXT; 10091 }; 10092 var isElement$1 = function (node) { 10093 return node.nodeType === ELEMENT; 10094 }; 10095 var toLast = function (node) { 10096 if (isText(node)) { 10097 return point(node, node.data.length); 10098 } else { 10099 var children = node.childNodes; 10100 return children.length > 0 ? toLast(children[children.length - 1]) : point(node, children.length); 10101 } 10102 }; 10103 var toLeaf = function (node, offset) { 10104 var children = node.childNodes; 10105 if (children.length > 0 && offset < children.length) { 10106 return toLeaf(children[offset], 0); 10107 } else if (children.length > 0 && isElement$1(node) && children.length === offset) { 10108 return toLast(children[children.length - 1]); 10109 } else { 10110 return point(node, offset); 10111 } 10112 }; 10113 10114 var isPreviousCharContent = function (dom, leaf) { 10115 return repeatLeft(dom, leaf.container, leaf.offset, function (element, offset) { 10116 return offset === 0 ? -1 : offset; 10117 }, dom.getRoot()).filter(function (spot) { 10118 var char = spot.container.data.charAt(spot.offset - 1); 10119 return !isWhitespace(char); 10120 }).isSome(); 10121 }; 10122 var isStartOfWord = function (dom) { 10123 return function (rng) { 10124 var leaf = toLeaf(rng.startContainer, rng.startOffset); 10125 return !isPreviousCharContent(dom, leaf); 10126 }; 10127 }; 10128 var getTriggerContext = function (dom, initRange, database) { 10129 return findMap(database.triggerChars, function (ch) { 10130 return getContext(dom, initRange, ch); 10131 }); 10132 }; 10133 var lookup$2 = function (editor, getDatabase) { 10134 var database = getDatabase(); 10135 var rng = editor.selection.getRng(); 10136 return getTriggerContext(editor.dom, rng, database).bind(function (context) { 10137 return lookupWithContext(editor, getDatabase, context); 10138 }); 10139 }; 10140 var lookupWithContext = function (editor, getDatabase, context, fetchOptions) { 10141 if (fetchOptions === void 0) { 10142 fetchOptions = {}; 10143 } 10144 var database = getDatabase(); 10145 var rng = editor.selection.getRng(); 10146 var startText = rng.startContainer.nodeValue; 10147 var autocompleters = filter$2(database.lookupByChar(context.triggerChar), function (autocompleter) { 10148 return context.text.length >= autocompleter.minChars && autocompleter.matches.getOrThunk(function () { 10149 return isStartOfWord(editor.dom); 10150 })(context.range, startText, context.text); 10151 }); 10152 if (autocompleters.length === 0) { 10153 return Optional.none(); 10154 } 10155 var lookupData = global$c.all(map$2(autocompleters, function (ac) { 10156 var fetchResult = ac.fetch(context.text, ac.maxResults, fetchOptions); 10157 return fetchResult.then(function (results) { 10158 return { 10159 matchText: context.text, 10160 items: results, 10161 columns: ac.columns, 10162 onAction: ac.onAction, 10163 highlightOn: ac.highlightOn 10164 }; 10165 }); 10166 })); 10167 return Optional.some({ 10168 lookupData: lookupData, 10169 context: context 10170 }); 10171 }; 10172 10173 var separatorMenuItemSchema = objOf([ 10174 requiredString('type'), 10175 optionString('text') 10176 ]); 10177 var createSeparatorMenuItem = function (spec) { 10178 return asRaw('separatormenuitem', separatorMenuItemSchema, spec); 10179 }; 10180 10181 var autocompleterItemSchema = objOf([ 10182 defaulted('type', 'autocompleteitem'), 10183 defaulted('active', false), 10184 defaulted('disabled', false), 10185 defaulted('meta', {}), 10186 requiredString('value'), 10187 optionString('text'), 10188 optionString('icon') 10189 ]); 10190 var autocompleterSchema = objOf([ 10191 requiredString('type'), 10192 requiredString('ch'), 10193 defaultedNumber('minChars', 1), 10194 defaulted('columns', 1), 10195 defaultedNumber('maxResults', 10), 10196 optionFunction('matches'), 10197 requiredFunction('fetch'), 10198 requiredFunction('onAction'), 10199 defaultedArrayOf('highlightOn', [], string) 10200 ]); 10201 var createSeparatorItem = function (spec) { 10202 return asRaw('Autocompleter.Separator', separatorMenuItemSchema, spec); 10203 }; 10204 var createAutocompleterItem = function (spec) { 10205 return asRaw('Autocompleter.Item', autocompleterItemSchema, spec); 10206 }; 10207 var createAutocompleter = function (spec) { 10208 return asRaw('Autocompleter', autocompleterSchema, spec); 10209 }; 10210 10211 var baseToolbarButtonFields = [ 10212 defaultedBoolean('disabled', false), 10213 optionString('tooltip'), 10214 optionString('icon'), 10215 optionString('text'), 10216 defaultedFunction('onSetup', function () { 10217 return noop; 10218 }) 10219 ]; 10220 var toolbarButtonSchema = objOf([ 10221 requiredString('type'), 10222 requiredFunction('onAction') 10223 ].concat(baseToolbarButtonFields)); 10224 var createToolbarButton = function (spec) { 10225 return asRaw('toolbarbutton', toolbarButtonSchema, spec); 10226 }; 10227 10228 var baseToolbarToggleButtonFields = [defaultedBoolean('active', false)].concat(baseToolbarButtonFields); 10229 var toggleButtonSchema = objOf(baseToolbarToggleButtonFields.concat([ 10230 requiredString('type'), 10231 requiredFunction('onAction') 10232 ])); 10233 var createToggleButton = function (spec) { 10234 return asRaw('ToggleButton', toggleButtonSchema, spec); 10235 }; 10236 10237 var contextBarFields = [ 10238 defaultedFunction('predicate', never), 10239 defaultedStringEnum('scope', 'node', [ 10240 'node', 10241 'editor' 10242 ]), 10243 defaultedStringEnum('position', 'selection', [ 10244 'node', 10245 'selection', 10246 'line' 10247 ]) 10248 ]; 10249 10250 var contextButtonFields = baseToolbarButtonFields.concat([ 10251 defaulted('type', 'contextformbutton'), 10252 defaulted('primary', false), 10253 requiredFunction('onAction'), 10254 customField('original', identity$1) 10255 ]); 10256 var contextToggleButtonFields = baseToolbarToggleButtonFields.concat([ 10257 defaulted('type', 'contextformbutton'), 10258 defaulted('primary', false), 10259 requiredFunction('onAction'), 10260 customField('original', identity$1) 10261 ]); 10262 var launchButtonFields = baseToolbarButtonFields.concat([defaulted('type', 'contextformbutton')]); 10263 var launchToggleButtonFields = baseToolbarToggleButtonFields.concat([defaulted('type', 'contextformtogglebutton')]); 10264 var toggleOrNormal = choose$1('type', { 10265 contextformbutton: contextButtonFields, 10266 contextformtogglebutton: contextToggleButtonFields 10267 }); 10268 var contextFormSchema = objOf([ 10269 defaulted('type', 'contextform'), 10270 defaultedFunction('initValue', constant$1('')), 10271 optionString('label'), 10272 requiredArrayOf('commands', toggleOrNormal), 10273 optionOf('launch', choose$1('type', { 10274 contextformbutton: launchButtonFields, 10275 contextformtogglebutton: launchToggleButtonFields 10276 })) 10277 ].concat(contextBarFields)); 10278 var createContextForm = function (spec) { 10279 return asRaw('ContextForm', contextFormSchema, spec); 10280 }; 10281 10282 var contextToolbarSchema = objOf([ 10283 defaulted('type', 'contexttoolbar'), 10284 requiredString('items') 10285 ].concat(contextBarFields)); 10286 var createContextToolbar = function (spec) { 10287 return asRaw('ContextToolbar', contextToolbarSchema, spec); 10288 }; 10289 10290 var stringArray = function (a) { 10291 var all = {}; 10292 each$1(a, function (key) { 10293 all[key] = {}; 10294 }); 10295 return keys(all); 10296 }; 10297 10298 var register$b = function (editor) { 10299 var popups = editor.ui.registry.getAll().popups; 10300 var dataset = map$1(popups, function (popup) { 10301 return createAutocompleter(popup).fold(function (err) { 10302 throw new Error(formatError(err)); 10303 }, identity$1); 10304 }); 10305 var triggerChars = stringArray(mapToArray(dataset, function (v) { 10306 return v.ch; 10307 })); 10308 var datasetValues = values(dataset); 10309 var lookupByChar = function (ch) { 10310 return filter$2(datasetValues, function (dv) { 10311 return dv.ch === ch; 10312 }); 10313 }; 10314 return { 10315 dataset: dataset, 10316 triggerChars: triggerChars, 10317 lookupByChar: lookupByChar 10318 }; 10319 }; 10320 10321 var ItemResponse; 10322 (function (ItemResponse) { 10323 ItemResponse[ItemResponse['CLOSE_ON_EXECUTE'] = 0] = 'CLOSE_ON_EXECUTE'; 10324 ItemResponse[ItemResponse['BUBBLE_TO_SANDBOX'] = 1] = 'BUBBLE_TO_SANDBOX'; 10325 }(ItemResponse || (ItemResponse = {}))); 10326 var ItemResponse$1 = ItemResponse; 10327 10328 var navClass = 'tox-menu-nav__js'; 10329 var selectableClass = 'tox-collection__item'; 10330 var colorClass = 'tox-swatch'; 10331 var presetClasses = { 10332 normal: navClass, 10333 color: colorClass 10334 }; 10335 var tickedClass = 'tox-collection__item--enabled'; 10336 var groupHeadingClass = 'tox-collection__group-heading'; 10337 var iconClass = 'tox-collection__item-icon'; 10338 var textClass = 'tox-collection__item-label'; 10339 var accessoryClass = 'tox-collection__item-accessory'; 10340 var caretClass = 'tox-collection__item-caret'; 10341 var checkmarkClass = 'tox-collection__item-checkmark'; 10342 var activeClass = 'tox-collection__item--active'; 10343 var containerClass = 'tox-collection__item-container'; 10344 var containerColumnClass = 'tox-collection__item-container--column'; 10345 var containerRowClass = 'tox-collection__item-container--row'; 10346 var containerAlignRightClass = 'tox-collection__item-container--align-right'; 10347 var containerAlignLeftClass = 'tox-collection__item-container--align-left'; 10348 var containerValignTopClass = 'tox-collection__item-container--valign-top'; 10349 var containerValignMiddleClass = 'tox-collection__item-container--valign-middle'; 10350 var containerValignBottomClass = 'tox-collection__item-container--valign-bottom'; 10351 var classForPreset = function (presets) { 10352 return get$e(presetClasses, presets).getOr(navClass); 10353 }; 10354 10355 var forMenu = function (presets) { 10356 if (presets === 'color') { 10357 return 'tox-swatches'; 10358 } else { 10359 return 'tox-menu'; 10360 } 10361 }; 10362 var classes = function (presets) { 10363 return { 10364 backgroundMenu: 'tox-background-menu', 10365 selectedMenu: 'tox-selected-menu', 10366 selectedItem: 'tox-collection__item--active', 10367 hasIcons: 'tox-menu--has-icons', 10368 menu: forMenu(presets), 10369 tieredMenu: 'tox-tiered-menu' 10370 }; 10371 }; 10372 10373 var markers = function (presets) { 10374 var menuClasses = classes(presets); 10375 return { 10376 backgroundMenu: menuClasses.backgroundMenu, 10377 selectedMenu: menuClasses.selectedMenu, 10378 menu: menuClasses.menu, 10379 selectedItem: menuClasses.selectedItem, 10380 item: classForPreset(presets) 10381 }; 10382 }; 10383 var dom$1 = function (hasIcons, columns, presets) { 10384 var menuClasses = classes(presets); 10385 return { 10386 tag: 'div', 10387 classes: flatten([ 10388 [ 10389 menuClasses.menu, 10390 'tox-menu-' + columns + '-column' 10391 ], 10392 hasIcons ? [menuClasses.hasIcons] : [] 10393 ]) 10394 }; 10395 }; 10396 var components = [Menu.parts.items({})]; 10397 var part = function (hasIcons, columns, presets) { 10398 var menuClasses = classes(presets); 10399 var d = { 10400 tag: 'div', 10401 classes: flatten([[menuClasses.tieredMenu]]) 10402 }; 10403 return { 10404 dom: d, 10405 markers: markers(presets) 10406 }; 10407 }; 10408 10409 var chunk = function (rowDom, numColumns) { 10410 return function (items) { 10411 var chunks = chunk$1(items, numColumns); 10412 return map$2(chunks, function (c) { 10413 return { 10414 dom: rowDom, 10415 components: c 10416 }; 10417 }); 10418 }; 10419 }; 10420 var forSwatch = function (columns) { 10421 return { 10422 dom: { 10423 tag: 'div', 10424 classes: [ 10425 'tox-menu', 10426 'tox-swatches-menu' 10427 ] 10428 }, 10429 components: [{ 10430 dom: { 10431 tag: 'div', 10432 classes: ['tox-swatches'] 10433 }, 10434 components: [Menu.parts.items({ 10435 preprocess: columns !== 'auto' ? chunk({ 10436 tag: 'div', 10437 classes: ['tox-swatches__row'] 10438 }, columns) : identity$1 10439 })] 10440 }] 10441 }; 10442 }; 10443 var forToolbar = function (columns) { 10444 return { 10445 dom: { 10446 tag: 'div', 10447 classes: [ 10448 'tox-menu', 10449 'tox-collection', 10450 'tox-collection--toolbar', 10451 'tox-collection--toolbar-lg' 10452 ] 10453 }, 10454 components: [Menu.parts.items({ 10455 preprocess: chunk({ 10456 tag: 'div', 10457 classes: ['tox-collection__group'] 10458 }, columns) 10459 })] 10460 }; 10461 }; 10462 var preprocessCollection = function (items, isSeparator) { 10463 var allSplits = []; 10464 var currentSplit = []; 10465 each$1(items, function (item, i) { 10466 if (isSeparator(item, i)) { 10467 if (currentSplit.length > 0) { 10468 allSplits.push(currentSplit); 10469 } 10470 currentSplit = []; 10471 if (has$2(item.dom, 'innerHtml')) { 10472 currentSplit.push(item); 10473 } 10474 } else { 10475 currentSplit.push(item); 10476 } 10477 }); 10478 if (currentSplit.length > 0) { 10479 allSplits.push(currentSplit); 10480 } 10481 return map$2(allSplits, function (s) { 10482 return { 10483 dom: { 10484 tag: 'div', 10485 classes: ['tox-collection__group'] 10486 }, 10487 components: s 10488 }; 10489 }); 10490 }; 10491 var forCollection = function (columns, initItems, _hasIcons) { 10492 return { 10493 dom: { 10494 tag: 'div', 10495 classes: [ 10496 'tox-menu', 10497 'tox-collection' 10498 ].concat(columns === 1 ? ['tox-collection--list'] : ['tox-collection--grid']) 10499 }, 10500 components: [Menu.parts.items({ 10501 preprocess: function (items) { 10502 if (columns !== 'auto' && columns > 1) { 10503 return chunk({ 10504 tag: 'div', 10505 classes: ['tox-collection__group'] 10506 }, columns)(items); 10507 } else { 10508 return preprocessCollection(items, function (_item, i) { 10509 return initItems[i].type === 'separator'; 10510 }); 10511 } 10512 } 10513 })] 10514 }; 10515 }; 10516 var forHorizontalCollection = function (initItems, _hasIcons) { 10517 return { 10518 dom: { 10519 tag: 'div', 10520 classes: [ 10521 'tox-collection', 10522 'tox-collection--horizontal' 10523 ] 10524 }, 10525 components: [Menu.parts.items({ 10526 preprocess: function (items) { 10527 return preprocessCollection(items, function (_item, i) { 10528 return initItems[i].type === 'separator'; 10529 }); 10530 } 10531 })] 10532 }; 10533 }; 10534 10535 var menuHasIcons = function (xs) { 10536 return exists(xs, function (item) { 10537 return 'icon' in item && item.icon !== undefined; 10538 }); 10539 }; 10540 var handleError = function (error) { 10541 console.error(formatError(error)); 10542 console.log(error); 10543 return Optional.none(); 10544 }; 10545 var createHorizontalPartialMenuWithAlloyItems = function (value, _hasIcons, items, _columns, _presets) { 10546 var structure = forHorizontalCollection(items); 10547 return { 10548 value: value, 10549 dom: structure.dom, 10550 components: structure.components, 10551 items: items 10552 }; 10553 }; 10554 var createPartialMenuWithAlloyItems = function (value, hasIcons, items, columns, presets) { 10555 if (presets === 'color') { 10556 var structure = forSwatch(columns); 10557 return { 10558 value: value, 10559 dom: structure.dom, 10560 components: structure.components, 10561 items: items 10562 }; 10563 } 10564 if (presets === 'normal' && columns === 'auto') { 10565 var structure = forCollection(columns, items); 10566 return { 10567 value: value, 10568 dom: structure.dom, 10569 components: structure.components, 10570 items: items 10571 }; 10572 } 10573 if (presets === 'normal' && columns === 1) { 10574 var structure = forCollection(1, items); 10575 return { 10576 value: value, 10577 dom: structure.dom, 10578 components: structure.components, 10579 items: items 10580 }; 10581 } 10582 if (presets === 'normal') { 10583 var structure = forCollection(columns, items); 10584 return { 10585 value: value, 10586 dom: structure.dom, 10587 components: structure.components, 10588 items: items 10589 }; 10590 } 10591 if (presets === 'listpreview' && columns !== 'auto') { 10592 var structure = forToolbar(columns); 10593 return { 10594 value: value, 10595 dom: structure.dom, 10596 components: structure.components, 10597 items: items 10598 }; 10599 } 10600 return { 10601 value: value, 10602 dom: dom$1(hasIcons, columns, presets), 10603 components: components, 10604 items: items 10605 }; 10606 }; 10607 10608 var cardImageFields = [ 10609 requiredString('type'), 10610 requiredString('src'), 10611 optionString('alt'), 10612 defaultedArrayOf('classes', [], string) 10613 ]; 10614 var cardImageSchema = objOf(cardImageFields); 10615 10616 var cardTextFields = [ 10617 requiredString('type'), 10618 requiredString('text'), 10619 optionString('name'), 10620 defaultedArrayOf('classes', ['tox-collection__item-label'], string) 10621 ]; 10622 var cardTextSchema = objOf(cardTextFields); 10623 10624 var itemSchema$1 = valueThunk(function () { 10625 return choose$2('type', { 10626 cardimage: cardImageSchema, 10627 cardtext: cardTextSchema, 10628 cardcontainer: cardContainerSchema 10629 }); 10630 }); 10631 var cardContainerSchema = objOf([ 10632 requiredString('type'), 10633 defaultedString('direction', 'horizontal'), 10634 defaultedString('align', 'left'), 10635 defaultedString('valign', 'middle'), 10636 requiredArrayOf('items', itemSchema$1) 10637 ]); 10638 10639 var commonMenuItemFields = [ 10640 defaultedBoolean('disabled', false), 10641 optionString('text'), 10642 optionString('shortcut'), 10643 field$1('value', 'value', defaultedThunk(function () { 10644 return generate$6('menuitem-value'); 10645 }), anyValue()), 10646 defaulted('meta', {}) 10647 ]; 10648 10649 var cardMenuItemSchema = objOf([ 10650 requiredString('type'), 10651 optionString('label'), 10652 requiredArrayOf('items', itemSchema$1), 10653 defaultedFunction('onSetup', function () { 10654 return noop; 10655 }), 10656 defaultedFunction('onAction', noop) 10657 ].concat(commonMenuItemFields)); 10658 var createCardMenuItem = function (spec) { 10659 return asRaw('cardmenuitem', cardMenuItemSchema, spec); 10660 }; 10661 10662 var choiceMenuItemSchema = objOf([ 10663 requiredString('type'), 10664 defaultedBoolean('active', false), 10665 optionString('icon') 10666 ].concat(commonMenuItemFields)); 10667 var createChoiceMenuItem = function (spec) { 10668 return asRaw('choicemenuitem', choiceMenuItemSchema, spec); 10669 }; 10670 10671 var baseFields = [ 10672 requiredString('type'), 10673 requiredString('fancytype'), 10674 defaultedFunction('onAction', noop) 10675 ]; 10676 var insertTableFields = [defaulted('initData', {})].concat(baseFields); 10677 var colorSwatchFields = [defaultedObjOf('initData', {}, [ 10678 defaultedBoolean('allowCustomColors', true), 10679 optionArrayOf('colors', anyValue()) 10680 ])].concat(baseFields); 10681 var fancyMenuItemSchema = choose$1('fancytype', { 10682 inserttable: insertTableFields, 10683 colorswatch: colorSwatchFields 10684 }); 10685 var createFancyMenuItem = function (spec) { 10686 return asRaw('fancymenuitem', fancyMenuItemSchema, spec); 10687 }; 10688 10689 var menuItemSchema = objOf([ 10690 requiredString('type'), 10691 defaultedFunction('onSetup', function () { 10692 return noop; 10693 }), 10694 defaultedFunction('onAction', noop), 10695 optionString('icon') 10696 ].concat(commonMenuItemFields)); 10697 var createMenuItem = function (spec) { 10698 return asRaw('menuitem', menuItemSchema, spec); 10699 }; 10700 10701 var nestedMenuItemSchema = objOf([ 10702 requiredString('type'), 10703 requiredFunction('getSubmenuItems'), 10704 defaultedFunction('onSetup', function () { 10705 return noop; 10706 }), 10707 optionString('icon') 10708 ].concat(commonMenuItemFields)); 10709 var createNestedMenuItem = function (spec) { 10710 return asRaw('nestedmenuitem', nestedMenuItemSchema, spec); 10711 }; 10712 10713 var toggleMenuItemSchema = objOf([ 10714 requiredString('type'), 10715 optionString('icon'), 10716 defaultedBoolean('active', false), 10717 defaultedFunction('onSetup', function () { 10718 return noop; 10719 }), 10720 requiredFunction('onAction') 10721 ].concat(commonMenuItemFields)); 10722 var createToggleMenuItem = function (spec) { 10723 return asRaw('togglemenuitem', toggleMenuItemSchema, spec); 10724 }; 10725 10726 var detectSize = function (comp, margin, selectorClass) { 10727 var descendants$1 = descendants(comp.element, '.' + selectorClass); 10728 if (descendants$1.length > 0) { 10729 var columnLength = findIndex$1(descendants$1, function (c) { 10730 var thisTop = c.dom.getBoundingClientRect().top; 10731 var cTop = descendants$1[0].dom.getBoundingClientRect().top; 10732 return Math.abs(thisTop - cTop) > margin; 10733 }).getOr(descendants$1.length); 10734 return Optional.some({ 10735 numColumns: columnLength, 10736 numRows: Math.ceil(descendants$1.length / columnLength) 10737 }); 10738 } else { 10739 return Optional.none(); 10740 } 10741 }; 10742 10743 var namedEvents = function (name, handlers) { 10744 return derive$1([config(name, handlers)]); 10745 }; 10746 var unnamedEvents = function (handlers) { 10747 return namedEvents(generate$6('unnamed-events'), handlers); 10748 }; 10749 var SimpleBehaviours = { 10750 namedEvents: namedEvents, 10751 unnamedEvents: unnamedEvents 10752 }; 10753 10754 var ExclusivityChannel = generate$6('tooltip.exclusive'); 10755 var ShowTooltipEvent = generate$6('tooltip.show'); 10756 var HideTooltipEvent = generate$6('tooltip.hide'); 10757 10758 var hideAllExclusive = function (component, _tConfig, _tState) { 10759 component.getSystem().broadcastOn([ExclusivityChannel], {}); 10760 }; 10761 var setComponents = function (component, tConfig, tState, specs) { 10762 tState.getTooltip().each(function (tooltip) { 10763 if (tooltip.getSystem().isConnected()) { 10764 Replacing.set(tooltip, specs); 10765 } 10766 }); 10767 }; 10768 10769 var TooltippingApis = /*#__PURE__*/Object.freeze({ 10770 __proto__: null, 10771 hideAllExclusive: hideAllExclusive, 10772 setComponents: setComponents 10773 }); 10774 10775 var events$9 = function (tooltipConfig, state) { 10776 var hide = function (comp) { 10777 state.getTooltip().each(function (p) { 10778 detach(p); 10779 tooltipConfig.onHide(comp, p); 10780 state.clearTooltip(); 10781 }); 10782 state.clearTimer(); 10783 }; 10784 var show = function (comp) { 10785 if (!state.isShowing()) { 10786 hideAllExclusive(comp); 10787 var sink = tooltipConfig.lazySink(comp).getOrDie(); 10788 var popup = comp.getSystem().build({ 10789 dom: tooltipConfig.tooltipDom, 10790 components: tooltipConfig.tooltipComponents, 10791 events: derive$2(tooltipConfig.mode === 'normal' ? [ 10792 run$1(mouseover(), function (_) { 10793 emit(comp, ShowTooltipEvent); 10794 }), 10795 run$1(mouseout(), function (_) { 10796 emit(comp, HideTooltipEvent); 10797 }) 10798 ] : []), 10799 behaviours: derive$1([Replacing.config({})]) 10800 }); 10801 state.setTooltip(popup); 10802 attach(sink, popup); 10803 tooltipConfig.onShow(comp, popup); 10804 Positioning.position(sink, popup, { anchor: tooltipConfig.anchor(comp) }); 10805 } 10806 }; 10807 return derive$2(flatten([ 10808 [ 10809 run$1(ShowTooltipEvent, function (comp) { 10810 state.resetTimer(function () { 10811 show(comp); 10812 }, tooltipConfig.delay); 10813 }), 10814 run$1(HideTooltipEvent, function (comp) { 10815 state.resetTimer(function () { 10816 hide(comp); 10817 }, tooltipConfig.delay); 10818 }), 10819 run$1(receive(), function (comp, message) { 10820 var receivingData = message; 10821 if (!receivingData.universal) { 10822 if (contains$2(receivingData.channels, ExclusivityChannel)) { 10823 hide(comp); 10824 } 10825 } 10826 }), 10827 runOnDetached(function (comp) { 10828 hide(comp); 10829 }) 10830 ], 10831 tooltipConfig.mode === 'normal' ? [ 10832 run$1(focusin(), function (comp) { 10833 emit(comp, ShowTooltipEvent); 10834 }), 10835 run$1(postBlur(), function (comp) { 10836 emit(comp, HideTooltipEvent); 10837 }), 10838 run$1(mouseover(), function (comp) { 10839 emit(comp, ShowTooltipEvent); 10840 }), 10841 run$1(mouseout(), function (comp) { 10842 emit(comp, HideTooltipEvent); 10843 }) 10844 ] : [ 10845 run$1(highlight$1(), function (comp, _se) { 10846 emit(comp, ShowTooltipEvent); 10847 }), 10848 run$1(dehighlight$1(), function (comp) { 10849 emit(comp, HideTooltipEvent); 10850 }) 10851 ] 10852 ])); 10853 }; 10854 10855 var ActiveTooltipping = /*#__PURE__*/Object.freeze({ 10856 __proto__: null, 10857 events: events$9 10858 }); 10859 10860 var TooltippingSchema = [ 10861 required$1('lazySink'), 10862 required$1('tooltipDom'), 10863 defaulted('exclusive', true), 10864 defaulted('tooltipComponents', []), 10865 defaulted('delay', 300), 10866 defaultedStringEnum('mode', 'normal', [ 10867 'normal', 10868 'follow-highlight' 10869 ]), 10870 defaulted('anchor', function (comp) { 10871 return { 10872 type: 'hotspot', 10873 hotspot: comp, 10874 layouts: { 10875 onLtr: constant$1([ 10876 south$2, 10877 north$2, 10878 southeast$2, 10879 northeast$2, 10880 southwest$2, 10881 northwest$2 10882 ]), 10883 onRtl: constant$1([ 10884 south$2, 10885 north$2, 10886 southeast$2, 10887 northeast$2, 10888 southwest$2, 10889 northwest$2 10890 ]) 10891 } 10892 }; 10893 }), 10894 onHandler('onHide'), 10895 onHandler('onShow') 10896 ]; 10897 10898 var init$b = function () { 10899 var timer = value$1(); 10900 var popup = value$1(); 10901 var clearTimer = function () { 10902 timer.on(clearTimeout); 10903 }; 10904 var resetTimer = function (f, delay) { 10905 clearTimer(); 10906 timer.set(setTimeout(f, delay)); 10907 }; 10908 var readState = constant$1('not-implemented'); 10909 return nu$8({ 10910 getTooltip: popup.get, 10911 isShowing: popup.isSet, 10912 setTooltip: popup.set, 10913 clearTooltip: popup.clear, 10914 clearTimer: clearTimer, 10915 resetTimer: resetTimer, 10916 readState: readState 10917 }); 10918 }; 10919 10920 var TooltippingState = /*#__PURE__*/Object.freeze({ 10921 __proto__: null, 10922 init: init$b 10923 }); 10924 10925 var Tooltipping = create$7({ 10926 fields: TooltippingSchema, 10927 name: 'tooltipping', 10928 active: ActiveTooltipping, 10929 state: TooltippingState, 10930 apis: TooltippingApis 10931 }); 10932 10933 var escape = function (text) { 10934 return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 10935 }; 10936 10937 var global$b = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils'); 10938 10939 var global$a = tinymce.util.Tools.resolve('tinymce.EditorManager'); 10940 10941 var getSkinUrl = function (editor) { 10942 var skin = editor.getParam('skin'); 10943 var skinUrl = editor.getParam('skin_url'); 10944 if (skin !== false) { 10945 var skinName = skin ? skin : 'oxide'; 10946 if (skinUrl) { 10947 skinUrl = editor.documentBaseURI.toAbsolute(skinUrl); 10948 } else { 10949 skinUrl = global$a.baseURL + '/skins/ui/' + skinName; 10950 } 10951 } 10952 return skinUrl; 10953 }; 10954 var isReadOnly = function (editor) { 10955 return editor.getParam('readonly', false, 'boolean'); 10956 }; 10957 var isSkinDisabled = function (editor) { 10958 return editor.getParam('skin') === false; 10959 }; 10960 var getHeightSetting = function (editor) { 10961 return editor.getParam('height', Math.max(editor.getElement().offsetHeight, 200)); 10962 }; 10963 var getWidthSetting = function (editor) { 10964 return editor.getParam('width', global$b.DOM.getStyle(editor.getElement(), 'width')); 10965 }; 10966 var getMinWidthSetting = function (editor) { 10967 return Optional.from(editor.getParam('min_width')).filter(isNumber); 10968 }; 10969 var getMinHeightSetting = function (editor) { 10970 return Optional.from(editor.getParam('min_height')).filter(isNumber); 10971 }; 10972 var getMaxWidthSetting = function (editor) { 10973 return Optional.from(editor.getParam('max_width')).filter(isNumber); 10974 }; 10975 var getMaxHeightSetting = function (editor) { 10976 return Optional.from(editor.getParam('max_height')).filter(isNumber); 10977 }; 10978 var getUserStyleFormats = function (editor) { 10979 return Optional.from(editor.getParam('style_formats')).filter(isArray); 10980 }; 10981 var isMergeStyleFormats = function (editor) { 10982 return editor.getParam('style_formats_merge', false, 'boolean'); 10983 }; 10984 var getLineHeightFormats = function (editor) { 10985 return editor.getParam('lineheight_formats', '1 1.1 1.2 1.3 1.4 1.5 2', 'string').split(' '); 10986 }; 10987 var getContentLanguages = function (editor) { 10988 return editor.getParam('content_langs', undefined, 'array'); 10989 }; 10990 var getRemovedMenuItems = function (editor) { 10991 return editor.getParam('removed_menuitems', ''); 10992 }; 10993 var isMenubarEnabled = function (editor) { 10994 return editor.getParam('menubar', true, 'boolean') !== false; 10995 }; 10996 var isToolbarEnabled = function (editor) { 10997 var toolbar = editor.getParam('toolbar', true); 10998 var isToolbarTrue = toolbar === true; 10999 var isToolbarString = isString(toolbar); 11000 var isToolbarObjectArray = isArray(toolbar) && toolbar.length > 0; 11001 return !isMultipleToolbars(editor) && (isToolbarObjectArray || isToolbarString || isToolbarTrue); 11002 }; 11003 var getMultipleToolbarsSetting = function (editor) { 11004 var toolbars = range$2(9, function (num) { 11005 return editor.getParam('toolbar' + (num + 1), false, 'string'); 11006 }); 11007 var toolbarArray = filter$2(toolbars, function (toolbar) { 11008 return typeof toolbar === 'string'; 11009 }); 11010 return toolbarArray.length > 0 ? Optional.some(toolbarArray) : Optional.none(); 11011 }; 11012 var isMultipleToolbars = function (editor) { 11013 return getMultipleToolbarsSetting(editor).fold(function () { 11014 var toolbar = editor.getParam('toolbar', [], 'string[]'); 11015 return toolbar.length > 0; 11016 }, always); 11017 }; 11018 var ToolbarMode; 11019 (function (ToolbarMode) { 11020 ToolbarMode['default'] = 'wrap'; 11021 ToolbarMode['floating'] = 'floating'; 11022 ToolbarMode['sliding'] = 'sliding'; 11023 ToolbarMode['scrolling'] = 'scrolling'; 11024 }(ToolbarMode || (ToolbarMode = {}))); 11025 var getToolbarMode = function (editor) { 11026 return editor.getParam('toolbar_mode', '', 'string'); 11027 }; 11028 var ToolbarLocation; 11029 (function (ToolbarLocation) { 11030 ToolbarLocation['auto'] = 'auto'; 11031 ToolbarLocation['top'] = 'top'; 11032 ToolbarLocation['bottom'] = 'bottom'; 11033 }(ToolbarLocation || (ToolbarLocation = {}))); 11034 var getToolbarGroups = function (editor) { 11035 return editor.getParam('toolbar_groups', {}, 'object'); 11036 }; 11037 var getToolbarLocation = function (editor) { 11038 return editor.getParam('toolbar_location', ToolbarLocation.auto, 'string'); 11039 }; 11040 var isToolbarLocationBottom = function (editor) { 11041 return getToolbarLocation(editor) === ToolbarLocation.bottom; 11042 }; 11043 var fixedContainerSelector = function (editor) { 11044 return editor.getParam('fixed_toolbar_container', '', 'string'); 11045 }; 11046 var fixedToolbarContainerTarget = function (editor) { 11047 return editor.getParam('fixed_toolbar_container_target'); 11048 }; 11049 var isToolbarPersist = function (editor) { 11050 return editor.getParam('toolbar_persist', false, 'boolean'); 11051 }; 11052 var fixedContainerTarget = function (editor) { 11053 if (!editor.inline) { 11054 return Optional.none(); 11055 } 11056 var selector = fixedContainerSelector(editor); 11057 if (selector.length > 0) { 11058 return descendant(body(), selector); 11059 } 11060 var element = fixedToolbarContainerTarget(editor); 11061 if (isNonNullable(element)) { 11062 return Optional.some(SugarElement.fromDom(element)); 11063 } 11064 return Optional.none(); 11065 }; 11066 var useFixedContainer = function (editor) { 11067 return editor.inline && fixedContainerTarget(editor).isSome(); 11068 }; 11069 var getUiContainer = function (editor) { 11070 var fixedContainer = fixedContainerTarget(editor); 11071 return fixedContainer.getOrThunk(function () { 11072 return getContentContainer(getRootNode(SugarElement.fromDom(editor.getElement()))); 11073 }); 11074 }; 11075 var isDistractionFree = function (editor) { 11076 return editor.inline && !isMenubarEnabled(editor) && !isToolbarEnabled(editor) && !isMultipleToolbars(editor); 11077 }; 11078 var isStickyToolbar = function (editor) { 11079 var isStickyToolbar = editor.getParam('toolbar_sticky', false, 'boolean'); 11080 return (isStickyToolbar || editor.inline) && !useFixedContainer(editor) && !isDistractionFree(editor); 11081 }; 11082 var getStickyToolbarOffset = function (editor) { 11083 return editor.getParam('toolbar_sticky_offset', 0, 'number'); 11084 }; 11085 var isDraggableModal$1 = function (editor) { 11086 return editor.getParam('draggable_modal', false, 'boolean'); 11087 }; 11088 var getMenus = function (editor) { 11089 var menu = editor.getParam('menu'); 11090 if (menu) { 11091 return map$1(menu, function (menu) { 11092 return __assign(__assign({}, menu), { items: menu.items }); 11093 }); 11094 } else { 11095 return {}; 11096 } 11097 }; 11098 var getMenubar = function (editor) { 11099 return editor.getParam('menubar'); 11100 }; 11101 var getToolbar = function (editor) { 11102 return editor.getParam('toolbar', true); 11103 }; 11104 var getFilePickerCallback = function (editor) { 11105 return editor.getParam('file_picker_callback'); 11106 }; 11107 var getFilePickerTypes = function (editor) { 11108 return editor.getParam('file_picker_types'); 11109 }; 11110 var getFileBrowserCallbackTypes = function (editor) { 11111 return editor.getParam('file_browser_callback_types'); 11112 }; 11113 var noTypeaheadUrls = function (editor) { 11114 return editor.getParam('typeahead_urls') === false; 11115 }; 11116 var getAnchorTop = function (editor) { 11117 return editor.getParam('anchor_top', '#top'); 11118 }; 11119 var getAnchorBottom = function (editor) { 11120 return editor.getParam('anchor_bottom', '#bottom'); 11121 }; 11122 var getFilePickerValidatorHandler = function (editor) { 11123 var handler = editor.getParam('file_picker_validator_handler', undefined, 'function'); 11124 if (handler === undefined) { 11125 return editor.getParam('filepicker_validator_handler', undefined, 'function'); 11126 } else { 11127 return handler; 11128 } 11129 }; 11130 11131 var ReadOnlyChannel = 'silver.readonly'; 11132 var ReadOnlyDataSchema = objOf([requiredBoolean('readonly')]); 11133 var broadcastReadonly = function (uiComponents, readonly) { 11134 var outerContainer = uiComponents.outerContainer; 11135 var target = outerContainer.element; 11136 if (readonly) { 11137 uiComponents.mothership.broadcastOn([dismissPopups()], { target: target }); 11138 uiComponents.uiMothership.broadcastOn([dismissPopups()], { target: target }); 11139 } 11140 uiComponents.mothership.broadcastOn([ReadOnlyChannel], { readonly: readonly }); 11141 uiComponents.uiMothership.broadcastOn([ReadOnlyChannel], { readonly: readonly }); 11142 }; 11143 var setupReadonlyModeSwitch = function (editor, uiComponents) { 11144 editor.on('init', function () { 11145 if (editor.mode.isReadOnly()) { 11146 broadcastReadonly(uiComponents, true); 11147 } 11148 }); 11149 editor.on('SwitchMode', function () { 11150 return broadcastReadonly(uiComponents, editor.mode.isReadOnly()); 11151 }); 11152 if (isReadOnly(editor)) { 11153 editor.setMode('readonly'); 11154 } 11155 }; 11156 var receivingConfig = function () { 11157 var _a; 11158 return Receiving.config({ 11159 channels: (_a = {}, _a[ReadOnlyChannel] = { 11160 schema: ReadOnlyDataSchema, 11161 onReceive: function (comp, data) { 11162 Disabling.set(comp, data.readonly); 11163 } 11164 }, _a) 11165 }); 11166 }; 11167 11168 var item = function (disabled) { 11169 return Disabling.config({ 11170 disabled: disabled, 11171 disableClass: 'tox-collection__item--state-disabled' 11172 }); 11173 }; 11174 var button = function (disabled) { 11175 return Disabling.config({ disabled: disabled }); 11176 }; 11177 var splitButton = function (disabled) { 11178 return Disabling.config({ 11179 disabled: disabled, 11180 disableClass: 'tox-tbtn--disabled' 11181 }); 11182 }; 11183 var toolbarButton = function (disabled) { 11184 return Disabling.config({ 11185 disabled: disabled, 11186 disableClass: 'tox-tbtn--disabled', 11187 useNative: false 11188 }); 11189 }; 11190 var DisablingConfigs = { 11191 item: item, 11192 button: button, 11193 splitButton: splitButton, 11194 toolbarButton: toolbarButton 11195 }; 11196 11197 var runWithApi = function (info, comp) { 11198 var api = info.getApi(comp); 11199 return function (f) { 11200 f(api); 11201 }; 11202 }; 11203 var onControlAttached = function (info, editorOffCell) { 11204 return runOnAttached(function (comp) { 11205 var run = runWithApi(info, comp); 11206 run(function (api) { 11207 var onDestroy = info.onSetup(api); 11208 if (isFunction(onDestroy)) { 11209 editorOffCell.set(onDestroy); 11210 } 11211 }); 11212 }); 11213 }; 11214 var onControlDetached = function (getApi, editorOffCell) { 11215 return runOnDetached(function (comp) { 11216 return runWithApi(getApi, comp)(editorOffCell.get()); 11217 }); 11218 }; 11219 11220 var _a$1; 11221 var onMenuItemExecute = function (info, itemResponse) { 11222 return runOnExecute$1(function (comp, simulatedEvent) { 11223 runWithApi(info, comp)(info.onAction); 11224 if (!info.triggersSubmenu && itemResponse === ItemResponse$1.CLOSE_ON_EXECUTE) { 11225 emit(comp, sandboxClose()); 11226 simulatedEvent.stop(); 11227 } 11228 }); 11229 }; 11230 var menuItemEventOrder = (_a$1 = {}, _a$1[execute$5()] = [ 11231 'disabling', 11232 'alloy.base.behaviour', 11233 'toggling', 11234 'item-events' 11235 ], _a$1); 11236 11237 var componentRenderPipeline = cat; 11238 var renderCommonItem = function (spec, structure, itemResponse, providersbackstage) { 11239 var editorOffCell = Cell(noop); 11240 return { 11241 type: 'item', 11242 dom: structure.dom, 11243 components: componentRenderPipeline(structure.optComponents), 11244 data: spec.data, 11245 eventOrder: menuItemEventOrder, 11246 hasSubmenu: spec.triggersSubmenu, 11247 itemBehaviours: derive$1([ 11248 config('item-events', [ 11249 onMenuItemExecute(spec, itemResponse), 11250 onControlAttached(spec, editorOffCell), 11251 onControlDetached(spec, editorOffCell) 11252 ]), 11253 DisablingConfigs.item(function () { 11254 return spec.disabled || providersbackstage.isDisabled(); 11255 }), 11256 receivingConfig(), 11257 Replacing.config({}) 11258 ].concat(spec.itemBehaviours)) 11259 }; 11260 }; 11261 var buildData = function (source) { 11262 return { 11263 value: source.value, 11264 meta: __assign({ text: source.text.getOr('') }, source.meta) 11265 }; 11266 }; 11267 11268 var global$9 = tinymce.util.Tools.resolve('tinymce.Env'); 11269 11270 var convertText = function (source) { 11271 var mac = { 11272 alt: '⌥', 11273 ctrl: '⌃', 11274 shift: '⇧', 11275 meta: '⌘', 11276 access: '⌃⌥' 11277 }; 11278 var other = { 11279 meta: 'Ctrl', 11280 access: 'Shift+Alt' 11281 }; 11282 var replace = global$9.mac ? mac : other; 11283 var shortcut = source.split('+'); 11284 var updated = map$2(shortcut, function (segment) { 11285 var search = segment.toLowerCase().trim(); 11286 return has$2(replace, search) ? replace[search] : segment; 11287 }); 11288 return global$9.mac ? updated.join('') : updated.join('+'); 11289 }; 11290 11291 var renderIcon$1 = function (name, icons, classes) { 11292 if (classes === void 0) { 11293 classes = [iconClass]; 11294 } 11295 return render$3(name, { 11296 tag: 'div', 11297 classes: classes 11298 }, icons); 11299 }; 11300 var renderText = function (text$1) { 11301 return { 11302 dom: { 11303 tag: 'div', 11304 classes: [textClass] 11305 }, 11306 components: [text(global$e.translate(text$1))] 11307 }; 11308 }; 11309 var renderHtml = function (html, classes) { 11310 return { 11311 dom: { 11312 tag: 'div', 11313 classes: classes, 11314 innerHtml: html 11315 } 11316 }; 11317 }; 11318 var renderStyledText = function (style, text$1) { 11319 return { 11320 dom: { 11321 tag: 'div', 11322 classes: [textClass] 11323 }, 11324 components: [{ 11325 dom: { 11326 tag: style.tag, 11327 styles: style.styles 11328 }, 11329 components: [text(global$e.translate(text$1))] 11330 }] 11331 }; 11332 }; 11333 var renderShortcut = function (shortcut) { 11334 return { 11335 dom: { 11336 tag: 'div', 11337 classes: [accessoryClass], 11338 innerHtml: convertText(shortcut) 11339 } 11340 }; 11341 }; 11342 var renderCheckmark = function (icons) { 11343 return renderIcon$1('checkmark', icons, [checkmarkClass]); 11344 }; 11345 var renderSubmenuCaret = function (icons) { 11346 return renderIcon$1('chevron-right', icons, [caretClass]); 11347 }; 11348 var renderDownwardsCaret = function (icons) { 11349 return renderIcon$1('chevron-down', icons, [caretClass]); 11350 }; 11351 var renderContainer = function (container, components) { 11352 var directionClass = container.direction === 'vertical' ? containerColumnClass : containerRowClass; 11353 var alignClass = container.align === 'left' ? containerAlignLeftClass : containerAlignRightClass; 11354 var getValignClass = function () { 11355 switch (container.valign) { 11356 case 'top': 11357 return containerValignTopClass; 11358 case 'middle': 11359 return containerValignMiddleClass; 11360 case 'bottom': 11361 return containerValignBottomClass; 11362 } 11363 }; 11364 return { 11365 dom: { 11366 tag: 'div', 11367 classes: [ 11368 containerClass, 11369 directionClass, 11370 alignClass, 11371 getValignClass() 11372 ] 11373 }, 11374 components: components 11375 }; 11376 }; 11377 var renderImage = function (src, classes, alt) { 11378 return { 11379 dom: { 11380 tag: 'img', 11381 classes: classes, 11382 attributes: { 11383 src: src, 11384 alt: alt.getOr('') 11385 } 11386 } 11387 }; 11388 }; 11389 11390 var renderColorStructure = function (item, providerBackstage, fallbackIcon) { 11391 var colorPickerCommand = 'custom'; 11392 var removeColorCommand = 'remove'; 11393 var itemText = item.ariaLabel; 11394 var itemValue = item.value; 11395 var iconSvg = item.iconContent.map(function (name) { 11396 return getOr(name, providerBackstage.icons, fallbackIcon); 11397 }); 11398 var getDom = function () { 11399 var common = colorClass; 11400 var icon = iconSvg.getOr(''); 11401 var attributes = itemText.map(function (text) { 11402 return { title: providerBackstage.translate(text) }; 11403 }).getOr({}); 11404 var baseDom = { 11405 tag: 'div', 11406 attributes: attributes, 11407 classes: [common] 11408 }; 11409 if (itemValue === colorPickerCommand) { 11410 return __assign(__assign({}, baseDom), { 11411 tag: 'button', 11412 classes: __spreadArray(__spreadArray([], baseDom.classes, true), ['tox-swatches__picker-btn'], false), 11413 innerHtml: icon 11414 }); 11415 } else if (itemValue === removeColorCommand) { 11416 return __assign(__assign({}, baseDom), { 11417 classes: __spreadArray(__spreadArray([], baseDom.classes, true), ['tox-swatch--remove'], false), 11418 innerHtml: icon 11419 }); 11420 } else { 11421 return __assign(__assign({}, baseDom), { 11422 attributes: __assign(__assign({}, baseDom.attributes), { 'data-mce-color': itemValue }), 11423 styles: { 'background-color': itemValue } 11424 }); 11425 } 11426 }; 11427 return { 11428 dom: getDom(), 11429 optComponents: [] 11430 }; 11431 }; 11432 var renderItemDomStructure = function (ariaLabel) { 11433 var domTitle = ariaLabel.map(function (label) { 11434 return { attributes: { title: global$e.translate(label) } }; 11435 }).getOr({}); 11436 return __assign({ 11437 tag: 'div', 11438 classes: [ 11439 navClass, 11440 selectableClass 11441 ] 11442 }, domTitle); 11443 }; 11444 var renderNormalItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) { 11445 var iconSpec = { 11446 tag: 'div', 11447 classes: [iconClass] 11448 }; 11449 var renderIcon = function (iconName) { 11450 return render$3(iconName, iconSpec, providersBackstage.icons, fallbackIcon); 11451 }; 11452 var renderEmptyIcon = function () { 11453 return Optional.some({ dom: iconSpec }); 11454 }; 11455 var leftIcon = renderIcons ? info.iconContent.map(renderIcon).orThunk(renderEmptyIcon) : Optional.none(); 11456 var checkmark = info.checkMark; 11457 var textRender = Optional.from(info.meta).fold(function () { 11458 return renderText; 11459 }, function (meta) { 11460 return has$2(meta, 'style') ? curry(renderStyledText, meta.style) : renderText; 11461 }); 11462 var content = info.htmlContent.fold(function () { 11463 return info.textContent.map(textRender); 11464 }, function (html) { 11465 return Optional.some(renderHtml(html, [textClass])); 11466 }); 11467 var menuItem = { 11468 dom: renderItemDomStructure(info.ariaLabel), 11469 optComponents: [ 11470 leftIcon, 11471 content, 11472 info.shortcutContent.map(renderShortcut), 11473 checkmark, 11474 info.caret 11475 ] 11476 }; 11477 return menuItem; 11478 }; 11479 var renderItemStructure = function (info, providersBackstage, renderIcons, fallbackIcon) { 11480 if (fallbackIcon === void 0) { 11481 fallbackIcon = Optional.none(); 11482 } 11483 if (info.presets === 'color') { 11484 return renderColorStructure(info, providersBackstage, fallbackIcon); 11485 } else { 11486 return renderNormalItemStructure(info, providersBackstage, renderIcons, fallbackIcon); 11487 } 11488 }; 11489 11490 var tooltipBehaviour = function (meta, sharedBackstage) { 11491 return get$e(meta, 'tooltipWorker').map(function (tooltipWorker) { 11492 return [Tooltipping.config({ 11493 lazySink: sharedBackstage.getSink, 11494 tooltipDom: { 11495 tag: 'div', 11496 classes: ['tox-tooltip-worker-container'] 11497 }, 11498 tooltipComponents: [], 11499 anchor: function (comp) { 11500 return { 11501 type: 'submenu', 11502 item: comp, 11503 overrides: { maxHeightFunction: expandable$1 } 11504 }; 11505 }, 11506 mode: 'follow-highlight', 11507 onShow: function (component, _tooltip) { 11508 tooltipWorker(function (elm) { 11509 Tooltipping.setComponents(component, [external$2({ element: SugarElement.fromDom(elm) })]); 11510 }); 11511 } 11512 })]; 11513 }).getOr([]); 11514 }; 11515 var encodeText = function (text) { 11516 return global$b.DOM.encode(text); 11517 }; 11518 var replaceText = function (text, matchText) { 11519 var translated = global$e.translate(text); 11520 var encoded = encodeText(translated); 11521 if (matchText.length > 0) { 11522 var escapedMatchRegex = new RegExp(escape(matchText), 'gi'); 11523 return encoded.replace(escapedMatchRegex, function (match) { 11524 return '<span class="tox-autocompleter-highlight">' + match + '</span>'; 11525 }); 11526 } else { 11527 return encoded; 11528 } 11529 }; 11530 var renderAutocompleteItem = function (spec, matchText, useText, presets, onItemValueHandler, itemResponse, sharedBackstage, renderIcons) { 11531 if (renderIcons === void 0) { 11532 renderIcons = true; 11533 } 11534 var structure = renderItemStructure({ 11535 presets: presets, 11536 textContent: Optional.none(), 11537 htmlContent: useText ? spec.text.map(function (text) { 11538 return replaceText(text, matchText); 11539 }) : Optional.none(), 11540 ariaLabel: spec.text, 11541 iconContent: spec.icon, 11542 shortcutContent: Optional.none(), 11543 checkMark: Optional.none(), 11544 caret: Optional.none(), 11545 value: spec.value 11546 }, sharedBackstage.providers, renderIcons, spec.icon); 11547 return renderCommonItem({ 11548 data: buildData(spec), 11549 disabled: spec.disabled, 11550 getApi: constant$1({}), 11551 onAction: function (_api) { 11552 return onItemValueHandler(spec.value, spec.meta); 11553 }, 11554 onSetup: constant$1(noop), 11555 triggersSubmenu: false, 11556 itemBehaviours: tooltipBehaviour(spec.meta, sharedBackstage) 11557 }, structure, itemResponse, sharedBackstage.providers); 11558 }; 11559 11560 var render$2 = function (items, extras) { 11561 return map$2(items, function (item) { 11562 switch (item.type) { 11563 case 'cardcontainer': 11564 return renderContainer(item, render$2(item.items, extras)); 11565 case 'cardimage': 11566 return renderImage(item.src, item.classes, item.alt); 11567 case 'cardtext': 11568 var shouldHighlight = item.name.exists(function (name) { 11569 return contains$2(extras.cardText.highlightOn, name); 11570 }); 11571 var matchText = shouldHighlight ? Optional.from(extras.cardText.matchText).getOr('') : ''; 11572 return renderHtml(replaceText(item.text, matchText), item.classes); 11573 } 11574 }); 11575 }; 11576 var renderCardMenuItem = function (spec, itemResponse, sharedBackstage, extras) { 11577 var getApi = function (component) { 11578 return { 11579 isDisabled: function () { 11580 return Disabling.isDisabled(component); 11581 }, 11582 setDisabled: function (state) { 11583 Disabling.set(component, state); 11584 each$1(descendants(component.element, '*'), function (elm) { 11585 component.getSystem().getByDom(elm).each(function (comp) { 11586 if (comp.hasConfigured(Disabling)) { 11587 Disabling.set(comp, state); 11588 } 11589 }); 11590 }); 11591 } 11592 }; 11593 }; 11594 var structure = { 11595 dom: renderItemDomStructure(spec.label), 11596 optComponents: [Optional.some({ 11597 dom: { 11598 tag: 'div', 11599 classes: [ 11600 containerClass, 11601 containerRowClass 11602 ] 11603 }, 11604 components: render$2(spec.items, extras) 11605 })] 11606 }; 11607 return renderCommonItem({ 11608 data: buildData(__assign({ text: Optional.none() }, spec)), 11609 disabled: spec.disabled, 11610 getApi: getApi, 11611 onAction: spec.onAction, 11612 onSetup: spec.onSetup, 11613 triggersSubmenu: false, 11614 itemBehaviours: Optional.from(extras.itemBehaviours).getOr([]) 11615 }, structure, itemResponse, sharedBackstage.providers); 11616 }; 11617 11618 var renderChoiceItem = function (spec, useText, presets, onItemValueHandler, isSelected, itemResponse, providersBackstage, renderIcons) { 11619 if (renderIcons === void 0) { 11620 renderIcons = true; 11621 } 11622 var getApi = function (component) { 11623 return { 11624 setActive: function (state) { 11625 Toggling.set(component, state); 11626 }, 11627 isActive: function () { 11628 return Toggling.isOn(component); 11629 }, 11630 isDisabled: function () { 11631 return Disabling.isDisabled(component); 11632 }, 11633 setDisabled: function (state) { 11634 return Disabling.set(component, state); 11635 } 11636 }; 11637 }; 11638 var structure = renderItemStructure({ 11639 presets: presets, 11640 textContent: useText ? spec.text : Optional.none(), 11641 htmlContent: Optional.none(), 11642 ariaLabel: spec.text, 11643 iconContent: spec.icon, 11644 shortcutContent: useText ? spec.shortcut : Optional.none(), 11645 checkMark: useText ? Optional.some(renderCheckmark(providersBackstage.icons)) : Optional.none(), 11646 caret: Optional.none(), 11647 value: spec.value 11648 }, providersBackstage, renderIcons); 11649 return deepMerge(renderCommonItem({ 11650 data: buildData(spec), 11651 disabled: spec.disabled, 11652 getApi: getApi, 11653 onAction: function (_api) { 11654 return onItemValueHandler(spec.value); 11655 }, 11656 onSetup: function (api) { 11657 api.setActive(isSelected); 11658 return noop; 11659 }, 11660 triggersSubmenu: false, 11661 itemBehaviours: [] 11662 }, structure, itemResponse, providersBackstage), { 11663 toggling: { 11664 toggleClass: tickedClass, 11665 toggleOnExecute: false, 11666 selected: spec.active 11667 } 11668 }); 11669 }; 11670 11671 var parts$f = generate$3(owner$2(), parts$h()); 11672 11673 var hexColour = function (value) { 11674 return { value: value }; 11675 }; 11676 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; 11677 var longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i; 11678 var isHexString = function (hex) { 11679 return shorthandRegex.test(hex) || longformRegex.test(hex); 11680 }; 11681 var normalizeHex = function (hex) { 11682 return removeLeading(hex, '#').toUpperCase(); 11683 }; 11684 var fromString$1 = function (hex) { 11685 return isHexString(hex) ? Optional.some({ value: normalizeHex(hex) }) : Optional.none(); 11686 }; 11687 var getLongForm = function (hex) { 11688 var hexString = hex.value.replace(shorthandRegex, function (m, r, g, b) { 11689 return r + r + g + g + b + b; 11690 }); 11691 return { value: hexString }; 11692 }; 11693 var extractValues = function (hex) { 11694 var longForm = getLongForm(hex); 11695 var splitForm = longformRegex.exec(longForm.value); 11696 return splitForm === null ? [ 11697 'FFFFFF', 11698 'FF', 11699 'FF', 11700 'FF' 11701 ] : splitForm; 11702 }; 11703 var toHex = function (component) { 11704 var hex = component.toString(16); 11705 return (hex.length === 1 ? '0' + hex : hex).toUpperCase(); 11706 }; 11707 var fromRgba = function (rgbaColour) { 11708 var value = toHex(rgbaColour.red) + toHex(rgbaColour.green) + toHex(rgbaColour.blue); 11709 return hexColour(value); 11710 }; 11711 11712 var min = Math.min; 11713 var max = Math.max; 11714 var round$1 = Math.round; 11715 var rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)/; 11716 var rgbaRegex = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*(\d?(?:\.\d+)?)\)/; 11717 var rgbaColour = function (red, green, blue, alpha) { 11718 return { 11719 red: red, 11720 green: green, 11721 blue: blue, 11722 alpha: alpha 11723 }; 11724 }; 11725 var isRgbaComponent = function (value) { 11726 var num = parseInt(value, 10); 11727 return num.toString() === value && num >= 0 && num <= 255; 11728 }; 11729 var fromHsv = function (hsv) { 11730 var r; 11731 var g; 11732 var b; 11733 var hue = (hsv.hue || 0) % 360; 11734 var saturation = hsv.saturation / 100; 11735 var brightness = hsv.value / 100; 11736 saturation = max(0, min(saturation, 1)); 11737 brightness = max(0, min(brightness, 1)); 11738 if (saturation === 0) { 11739 r = g = b = round$1(255 * brightness); 11740 return rgbaColour(r, g, b, 1); 11741 } 11742 var side = hue / 60; 11743 var chroma = brightness * saturation; 11744 var x = chroma * (1 - Math.abs(side % 2 - 1)); 11745 var match = brightness - chroma; 11746 switch (Math.floor(side)) { 11747 case 0: 11748 r = chroma; 11749 g = x; 11750 b = 0; 11751 break; 11752 case 1: 11753 r = x; 11754 g = chroma; 11755 b = 0; 11756 break; 11757 case 2: 11758 r = 0; 11759 g = chroma; 11760 b = x; 11761 break; 11762 case 3: 11763 r = 0; 11764 g = x; 11765 b = chroma; 11766 break; 11767 case 4: 11768 r = x; 11769 g = 0; 11770 b = chroma; 11771 break; 11772 case 5: 11773 r = chroma; 11774 g = 0; 11775 b = x; 11776 break; 11777 default: 11778 r = g = b = 0; 11779 } 11780 r = round$1(255 * (r + match)); 11781 g = round$1(255 * (g + match)); 11782 b = round$1(255 * (b + match)); 11783 return rgbaColour(r, g, b, 1); 11784 }; 11785 var fromHex = function (hexColour) { 11786 var result = extractValues(hexColour); 11787 var red = parseInt(result[1], 16); 11788 var green = parseInt(result[2], 16); 11789 var blue = parseInt(result[3], 16); 11790 return rgbaColour(red, green, blue, 1); 11791 }; 11792 var fromStringValues = function (red, green, blue, alpha) { 11793 var r = parseInt(red, 10); 11794 var g = parseInt(green, 10); 11795 var b = parseInt(blue, 10); 11796 var a = parseFloat(alpha); 11797 return rgbaColour(r, g, b, a); 11798 }; 11799 var fromString = function (rgbaString) { 11800 if (rgbaString === 'transparent') { 11801 return Optional.some(rgbaColour(0, 0, 0, 0)); 11802 } 11803 var rgbMatch = rgbRegex.exec(rgbaString); 11804 if (rgbMatch !== null) { 11805 return Optional.some(fromStringValues(rgbMatch[1], rgbMatch[2], rgbMatch[3], '1')); 11806 } 11807 var rgbaMatch = rgbaRegex.exec(rgbaString); 11808 if (rgbaMatch !== null) { 11809 return Optional.some(fromStringValues(rgbaMatch[1], rgbaMatch[2], rgbaMatch[3], rgbaMatch[4])); 11810 } 11811 return Optional.none(); 11812 }; 11813 var toString = function (rgba) { 11814 return 'rgba(' + rgba.red + ',' + rgba.green + ',' + rgba.blue + ',' + rgba.alpha + ')'; 11815 }; 11816 var red = rgbaColour(255, 0, 0, 1); 11817 11818 var fireSkinLoaded$1 = function (editor) { 11819 return editor.fire('SkinLoaded'); 11820 }; 11821 var fireSkinLoadError$1 = function (editor, error) { 11822 return editor.fire('SkinLoadError', error); 11823 }; 11824 var fireResizeEditor = function (editor) { 11825 return editor.fire('ResizeEditor'); 11826 }; 11827 var fireResizeContent = function (editor, e) { 11828 return editor.fire('ResizeContent', e); 11829 }; 11830 var fireScrollContent = function (editor, e) { 11831 return editor.fire('ScrollContent', e); 11832 }; 11833 var fireTextColorChange = function (editor, data) { 11834 return editor.fire('TextColorChange', data); 11835 }; 11836 11837 var hsvColour = function (hue, saturation, value) { 11838 return { 11839 hue: hue, 11840 saturation: saturation, 11841 value: value 11842 }; 11843 }; 11844 var fromRgb = function (rgbaColour) { 11845 var h = 0; 11846 var s = 0; 11847 var v = 0; 11848 var r = rgbaColour.red / 255; 11849 var g = rgbaColour.green / 255; 11850 var b = rgbaColour.blue / 255; 11851 var minRGB = Math.min(r, Math.min(g, b)); 11852 var maxRGB = Math.max(r, Math.max(g, b)); 11853 if (minRGB === maxRGB) { 11854 v = minRGB; 11855 return hsvColour(0, 0, v * 100); 11856 } 11857 var d = r === minRGB ? g - b : b === minRGB ? r - g : b - r; 11858 h = r === minRGB ? 3 : b === minRGB ? 1 : 5; 11859 h = 60 * (h - d / (maxRGB - minRGB)); 11860 s = (maxRGB - minRGB) / maxRGB; 11861 v = maxRGB; 11862 return hsvColour(Math.round(h), Math.round(s * 100), Math.round(v * 100)); 11863 }; 11864 11865 var hexToHsv = function (hex) { 11866 return fromRgb(fromHex(hex)); 11867 }; 11868 var hsvToHex = function (hsv) { 11869 return fromRgba(fromHsv(hsv)); 11870 }; 11871 var anyToHex = function (color) { 11872 return fromString$1(color).orThunk(function () { 11873 return fromString(color).map(fromRgba); 11874 }).getOrThunk(function () { 11875 var canvas = document.createElement('canvas'); 11876 canvas.height = 1; 11877 canvas.width = 1; 11878 var canvasContext = canvas.getContext('2d'); 11879 canvasContext.clearRect(0, 0, canvas.width, canvas.height); 11880 canvasContext.fillStyle = '#FFFFFF'; 11881 canvasContext.fillStyle = color; 11882 canvasContext.fillRect(0, 0, 1, 1); 11883 var rgba = canvasContext.getImageData(0, 0, 1, 1).data; 11884 var r = rgba[0]; 11885 var g = rgba[1]; 11886 var b = rgba[2]; 11887 var a = rgba[3]; 11888 return fromRgba(rgbaColour(r, g, b, a)); 11889 }); 11890 }; 11891 11892 var global$8 = tinymce.util.Tools.resolve('tinymce.util.LocalStorage'); 11893 11894 var storageName = 'tinymce-custom-colors'; 11895 function ColorCache (max) { 11896 if (max === void 0) { 11897 max = 10; 11898 } 11899 var storageString = global$8.getItem(storageName); 11900 var localstorage = isString(storageString) ? JSON.parse(storageString) : []; 11901 var prune = function (list) { 11902 var diff = max - list.length; 11903 return diff < 0 ? list.slice(0, max) : list; 11904 }; 11905 var cache = prune(localstorage); 11906 var add = function (key) { 11907 indexOf(cache, key).each(remove); 11908 cache.unshift(key); 11909 if (cache.length > max) { 11910 cache.pop(); 11911 } 11912 global$8.setItem(storageName, JSON.stringify(cache)); 11913 }; 11914 var remove = function (idx) { 11915 cache.splice(idx, 1); 11916 }; 11917 var state = function () { 11918 return cache.slice(0); 11919 }; 11920 return { 11921 add: add, 11922 state: state 11923 }; 11924 } 11925 11926 var choiceItem = 'choiceitem'; 11927 var defaultColors = [ 11928 { 11929 type: choiceItem, 11930 text: 'Light Green', 11931 value: '#BFEDD2' 11932 }, 11933 { 11934 type: choiceItem, 11935 text: 'Light Yellow', 11936 value: '#FBEEB8' 11937 }, 11938 { 11939 type: choiceItem, 11940 text: 'Light Red', 11941 value: '#F8CAC6' 11942 }, 11943 { 11944 type: choiceItem, 11945 text: 'Light Purple', 11946 value: '#ECCAFA' 11947 }, 11948 { 11949 type: choiceItem, 11950 text: 'Light Blue', 11951 value: '#C2E0F4' 11952 }, 11953 { 11954 type: choiceItem, 11955 text: 'Green', 11956 value: '#2DC26B' 11957 }, 11958 { 11959 type: choiceItem, 11960 text: 'Yellow', 11961 value: '#F1C40F' 11962 }, 11963 { 11964 type: choiceItem, 11965 text: 'Red', 11966 value: '#E03E2D' 11967 }, 11968 { 11969 type: choiceItem, 11970 text: 'Purple', 11971 value: '#B96AD9' 11972 }, 11973 { 11974 type: choiceItem, 11975 text: 'Blue', 11976 value: '#3598DB' 11977 }, 11978 { 11979 type: choiceItem, 11980 text: 'Dark Turquoise', 11981 value: '#169179' 11982 }, 11983 { 11984 type: choiceItem, 11985 text: 'Orange', 11986 value: '#E67E23' 11987 }, 11988 { 11989 type: choiceItem, 11990 text: 'Dark Red', 11991 value: '#BA372A' 11992 }, 11993 { 11994 type: choiceItem, 11995 text: 'Dark Purple', 11996 value: '#843FA1' 11997 }, 11998 { 11999 type: choiceItem, 12000 text: 'Dark Blue', 12001 value: '#236FA1' 12002 }, 12003 { 12004 type: choiceItem, 12005 text: 'Light Gray', 12006 value: '#ECF0F1' 12007 }, 12008 { 12009 type: choiceItem, 12010 text: 'Medium Gray', 12011 value: '#CED4D9' 12012 }, 12013 { 12014 type: choiceItem, 12015 text: 'Gray', 12016 value: '#95A5A6' 12017 }, 12018 { 12019 type: choiceItem, 12020 text: 'Dark Gray', 12021 value: '#7E8C8D' 12022 }, 12023 { 12024 type: choiceItem, 12025 text: 'Navy Blue', 12026 value: '#34495E' 12027 }, 12028 { 12029 type: choiceItem, 12030 text: 'Black', 12031 value: '#000000' 12032 }, 12033 { 12034 type: choiceItem, 12035 text: 'White', 12036 value: '#ffffff' 12037 } 12038 ]; 12039 var colorCache = ColorCache(10); 12040 var mapColors = function (colorMap) { 12041 var colors = []; 12042 for (var i = 0; i < colorMap.length; i += 2) { 12043 colors.push({ 12044 text: colorMap[i + 1], 12045 value: '#' + anyToHex(colorMap[i]).value, 12046 type: 'choiceitem' 12047 }); 12048 } 12049 return colors; 12050 }; 12051 var getColorCols$2 = function (editor, defaultCols) { 12052 return editor.getParam('color_cols', defaultCols, 'number'); 12053 }; 12054 var hasCustomColors$1 = function (editor) { 12055 return editor.getParam('custom_colors') !== false; 12056 }; 12057 var getColorMap = function (editor) { 12058 return editor.getParam('color_map'); 12059 }; 12060 var getColors$2 = function (editor) { 12061 var unmapped = getColorMap(editor); 12062 return unmapped !== undefined ? mapColors(unmapped) : defaultColors; 12063 }; 12064 var getCurrentColors = function () { 12065 return map$2(colorCache.state(), function (color) { 12066 return { 12067 type: choiceItem, 12068 text: color, 12069 value: color 12070 }; 12071 }); 12072 }; 12073 var addColor = function (color) { 12074 colorCache.add(color); 12075 }; 12076 12077 var fallbackColor = '#000000'; 12078 var getCurrentColor = function (editor, format) { 12079 var color; 12080 editor.dom.getParents(editor.selection.getStart(), function (elm) { 12081 var value; 12082 if (value = elm.style[format === 'forecolor' ? 'color' : 'background-color']) { 12083 color = color ? color : value; 12084 } 12085 }); 12086 return Optional.from(color); 12087 }; 12088 var applyFormat = function (editor, format, value) { 12089 editor.undoManager.transact(function () { 12090 editor.focus(); 12091 editor.formatter.apply(format, { value: value }); 12092 editor.nodeChanged(); 12093 }); 12094 }; 12095 var removeFormat = function (editor, format) { 12096 editor.undoManager.transact(function () { 12097 editor.focus(); 12098 editor.formatter.remove(format, { value: null }, null, true); 12099 editor.nodeChanged(); 12100 }); 12101 }; 12102 var registerCommands = function (editor) { 12103 editor.addCommand('mceApplyTextcolor', function (format, value) { 12104 applyFormat(editor, format, value); 12105 }); 12106 editor.addCommand('mceRemoveTextcolor', function (format) { 12107 removeFormat(editor, format); 12108 }); 12109 }; 12110 var calcCols = function (colors) { 12111 return Math.max(5, Math.ceil(Math.sqrt(colors))); 12112 }; 12113 var getColorCols$1 = function (editor) { 12114 var colors = getColors$2(editor); 12115 var defaultCols = calcCols(colors.length); 12116 return getColorCols$2(editor, defaultCols); 12117 }; 12118 var getAdditionalColors = function (hasCustom) { 12119 var type = 'choiceitem'; 12120 var remove = { 12121 type: type, 12122 text: 'Remove color', 12123 icon: 'color-swatch-remove-color', 12124 value: 'remove' 12125 }; 12126 var custom = { 12127 type: type, 12128 text: 'Custom color', 12129 icon: 'color-picker', 12130 value: 'custom' 12131 }; 12132 return hasCustom ? [ 12133 remove, 12134 custom 12135 ] : [remove]; 12136 }; 12137 var applyColor = function (editor, format, value, onChoice) { 12138 if (value === 'custom') { 12139 var dialog = colorPickerDialog(editor); 12140 dialog(function (colorOpt) { 12141 colorOpt.each(function (color) { 12142 addColor(color); 12143 editor.execCommand('mceApplyTextcolor', format, color); 12144 onChoice(color); 12145 }); 12146 }, fallbackColor); 12147 } else if (value === 'remove') { 12148 onChoice(''); 12149 editor.execCommand('mceRemoveTextcolor', format); 12150 } else { 12151 onChoice(value); 12152 editor.execCommand('mceApplyTextcolor', format, value); 12153 } 12154 }; 12155 var getColors$1 = function (colors, hasCustom) { 12156 return colors.concat(getCurrentColors().concat(getAdditionalColors(hasCustom))); 12157 }; 12158 var getFetch$1 = function (colors, hasCustom) { 12159 return function (callback) { 12160 callback(getColors$1(colors, hasCustom)); 12161 }; 12162 }; 12163 var setIconColor = function (splitButtonApi, name, newColor) { 12164 var id = name === 'forecolor' ? 'tox-icon-text-color__color' : 'tox-icon-highlight-bg-color__color'; 12165 splitButtonApi.setIconFill(id, newColor); 12166 }; 12167 var registerTextColorButton = function (editor, name, format, tooltip, lastColor) { 12168 editor.ui.registry.addSplitButton(name, { 12169 tooltip: tooltip, 12170 presets: 'color', 12171 icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color', 12172 select: function (value) { 12173 var optCurrentRgb = getCurrentColor(editor, format); 12174 return optCurrentRgb.bind(function (currentRgb) { 12175 return fromString(currentRgb).map(function (rgba) { 12176 var currentHex = fromRgba(rgba).value; 12177 return contains$1(value.toLowerCase(), currentHex); 12178 }); 12179 }).getOr(false); 12180 }, 12181 columns: getColorCols$1(editor), 12182 fetch: getFetch$1(getColors$2(editor), hasCustomColors$1(editor)), 12183 onAction: function (_splitButtonApi) { 12184 applyColor(editor, format, lastColor.get(), noop); 12185 }, 12186 onItemAction: function (_splitButtonApi, value) { 12187 applyColor(editor, format, value, function (newColor) { 12188 lastColor.set(newColor); 12189 fireTextColorChange(editor, { 12190 name: name, 12191 color: newColor 12192 }); 12193 }); 12194 }, 12195 onSetup: function (splitButtonApi) { 12196 setIconColor(splitButtonApi, name, lastColor.get()); 12197 var handler = function (e) { 12198 if (e.name === name) { 12199 setIconColor(splitButtonApi, e.name, e.color); 12200 } 12201 }; 12202 editor.on('TextColorChange', handler); 12203 return function () { 12204 editor.off('TextColorChange', handler); 12205 }; 12206 } 12207 }); 12208 }; 12209 var registerTextColorMenuItem = function (editor, name, format, text) { 12210 editor.ui.registry.addNestedMenuItem(name, { 12211 text: text, 12212 icon: name === 'forecolor' ? 'text-color' : 'highlight-bg-color', 12213 getSubmenuItems: function () { 12214 return [{ 12215 type: 'fancymenuitem', 12216 fancytype: 'colorswatch', 12217 onAction: function (data) { 12218 applyColor(editor, format, data.value, noop); 12219 } 12220 }]; 12221 } 12222 }); 12223 }; 12224 var colorPickerDialog = function (editor) { 12225 return function (callback, value) { 12226 var isValid = false; 12227 var onSubmit = function (api) { 12228 var data = api.getData(); 12229 var hex = data.colorpicker; 12230 if (isValid) { 12231 callback(Optional.from(hex)); 12232 api.close(); 12233 } else { 12234 editor.windowManager.alert(editor.translate([ 12235 'Invalid hex color code: {0}', 12236 hex 12237 ])); 12238 } 12239 }; 12240 var onAction = function (_api, details) { 12241 if (details.name === 'hex-valid') { 12242 isValid = details.value; 12243 } 12244 }; 12245 var initialData = { colorpicker: value }; 12246 editor.windowManager.open({ 12247 title: 'Color Picker', 12248 size: 'normal', 12249 body: { 12250 type: 'panel', 12251 items: [{ 12252 type: 'colorpicker', 12253 name: 'colorpicker', 12254 label: 'Color' 12255 }] 12256 }, 12257 buttons: [ 12258 { 12259 type: 'cancel', 12260 name: 'cancel', 12261 text: 'Cancel' 12262 }, 12263 { 12264 type: 'submit', 12265 name: 'save', 12266 text: 'Save', 12267 primary: true 12268 } 12269 ], 12270 initialData: initialData, 12271 onAction: onAction, 12272 onSubmit: onSubmit, 12273 onClose: noop, 12274 onCancel: function () { 12275 callback(Optional.none()); 12276 } 12277 }); 12278 }; 12279 }; 12280 var register$a = function (editor) { 12281 registerCommands(editor); 12282 var lastForeColor = Cell(fallbackColor); 12283 var lastBackColor = Cell(fallbackColor); 12284 registerTextColorButton(editor, 'forecolor', 'forecolor', 'Text color', lastForeColor); 12285 registerTextColorButton(editor, 'backcolor', 'hilitecolor', 'Background color', lastBackColor); 12286 registerTextColorMenuItem(editor, 'forecolor', 'forecolor', 'Text color'); 12287 registerTextColorMenuItem(editor, 'backcolor', 'hilitecolor', 'Background color'); 12288 }; 12289 12290 var createPartialChoiceMenu = function (value, items, onItemValueHandler, columns, presets, itemResponse, select, providersBackstage) { 12291 var hasIcons = menuHasIcons(items); 12292 var presetItemTypes = presets !== 'color' ? 'normal' : 'color'; 12293 var alloyItems = createChoiceItems(items, onItemValueHandler, columns, presetItemTypes, itemResponse, select, providersBackstage); 12294 return createPartialMenuWithAlloyItems(value, hasIcons, alloyItems, columns, presets); 12295 }; 12296 var createChoiceItems = function (items, onItemValueHandler, columns, itemPresets, itemResponse, select, providersBackstage) { 12297 return cat(map$2(items, function (item) { 12298 if (item.type === 'choiceitem') { 12299 return createChoiceMenuItem(item).fold(handleError, function (d) { 12300 return Optional.some(renderChoiceItem(d, columns === 1, itemPresets, onItemValueHandler, select(item.value), itemResponse, providersBackstage, menuHasIcons(items))); 12301 }); 12302 } else { 12303 return Optional.none(); 12304 } 12305 })); 12306 }; 12307 12308 var deriveMenuMovement = function (columns, presets) { 12309 var menuMarkers = markers(presets); 12310 if (columns === 1) { 12311 return { 12312 mode: 'menu', 12313 moveOnTab: true 12314 }; 12315 } else if (columns === 'auto') { 12316 return { 12317 mode: 'grid', 12318 selector: '.' + menuMarkers.item, 12319 initSize: { 12320 numColumns: 1, 12321 numRows: 1 12322 } 12323 }; 12324 } else { 12325 var rowClass = presets === 'color' ? 'tox-swatches__row' : 'tox-collection__group'; 12326 return { 12327 mode: 'matrix', 12328 rowSelector: '.' + rowClass 12329 }; 12330 } 12331 }; 12332 var deriveCollectionMovement = function (columns, presets) { 12333 if (columns === 1) { 12334 return { 12335 mode: 'menu', 12336 moveOnTab: false, 12337 selector: '.tox-collection__item' 12338 }; 12339 } else if (columns === 'auto') { 12340 return { 12341 mode: 'flatgrid', 12342 selector: '.' + 'tox-collection__item', 12343 initSize: { 12344 numColumns: 1, 12345 numRows: 1 12346 } 12347 }; 12348 } else { 12349 return { 12350 mode: 'matrix', 12351 selectors: { 12352 row: presets === 'color' ? '.tox-swatches__row' : '.tox-collection__group', 12353 cell: presets === 'color' ? '.' + colorClass : '.' + selectableClass 12354 } 12355 }; 12356 } 12357 }; 12358 12359 var renderColorSwatchItem = function (spec, backstage) { 12360 var items = getColorItems(spec, backstage); 12361 var columns = backstage.colorinput.getColorCols(); 12362 var presets = 'color'; 12363 var menuSpec = createPartialChoiceMenu(generate$6('menu-value'), items, function (value) { 12364 spec.onAction({ value: value }); 12365 }, columns, presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, backstage.shared.providers); 12366 var widgetSpec = __assign(__assign({}, menuSpec), { 12367 markers: markers(presets), 12368 movement: deriveMenuMovement(columns, presets) 12369 }); 12370 return { 12371 type: 'widget', 12372 data: { value: generate$6('widget-id') }, 12373 dom: { 12374 tag: 'div', 12375 classes: ['tox-fancymenuitem'] 12376 }, 12377 autofocus: true, 12378 components: [parts$f.widget(Menu.sketch(widgetSpec))] 12379 }; 12380 }; 12381 var getColorItems = function (spec, backstage) { 12382 var useCustomColors = spec.initData.allowCustomColors && backstage.colorinput.hasCustomColors(); 12383 return spec.initData.colors.fold(function () { 12384 return getColors$1(backstage.colorinput.getColors(), useCustomColors); 12385 }, function (colors) { 12386 return colors.concat(getAdditionalColors(useCustomColors)); 12387 }); 12388 }; 12389 12390 var cellOverEvent = generate$6('cell-over'); 12391 var cellExecuteEvent = generate$6('cell-execute'); 12392 var makeCell = function (row, col, labelId) { 12393 var _a; 12394 var emitCellOver = function (c) { 12395 return emitWith(c, cellOverEvent, { 12396 row: row, 12397 col: col 12398 }); 12399 }; 12400 var emitExecute = function (c) { 12401 return emitWith(c, cellExecuteEvent, { 12402 row: row, 12403 col: col 12404 }); 12405 }; 12406 var onClick = function (c, se) { 12407 se.stop(); 12408 emitExecute(c); 12409 }; 12410 return build$1({ 12411 dom: { 12412 tag: 'div', 12413 attributes: (_a = { role: 'button' }, _a['aria-labelledby'] = labelId, _a) 12414 }, 12415 behaviours: derive$1([ 12416 config('insert-table-picker-cell', [ 12417 run$1(mouseover(), Focusing.focus), 12418 run$1(execute$5(), emitExecute), 12419 run$1(click(), onClick), 12420 run$1(tap(), onClick) 12421 ]), 12422 Toggling.config({ 12423 toggleClass: 'tox-insert-table-picker__selected', 12424 toggleOnExecute: false 12425 }), 12426 Focusing.config({ onFocus: emitCellOver }) 12427 ]) 12428 }); 12429 }; 12430 var makeCells = function (labelId, numRows, numCols) { 12431 var cells = []; 12432 for (var i = 0; i < numRows; i++) { 12433 var row = []; 12434 for (var j = 0; j < numCols; j++) { 12435 row.push(makeCell(i, j, labelId)); 12436 } 12437 cells.push(row); 12438 } 12439 return cells; 12440 }; 12441 var selectCells = function (cells, selectedRow, selectedColumn, numRows, numColumns) { 12442 for (var i = 0; i < numRows; i++) { 12443 for (var j = 0; j < numColumns; j++) { 12444 Toggling.set(cells[i][j], i <= selectedRow && j <= selectedColumn); 12445 } 12446 } 12447 }; 12448 var makeComponents = function (cells) { 12449 return bind$3(cells, function (cellRow) { 12450 return map$2(cellRow, premade); 12451 }); 12452 }; 12453 var makeLabelText = function (row, col) { 12454 return text(col + 'x' + row); 12455 }; 12456 var renderInsertTableMenuItem = function (spec) { 12457 var numRows = 10; 12458 var numColumns = 10; 12459 var sizeLabelId = generate$6('size-label'); 12460 var cells = makeCells(sizeLabelId, numRows, numColumns); 12461 var emptyLabelText = makeLabelText(0, 0); 12462 var memLabel = record({ 12463 dom: { 12464 tag: 'span', 12465 classes: ['tox-insert-table-picker__label'], 12466 attributes: { id: sizeLabelId } 12467 }, 12468 components: [emptyLabelText], 12469 behaviours: derive$1([Replacing.config({})]) 12470 }); 12471 return { 12472 type: 'widget', 12473 data: { value: generate$6('widget-id') }, 12474 dom: { 12475 tag: 'div', 12476 classes: ['tox-fancymenuitem'] 12477 }, 12478 autofocus: true, 12479 components: [parts$f.widget({ 12480 dom: { 12481 tag: 'div', 12482 classes: ['tox-insert-table-picker'] 12483 }, 12484 components: makeComponents(cells).concat(memLabel.asSpec()), 12485 behaviours: derive$1([ 12486 config('insert-table-picker', [ 12487 runOnAttached(function (c) { 12488 Replacing.set(memLabel.get(c), [emptyLabelText]); 12489 }), 12490 runWithTarget(cellOverEvent, function (c, t, e) { 12491 var _a = e.event, row = _a.row, col = _a.col; 12492 selectCells(cells, row, col, numRows, numColumns); 12493 Replacing.set(memLabel.get(c), [makeLabelText(row + 1, col + 1)]); 12494 }), 12495 runWithTarget(cellExecuteEvent, function (c, _, e) { 12496 var _a = e.event, row = _a.row, col = _a.col; 12497 spec.onAction({ 12498 numRows: row + 1, 12499 numColumns: col + 1 12500 }); 12501 emit(c, sandboxClose()); 12502 }) 12503 ]), 12504 Keying.config({ 12505 initSize: { 12506 numRows: numRows, 12507 numColumns: numColumns 12508 }, 12509 mode: 'flatgrid', 12510 selector: '[role="button"]' 12511 }) 12512 ]) 12513 })] 12514 }; 12515 }; 12516 12517 var fancyMenuItems = { 12518 inserttable: renderInsertTableMenuItem, 12519 colorswatch: renderColorSwatchItem 12520 }; 12521 var renderFancyMenuItem = function (spec, backstage) { 12522 return get$e(fancyMenuItems, spec.fancytype).map(function (render) { 12523 return render(spec, backstage); 12524 }); 12525 }; 12526 12527 var renderNestedItem = function (spec, itemResponse, providersBackstage, renderIcons, downwardsCaret) { 12528 if (renderIcons === void 0) { 12529 renderIcons = true; 12530 } 12531 if (downwardsCaret === void 0) { 12532 downwardsCaret = false; 12533 } 12534 var caret = downwardsCaret ? renderDownwardsCaret(providersBackstage.icons) : renderSubmenuCaret(providersBackstage.icons); 12535 var getApi = function (component) { 12536 return { 12537 isDisabled: function () { 12538 return Disabling.isDisabled(component); 12539 }, 12540 setDisabled: function (state) { 12541 return Disabling.set(component, state); 12542 } 12543 }; 12544 }; 12545 var structure = renderItemStructure({ 12546 presets: 'normal', 12547 iconContent: spec.icon, 12548 textContent: spec.text, 12549 htmlContent: Optional.none(), 12550 ariaLabel: spec.text, 12551 caret: Optional.some(caret), 12552 checkMark: Optional.none(), 12553 shortcutContent: spec.shortcut 12554 }, providersBackstage, renderIcons); 12555 return renderCommonItem({ 12556 data: buildData(spec), 12557 getApi: getApi, 12558 disabled: spec.disabled, 12559 onAction: noop, 12560 onSetup: spec.onSetup, 12561 triggersSubmenu: true, 12562 itemBehaviours: [] 12563 }, structure, itemResponse, providersBackstage); 12564 }; 12565 12566 var renderNormalItem = function (spec, itemResponse, providersBackstage, renderIcons) { 12567 if (renderIcons === void 0) { 12568 renderIcons = true; 12569 } 12570 var getApi = function (component) { 12571 return { 12572 isDisabled: function () { 12573 return Disabling.isDisabled(component); 12574 }, 12575 setDisabled: function (state) { 12576 return Disabling.set(component, state); 12577 } 12578 }; 12579 }; 12580 var structure = renderItemStructure({ 12581 presets: 'normal', 12582 iconContent: spec.icon, 12583 textContent: spec.text, 12584 htmlContent: Optional.none(), 12585 ariaLabel: spec.text, 12586 caret: Optional.none(), 12587 checkMark: Optional.none(), 12588 shortcutContent: spec.shortcut 12589 }, providersBackstage, renderIcons); 12590 return renderCommonItem({ 12591 data: buildData(spec), 12592 getApi: getApi, 12593 disabled: spec.disabled, 12594 onAction: spec.onAction, 12595 onSetup: spec.onSetup, 12596 triggersSubmenu: false, 12597 itemBehaviours: [] 12598 }, structure, itemResponse, providersBackstage); 12599 }; 12600 12601 var renderSeparatorItem = function (spec) { 12602 var innerHtml = spec.text.fold(function () { 12603 return {}; 12604 }, function (text) { 12605 return { innerHtml: text }; 12606 }); 12607 return { 12608 type: 'separator', 12609 dom: __assign({ 12610 tag: 'div', 12611 classes: [ 12612 selectableClass, 12613 groupHeadingClass 12614 ] 12615 }, innerHtml), 12616 components: [] 12617 }; 12618 }; 12619 12620 var renderToggleMenuItem = function (spec, itemResponse, providersBackstage, renderIcons) { 12621 if (renderIcons === void 0) { 12622 renderIcons = true; 12623 } 12624 var getApi = function (component) { 12625 return { 12626 setActive: function (state) { 12627 Toggling.set(component, state); 12628 }, 12629 isActive: function () { 12630 return Toggling.isOn(component); 12631 }, 12632 isDisabled: function () { 12633 return Disabling.isDisabled(component); 12634 }, 12635 setDisabled: function (state) { 12636 return Disabling.set(component, state); 12637 } 12638 }; 12639 }; 12640 var structure = renderItemStructure({ 12641 iconContent: spec.icon, 12642 textContent: spec.text, 12643 htmlContent: Optional.none(), 12644 ariaLabel: spec.text, 12645 checkMark: Optional.some(renderCheckmark(providersBackstage.icons)), 12646 caret: Optional.none(), 12647 shortcutContent: spec.shortcut, 12648 presets: 'normal', 12649 meta: spec.meta 12650 }, providersBackstage, renderIcons); 12651 return deepMerge(renderCommonItem({ 12652 data: buildData(spec), 12653 disabled: spec.disabled, 12654 getApi: getApi, 12655 onAction: spec.onAction, 12656 onSetup: spec.onSetup, 12657 triggersSubmenu: false, 12658 itemBehaviours: [] 12659 }, structure, itemResponse, providersBackstage), { 12660 toggling: { 12661 toggleClass: tickedClass, 12662 toggleOnExecute: false, 12663 selected: spec.active 12664 } 12665 }); 12666 }; 12667 12668 var autocomplete = renderAutocompleteItem; 12669 var separator$3 = renderSeparatorItem; 12670 var normal = renderNormalItem; 12671 var nested = renderNestedItem; 12672 var toggle$1 = renderToggleMenuItem; 12673 var fancy = renderFancyMenuItem; 12674 var card = renderCardMenuItem; 12675 12676 var FocusMode; 12677 (function (FocusMode) { 12678 FocusMode[FocusMode['ContentFocus'] = 0] = 'ContentFocus'; 12679 FocusMode[FocusMode['UiFocus'] = 1] = 'UiFocus'; 12680 }(FocusMode || (FocusMode = {}))); 12681 var createMenuItemFromBridge = function (item, itemResponse, backstage, menuHasIcons, isHorizontalMenu) { 12682 var providersBackstage = backstage.shared.providers; 12683 var parseForHorizontalMenu = function (menuitem) { 12684 return !isHorizontalMenu ? menuitem : __assign(__assign({}, menuitem), { 12685 shortcut: Optional.none(), 12686 icon: menuitem.text.isSome() ? Optional.none() : menuitem.icon 12687 }); 12688 }; 12689 switch (item.type) { 12690 case 'menuitem': 12691 return createMenuItem(item).fold(handleError, function (d) { 12692 return Optional.some(normal(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons)); 12693 }); 12694 case 'nestedmenuitem': 12695 return createNestedMenuItem(item).fold(handleError, function (d) { 12696 return Optional.some(nested(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons, isHorizontalMenu)); 12697 }); 12698 case 'togglemenuitem': 12699 return createToggleMenuItem(item).fold(handleError, function (d) { 12700 return Optional.some(toggle$1(parseForHorizontalMenu(d), itemResponse, providersBackstage, menuHasIcons)); 12701 }); 12702 case 'separator': 12703 return createSeparatorMenuItem(item).fold(handleError, function (d) { 12704 return Optional.some(separator$3(d)); 12705 }); 12706 case 'fancymenuitem': 12707 return createFancyMenuItem(item).fold(handleError, function (d) { 12708 return fancy(parseForHorizontalMenu(d), backstage); 12709 }); 12710 default: { 12711 console.error('Unknown item in general menu', item); 12712 return Optional.none(); 12713 } 12714 } 12715 }; 12716 var createAutocompleteItems = function (items, matchText, onItemValueHandler, columns, itemResponse, sharedBackstage, highlightOn) { 12717 var renderText = columns === 1; 12718 var renderIcons = !renderText || menuHasIcons(items); 12719 return cat(map$2(items, function (item) { 12720 switch (item.type) { 12721 case 'separator': 12722 return createSeparatorItem(item).fold(handleError, function (d) { 12723 return Optional.some(separator$3(d)); 12724 }); 12725 case 'cardmenuitem': 12726 return createCardMenuItem(item).fold(handleError, function (d) { 12727 return Optional.some(card(__assign(__assign({}, d), { 12728 onAction: function (api) { 12729 d.onAction(api); 12730 onItemValueHandler(d.value, d.meta); 12731 } 12732 }), itemResponse, sharedBackstage, { 12733 itemBehaviours: tooltipBehaviour(d.meta, sharedBackstage), 12734 cardText: { 12735 matchText: matchText, 12736 highlightOn: highlightOn 12737 } 12738 })); 12739 }); 12740 case 'autocompleteitem': 12741 default: 12742 return createAutocompleterItem(item).fold(handleError, function (d) { 12743 return Optional.some(autocomplete(d, matchText, renderText, 'normal', onItemValueHandler, itemResponse, sharedBackstage, renderIcons)); 12744 }); 12745 } 12746 })); 12747 }; 12748 var createPartialMenu = function (value, items, itemResponse, backstage, isHorizontalMenu) { 12749 var hasIcons = menuHasIcons(items); 12750 var alloyItems = cat(map$2(items, function (item) { 12751 var itemHasIcon = function (i) { 12752 return isHorizontalMenu ? !has$2(i, 'text') : hasIcons; 12753 }; 12754 var createItem = function (i) { 12755 return createMenuItemFromBridge(i, itemResponse, backstage, itemHasIcon(i), isHorizontalMenu); 12756 }; 12757 if (item.type === 'nestedmenuitem' && item.getSubmenuItems().length <= 0) { 12758 return createItem(__assign(__assign({}, item), { disabled: true })); 12759 } else { 12760 return createItem(item); 12761 } 12762 })); 12763 var createPartial = isHorizontalMenu ? createHorizontalPartialMenuWithAlloyItems : createPartialMenuWithAlloyItems; 12764 return createPartial(value, hasIcons, alloyItems, 1, 'normal'); 12765 }; 12766 var createTieredDataFrom = function (partialMenu) { 12767 return tieredMenu.singleData(partialMenu.value, partialMenu); 12768 }; 12769 var createMenuFrom = function (partialMenu, columns, focusMode, presets) { 12770 var focusManager = focusMode === FocusMode.ContentFocus ? highlights() : dom$2(); 12771 var movement = deriveMenuMovement(columns, presets); 12772 var menuMarkers = markers(presets); 12773 return { 12774 dom: partialMenu.dom, 12775 components: partialMenu.components, 12776 items: partialMenu.items, 12777 value: partialMenu.value, 12778 markers: { 12779 selectedItem: menuMarkers.selectedItem, 12780 item: menuMarkers.item 12781 }, 12782 movement: movement, 12783 fakeFocus: focusMode === FocusMode.ContentFocus, 12784 focusManager: focusManager, 12785 menuBehaviours: SimpleBehaviours.unnamedEvents(columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) { 12786 detectSize(comp, 4, menuMarkers.item).each(function (_a) { 12787 var numColumns = _a.numColumns, numRows = _a.numRows; 12788 Keying.setGridSize(comp, numRows, numColumns); 12789 }); 12790 })]) 12791 }; 12792 }; 12793 12794 var register$9 = function (editor, sharedBackstage) { 12795 var activeAutocompleter = value$1(); 12796 var processingAction = Cell(false); 12797 var autocompleter = build$1(InlineView.sketch({ 12798 dom: { 12799 tag: 'div', 12800 classes: ['tox-autocompleter'] 12801 }, 12802 components: [], 12803 fireDismissalEventInstead: {}, 12804 inlineBehaviours: derive$1([config('dismissAutocompleter', [run$1(dismissRequested(), function () { 12805 return cancelIfNecessary(); 12806 })])]), 12807 lazySink: sharedBackstage.getSink 12808 })); 12809 var isMenuOpen = function () { 12810 return InlineView.isOpen(autocompleter); 12811 }; 12812 var isActive = function () { 12813 return activeAutocompleter.get().isSome(); 12814 }; 12815 var hideIfNecessary = function () { 12816 if (isActive()) { 12817 InlineView.hide(autocompleter); 12818 } 12819 }; 12820 var cancelIfNecessary = function () { 12821 if (isActive()) { 12822 var lastElement = activeAutocompleter.get().map(function (ac) { 12823 return ac.element; 12824 }); 12825 detect(lastElement.getOr(SugarElement.fromDom(editor.selection.getNode()))).each(unwrap); 12826 hideIfNecessary(); 12827 activeAutocompleter.clear(); 12828 processingAction.set(false); 12829 } 12830 }; 12831 var getAutocompleters = cached(function () { 12832 return register$b(editor); 12833 }); 12834 var getCombinedItems = function (triggerChar, matches) { 12835 var columns = findMap(matches, function (m) { 12836 return Optional.from(m.columns); 12837 }).getOr(1); 12838 return bind$3(matches, function (match) { 12839 var choices = match.items; 12840 return createAutocompleteItems(choices, match.matchText, function (itemValue, itemMeta) { 12841 var nr = editor.selection.getRng(); 12842 getContext(editor.dom, nr, triggerChar).fold(function () { 12843 return console.error('Lost context. Cursor probably moved'); 12844 }, function (_a) { 12845 var range = _a.range; 12846 var autocompleterApi = { 12847 hide: function () { 12848 cancelIfNecessary(); 12849 }, 12850 reload: function (fetchOptions) { 12851 hideIfNecessary(); 12852 load(fetchOptions); 12853 } 12854 }; 12855 processingAction.set(true); 12856 match.onAction(autocompleterApi, range, itemValue, itemMeta); 12857 processingAction.set(false); 12858 }); 12859 }, columns, ItemResponse$1.BUBBLE_TO_SANDBOX, sharedBackstage, match.highlightOn); 12860 }); 12861 }; 12862 var commenceIfNecessary = function (context) { 12863 if (!isActive()) { 12864 var wrapper = create$4(editor, context.range); 12865 activeAutocompleter.set({ 12866 triggerChar: context.triggerChar, 12867 element: wrapper, 12868 matchLength: context.text.length 12869 }); 12870 processingAction.set(false); 12871 } 12872 }; 12873 var display = function (ac, context, lookupData, items) { 12874 ac.matchLength = context.text.length; 12875 var columns = findMap(lookupData, function (ld) { 12876 return Optional.from(ld.columns); 12877 }).getOr(1); 12878 InlineView.showAt(autocompleter, Menu.sketch(createMenuFrom(createPartialMenuWithAlloyItems('autocompleter-value', true, items, columns, 'normal'), columns, FocusMode.ContentFocus, 'normal')), { 12879 anchor: { 12880 type: 'node', 12881 root: SugarElement.fromDom(editor.getBody()), 12882 node: Optional.from(ac.element) 12883 } 12884 }); 12885 InlineView.getContent(autocompleter).each(Highlighting.highlightFirst); 12886 }; 12887 var doLookup = function (fetchOptions) { 12888 return activeAutocompleter.get().map(function (ac) { 12889 return getContext(editor.dom, editor.selection.getRng(), ac.triggerChar).bind(function (newContext) { 12890 return lookupWithContext(editor, getAutocompleters, newContext, fetchOptions); 12891 }); 12892 }).getOrThunk(function () { 12893 return lookup$2(editor, getAutocompleters); 12894 }); 12895 }; 12896 var load = function (fetchOptions) { 12897 doLookup(fetchOptions).fold(cancelIfNecessary, function (lookupInfo) { 12898 commenceIfNecessary(lookupInfo.context); 12899 lookupInfo.lookupData.then(function (lookupData) { 12900 activeAutocompleter.get().map(function (ac) { 12901 var context = lookupInfo.context; 12902 if (ac.triggerChar === context.triggerChar) { 12903 var combinedItems = getCombinedItems(context.triggerChar, lookupData); 12904 if (combinedItems.length > 0) { 12905 display(ac, context, lookupData, combinedItems); 12906 } else if (context.text.length - ac.matchLength >= 10) { 12907 cancelIfNecessary(); 12908 } else { 12909 hideIfNecessary(); 12910 } 12911 } 12912 }); 12913 }); 12914 }); 12915 }; 12916 var onKeypress = last(function (e) { 12917 if (e.which === 27) { 12918 return; 12919 } 12920 load(); 12921 }, 50); 12922 var autocompleterUiApi = { 12923 onKeypress: onKeypress, 12924 cancelIfNecessary: cancelIfNecessary, 12925 isMenuOpen: isMenuOpen, 12926 isActive: isActive, 12927 isProcessingAction: processingAction.get, 12928 getView: function () { 12929 return InlineView.getContent(autocompleter); 12930 } 12931 }; 12932 if (editor.hasPlugin('rtc') === false) { 12933 AutocompleterEditorEvents.setup(autocompleterUiApi, editor); 12934 } 12935 }; 12936 var Autocompleter = { register: register$9 }; 12937 12938 var closest = function (scope, selector, isRoot) { 12939 return closest$1(scope, selector, isRoot).isSome(); 12940 }; 12941 12942 var DelayedFunction = function (fun, delay) { 12943 var ref = null; 12944 var schedule = function () { 12945 var args = []; 12946 for (var _i = 0; _i < arguments.length; _i++) { 12947 args[_i] = arguments[_i]; 12948 } 12949 ref = setTimeout(function () { 12950 fun.apply(null, args); 12951 ref = null; 12952 }, delay); 12953 }; 12954 var cancel = function () { 12955 if (ref !== null) { 12956 clearTimeout(ref); 12957 ref = null; 12958 } 12959 }; 12960 return { 12961 cancel: cancel, 12962 schedule: schedule 12963 }; 12964 }; 12965 12966 var SIGNIFICANT_MOVE = 5; 12967 var LONGPRESS_DELAY = 400; 12968 var getTouch = function (event) { 12969 var raw = event.raw; 12970 if (raw.touches === undefined || raw.touches.length !== 1) { 12971 return Optional.none(); 12972 } 12973 return Optional.some(raw.touches[0]); 12974 }; 12975 var isFarEnough = function (touch, data) { 12976 var distX = Math.abs(touch.clientX - data.x); 12977 var distY = Math.abs(touch.clientY - data.y); 12978 return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE; 12979 }; 12980 var monitor = function (settings) { 12981 var startData = value$1(); 12982 var longpressFired = Cell(false); 12983 var longpress$1 = DelayedFunction(function (event) { 12984 settings.triggerEvent(longpress(), event); 12985 longpressFired.set(true); 12986 }, LONGPRESS_DELAY); 12987 var handleTouchstart = function (event) { 12988 getTouch(event).each(function (touch) { 12989 longpress$1.cancel(); 12990 var data = { 12991 x: touch.clientX, 12992 y: touch.clientY, 12993 target: event.target 12994 }; 12995 longpress$1.schedule(event); 12996 longpressFired.set(false); 12997 startData.set(data); 12998 }); 12999 return Optional.none(); 13000 }; 13001 var handleTouchmove = function (event) { 13002 longpress$1.cancel(); 13003 getTouch(event).each(function (touch) { 13004 startData.on(function (data) { 13005 if (isFarEnough(touch, data)) { 13006 startData.clear(); 13007 } 13008 }); 13009 }); 13010 return Optional.none(); 13011 }; 13012 var handleTouchend = function (event) { 13013 longpress$1.cancel(); 13014 var isSame = function (data) { 13015 return eq(data.target, event.target); 13016 }; 13017 return startData.get().filter(isSame).map(function (_data) { 13018 if (longpressFired.get()) { 13019 event.prevent(); 13020 return false; 13021 } else { 13022 return settings.triggerEvent(tap(), event); 13023 } 13024 }); 13025 }; 13026 var handlers = wrapAll([ 13027 { 13028 key: touchstart(), 13029 value: handleTouchstart 13030 }, 13031 { 13032 key: touchmove(), 13033 value: handleTouchmove 13034 }, 13035 { 13036 key: touchend(), 13037 value: handleTouchend 13038 } 13039 ]); 13040 var fireIfReady = function (event, type) { 13041 return get$e(handlers, type).bind(function (handler) { 13042 return handler(event); 13043 }); 13044 }; 13045 return { fireIfReady: fireIfReady }; 13046 }; 13047 13048 var isDangerous = function (event) { 13049 var keyEv = event.raw; 13050 return keyEv.which === BACKSPACE[0] && !contains$2([ 13051 'input', 13052 'textarea' 13053 ], name$2(event.target)) && !closest(event.target, '[contenteditable="true"]'); 13054 }; 13055 var isFirefox = function () { 13056 return detect$1().browser.isFirefox(); 13057 }; 13058 var bindFocus = function (container, handler) { 13059 if (isFirefox()) { 13060 return capture(container, 'focus', handler); 13061 } else { 13062 return bind(container, 'focusin', handler); 13063 } 13064 }; 13065 var bindBlur = function (container, handler) { 13066 if (isFirefox()) { 13067 return capture(container, 'blur', handler); 13068 } else { 13069 return bind(container, 'focusout', handler); 13070 } 13071 }; 13072 var setup$d = function (container, rawSettings) { 13073 var settings = __assign({ stopBackspace: true }, rawSettings); 13074 var pointerEvents = [ 13075 'touchstart', 13076 'touchmove', 13077 'touchend', 13078 'touchcancel', 13079 'gesturestart', 13080 'mousedown', 13081 'mouseup', 13082 'mouseover', 13083 'mousemove', 13084 'mouseout', 13085 'click' 13086 ]; 13087 var tapEvent = monitor(settings); 13088 var simpleEvents = map$2(pointerEvents.concat([ 13089 'selectstart', 13090 'input', 13091 'contextmenu', 13092 'change', 13093 'transitionend', 13094 'transitioncancel', 13095 'drag', 13096 'dragstart', 13097 'dragend', 13098 'dragenter', 13099 'dragleave', 13100 'dragover', 13101 'drop', 13102 'keyup' 13103 ]), function (type) { 13104 return bind(container, type, function (event) { 13105 tapEvent.fireIfReady(event, type).each(function (tapStopped) { 13106 if (tapStopped) { 13107 event.kill(); 13108 } 13109 }); 13110 var stopped = settings.triggerEvent(type, event); 13111 if (stopped) { 13112 event.kill(); 13113 } 13114 }); 13115 }); 13116 var pasteTimeout = value$1(); 13117 var onPaste = bind(container, 'paste', function (event) { 13118 tapEvent.fireIfReady(event, 'paste').each(function (tapStopped) { 13119 if (tapStopped) { 13120 event.kill(); 13121 } 13122 }); 13123 var stopped = settings.triggerEvent('paste', event); 13124 if (stopped) { 13125 event.kill(); 13126 } 13127 pasteTimeout.set(setTimeout(function () { 13128 settings.triggerEvent(postPaste(), event); 13129 }, 0)); 13130 }); 13131 var onKeydown = bind(container, 'keydown', function (event) { 13132 var stopped = settings.triggerEvent('keydown', event); 13133 if (stopped) { 13134 event.kill(); 13135 } else if (settings.stopBackspace && isDangerous(event)) { 13136 event.prevent(); 13137 } 13138 }); 13139 var onFocusIn = bindFocus(container, function (event) { 13140 var stopped = settings.triggerEvent('focusin', event); 13141 if (stopped) { 13142 event.kill(); 13143 } 13144 }); 13145 var focusoutTimeout = value$1(); 13146 var onFocusOut = bindBlur(container, function (event) { 13147 var stopped = settings.triggerEvent('focusout', event); 13148 if (stopped) { 13149 event.kill(); 13150 } 13151 focusoutTimeout.set(setTimeout(function () { 13152 settings.triggerEvent(postBlur(), event); 13153 }, 0)); 13154 }); 13155 var unbind = function () { 13156 each$1(simpleEvents, function (e) { 13157 e.unbind(); 13158 }); 13159 onKeydown.unbind(); 13160 onFocusIn.unbind(); 13161 onFocusOut.unbind(); 13162 onPaste.unbind(); 13163 pasteTimeout.on(clearTimeout); 13164 focusoutTimeout.on(clearTimeout); 13165 }; 13166 return { unbind: unbind }; 13167 }; 13168 13169 var derive = function (rawEvent, rawTarget) { 13170 var source = get$e(rawEvent, 'target').getOr(rawTarget); 13171 return Cell(source); 13172 }; 13173 13174 var fromSource = function (event, source) { 13175 var stopper = Cell(false); 13176 var cutter = Cell(false); 13177 var stop = function () { 13178 stopper.set(true); 13179 }; 13180 var cut = function () { 13181 cutter.set(true); 13182 }; 13183 return { 13184 stop: stop, 13185 cut: cut, 13186 isStopped: stopper.get, 13187 isCut: cutter.get, 13188 event: event, 13189 setSource: source.set, 13190 getSource: source.get 13191 }; 13192 }; 13193 var fromExternal = function (event) { 13194 var stopper = Cell(false); 13195 var stop = function () { 13196 stopper.set(true); 13197 }; 13198 return { 13199 stop: stop, 13200 cut: noop, 13201 isStopped: stopper.get, 13202 isCut: never, 13203 event: event, 13204 setSource: die('Cannot set source of a broadcasted event'), 13205 getSource: die('Cannot get source of a broadcasted event') 13206 }; 13207 }; 13208 13209 var adt$1 = Adt.generate([ 13210 { stopped: [] }, 13211 { resume: ['element'] }, 13212 { complete: [] } 13213 ]); 13214 var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) { 13215 var handler = lookup(eventType, target); 13216 var simulatedEvent = fromSource(rawEvent, source); 13217 return handler.fold(function () { 13218 logger.logEventNoHandlers(eventType, target); 13219 return adt$1.complete(); 13220 }, function (handlerInfo) { 13221 var descHandler = handlerInfo.descHandler; 13222 var eventHandler = getCurried(descHandler); 13223 eventHandler(simulatedEvent); 13224 if (simulatedEvent.isStopped()) { 13225 logger.logEventStopped(eventType, handlerInfo.element, descHandler.purpose); 13226 return adt$1.stopped(); 13227 } else if (simulatedEvent.isCut()) { 13228 logger.logEventCut(eventType, handlerInfo.element, descHandler.purpose); 13229 return adt$1.complete(); 13230 } else { 13231 return parent(handlerInfo.element).fold(function () { 13232 logger.logNoParent(eventType, handlerInfo.element, descHandler.purpose); 13233 return adt$1.complete(); 13234 }, function (parent) { 13235 logger.logEventResponse(eventType, handlerInfo.element, descHandler.purpose); 13236 return adt$1.resume(parent); 13237 }); 13238 } 13239 }); 13240 }; 13241 var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) { 13242 return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(always, function (parent) { 13243 return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent, source, logger); 13244 }, never); 13245 }; 13246 var triggerHandler = function (lookup, eventType, rawEvent, target, logger) { 13247 var source = derive(rawEvent, target); 13248 return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger); 13249 }; 13250 var broadcast = function (listeners, rawEvent, _logger) { 13251 var simulatedEvent = fromExternal(rawEvent); 13252 each$1(listeners, function (listener) { 13253 var descHandler = listener.descHandler; 13254 var handler = getCurried(descHandler); 13255 handler(simulatedEvent); 13256 }); 13257 return simulatedEvent.isStopped(); 13258 }; 13259 var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) { 13260 return triggerOnUntilStopped(lookup, eventType, rawEvent, rawEvent.target, logger); 13261 }; 13262 var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) { 13263 var source = derive(rawEvent, rawTarget); 13264 return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger); 13265 }; 13266 13267 var eventHandler = function (element, descHandler) { 13268 return { 13269 element: element, 13270 descHandler: descHandler 13271 }; 13272 }; 13273 var broadcastHandler = function (id, handler) { 13274 return { 13275 id: id, 13276 descHandler: handler 13277 }; 13278 }; 13279 var EventRegistry = function () { 13280 var registry = {}; 13281 var registerId = function (extraArgs, id, events) { 13282 each(events, function (v, k) { 13283 var handlers = registry[k] !== undefined ? registry[k] : {}; 13284 handlers[id] = curryArgs(v, extraArgs); 13285 registry[k] = handlers; 13286 }); 13287 }; 13288 var findHandler = function (handlers, elem) { 13289 return read$1(elem).bind(function (id) { 13290 return get$e(handlers, id); 13291 }).map(function (descHandler) { 13292 return eventHandler(elem, descHandler); 13293 }); 13294 }; 13295 var filterByType = function (type) { 13296 return get$e(registry, type).map(function (handlers) { 13297 return mapToArray(handlers, function (f, id) { 13298 return broadcastHandler(id, f); 13299 }); 13300 }).getOr([]); 13301 }; 13302 var find = function (isAboveRoot, type, target) { 13303 return get$e(registry, type).bind(function (handlers) { 13304 return closest$4(target, function (elem) { 13305 return findHandler(handlers, elem); 13306 }, isAboveRoot); 13307 }); 13308 }; 13309 var unregisterId = function (id) { 13310 each(registry, function (handlersById, _eventName) { 13311 if (has$2(handlersById, id)) { 13312 delete handlersById[id]; 13313 } 13314 }); 13315 }; 13316 return { 13317 registerId: registerId, 13318 unregisterId: unregisterId, 13319 filterByType: filterByType, 13320 find: find 13321 }; 13322 }; 13323 13324 var Registry = function () { 13325 var events = EventRegistry(); 13326 var components = {}; 13327 var readOrTag = function (component) { 13328 var elem = component.element; 13329 return read$1(elem).getOrThunk(function () { 13330 return write('uid-', component.element); 13331 }); 13332 }; 13333 var failOnDuplicate = function (component, tagId) { 13334 var conflict = components[tagId]; 13335 if (conflict === component) { 13336 unregister(component); 13337 } else { 13338 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'); 13339 } 13340 }; 13341 var register = function (component) { 13342 var tagId = readOrTag(component); 13343 if (hasNonNullableKey(components, tagId)) { 13344 failOnDuplicate(component, tagId); 13345 } 13346 var extraArgs = [component]; 13347 events.registerId(extraArgs, tagId, component.events); 13348 components[tagId] = component; 13349 }; 13350 var unregister = function (component) { 13351 read$1(component.element).each(function (tagId) { 13352 delete components[tagId]; 13353 events.unregisterId(tagId); 13354 }); 13355 }; 13356 var filter = function (type) { 13357 return events.filterByType(type); 13358 }; 13359 var find = function (isAboveRoot, type, target) { 13360 return events.find(isAboveRoot, type, target); 13361 }; 13362 var getById = function (id) { 13363 return get$e(components, id); 13364 }; 13365 return { 13366 find: find, 13367 filter: filter, 13368 register: register, 13369 unregister: unregister, 13370 getById: getById 13371 }; 13372 }; 13373 13374 var factory$j = function (detail) { 13375 var _a = detail.dom, attributes = _a.attributes, domWithoutAttributes = __rest(_a, ['attributes']); 13376 return { 13377 uid: detail.uid, 13378 dom: __assign({ 13379 tag: 'div', 13380 attributes: __assign({ role: 'presentation' }, attributes) 13381 }, domWithoutAttributes), 13382 components: detail.components, 13383 behaviours: get$2(detail.containerBehaviours), 13384 events: detail.events, 13385 domModification: detail.domModification, 13386 eventOrder: detail.eventOrder 13387 }; 13388 }; 13389 var Container = single({ 13390 name: 'Container', 13391 factory: factory$j, 13392 configFields: [ 13393 defaulted('components', []), 13394 field('containerBehaviours', []), 13395 defaulted('events', {}), 13396 defaulted('domModification', {}), 13397 defaulted('eventOrder', {}) 13398 ] 13399 }); 13400 13401 var takeover = function (root) { 13402 var isAboveRoot = function (el) { 13403 return parent(root.element).fold(always, function (parent) { 13404 return eq(el, parent); 13405 }); 13406 }; 13407 var registry = Registry(); 13408 var lookup = function (eventName, target) { 13409 return registry.find(isAboveRoot, eventName, target); 13410 }; 13411 var domEvents = setup$d(root.element, { 13412 triggerEvent: function (eventName, event) { 13413 return monitorEvent(eventName, event.target, function (logger) { 13414 return triggerUntilStopped(lookup, eventName, event, logger); 13415 }); 13416 } 13417 }); 13418 var systemApi = { 13419 debugInfo: constant$1('real'), 13420 triggerEvent: function (eventName, target, data) { 13421 monitorEvent(eventName, target, function (logger) { 13422 return triggerOnUntilStopped(lookup, eventName, data, target, logger); 13423 }); 13424 }, 13425 triggerFocus: function (target, originator) { 13426 read$1(target).fold(function () { 13427 focus$3(target); 13428 }, function (_alloyId) { 13429 monitorEvent(focus$4(), target, function (logger) { 13430 triggerHandler(lookup, focus$4(), { 13431 originator: originator, 13432 kill: noop, 13433 prevent: noop, 13434 target: target 13435 }, target, logger); 13436 return false; 13437 }); 13438 }); 13439 }, 13440 triggerEscape: function (comp, simulatedEvent) { 13441 systemApi.triggerEvent('keydown', comp.element, simulatedEvent.event); 13442 }, 13443 getByUid: function (uid) { 13444 return getByUid(uid); 13445 }, 13446 getByDom: function (elem) { 13447 return getByDom(elem); 13448 }, 13449 build: build$1, 13450 addToGui: function (c) { 13451 add(c); 13452 }, 13453 removeFromGui: function (c) { 13454 remove(c); 13455 }, 13456 addToWorld: function (c) { 13457 addToWorld(c); 13458 }, 13459 removeFromWorld: function (c) { 13460 removeFromWorld(c); 13461 }, 13462 broadcast: function (message) { 13463 broadcast$1(message); 13464 }, 13465 broadcastOn: function (channels, message) { 13466 broadcastOn(channels, message); 13467 }, 13468 broadcastEvent: function (eventName, event) { 13469 broadcastEvent(eventName, event); 13470 }, 13471 isConnected: always 13472 }; 13473 var addToWorld = function (component) { 13474 component.connect(systemApi); 13475 if (!isText$1(component.element)) { 13476 registry.register(component); 13477 each$1(component.components(), addToWorld); 13478 systemApi.triggerEvent(systemInit(), component.element, { target: component.element }); 13479 } 13480 }; 13481 var removeFromWorld = function (component) { 13482 if (!isText$1(component.element)) { 13483 each$1(component.components(), removeFromWorld); 13484 registry.unregister(component); 13485 } 13486 component.disconnect(); 13487 }; 13488 var add = function (component) { 13489 attach(root, component); 13490 }; 13491 var remove = function (component) { 13492 detach(component); 13493 }; 13494 var destroy = function () { 13495 domEvents.unbind(); 13496 remove$5(root.element); 13497 }; 13498 var broadcastData = function (data) { 13499 var receivers = registry.filter(receive()); 13500 each$1(receivers, function (receiver) { 13501 var descHandler = receiver.descHandler; 13502 var handler = getCurried(descHandler); 13503 handler(data); 13504 }); 13505 }; 13506 var broadcast$1 = function (message) { 13507 broadcastData({ 13508 universal: true, 13509 data: message 13510 }); 13511 }; 13512 var broadcastOn = function (channels, message) { 13513 broadcastData({ 13514 universal: false, 13515 channels: channels, 13516 data: message 13517 }); 13518 }; 13519 var broadcastEvent = function (eventName, event) { 13520 var listeners = registry.filter(eventName); 13521 return broadcast(listeners, event); 13522 }; 13523 var getByUid = function (uid) { 13524 return registry.getById(uid).fold(function () { 13525 return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.')); 13526 }, Result.value); 13527 }; 13528 var getByDom = function (elem) { 13529 var uid = read$1(elem).getOr('not found'); 13530 return getByUid(uid); 13531 }; 13532 addToWorld(root); 13533 return { 13534 root: root, 13535 element: root.element, 13536 destroy: destroy, 13537 add: add, 13538 remove: remove, 13539 getByUid: getByUid, 13540 getByDom: getByDom, 13541 addToWorld: addToWorld, 13542 removeFromWorld: removeFromWorld, 13543 broadcast: broadcast$1, 13544 broadcastOn: broadcastOn, 13545 broadcastEvent: broadcastEvent 13546 }; 13547 }; 13548 13549 var renderBar = function (spec, backstage) { 13550 return { 13551 dom: { 13552 tag: 'div', 13553 classes: [ 13554 'tox-bar', 13555 'tox-form__controls-h-stack' 13556 ] 13557 }, 13558 components: map$2(spec.items, backstage.interpreter) 13559 }; 13560 }; 13561 13562 var schema$l = constant$1([ 13563 defaulted('prefix', 'form-field'), 13564 field('fieldBehaviours', [ 13565 Composing, 13566 Representing 13567 ]) 13568 ]); 13569 var parts$e = constant$1([ 13570 optional({ 13571 schema: [required$1('dom')], 13572 name: 'label' 13573 }), 13574 optional({ 13575 factory: { 13576 sketch: function (spec) { 13577 return { 13578 uid: spec.uid, 13579 dom: { 13580 tag: 'span', 13581 styles: { display: 'none' }, 13582 attributes: { 'aria-hidden': 'true' }, 13583 innerHtml: spec.text 13584 } 13585 }; 13586 } 13587 }, 13588 schema: [required$1('text')], 13589 name: 'aria-descriptor' 13590 }), 13591 required({ 13592 factory: { 13593 sketch: function (spec) { 13594 var excludeFactory = exclude(spec, ['factory']); 13595 return spec.factory.sketch(excludeFactory); 13596 } 13597 }, 13598 schema: [required$1('factory')], 13599 name: 'field' 13600 }) 13601 ]); 13602 13603 var factory$i = function (detail, components, _spec, _externals) { 13604 var behaviours = augment(detail.fieldBehaviours, [ 13605 Composing.config({ 13606 find: function (container) { 13607 return getPart(container, detail, 'field'); 13608 } 13609 }), 13610 Representing.config({ 13611 store: { 13612 mode: 'manual', 13613 getValue: function (field) { 13614 return Composing.getCurrent(field).bind(Representing.getValue); 13615 }, 13616 setValue: function (field, value) { 13617 Composing.getCurrent(field).each(function (current) { 13618 Representing.setValue(current, value); 13619 }); 13620 } 13621 } 13622 }) 13623 ]); 13624 var events = derive$2([runOnAttached(function (component, _simulatedEvent) { 13625 var ps = getParts(component, detail, [ 13626 'label', 13627 'field', 13628 'aria-descriptor' 13629 ]); 13630 ps.field().each(function (field) { 13631 var id = generate$6(detail.prefix); 13632 ps.label().each(function (label) { 13633 set$8(label.element, 'for', id); 13634 set$8(field.element, 'id', id); 13635 }); 13636 ps['aria-descriptor']().each(function (descriptor) { 13637 var descriptorId = generate$6(detail.prefix); 13638 set$8(descriptor.element, 'id', descriptorId); 13639 set$8(field.element, 'aria-describedby', descriptorId); 13640 }); 13641 }); 13642 })]); 13643 var apis = { 13644 getField: function (container) { 13645 return getPart(container, detail, 'field'); 13646 }, 13647 getLabel: function (container) { 13648 return getPart(container, detail, 'label'); 13649 } 13650 }; 13651 return { 13652 uid: detail.uid, 13653 dom: detail.dom, 13654 components: components, 13655 behaviours: behaviours, 13656 events: events, 13657 apis: apis 13658 }; 13659 }; 13660 var FormField = composite({ 13661 name: 'FormField', 13662 configFields: schema$l(), 13663 partFields: parts$e(), 13664 factory: factory$i, 13665 apis: { 13666 getField: function (apis, comp) { 13667 return apis.getField(comp); 13668 }, 13669 getLabel: function (apis, comp) { 13670 return apis.getLabel(comp); 13671 } 13672 } 13673 }); 13674 13675 var exhibit$2 = function (base, tabConfig) { 13676 return nu$7({ 13677 attributes: wrapAll([{ 13678 key: tabConfig.tabAttr, 13679 value: 'true' 13680 }]) 13681 }); 13682 }; 13683 13684 var ActiveTabstopping = /*#__PURE__*/Object.freeze({ 13685 __proto__: null, 13686 exhibit: exhibit$2 13687 }); 13688 13689 var TabstopSchema = [defaulted('tabAttr', 'data-alloy-tabstop')]; 13690 13691 var Tabstopping = create$7({ 13692 fields: TabstopSchema, 13693 name: 'tabstopping', 13694 active: ActiveTabstopping 13695 }); 13696 13697 var global$7 = tinymce.util.Tools.resolve('tinymce.html.Entities'); 13698 13699 var renderFormFieldWith = function (pLabel, pField, extraClasses, extraBehaviours) { 13700 var spec = renderFormFieldSpecWith(pLabel, pField, extraClasses, extraBehaviours); 13701 return FormField.sketch(spec); 13702 }; 13703 var renderFormField = function (pLabel, pField) { 13704 return renderFormFieldWith(pLabel, pField, [], []); 13705 }; 13706 var renderFormFieldSpecWith = function (pLabel, pField, extraClasses, extraBehaviours) { 13707 return { 13708 dom: renderFormFieldDomWith(extraClasses), 13709 components: pLabel.toArray().concat([pField]), 13710 fieldBehaviours: derive$1(extraBehaviours) 13711 }; 13712 }; 13713 var renderFormFieldDom = function () { 13714 return renderFormFieldDomWith([]); 13715 }; 13716 var renderFormFieldDomWith = function (extraClasses) { 13717 return { 13718 tag: 'div', 13719 classes: ['tox-form__group'].concat(extraClasses) 13720 }; 13721 }; 13722 var renderLabel$2 = function (label, providersBackstage) { 13723 return FormField.parts.label({ 13724 dom: { 13725 tag: 'label', 13726 classes: ['tox-label'], 13727 innerHtml: providersBackstage.translate(label) 13728 } 13729 }); 13730 }; 13731 13732 var formChangeEvent = generate$6('form-component-change'); 13733 var formCloseEvent = generate$6('form-close'); 13734 var formCancelEvent = generate$6('form-cancel'); 13735 var formActionEvent = generate$6('form-action'); 13736 var formSubmitEvent = generate$6('form-submit'); 13737 var formBlockEvent = generate$6('form-block'); 13738 var formUnblockEvent = generate$6('form-unblock'); 13739 var formTabChangeEvent = generate$6('form-tabchange'); 13740 var formResizeEvent = generate$6('form-resize'); 13741 13742 var renderCollection = function (spec, providersBackstage) { 13743 var _a; 13744 var pLabel = spec.label.map(function (label) { 13745 return renderLabel$2(label, providersBackstage); 13746 }); 13747 var runOnItem = function (f) { 13748 return function (comp, se) { 13749 closest$1(se.event.target, '[data-collection-item-value]').each(function (target) { 13750 f(comp, se, target, get$d(target, 'data-collection-item-value')); 13751 }); 13752 }; 13753 }; 13754 var setContents = function (comp, items) { 13755 var htmlLines = map$2(items, function (item) { 13756 var itemText = global$e.translate(item.text); 13757 var textContent = spec.columns === 1 ? '<div class="tox-collection__item-label">' + itemText + '</div>' : ''; 13758 var iconContent = '<div class="tox-collection__item-icon">' + item.icon + '</div>'; 13759 var mapItemName = { 13760 '_': ' ', 13761 ' - ': ' ', 13762 '-': ' ' 13763 }; 13764 var ariaLabel = itemText.replace(/\_| \- |\-/g, function (match) { 13765 return mapItemName[match]; 13766 }); 13767 var disabledClass = providersBackstage.isDisabled() ? ' tox-collection__item--state-disabled' : ''; 13768 return '<div class="tox-collection__item' + disabledClass + '" tabindex="-1" data-collection-item-value="' + global$7.encodeAllRaw(item.value) + '" title="' + ariaLabel + '" aria-label="' + ariaLabel + '">' + iconContent + textContent + '</div>'; 13769 }); 13770 var chunks = spec.columns !== 'auto' && spec.columns > 1 ? chunk$1(htmlLines, spec.columns) : [htmlLines]; 13771 var html = map$2(chunks, function (ch) { 13772 return '<div class="tox-collection__group">' + ch.join('') + '</div>'; 13773 }); 13774 set$5(comp.element, html.join('')); 13775 }; 13776 var onClick = runOnItem(function (comp, se, tgt, itemValue) { 13777 se.stop(); 13778 if (!providersBackstage.isDisabled()) { 13779 emitWith(comp, formActionEvent, { 13780 name: spec.name, 13781 value: itemValue 13782 }); 13783 } 13784 }); 13785 var collectionEvents = [ 13786 run$1(mouseover(), runOnItem(function (comp, se, tgt) { 13787 focus$3(tgt); 13788 })), 13789 run$1(click(), onClick), 13790 run$1(tap(), onClick), 13791 run$1(focusin(), runOnItem(function (comp, se, tgt) { 13792 descendant(comp.element, '.' + activeClass).each(function (currentActive) { 13793 remove$2(currentActive, activeClass); 13794 }); 13795 add$2(tgt, activeClass); 13796 })), 13797 run$1(focusout(), runOnItem(function (comp) { 13798 descendant(comp.element, '.' + activeClass).each(function (currentActive) { 13799 remove$2(currentActive, activeClass); 13800 }); 13801 })), 13802 runOnExecute$1(runOnItem(function (comp, se, tgt, itemValue) { 13803 emitWith(comp, formActionEvent, { 13804 name: spec.name, 13805 value: itemValue 13806 }); 13807 })) 13808 ]; 13809 var iterCollectionItems = function (comp, applyAttributes) { 13810 return map$2(descendants(comp.element, '.tox-collection__item'), applyAttributes); 13811 }; 13812 var pField = FormField.parts.field({ 13813 dom: { 13814 tag: 'div', 13815 classes: ['tox-collection'].concat(spec.columns !== 1 ? ['tox-collection--grid'] : ['tox-collection--list']) 13816 }, 13817 components: [], 13818 factory: { sketch: identity$1 }, 13819 behaviours: derive$1([ 13820 Disabling.config({ 13821 disabled: providersBackstage.isDisabled, 13822 onDisabled: function (comp) { 13823 iterCollectionItems(comp, function (childElm) { 13824 add$2(childElm, 'tox-collection__item--state-disabled'); 13825 set$8(childElm, 'aria-disabled', true); 13826 }); 13827 }, 13828 onEnabled: function (comp) { 13829 iterCollectionItems(comp, function (childElm) { 13830 remove$2(childElm, 'tox-collection__item--state-disabled'); 13831 remove$7(childElm, 'aria-disabled'); 13832 }); 13833 } 13834 }), 13835 receivingConfig(), 13836 Replacing.config({}), 13837 Representing.config({ 13838 store: { 13839 mode: 'memory', 13840 initialValue: [] 13841 }, 13842 onSetValue: function (comp, items) { 13843 setContents(comp, items); 13844 if (spec.columns === 'auto') { 13845 detectSize(comp, 5, 'tox-collection__item').each(function (_a) { 13846 var numRows = _a.numRows, numColumns = _a.numColumns; 13847 Keying.setGridSize(comp, numRows, numColumns); 13848 }); 13849 } 13850 emit(comp, formResizeEvent); 13851 } 13852 }), 13853 Tabstopping.config({}), 13854 Keying.config(deriveCollectionMovement(spec.columns, 'normal')), 13855 config('collection-events', collectionEvents) 13856 ]), 13857 eventOrder: (_a = {}, _a[execute$5()] = [ 13858 'disabling', 13859 'alloy.base.behaviour', 13860 'collection-events' 13861 ], _a) 13862 }); 13863 var extraClasses = ['tox-form__group--collection']; 13864 return renderFormFieldWith(pLabel, pField, extraClasses, []); 13865 }; 13866 13867 var schema$k = constant$1([ 13868 option('data'), 13869 defaulted('inputAttributes', {}), 13870 defaulted('inputStyles', {}), 13871 defaulted('tag', 'input'), 13872 defaulted('inputClasses', []), 13873 onHandler('onSetValue'), 13874 defaulted('styles', {}), 13875 defaulted('eventOrder', {}), 13876 field('inputBehaviours', [ 13877 Representing, 13878 Focusing 13879 ]), 13880 defaulted('selectOnFocus', true) 13881 ]); 13882 var focusBehaviours = function (detail) { 13883 return derive$1([Focusing.config({ 13884 onFocus: !detail.selectOnFocus ? noop : function (component) { 13885 var input = component.element; 13886 var value = get$5(input); 13887 input.dom.setSelectionRange(0, value.length); 13888 } 13889 })]); 13890 }; 13891 var behaviours = function (detail) { 13892 return __assign(__assign({}, focusBehaviours(detail)), augment(detail.inputBehaviours, [Representing.config({ 13893 store: __assign(__assign({ mode: 'manual' }, detail.data.map(function (data) { 13894 return { initialValue: data }; 13895 }).getOr({})), { 13896 getValue: function (input) { 13897 return get$5(input.element); 13898 }, 13899 setValue: function (input, data) { 13900 var current = get$5(input.element); 13901 if (current !== data) { 13902 set$4(input.element, data); 13903 } 13904 } 13905 }), 13906 onSetValue: detail.onSetValue 13907 })])); 13908 }; 13909 var dom = function (detail) { 13910 return { 13911 tag: detail.tag, 13912 attributes: __assign({ type: 'text' }, detail.inputAttributes), 13913 styles: detail.inputStyles, 13914 classes: detail.inputClasses 13915 }; 13916 }; 13917 13918 var factory$h = function (detail, _spec) { 13919 return { 13920 uid: detail.uid, 13921 dom: dom(detail), 13922 components: [], 13923 behaviours: behaviours(detail), 13924 eventOrder: detail.eventOrder 13925 }; 13926 }; 13927 var Input = single({ 13928 name: 'Input', 13929 configFields: schema$k(), 13930 factory: factory$h 13931 }); 13932 13933 var exports$1 = {}, module = { exports: exports$1 }; 13934 (function (define, exports, module, require) { 13935 (function (global, factory) { 13936 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()); 13937 }(this, function () { 13938 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; 13939 var promise = { exports: {} }; 13940 (function (module) { 13941 (function (root) { 13942 var setTimeoutFunc = setTimeout; 13943 function noop() { 13944 } 13945 function bind(fn, thisArg) { 13946 return function () { 13947 fn.apply(thisArg, arguments); 13948 }; 13949 } 13950 function Promise(fn) { 13951 if (typeof this !== 'object') 13952 throw new TypeError('Promises must be constructed via new'); 13953 if (typeof fn !== 'function') 13954 throw new TypeError('not a function'); 13955 this._state = 0; 13956 this._handled = false; 13957 this._value = undefined; 13958 this._deferreds = []; 13959 doResolve(fn, this); 13960 } 13961 function handle(self, deferred) { 13962 while (self._state === 3) { 13963 self = self._value; 13964 } 13965 if (self._state === 0) { 13966 self._deferreds.push(deferred); 13967 return; 13968 } 13969 self._handled = true; 13970 Promise._immediateFn(function () { 13971 var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; 13972 if (cb === null) { 13973 (self._state === 1 ? resolve : reject)(deferred.promise, self._value); 13974 return; 13975 } 13976 var ret; 13977 try { 13978 ret = cb(self._value); 13979 } catch (e) { 13980 reject(deferred.promise, e); 13981 return; 13982 } 13983 resolve(deferred.promise, ret); 13984 }); 13985 } 13986 function resolve(self, newValue) { 13987 try { 13988 if (newValue === self) 13989 throw new TypeError('A promise cannot be resolved with itself.'); 13990 if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { 13991 var then = newValue.then; 13992 if (newValue instanceof Promise) { 13993 self._state = 3; 13994 self._value = newValue; 13995 finale(self); 13996 return; 13997 } else if (typeof then === 'function') { 13998 doResolve(bind(then, newValue), self); 13999 return; 14000 } 14001 } 14002 self._state = 1; 14003 self._value = newValue; 14004 finale(self); 14005 } catch (e) { 14006 reject(self, e); 14007 } 14008 } 14009 function reject(self, newValue) { 14010 self._state = 2; 14011 self._value = newValue; 14012 finale(self); 14013 } 14014 function finale(self) { 14015 if (self._state === 2 && self._deferreds.length === 0) { 14016 Promise._immediateFn(function () { 14017 if (!self._handled) { 14018 Promise._unhandledRejectionFn(self._value); 14019 } 14020 }); 14021 } 14022 for (var i = 0, len = self._deferreds.length; i < len; i++) { 14023 handle(self, self._deferreds[i]); 14024 } 14025 self._deferreds = null; 14026 } 14027 function Handler(onFulfilled, onRejected, promise) { 14028 this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; 14029 this.onRejected = typeof onRejected === 'function' ? onRejected : null; 14030 this.promise = promise; 14031 } 14032 function doResolve(fn, self) { 14033 var done = false; 14034 try { 14035 fn(function (value) { 14036 if (done) 14037 return; 14038 done = true; 14039 resolve(self, value); 14040 }, function (reason) { 14041 if (done) 14042 return; 14043 done = true; 14044 reject(self, reason); 14045 }); 14046 } catch (ex) { 14047 if (done) 14048 return; 14049 done = true; 14050 reject(self, ex); 14051 } 14052 } 14053 Promise.prototype['catch'] = function (onRejected) { 14054 return this.then(null, onRejected); 14055 }; 14056 Promise.prototype.then = function (onFulfilled, onRejected) { 14057 var prom = new this.constructor(noop); 14058 handle(this, new Handler(onFulfilled, onRejected, prom)); 14059 return prom; 14060 }; 14061 Promise.all = function (arr) { 14062 var args = Array.prototype.slice.call(arr); 14063 return new Promise(function (resolve, reject) { 14064 if (args.length === 0) 14065 return resolve([]); 14066 var remaining = args.length; 14067 function res(i, val) { 14068 try { 14069 if (val && (typeof val === 'object' || typeof val === 'function')) { 14070 var then = val.then; 14071 if (typeof then === 'function') { 14072 then.call(val, function (val) { 14073 res(i, val); 14074 }, reject); 14075 return; 14076 } 14077 } 14078 args[i] = val; 14079 if (--remaining === 0) { 14080 resolve(args); 14081 } 14082 } catch (ex) { 14083 reject(ex); 14084 } 14085 } 14086 for (var i = 0; i < args.length; i++) { 14087 res(i, args[i]); 14088 } 14089 }); 14090 }; 14091 Promise.resolve = function (value) { 14092 if (value && typeof value === 'object' && value.constructor === Promise) { 14093 return value; 14094 } 14095 return new Promise(function (resolve) { 14096 resolve(value); 14097 }); 14098 }; 14099 Promise.reject = function (value) { 14100 return new Promise(function (resolve, reject) { 14101 reject(value); 14102 }); 14103 }; 14104 Promise.race = function (values) { 14105 return new Promise(function (resolve, reject) { 14106 for (var i = 0, len = values.length; i < len; i++) { 14107 values[i].then(resolve, reject); 14108 } 14109 }); 14110 }; 14111 Promise._immediateFn = typeof setImmediate === 'function' ? function (fn) { 14112 setImmediate(fn); 14113 } : function (fn) { 14114 setTimeoutFunc(fn, 0); 14115 }; 14116 Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) { 14117 if (typeof console !== 'undefined' && console) { 14118 console.warn('Possible Unhandled Promise Rejection:', err); 14119 } 14120 }; 14121 Promise._setImmediateFn = function _setImmediateFn(fn) { 14122 Promise._immediateFn = fn; 14123 }; 14124 Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) { 14125 Promise._unhandledRejectionFn = fn; 14126 }; 14127 if (module.exports) { 14128 module.exports = Promise; 14129 } else if (!root.Promise) { 14130 root.Promise = Promise; 14131 } 14132 }(commonjsGlobal)); 14133 }(promise)); 14134 var promisePolyfill = promise.exports; 14135 var Global = function () { 14136 if (typeof window !== 'undefined') { 14137 return window; 14138 } else { 14139 return Function('return this;')(); 14140 } 14141 }(); 14142 var promisePolyfill_1 = { boltExport: Global.Promise || promisePolyfill }; 14143 return promisePolyfill_1; 14144 })); 14145 }(undefined, exports$1, module)); 14146 var Promise$1 = module.exports.boltExport; 14147 14148 var nu$3 = function (baseFn) { 14149 var data = Optional.none(); 14150 var callbacks = []; 14151 var map = function (f) { 14152 return nu$3(function (nCallback) { 14153 get(function (data) { 14154 nCallback(f(data)); 14155 }); 14156 }); 14157 }; 14158 var get = function (nCallback) { 14159 if (isReady()) { 14160 call(nCallback); 14161 } else { 14162 callbacks.push(nCallback); 14163 } 14164 }; 14165 var set = function (x) { 14166 if (!isReady()) { 14167 data = Optional.some(x); 14168 run(callbacks); 14169 callbacks = []; 14170 } 14171 }; 14172 var isReady = function () { 14173 return data.isSome(); 14174 }; 14175 var run = function (cbs) { 14176 each$1(cbs, call); 14177 }; 14178 var call = function (cb) { 14179 data.each(function (x) { 14180 setTimeout(function () { 14181 cb(x); 14182 }, 0); 14183 }); 14184 }; 14185 baseFn(set); 14186 return { 14187 get: get, 14188 map: map, 14189 isReady: isReady 14190 }; 14191 }; 14192 var pure$1 = function (a) { 14193 return nu$3(function (callback) { 14194 callback(a); 14195 }); 14196 }; 14197 var LazyValue = { 14198 nu: nu$3, 14199 pure: pure$1 14200 }; 14201 14202 var errorReporter = function (err) { 14203 setTimeout(function () { 14204 throw err; 14205 }, 0); 14206 }; 14207 var make$5 = function (run) { 14208 var get = function (callback) { 14209 run().then(callback, errorReporter); 14210 }; 14211 var map = function (fab) { 14212 return make$5(function () { 14213 return run().then(fab); 14214 }); 14215 }; 14216 var bind = function (aFutureB) { 14217 return make$5(function () { 14218 return run().then(function (v) { 14219 return aFutureB(v).toPromise(); 14220 }); 14221 }); 14222 }; 14223 var anonBind = function (futureB) { 14224 return make$5(function () { 14225 return run().then(function () { 14226 return futureB.toPromise(); 14227 }); 14228 }); 14229 }; 14230 var toLazy = function () { 14231 return LazyValue.nu(get); 14232 }; 14233 var toCached = function () { 14234 var cache = null; 14235 return make$5(function () { 14236 if (cache === null) { 14237 cache = run(); 14238 } 14239 return cache; 14240 }); 14241 }; 14242 var toPromise = run; 14243 return { 14244 map: map, 14245 bind: bind, 14246 anonBind: anonBind, 14247 toLazy: toLazy, 14248 toCached: toCached, 14249 toPromise: toPromise, 14250 get: get 14251 }; 14252 }; 14253 var nu$2 = function (baseFn) { 14254 return make$5(function () { 14255 return new Promise$1(baseFn); 14256 }); 14257 }; 14258 var pure = function (a) { 14259 return make$5(function () { 14260 return Promise$1.resolve(a); 14261 }); 14262 }; 14263 var Future = { 14264 nu: nu$2, 14265 pure: pure 14266 }; 14267 14268 var ariaElements = [ 14269 'input', 14270 'textarea' 14271 ]; 14272 var isAriaElement = function (elem) { 14273 var name = name$2(elem); 14274 return contains$2(ariaElements, name); 14275 }; 14276 var markValid = function (component, invalidConfig) { 14277 var elem = invalidConfig.getRoot(component).getOr(component.element); 14278 remove$2(elem, invalidConfig.invalidClass); 14279 invalidConfig.notify.each(function (notifyInfo) { 14280 if (isAriaElement(component.element)) { 14281 set$8(component.element, 'aria-invalid', false); 14282 } 14283 notifyInfo.getContainer(component).each(function (container) { 14284 set$5(container, notifyInfo.validHtml); 14285 }); 14286 notifyInfo.onValid(component); 14287 }); 14288 }; 14289 var markInvalid = function (component, invalidConfig, invalidState, text) { 14290 var elem = invalidConfig.getRoot(component).getOr(component.element); 14291 add$2(elem, invalidConfig.invalidClass); 14292 invalidConfig.notify.each(function (notifyInfo) { 14293 if (isAriaElement(component.element)) { 14294 set$8(component.element, 'aria-invalid', true); 14295 } 14296 notifyInfo.getContainer(component).each(function (container) { 14297 set$5(container, text); 14298 }); 14299 notifyInfo.onInvalid(component, text); 14300 }); 14301 }; 14302 var query = function (component, invalidConfig, _invalidState) { 14303 return invalidConfig.validator.fold(function () { 14304 return Future.pure(Result.value(true)); 14305 }, function (validatorInfo) { 14306 return validatorInfo.validate(component); 14307 }); 14308 }; 14309 var run = function (component, invalidConfig, invalidState) { 14310 invalidConfig.notify.each(function (notifyInfo) { 14311 notifyInfo.onValidate(component); 14312 }); 14313 return query(component, invalidConfig).map(function (valid) { 14314 if (component.getSystem().isConnected()) { 14315 return valid.fold(function (err) { 14316 markInvalid(component, invalidConfig, invalidState, err); 14317 return Result.error(err); 14318 }, function (v) { 14319 markValid(component, invalidConfig); 14320 return Result.value(v); 14321 }); 14322 } else { 14323 return Result.error('No longer in system'); 14324 } 14325 }); 14326 }; 14327 var isInvalid = function (component, invalidConfig) { 14328 var elem = invalidConfig.getRoot(component).getOr(component.element); 14329 return has(elem, invalidConfig.invalidClass); 14330 }; 14331 14332 var InvalidateApis = /*#__PURE__*/Object.freeze({ 14333 __proto__: null, 14334 markValid: markValid, 14335 markInvalid: markInvalid, 14336 query: query, 14337 run: run, 14338 isInvalid: isInvalid 14339 }); 14340 14341 var events$8 = function (invalidConfig, invalidState) { 14342 return invalidConfig.validator.map(function (validatorInfo) { 14343 return derive$2([run$1(validatorInfo.onEvent, function (component) { 14344 run(component, invalidConfig, invalidState).get(identity$1); 14345 })].concat(validatorInfo.validateOnLoad ? [runOnAttached(function (component) { 14346 run(component, invalidConfig, invalidState).get(noop); 14347 })] : [])); 14348 }).getOr({}); 14349 }; 14350 14351 var ActiveInvalidate = /*#__PURE__*/Object.freeze({ 14352 __proto__: null, 14353 events: events$8 14354 }); 14355 14356 var InvalidateSchema = [ 14357 required$1('invalidClass'), 14358 defaulted('getRoot', Optional.none), 14359 optionObjOf('notify', [ 14360 defaulted('aria', 'alert'), 14361 defaulted('getContainer', Optional.none), 14362 defaulted('validHtml', ''), 14363 onHandler('onValid'), 14364 onHandler('onInvalid'), 14365 onHandler('onValidate') 14366 ]), 14367 optionObjOf('validator', [ 14368 required$1('validate'), 14369 defaulted('onEvent', 'input'), 14370 defaulted('validateOnLoad', true) 14371 ]) 14372 ]; 14373 14374 var Invalidating = create$7({ 14375 fields: InvalidateSchema, 14376 name: 'invalidating', 14377 active: ActiveInvalidate, 14378 apis: InvalidateApis, 14379 extra: { 14380 validation: function (validator) { 14381 return function (component) { 14382 var v = Representing.getValue(component); 14383 return Future.pure(validator(v)); 14384 }; 14385 } 14386 } 14387 }); 14388 14389 var getCoupled = function (component, coupleConfig, coupleState, name) { 14390 return coupleState.getOrCreate(component, coupleConfig, name); 14391 }; 14392 14393 var CouplingApis = /*#__PURE__*/Object.freeze({ 14394 __proto__: null, 14395 getCoupled: getCoupled 14396 }); 14397 14398 var CouplingSchema = [requiredOf('others', setOf(Result.value, anyValue()))]; 14399 14400 var init$a = function () { 14401 var coupled = {}; 14402 var getOrCreate = function (component, coupleConfig, name) { 14403 var available = keys(coupleConfig.others); 14404 if (!available) { 14405 throw new Error('Cannot find coupled component: ' + name + '. Known coupled components: ' + JSON.stringify(available, null, 2)); 14406 } else { 14407 return get$e(coupled, name).getOrThunk(function () { 14408 var builder = get$e(coupleConfig.others, name).getOrDie('No information found for coupled component: ' + name); 14409 var spec = builder(component); 14410 var built = component.getSystem().build(spec); 14411 coupled[name] = built; 14412 return built; 14413 }); 14414 } 14415 }; 14416 var readState = constant$1({}); 14417 return nu$8({ 14418 readState: readState, 14419 getOrCreate: getOrCreate 14420 }); 14421 }; 14422 14423 var CouplingState = /*#__PURE__*/Object.freeze({ 14424 __proto__: null, 14425 init: init$a 14426 }); 14427 14428 var Coupling = create$7({ 14429 fields: CouplingSchema, 14430 name: 'coupling', 14431 apis: CouplingApis, 14432 state: CouplingState 14433 }); 14434 14435 var suffix = constant$1('sink'); 14436 var partType$1 = constant$1(optional({ 14437 name: suffix(), 14438 overrides: constant$1({ 14439 dom: { tag: 'div' }, 14440 behaviours: derive$1([Positioning.config({ useFixed: always })]), 14441 events: derive$2([ 14442 cutter(keydown()), 14443 cutter(mousedown()), 14444 cutter(click()) 14445 ]) 14446 }) 14447 })); 14448 14449 var HighlightOnOpen; 14450 (function (HighlightOnOpen) { 14451 HighlightOnOpen[HighlightOnOpen['HighlightFirst'] = 0] = 'HighlightFirst'; 14452 HighlightOnOpen[HighlightOnOpen['HighlightNone'] = 1] = 'HighlightNone'; 14453 }(HighlightOnOpen || (HighlightOnOpen = {}))); 14454 var getAnchor = function (detail, component) { 14455 var hotspot = detail.getHotspot(component).getOr(component); 14456 var type = 'hotspot'; 14457 var overrides = detail.getAnchorOverrides(); 14458 return detail.layouts.fold(function () { 14459 return { 14460 type: type, 14461 hotspot: hotspot, 14462 overrides: overrides 14463 }; 14464 }, function (layouts) { 14465 return { 14466 type: type, 14467 hotspot: hotspot, 14468 overrides: overrides, 14469 layouts: layouts 14470 }; 14471 }); 14472 }; 14473 var fetch = function (detail, mapFetch, component) { 14474 var fetcher = detail.fetch; 14475 return fetcher(component).map(mapFetch); 14476 }; 14477 var openF = function (detail, mapFetch, anchor, component, sandbox, externals, highlightOnOpen) { 14478 var futureData = fetch(detail, mapFetch, component); 14479 var getLazySink = getSink(component, detail); 14480 return futureData.map(function (tdata) { 14481 return tdata.bind(function (data) { 14482 return Optional.from(tieredMenu.sketch(__assign(__assign({}, externals.menu()), { 14483 uid: generate$5(''), 14484 data: data, 14485 highlightImmediately: highlightOnOpen === HighlightOnOpen.HighlightFirst, 14486 onOpenMenu: function (tmenu, menu) { 14487 var sink = getLazySink().getOrDie(); 14488 Positioning.position(sink, menu, { anchor: anchor }); 14489 Sandboxing.decloak(sandbox); 14490 }, 14491 onOpenSubmenu: function (tmenu, item, submenu) { 14492 var sink = getLazySink().getOrDie(); 14493 Positioning.position(sink, submenu, { 14494 anchor: { 14495 type: 'submenu', 14496 item: item 14497 } 14498 }); 14499 Sandboxing.decloak(sandbox); 14500 }, 14501 onRepositionMenu: function (tmenu, primaryMenu, submenuTriggers) { 14502 var sink = getLazySink().getOrDie(); 14503 Positioning.position(sink, primaryMenu, { anchor: anchor }); 14504 each$1(submenuTriggers, function (st) { 14505 Positioning.position(sink, st.triggeredMenu, { 14506 anchor: { 14507 type: 'submenu', 14508 item: st.triggeringItem 14509 } 14510 }); 14511 }); 14512 }, 14513 onEscape: function () { 14514 Focusing.focus(component); 14515 Sandboxing.close(sandbox); 14516 return Optional.some(true); 14517 } 14518 }))); 14519 }); 14520 }); 14521 }; 14522 var open = function (detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen) { 14523 var anchor = getAnchor(detail, hotspot); 14524 var processed = openF(detail, mapFetch, anchor, hotspot, sandbox, externals, highlightOnOpen); 14525 return processed.map(function (tdata) { 14526 tdata.fold(function () { 14527 if (Sandboxing.isOpen(sandbox)) { 14528 Sandboxing.close(sandbox); 14529 } 14530 }, function (data) { 14531 Sandboxing.cloak(sandbox); 14532 Sandboxing.open(sandbox, data); 14533 onOpenSync(sandbox); 14534 }); 14535 return sandbox; 14536 }); 14537 }; 14538 var close = function (detail, mapFetch, component, sandbox, _externals, _onOpenSync, _highlightOnOpen) { 14539 Sandboxing.close(sandbox); 14540 return Future.pure(sandbox); 14541 }; 14542 var togglePopup = function (detail, mapFetch, hotspot, externals, onOpenSync, highlightOnOpen) { 14543 var sandbox = Coupling.getCoupled(hotspot, 'sandbox'); 14544 var showing = Sandboxing.isOpen(sandbox); 14545 var action = showing ? close : open; 14546 return action(detail, mapFetch, hotspot, sandbox, externals, onOpenSync, highlightOnOpen); 14547 }; 14548 var matchWidth = function (hotspot, container, useMinWidth) { 14549 var menu = Composing.getCurrent(container).getOr(container); 14550 var buttonWidth = get$a(hotspot.element); 14551 if (useMinWidth) { 14552 set$7(menu.element, 'min-width', buttonWidth + 'px'); 14553 } else { 14554 set$6(menu.element, buttonWidth); 14555 } 14556 }; 14557 var getSink = function (anyInSystem, sinkDetail) { 14558 return anyInSystem.getSystem().getByUid(sinkDetail.uid + '-' + suffix()).map(function (internalSink) { 14559 return function () { 14560 return Result.value(internalSink); 14561 }; 14562 }).getOrThunk(function () { 14563 return sinkDetail.lazySink.fold(function () { 14564 return function () { 14565 return Result.error(new Error('No internal sink is specified, nor could an external sink be found')); 14566 }; 14567 }, function (lazySinkFn) { 14568 return function () { 14569 return lazySinkFn(anyInSystem); 14570 }; 14571 }); 14572 }); 14573 }; 14574 var doRepositionMenus = function (sandbox) { 14575 Sandboxing.getState(sandbox).each(function (tmenu) { 14576 tieredMenu.repositionMenus(tmenu); 14577 }); 14578 }; 14579 var makeSandbox$1 = function (detail, hotspot, extras) { 14580 var ariaOwner = manager(); 14581 var onOpen = function (component, menu) { 14582 var anchor = getAnchor(detail, hotspot); 14583 ariaOwner.link(hotspot.element); 14584 if (detail.matchWidth) { 14585 matchWidth(anchor.hotspot, menu, detail.useMinWidth); 14586 } 14587 detail.onOpen(anchor, component, menu); 14588 if (extras !== undefined && extras.onOpen !== undefined) { 14589 extras.onOpen(component, menu); 14590 } 14591 }; 14592 var onClose = function (component, menu) { 14593 ariaOwner.unlink(hotspot.element); 14594 if (extras !== undefined && extras.onClose !== undefined) { 14595 extras.onClose(component, menu); 14596 } 14597 }; 14598 var lazySink = getSink(hotspot, detail); 14599 return { 14600 dom: { 14601 tag: 'div', 14602 classes: detail.sandboxClasses, 14603 attributes: { 14604 id: ariaOwner.id, 14605 role: 'listbox' 14606 } 14607 }, 14608 behaviours: SketchBehaviours.augment(detail.sandboxBehaviours, [ 14609 Representing.config({ 14610 store: { 14611 mode: 'memory', 14612 initialValue: hotspot 14613 } 14614 }), 14615 Sandboxing.config({ 14616 onOpen: onOpen, 14617 onClose: onClose, 14618 isPartOf: function (container, data, queryElem) { 14619 return isPartOf$1(data, queryElem) || isPartOf$1(hotspot, queryElem); 14620 }, 14621 getAttachPoint: function () { 14622 return lazySink().getOrDie(); 14623 } 14624 }), 14625 Composing.config({ 14626 find: function (sandbox) { 14627 return Sandboxing.getState(sandbox).bind(function (menu) { 14628 return Composing.getCurrent(menu); 14629 }); 14630 } 14631 }), 14632 Receiving.config({ channels: __assign(__assign({}, receivingChannel$1({ isExtraPart: never })), receivingChannel({ doReposition: doRepositionMenus })) }) 14633 ]) 14634 }; 14635 }; 14636 var repositionMenus = function (comp) { 14637 var sandbox = Coupling.getCoupled(comp, 'sandbox'); 14638 doRepositionMenus(sandbox); 14639 }; 14640 14641 var sandboxFields = function () { 14642 return [ 14643 defaulted('sandboxClasses', []), 14644 SketchBehaviours.field('sandboxBehaviours', [ 14645 Composing, 14646 Receiving, 14647 Sandboxing, 14648 Representing 14649 ]) 14650 ]; 14651 }; 14652 14653 var schema$j = constant$1([ 14654 required$1('dom'), 14655 required$1('fetch'), 14656 onHandler('onOpen'), 14657 onKeyboardHandler('onExecute'), 14658 defaulted('getHotspot', Optional.some), 14659 defaulted('getAnchorOverrides', constant$1({})), 14660 schema$y(), 14661 field('dropdownBehaviours', [ 14662 Toggling, 14663 Coupling, 14664 Keying, 14665 Focusing 14666 ]), 14667 required$1('toggleClass'), 14668 defaulted('eventOrder', {}), 14669 option('lazySink'), 14670 defaulted('matchWidth', false), 14671 defaulted('useMinWidth', false), 14672 option('role') 14673 ].concat(sandboxFields())); 14674 var parts$d = constant$1([ 14675 external$1({ 14676 schema: [tieredMenuMarkers()], 14677 name: 'menu', 14678 defaults: function (detail) { 14679 return { onExecute: detail.onExecute }; 14680 } 14681 }), 14682 partType$1() 14683 ]); 14684 14685 var factory$g = function (detail, components, _spec, externals) { 14686 var _a; 14687 var lookupAttr = function (attr) { 14688 return get$e(detail.dom, 'attributes').bind(function (attrs) { 14689 return get$e(attrs, attr); 14690 }); 14691 }; 14692 var switchToMenu = function (sandbox) { 14693 Sandboxing.getState(sandbox).each(function (tmenu) { 14694 tieredMenu.highlightPrimary(tmenu); 14695 }); 14696 }; 14697 var action = function (component) { 14698 var onOpenSync = switchToMenu; 14699 togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop); 14700 }; 14701 var apis = { 14702 expand: function (comp) { 14703 if (!Toggling.isOn(comp)) { 14704 togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightNone).get(noop); 14705 } 14706 }, 14707 open: function (comp) { 14708 if (!Toggling.isOn(comp)) { 14709 togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop); 14710 } 14711 }, 14712 isOpen: Toggling.isOn, 14713 close: function (comp) { 14714 if (Toggling.isOn(comp)) { 14715 togglePopup(detail, identity$1, comp, externals, noop, HighlightOnOpen.HighlightFirst).get(noop); 14716 } 14717 }, 14718 repositionMenus: function (comp) { 14719 if (Toggling.isOn(comp)) { 14720 repositionMenus(comp); 14721 } 14722 } 14723 }; 14724 var triggerExecute = function (comp, _se) { 14725 emitExecute(comp); 14726 return Optional.some(true); 14727 }; 14728 return { 14729 uid: detail.uid, 14730 dom: detail.dom, 14731 components: components, 14732 behaviours: augment(detail.dropdownBehaviours, [ 14733 Toggling.config({ 14734 toggleClass: detail.toggleClass, 14735 aria: { mode: 'expanded' } 14736 }), 14737 Coupling.config({ 14738 others: { 14739 sandbox: function (hotspot) { 14740 return makeSandbox$1(detail, hotspot, { 14741 onOpen: function () { 14742 return Toggling.on(hotspot); 14743 }, 14744 onClose: function () { 14745 return Toggling.off(hotspot); 14746 } 14747 }); 14748 } 14749 } 14750 }), 14751 Keying.config({ 14752 mode: 'special', 14753 onSpace: triggerExecute, 14754 onEnter: triggerExecute, 14755 onDown: function (comp, _se) { 14756 if (Dropdown.isOpen(comp)) { 14757 var sandbox = Coupling.getCoupled(comp, 'sandbox'); 14758 switchToMenu(sandbox); 14759 } else { 14760 Dropdown.open(comp); 14761 } 14762 return Optional.some(true); 14763 }, 14764 onEscape: function (comp, _se) { 14765 if (Dropdown.isOpen(comp)) { 14766 Dropdown.close(comp); 14767 return Optional.some(true); 14768 } else { 14769 return Optional.none(); 14770 } 14771 } 14772 }), 14773 Focusing.config({}) 14774 ]), 14775 events: events$a(Optional.some(action)), 14776 eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [ 14777 'disabling', 14778 'toggling', 14779 'alloy.base.behaviour' 14780 ], _a)), 14781 apis: apis, 14782 domModification: { 14783 attributes: __assign(__assign({ 'aria-haspopup': 'true' }, detail.role.fold(function () { 14784 return {}; 14785 }, function (role) { 14786 return { role: role }; 14787 })), detail.dom.tag === 'button' ? { type: lookupAttr('type').getOr('button') } : {}) 14788 } 14789 }; 14790 }; 14791 var Dropdown = composite({ 14792 name: 'Dropdown', 14793 configFields: schema$j(), 14794 partFields: parts$d(), 14795 factory: factory$g, 14796 apis: { 14797 open: function (apis, comp) { 14798 return apis.open(comp); 14799 }, 14800 expand: function (apis, comp) { 14801 return apis.expand(comp); 14802 }, 14803 close: function (apis, comp) { 14804 return apis.close(comp); 14805 }, 14806 isOpen: function (apis, comp) { 14807 return apis.isOpen(comp); 14808 }, 14809 repositionMenus: function (apis, comp) { 14810 return apis.repositionMenus(comp); 14811 } 14812 } 14813 }); 14814 14815 var exhibit$1 = function () { 14816 return nu$7({ 14817 styles: { 14818 '-webkit-user-select': 'none', 14819 'user-select': 'none', 14820 '-ms-user-select': 'none', 14821 '-moz-user-select': '-moz-none' 14822 }, 14823 attributes: { unselectable: 'on' } 14824 }); 14825 }; 14826 var events$7 = function () { 14827 return derive$2([abort(selectstart(), always)]); 14828 }; 14829 14830 var ActiveUnselecting = /*#__PURE__*/Object.freeze({ 14831 __proto__: null, 14832 events: events$7, 14833 exhibit: exhibit$1 14834 }); 14835 14836 var Unselecting = create$7({ 14837 fields: [], 14838 name: 'unselecting', 14839 active: ActiveUnselecting 14840 }); 14841 14842 var renderPanelButton = function (spec, sharedBackstage) { 14843 return Dropdown.sketch({ 14844 dom: spec.dom, 14845 components: spec.components, 14846 toggleClass: 'mce-active', 14847 dropdownBehaviours: derive$1([ 14848 DisablingConfigs.button(sharedBackstage.providers.isDisabled), 14849 receivingConfig(), 14850 Unselecting.config({}), 14851 Tabstopping.config({}) 14852 ]), 14853 layouts: spec.layouts, 14854 sandboxClasses: ['tox-dialog__popups'], 14855 lazySink: sharedBackstage.getSink, 14856 fetch: function (comp) { 14857 return Future.nu(function (callback) { 14858 return spec.fetch(callback); 14859 }).map(function (items) { 14860 return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) { 14861 spec.onItemAction(comp, value); 14862 }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, never, sharedBackstage.providers), { movement: deriveMenuMovement(spec.columns, spec.presets) }))); 14863 }); 14864 }, 14865 parts: { menu: part(false, 1, spec.presets) } 14866 }); 14867 }; 14868 14869 var colorInputChangeEvent = generate$6('color-input-change'); 14870 var colorSwatchChangeEvent = generate$6('color-swatch-change'); 14871 var colorPickerCancelEvent = generate$6('color-picker-cancel'); 14872 var renderColorInput = function (spec, sharedBackstage, colorInputBackstage) { 14873 var pField = FormField.parts.field({ 14874 factory: Input, 14875 inputClasses: ['tox-textfield'], 14876 onSetValue: function (c) { 14877 return Invalidating.run(c).get(noop); 14878 }, 14879 inputBehaviours: derive$1([ 14880 Disabling.config({ disabled: sharedBackstage.providers.isDisabled }), 14881 receivingConfig(), 14882 Tabstopping.config({}), 14883 Invalidating.config({ 14884 invalidClass: 'tox-textbox-field-invalid', 14885 getRoot: function (comp) { 14886 return parent(comp.element); 14887 }, 14888 notify: { 14889 onValid: function (comp) { 14890 var val = Representing.getValue(comp); 14891 emitWith(comp, colorInputChangeEvent, { color: val }); 14892 } 14893 }, 14894 validator: { 14895 validateOnLoad: false, 14896 validate: function (input) { 14897 var inputValue = Representing.getValue(input); 14898 if (inputValue.length === 0) { 14899 return Future.pure(Result.value(true)); 14900 } else { 14901 var span = SugarElement.fromTag('span'); 14902 set$7(span, 'background-color', inputValue); 14903 var res = getRaw(span, 'background-color').fold(function () { 14904 return Result.error('blah'); 14905 }, function (_) { 14906 return Result.value(inputValue); 14907 }); 14908 return Future.pure(res); 14909 } 14910 } 14911 } 14912 }) 14913 ]), 14914 selectOnFocus: false 14915 }); 14916 var pLabel = spec.label.map(function (label) { 14917 return renderLabel$2(label, sharedBackstage.providers); 14918 }); 14919 var emitSwatchChange = function (colorBit, value) { 14920 emitWith(colorBit, colorSwatchChangeEvent, { value: value }); 14921 }; 14922 var onItemAction = function (comp, value) { 14923 memColorButton.getOpt(comp).each(function (colorBit) { 14924 if (value === 'custom') { 14925 colorInputBackstage.colorPicker(function (valueOpt) { 14926 valueOpt.fold(function () { 14927 return emit(colorBit, colorPickerCancelEvent); 14928 }, function (value) { 14929 emitSwatchChange(colorBit, value); 14930 addColor(value); 14931 }); 14932 }, '#ffffff'); 14933 } else if (value === 'remove') { 14934 emitSwatchChange(colorBit, ''); 14935 } else { 14936 emitSwatchChange(colorBit, value); 14937 } 14938 }); 14939 }; 14940 var memColorButton = record(renderPanelButton({ 14941 dom: { 14942 tag: 'span', 14943 attributes: { 'aria-label': sharedBackstage.providers.translate('Color swatch') } 14944 }, 14945 layouts: { 14946 onRtl: function () { 14947 return [ 14948 southwest$2, 14949 southeast$2, 14950 south$2 14951 ]; 14952 }, 14953 onLtr: function () { 14954 return [ 14955 southeast$2, 14956 southwest$2, 14957 south$2 14958 ]; 14959 } 14960 }, 14961 components: [], 14962 fetch: getFetch$1(colorInputBackstage.getColors(), colorInputBackstage.hasCustomColors()), 14963 columns: colorInputBackstage.getColorCols(), 14964 presets: 'color', 14965 onItemAction: onItemAction 14966 }, sharedBackstage)); 14967 return FormField.sketch({ 14968 dom: { 14969 tag: 'div', 14970 classes: ['tox-form__group'] 14971 }, 14972 components: pLabel.toArray().concat([{ 14973 dom: { 14974 tag: 'div', 14975 classes: ['tox-color-input'] 14976 }, 14977 components: [ 14978 pField, 14979 memColorButton.asSpec() 14980 ] 14981 }]), 14982 fieldBehaviours: derive$1([config('form-field-events', [ 14983 run$1(colorInputChangeEvent, function (comp, se) { 14984 memColorButton.getOpt(comp).each(function (colorButton) { 14985 set$7(colorButton.element, 'background-color', se.event.color); 14986 }); 14987 emitWith(comp, formChangeEvent, { name: spec.name }); 14988 }), 14989 run$1(colorSwatchChangeEvent, function (comp, se) { 14990 FormField.getField(comp).each(function (field) { 14991 Representing.setValue(field, se.event.value); 14992 Composing.getCurrent(comp).each(Focusing.focus); 14993 }); 14994 }), 14995 run$1(colorPickerCancelEvent, function (comp, _se) { 14996 FormField.getField(comp).each(function (_field) { 14997 Composing.getCurrent(comp).each(Focusing.focus); 14998 }); 14999 }) 15000 ])]) 15001 }); 15002 }; 15003 15004 var labelPart = optional({ 15005 schema: [required$1('dom')], 15006 name: 'label' 15007 }); 15008 var edgePart = function (name) { 15009 return optional({ 15010 name: '' + name + '-edge', 15011 overrides: function (detail) { 15012 var action = detail.model.manager.edgeActions[name]; 15013 return action.fold(function () { 15014 return {}; 15015 }, function (a) { 15016 return { 15017 events: derive$2([ 15018 runActionExtra(touchstart(), function (comp, se, d) { 15019 return a(comp, d); 15020 }, [detail]), 15021 runActionExtra(mousedown(), function (comp, se, d) { 15022 return a(comp, d); 15023 }, [detail]), 15024 runActionExtra(mousemove(), function (comp, se, det) { 15025 if (det.mouseIsDown.get()) { 15026 a(comp, det); 15027 } 15028 }, [detail]) 15029 ]) 15030 }; 15031 }); 15032 } 15033 }); 15034 }; 15035 var tlEdgePart = edgePart('top-left'); 15036 var tedgePart = edgePart('top'); 15037 var trEdgePart = edgePart('top-right'); 15038 var redgePart = edgePart('right'); 15039 var brEdgePart = edgePart('bottom-right'); 15040 var bedgePart = edgePart('bottom'); 15041 var blEdgePart = edgePart('bottom-left'); 15042 var ledgePart = edgePart('left'); 15043 var thumbPart = required({ 15044 name: 'thumb', 15045 defaults: constant$1({ dom: { styles: { position: 'absolute' } } }), 15046 overrides: function (detail) { 15047 return { 15048 events: derive$2([ 15049 redirectToPart(touchstart(), detail, 'spectrum'), 15050 redirectToPart(touchmove(), detail, 'spectrum'), 15051 redirectToPart(touchend(), detail, 'spectrum'), 15052 redirectToPart(mousedown(), detail, 'spectrum'), 15053 redirectToPart(mousemove(), detail, 'spectrum'), 15054 redirectToPart(mouseup(), detail, 'spectrum') 15055 ]) 15056 }; 15057 } 15058 }); 15059 var spectrumPart = required({ 15060 schema: [customField('mouseIsDown', function () { 15061 return Cell(false); 15062 })], 15063 name: 'spectrum', 15064 overrides: function (detail) { 15065 var modelDetail = detail.model; 15066 var model = modelDetail.manager; 15067 var setValueFrom = function (component, simulatedEvent) { 15068 return model.getValueFromEvent(simulatedEvent).map(function (value) { 15069 return model.setValueFrom(component, detail, value); 15070 }); 15071 }; 15072 return { 15073 behaviours: derive$1([ 15074 Keying.config({ 15075 mode: 'special', 15076 onLeft: function (spectrum) { 15077 return model.onLeft(spectrum, detail); 15078 }, 15079 onRight: function (spectrum) { 15080 return model.onRight(spectrum, detail); 15081 }, 15082 onUp: function (spectrum) { 15083 return model.onUp(spectrum, detail); 15084 }, 15085 onDown: function (spectrum) { 15086 return model.onDown(spectrum, detail); 15087 } 15088 }), 15089 Focusing.config({}) 15090 ]), 15091 events: derive$2([ 15092 run$1(touchstart(), setValueFrom), 15093 run$1(touchmove(), setValueFrom), 15094 run$1(mousedown(), setValueFrom), 15095 run$1(mousemove(), function (spectrum, se) { 15096 if (detail.mouseIsDown.get()) { 15097 setValueFrom(spectrum, se); 15098 } 15099 }) 15100 ]) 15101 }; 15102 } 15103 }); 15104 var SliderParts = [ 15105 labelPart, 15106 ledgePart, 15107 redgePart, 15108 tedgePart, 15109 bedgePart, 15110 tlEdgePart, 15111 trEdgePart, 15112 blEdgePart, 15113 brEdgePart, 15114 thumbPart, 15115 spectrumPart 15116 ]; 15117 15118 var _sliderChangeEvent = 'slider.change.value'; 15119 var sliderChangeEvent = constant$1(_sliderChangeEvent); 15120 var isTouchEvent$2 = function (evt) { 15121 return evt.type.indexOf('touch') !== -1; 15122 }; 15123 var getEventSource = function (simulatedEvent) { 15124 var evt = simulatedEvent.event.raw; 15125 if (isTouchEvent$2(evt)) { 15126 var touchEvent = evt; 15127 return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Optional.some(touchEvent.touches[0]).map(function (t) { 15128 return SugarPosition(t.clientX, t.clientY); 15129 }) : Optional.none(); 15130 } else { 15131 var mouseEvent = evt; 15132 return mouseEvent.clientX !== undefined ? Optional.some(mouseEvent).map(function (me) { 15133 return SugarPosition(me.clientX, me.clientY); 15134 }) : Optional.none(); 15135 } 15136 }; 15137 15138 var t = 'top', r = 'right', b = 'bottom', l = 'left'; 15139 var minX = function (detail) { 15140 return detail.model.minX; 15141 }; 15142 var minY = function (detail) { 15143 return detail.model.minY; 15144 }; 15145 var min1X = function (detail) { 15146 return detail.model.minX - 1; 15147 }; 15148 var min1Y = function (detail) { 15149 return detail.model.minY - 1; 15150 }; 15151 var maxX = function (detail) { 15152 return detail.model.maxX; 15153 }; 15154 var maxY = function (detail) { 15155 return detail.model.maxY; 15156 }; 15157 var max1X = function (detail) { 15158 return detail.model.maxX + 1; 15159 }; 15160 var max1Y = function (detail) { 15161 return detail.model.maxY + 1; 15162 }; 15163 var range = function (detail, max, min) { 15164 return max(detail) - min(detail); 15165 }; 15166 var xRange = function (detail) { 15167 return range(detail, maxX, minX); 15168 }; 15169 var yRange = function (detail) { 15170 return range(detail, maxY, minY); 15171 }; 15172 var halfX = function (detail) { 15173 return xRange(detail) / 2; 15174 }; 15175 var halfY = function (detail) { 15176 return yRange(detail) / 2; 15177 }; 15178 var step = function (detail) { 15179 return detail.stepSize; 15180 }; 15181 var snap = function (detail) { 15182 return detail.snapToGrid; 15183 }; 15184 var snapStart = function (detail) { 15185 return detail.snapStart; 15186 }; 15187 var rounded = function (detail) { 15188 return detail.rounded; 15189 }; 15190 var hasEdge = function (detail, edgeName) { 15191 return detail[edgeName + '-edge'] !== undefined; 15192 }; 15193 var hasLEdge = function (detail) { 15194 return hasEdge(detail, l); 15195 }; 15196 var hasREdge = function (detail) { 15197 return hasEdge(detail, r); 15198 }; 15199 var hasTEdge = function (detail) { 15200 return hasEdge(detail, t); 15201 }; 15202 var hasBEdge = function (detail) { 15203 return hasEdge(detail, b); 15204 }; 15205 var currentValue = function (detail) { 15206 return detail.model.value.get(); 15207 }; 15208 15209 var xValue = function (x) { 15210 return { x: x }; 15211 }; 15212 var yValue = function (y) { 15213 return { y: y }; 15214 }; 15215 var xyValue = function (x, y) { 15216 return { 15217 x: x, 15218 y: y 15219 }; 15220 }; 15221 var fireSliderChange$3 = function (component, value) { 15222 emitWith(component, sliderChangeEvent(), { value: value }); 15223 }; 15224 var setToTLEdgeXY = function (edge, detail) { 15225 fireSliderChange$3(edge, xyValue(min1X(detail), min1Y(detail))); 15226 }; 15227 var setToTEdge = function (edge, detail) { 15228 fireSliderChange$3(edge, yValue(min1Y(detail))); 15229 }; 15230 var setToTEdgeXY = function (edge, detail) { 15231 fireSliderChange$3(edge, xyValue(halfX(detail), min1Y(detail))); 15232 }; 15233 var setToTREdgeXY = function (edge, detail) { 15234 fireSliderChange$3(edge, xyValue(max1X(detail), min1Y(detail))); 15235 }; 15236 var setToREdge = function (edge, detail) { 15237 fireSliderChange$3(edge, xValue(max1X(detail))); 15238 }; 15239 var setToREdgeXY = function (edge, detail) { 15240 fireSliderChange$3(edge, xyValue(max1X(detail), halfY(detail))); 15241 }; 15242 var setToBREdgeXY = function (edge, detail) { 15243 fireSliderChange$3(edge, xyValue(max1X(detail), max1Y(detail))); 15244 }; 15245 var setToBEdge = function (edge, detail) { 15246 fireSliderChange$3(edge, yValue(max1Y(detail))); 15247 }; 15248 var setToBEdgeXY = function (edge, detail) { 15249 fireSliderChange$3(edge, xyValue(halfX(detail), max1Y(detail))); 15250 }; 15251 var setToBLEdgeXY = function (edge, detail) { 15252 fireSliderChange$3(edge, xyValue(min1X(detail), max1Y(detail))); 15253 }; 15254 var setToLEdge = function (edge, detail) { 15255 fireSliderChange$3(edge, xValue(min1X(detail))); 15256 }; 15257 var setToLEdgeXY = function (edge, detail) { 15258 fireSliderChange$3(edge, xyValue(min1X(detail), halfY(detail))); 15259 }; 15260 15261 var reduceBy = function (value, min, max, step) { 15262 if (value < min) { 15263 return value; 15264 } else if (value > max) { 15265 return max; 15266 } else if (value === min) { 15267 return min - 1; 15268 } else { 15269 return Math.max(min, value - step); 15270 } 15271 }; 15272 var increaseBy = function (value, min, max, step) { 15273 if (value > max) { 15274 return value; 15275 } else if (value < min) { 15276 return min; 15277 } else if (value === max) { 15278 return max + 1; 15279 } else { 15280 return Math.min(max, value + step); 15281 } 15282 }; 15283 var capValue = function (value, min, max) { 15284 return Math.max(min, Math.min(max, value)); 15285 }; 15286 var snapValueOf = function (value, min, max, step, snapStart) { 15287 return snapStart.fold(function () { 15288 var initValue = value - min; 15289 var extraValue = Math.round(initValue / step) * step; 15290 return capValue(min + extraValue, min - 1, max + 1); 15291 }, function (start) { 15292 var remainder = (value - start) % step; 15293 var adjustment = Math.round(remainder / step); 15294 var rawSteps = Math.floor((value - start) / step); 15295 var maxSteps = Math.floor((max - start) / step); 15296 var numSteps = Math.min(maxSteps, rawSteps + adjustment); 15297 var r = start + numSteps * step; 15298 return Math.max(start, r); 15299 }); 15300 }; 15301 var findOffsetOf = function (value, min, max) { 15302 return Math.min(max, Math.max(value, min)) - min; 15303 }; 15304 var findValueOf = function (args) { 15305 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; 15306 var capMin = hasMinEdge ? min - 1 : min; 15307 var capMax = hasMaxEdge ? max + 1 : max; 15308 if (value < minBound) { 15309 return capMin; 15310 } else if (value > maxBound) { 15311 return capMax; 15312 } else { 15313 var offset = findOffsetOf(value, minBound, maxBound); 15314 var newValue = capValue(offset / screenRange * range + min, capMin, capMax); 15315 if (snap && newValue >= min && newValue <= max) { 15316 return snapValueOf(newValue, min, max, step, snapStart); 15317 } else if (rounded) { 15318 return Math.round(newValue); 15319 } else { 15320 return newValue; 15321 } 15322 } 15323 }; 15324 var findOffsetOfValue$2 = function (args) { 15325 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; 15326 if (value < min) { 15327 return hasMinEdge ? 0 : centerMinEdge; 15328 } else if (value > max) { 15329 return hasMaxEdge ? maxBound : centerMaxEdge; 15330 } else { 15331 return (value - min) / range * maxOffset; 15332 } 15333 }; 15334 15335 var top = 'top', right = 'right', bottom = 'bottom', left = 'left', width = 'width', height = 'height'; 15336 var getBounds = function (component) { 15337 return component.element.dom.getBoundingClientRect(); 15338 }; 15339 var getBoundsProperty = function (bounds, property) { 15340 return bounds[property]; 15341 }; 15342 var getMinXBounds = function (component) { 15343 var bounds = getBounds(component); 15344 return getBoundsProperty(bounds, left); 15345 }; 15346 var getMaxXBounds = function (component) { 15347 var bounds = getBounds(component); 15348 return getBoundsProperty(bounds, right); 15349 }; 15350 var getMinYBounds = function (component) { 15351 var bounds = getBounds(component); 15352 return getBoundsProperty(bounds, top); 15353 }; 15354 var getMaxYBounds = function (component) { 15355 var bounds = getBounds(component); 15356 return getBoundsProperty(bounds, bottom); 15357 }; 15358 var getXScreenRange = function (component) { 15359 var bounds = getBounds(component); 15360 return getBoundsProperty(bounds, width); 15361 }; 15362 var getYScreenRange = function (component) { 15363 var bounds = getBounds(component); 15364 return getBoundsProperty(bounds, height); 15365 }; 15366 var getCenterOffsetOf = function (componentMinEdge, componentMaxEdge, spectrumMinEdge) { 15367 return (componentMinEdge + componentMaxEdge) / 2 - spectrumMinEdge; 15368 }; 15369 var getXCenterOffSetOf = function (component, spectrum) { 15370 var componentBounds = getBounds(component); 15371 var spectrumBounds = getBounds(spectrum); 15372 var componentMinEdge = getBoundsProperty(componentBounds, left); 15373 var componentMaxEdge = getBoundsProperty(componentBounds, right); 15374 var spectrumMinEdge = getBoundsProperty(spectrumBounds, left); 15375 return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge); 15376 }; 15377 var getYCenterOffSetOf = function (component, spectrum) { 15378 var componentBounds = getBounds(component); 15379 var spectrumBounds = getBounds(spectrum); 15380 var componentMinEdge = getBoundsProperty(componentBounds, top); 15381 var componentMaxEdge = getBoundsProperty(componentBounds, bottom); 15382 var spectrumMinEdge = getBoundsProperty(spectrumBounds, top); 15383 return getCenterOffsetOf(componentMinEdge, componentMaxEdge, spectrumMinEdge); 15384 }; 15385 15386 var fireSliderChange$2 = function (spectrum, value) { 15387 emitWith(spectrum, sliderChangeEvent(), { value: value }); 15388 }; 15389 var sliderValue$2 = function (x) { 15390 return { x: x }; 15391 }; 15392 var findValueOfOffset$1 = function (spectrum, detail, left) { 15393 var args = { 15394 min: minX(detail), 15395 max: maxX(detail), 15396 range: xRange(detail), 15397 value: left, 15398 step: step(detail), 15399 snap: snap(detail), 15400 snapStart: snapStart(detail), 15401 rounded: rounded(detail), 15402 hasMinEdge: hasLEdge(detail), 15403 hasMaxEdge: hasREdge(detail), 15404 minBound: getMinXBounds(spectrum), 15405 maxBound: getMaxXBounds(spectrum), 15406 screenRange: getXScreenRange(spectrum) 15407 }; 15408 return findValueOf(args); 15409 }; 15410 var setValueFrom$2 = function (spectrum, detail, value) { 15411 var xValue = findValueOfOffset$1(spectrum, detail, value); 15412 var sliderVal = sliderValue$2(xValue); 15413 fireSliderChange$2(spectrum, sliderVal); 15414 return xValue; 15415 }; 15416 var setToMin$2 = function (spectrum, detail) { 15417 var min = minX(detail); 15418 fireSliderChange$2(spectrum, sliderValue$2(min)); 15419 }; 15420 var setToMax$2 = function (spectrum, detail) { 15421 var max = maxX(detail); 15422 fireSliderChange$2(spectrum, sliderValue$2(max)); 15423 }; 15424 var moveBy$2 = function (direction, spectrum, detail) { 15425 var f = direction > 0 ? increaseBy : reduceBy; 15426 var xValue = f(currentValue(detail).x, minX(detail), maxX(detail), step(detail)); 15427 fireSliderChange$2(spectrum, sliderValue$2(xValue)); 15428 return Optional.some(xValue); 15429 }; 15430 var handleMovement$2 = function (direction) { 15431 return function (spectrum, detail) { 15432 return moveBy$2(direction, spectrum, detail).map(always); 15433 }; 15434 }; 15435 var getValueFromEvent$2 = function (simulatedEvent) { 15436 var pos = getEventSource(simulatedEvent); 15437 return pos.map(function (p) { 15438 return p.left; 15439 }); 15440 }; 15441 var findOffsetOfValue$1 = function (spectrum, detail, value, minEdge, maxEdge) { 15442 var minOffset = 0; 15443 var maxOffset = getXScreenRange(spectrum); 15444 var centerMinEdge = minEdge.bind(function (edge) { 15445 return Optional.some(getXCenterOffSetOf(edge, spectrum)); 15446 }).getOr(minOffset); 15447 var centerMaxEdge = maxEdge.bind(function (edge) { 15448 return Optional.some(getXCenterOffSetOf(edge, spectrum)); 15449 }).getOr(maxOffset); 15450 var args = { 15451 min: minX(detail), 15452 max: maxX(detail), 15453 range: xRange(detail), 15454 value: value, 15455 hasMinEdge: hasLEdge(detail), 15456 hasMaxEdge: hasREdge(detail), 15457 minBound: getMinXBounds(spectrum), 15458 minOffset: minOffset, 15459 maxBound: getMaxXBounds(spectrum), 15460 maxOffset: maxOffset, 15461 centerMinEdge: centerMinEdge, 15462 centerMaxEdge: centerMaxEdge 15463 }; 15464 return findOffsetOfValue$2(args); 15465 }; 15466 var findPositionOfValue$1 = function (slider, spectrum, value, minEdge, maxEdge, detail) { 15467 var offset = findOffsetOfValue$1(spectrum, detail, value, minEdge, maxEdge); 15468 return getMinXBounds(spectrum) - getMinXBounds(slider) + offset; 15469 }; 15470 var setPositionFromValue$2 = function (slider, thumb, detail, edges) { 15471 var value = currentValue(detail); 15472 var pos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail); 15473 var thumbRadius = get$a(thumb.element) / 2; 15474 set$7(thumb.element, 'left', pos - thumbRadius + 'px'); 15475 }; 15476 var onLeft$2 = handleMovement$2(-1); 15477 var onRight$2 = handleMovement$2(1); 15478 var onUp$2 = Optional.none; 15479 var onDown$2 = Optional.none; 15480 var edgeActions$2 = { 15481 'top-left': Optional.none(), 15482 'top': Optional.none(), 15483 'top-right': Optional.none(), 15484 'right': Optional.some(setToREdge), 15485 'bottom-right': Optional.none(), 15486 'bottom': Optional.none(), 15487 'bottom-left': Optional.none(), 15488 'left': Optional.some(setToLEdge) 15489 }; 15490 15491 var HorizontalModel = /*#__PURE__*/Object.freeze({ 15492 __proto__: null, 15493 setValueFrom: setValueFrom$2, 15494 setToMin: setToMin$2, 15495 setToMax: setToMax$2, 15496 findValueOfOffset: findValueOfOffset$1, 15497 getValueFromEvent: getValueFromEvent$2, 15498 findPositionOfValue: findPositionOfValue$1, 15499 setPositionFromValue: setPositionFromValue$2, 15500 onLeft: onLeft$2, 15501 onRight: onRight$2, 15502 onUp: onUp$2, 15503 onDown: onDown$2, 15504 edgeActions: edgeActions$2 15505 }); 15506 15507 var fireSliderChange$1 = function (spectrum, value) { 15508 emitWith(spectrum, sliderChangeEvent(), { value: value }); 15509 }; 15510 var sliderValue$1 = function (y) { 15511 return { y: y }; 15512 }; 15513 var findValueOfOffset = function (spectrum, detail, top) { 15514 var args = { 15515 min: minY(detail), 15516 max: maxY(detail), 15517 range: yRange(detail), 15518 value: top, 15519 step: step(detail), 15520 snap: snap(detail), 15521 snapStart: snapStart(detail), 15522 rounded: rounded(detail), 15523 hasMinEdge: hasTEdge(detail), 15524 hasMaxEdge: hasBEdge(detail), 15525 minBound: getMinYBounds(spectrum), 15526 maxBound: getMaxYBounds(spectrum), 15527 screenRange: getYScreenRange(spectrum) 15528 }; 15529 return findValueOf(args); 15530 }; 15531 var setValueFrom$1 = function (spectrum, detail, value) { 15532 var yValue = findValueOfOffset(spectrum, detail, value); 15533 var sliderVal = sliderValue$1(yValue); 15534 fireSliderChange$1(spectrum, sliderVal); 15535 return yValue; 15536 }; 15537 var setToMin$1 = function (spectrum, detail) { 15538 var min = minY(detail); 15539 fireSliderChange$1(spectrum, sliderValue$1(min)); 15540 }; 15541 var setToMax$1 = function (spectrum, detail) { 15542 var max = maxY(detail); 15543 fireSliderChange$1(spectrum, sliderValue$1(max)); 15544 }; 15545 var moveBy$1 = function (direction, spectrum, detail) { 15546 var f = direction > 0 ? increaseBy : reduceBy; 15547 var yValue = f(currentValue(detail).y, minY(detail), maxY(detail), step(detail)); 15548 fireSliderChange$1(spectrum, sliderValue$1(yValue)); 15549 return Optional.some(yValue); 15550 }; 15551 var handleMovement$1 = function (direction) { 15552 return function (spectrum, detail) { 15553 return moveBy$1(direction, spectrum, detail).map(always); 15554 }; 15555 }; 15556 var getValueFromEvent$1 = function (simulatedEvent) { 15557 var pos = getEventSource(simulatedEvent); 15558 return pos.map(function (p) { 15559 return p.top; 15560 }); 15561 }; 15562 var findOffsetOfValue = function (spectrum, detail, value, minEdge, maxEdge) { 15563 var minOffset = 0; 15564 var maxOffset = getYScreenRange(spectrum); 15565 var centerMinEdge = minEdge.bind(function (edge) { 15566 return Optional.some(getYCenterOffSetOf(edge, spectrum)); 15567 }).getOr(minOffset); 15568 var centerMaxEdge = maxEdge.bind(function (edge) { 15569 return Optional.some(getYCenterOffSetOf(edge, spectrum)); 15570 }).getOr(maxOffset); 15571 var args = { 15572 min: minY(detail), 15573 max: maxY(detail), 15574 range: yRange(detail), 15575 value: value, 15576 hasMinEdge: hasTEdge(detail), 15577 hasMaxEdge: hasBEdge(detail), 15578 minBound: getMinYBounds(spectrum), 15579 minOffset: minOffset, 15580 maxBound: getMaxYBounds(spectrum), 15581 maxOffset: maxOffset, 15582 centerMinEdge: centerMinEdge, 15583 centerMaxEdge: centerMaxEdge 15584 }; 15585 return findOffsetOfValue$2(args); 15586 }; 15587 var findPositionOfValue = function (slider, spectrum, value, minEdge, maxEdge, detail) { 15588 var offset = findOffsetOfValue(spectrum, detail, value, minEdge, maxEdge); 15589 return getMinYBounds(spectrum) - getMinYBounds(slider) + offset; 15590 }; 15591 var setPositionFromValue$1 = function (slider, thumb, detail, edges) { 15592 var value = currentValue(detail); 15593 var pos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail); 15594 var thumbRadius = get$b(thumb.element) / 2; 15595 set$7(thumb.element, 'top', pos - thumbRadius + 'px'); 15596 }; 15597 var onLeft$1 = Optional.none; 15598 var onRight$1 = Optional.none; 15599 var onUp$1 = handleMovement$1(-1); 15600 var onDown$1 = handleMovement$1(1); 15601 var edgeActions$1 = { 15602 'top-left': Optional.none(), 15603 'top': Optional.some(setToTEdge), 15604 'top-right': Optional.none(), 15605 'right': Optional.none(), 15606 'bottom-right': Optional.none(), 15607 'bottom': Optional.some(setToBEdge), 15608 'bottom-left': Optional.none(), 15609 'left': Optional.none() 15610 }; 15611 15612 var VerticalModel = /*#__PURE__*/Object.freeze({ 15613 __proto__: null, 15614 setValueFrom: setValueFrom$1, 15615 setToMin: setToMin$1, 15616 setToMax: setToMax$1, 15617 findValueOfOffset: findValueOfOffset, 15618 getValueFromEvent: getValueFromEvent$1, 15619 findPositionOfValue: findPositionOfValue, 15620 setPositionFromValue: setPositionFromValue$1, 15621 onLeft: onLeft$1, 15622 onRight: onRight$1, 15623 onUp: onUp$1, 15624 onDown: onDown$1, 15625 edgeActions: edgeActions$1 15626 }); 15627 15628 var fireSliderChange = function (spectrum, value) { 15629 emitWith(spectrum, sliderChangeEvent(), { value: value }); 15630 }; 15631 var sliderValue = function (x, y) { 15632 return { 15633 x: x, 15634 y: y 15635 }; 15636 }; 15637 var setValueFrom = function (spectrum, detail, value) { 15638 var xValue = findValueOfOffset$1(spectrum, detail, value.left); 15639 var yValue = findValueOfOffset(spectrum, detail, value.top); 15640 var val = sliderValue(xValue, yValue); 15641 fireSliderChange(spectrum, val); 15642 return val; 15643 }; 15644 var moveBy = function (direction, isVerticalMovement, spectrum, detail) { 15645 var f = direction > 0 ? increaseBy : reduceBy; 15646 var xValue = isVerticalMovement ? currentValue(detail).x : f(currentValue(detail).x, minX(detail), maxX(detail), step(detail)); 15647 var yValue = !isVerticalMovement ? currentValue(detail).y : f(currentValue(detail).y, minY(detail), maxY(detail), step(detail)); 15648 fireSliderChange(spectrum, sliderValue(xValue, yValue)); 15649 return Optional.some(xValue); 15650 }; 15651 var handleMovement = function (direction, isVerticalMovement) { 15652 return function (spectrum, detail) { 15653 return moveBy(direction, isVerticalMovement, spectrum, detail).map(always); 15654 }; 15655 }; 15656 var setToMin = function (spectrum, detail) { 15657 var mX = minX(detail); 15658 var mY = minY(detail); 15659 fireSliderChange(spectrum, sliderValue(mX, mY)); 15660 }; 15661 var setToMax = function (spectrum, detail) { 15662 var mX = maxX(detail); 15663 var mY = maxY(detail); 15664 fireSliderChange(spectrum, sliderValue(mX, mY)); 15665 }; 15666 var getValueFromEvent = function (simulatedEvent) { 15667 return getEventSource(simulatedEvent); 15668 }; 15669 var setPositionFromValue = function (slider, thumb, detail, edges) { 15670 var value = currentValue(detail); 15671 var xPos = findPositionOfValue$1(slider, edges.getSpectrum(slider), value.x, edges.getLeftEdge(slider), edges.getRightEdge(slider), detail); 15672 var yPos = findPositionOfValue(slider, edges.getSpectrum(slider), value.y, edges.getTopEdge(slider), edges.getBottomEdge(slider), detail); 15673 var thumbXRadius = get$a(thumb.element) / 2; 15674 var thumbYRadius = get$b(thumb.element) / 2; 15675 set$7(thumb.element, 'left', xPos - thumbXRadius + 'px'); 15676 set$7(thumb.element, 'top', yPos - thumbYRadius + 'px'); 15677 }; 15678 var onLeft = handleMovement(-1, false); 15679 var onRight = handleMovement(1, false); 15680 var onUp = handleMovement(-1, true); 15681 var onDown = handleMovement(1, true); 15682 var edgeActions = { 15683 'top-left': Optional.some(setToTLEdgeXY), 15684 'top': Optional.some(setToTEdgeXY), 15685 'top-right': Optional.some(setToTREdgeXY), 15686 'right': Optional.some(setToREdgeXY), 15687 'bottom-right': Optional.some(setToBREdgeXY), 15688 'bottom': Optional.some(setToBEdgeXY), 15689 'bottom-left': Optional.some(setToBLEdgeXY), 15690 'left': Optional.some(setToLEdgeXY) 15691 }; 15692 15693 var TwoDModel = /*#__PURE__*/Object.freeze({ 15694 __proto__: null, 15695 setValueFrom: setValueFrom, 15696 setToMin: setToMin, 15697 setToMax: setToMax, 15698 getValueFromEvent: getValueFromEvent, 15699 setPositionFromValue: setPositionFromValue, 15700 onLeft: onLeft, 15701 onRight: onRight, 15702 onUp: onUp, 15703 onDown: onDown, 15704 edgeActions: edgeActions 15705 }); 15706 15707 var SliderSchema = [ 15708 defaulted('stepSize', 1), 15709 defaulted('onChange', noop), 15710 defaulted('onChoose', noop), 15711 defaulted('onInit', noop), 15712 defaulted('onDragStart', noop), 15713 defaulted('onDragEnd', noop), 15714 defaulted('snapToGrid', false), 15715 defaulted('rounded', true), 15716 option('snapStart'), 15717 requiredOf('model', choose$1('mode', { 15718 x: [ 15719 defaulted('minX', 0), 15720 defaulted('maxX', 100), 15721 customField('value', function (spec) { 15722 return Cell(spec.mode.minX); 15723 }), 15724 required$1('getInitialValue'), 15725 output$1('manager', HorizontalModel) 15726 ], 15727 y: [ 15728 defaulted('minY', 0), 15729 defaulted('maxY', 100), 15730 customField('value', function (spec) { 15731 return Cell(spec.mode.minY); 15732 }), 15733 required$1('getInitialValue'), 15734 output$1('manager', VerticalModel) 15735 ], 15736 xy: [ 15737 defaulted('minX', 0), 15738 defaulted('maxX', 100), 15739 defaulted('minY', 0), 15740 defaulted('maxY', 100), 15741 customField('value', function (spec) { 15742 return Cell({ 15743 x: spec.mode.minX, 15744 y: spec.mode.minY 15745 }); 15746 }), 15747 required$1('getInitialValue'), 15748 output$1('manager', TwoDModel) 15749 ] 15750 })), 15751 field('sliderBehaviours', [ 15752 Keying, 15753 Representing 15754 ]), 15755 customField('mouseIsDown', function () { 15756 return Cell(false); 15757 }) 15758 ]; 15759 15760 var sketch$2 = function (detail, components, _spec, _externals) { 15761 var _a; 15762 var getThumb = function (component) { 15763 return getPartOrDie(component, detail, 'thumb'); 15764 }; 15765 var getSpectrum = function (component) { 15766 return getPartOrDie(component, detail, 'spectrum'); 15767 }; 15768 var getLeftEdge = function (component) { 15769 return getPart(component, detail, 'left-edge'); 15770 }; 15771 var getRightEdge = function (component) { 15772 return getPart(component, detail, 'right-edge'); 15773 }; 15774 var getTopEdge = function (component) { 15775 return getPart(component, detail, 'top-edge'); 15776 }; 15777 var getBottomEdge = function (component) { 15778 return getPart(component, detail, 'bottom-edge'); 15779 }; 15780 var modelDetail = detail.model; 15781 var model = modelDetail.manager; 15782 var refresh = function (slider, thumb) { 15783 model.setPositionFromValue(slider, thumb, detail, { 15784 getLeftEdge: getLeftEdge, 15785 getRightEdge: getRightEdge, 15786 getTopEdge: getTopEdge, 15787 getBottomEdge: getBottomEdge, 15788 getSpectrum: getSpectrum 15789 }); 15790 }; 15791 var setValue = function (slider, newValue) { 15792 modelDetail.value.set(newValue); 15793 var thumb = getThumb(slider); 15794 refresh(slider, thumb); 15795 }; 15796 var changeValue = function (slider, newValue) { 15797 setValue(slider, newValue); 15798 var thumb = getThumb(slider); 15799 detail.onChange(slider, thumb, newValue); 15800 return Optional.some(true); 15801 }; 15802 var resetToMin = function (slider) { 15803 model.setToMin(slider, detail); 15804 }; 15805 var resetToMax = function (slider) { 15806 model.setToMax(slider, detail); 15807 }; 15808 var choose = function (slider) { 15809 var fireOnChoose = function () { 15810 getPart(slider, detail, 'thumb').each(function (thumb) { 15811 var value = modelDetail.value.get(); 15812 detail.onChoose(slider, thumb, value); 15813 }); 15814 }; 15815 var wasDown = detail.mouseIsDown.get(); 15816 detail.mouseIsDown.set(false); 15817 if (wasDown) { 15818 fireOnChoose(); 15819 } 15820 }; 15821 var onDragStart = function (slider, simulatedEvent) { 15822 simulatedEvent.stop(); 15823 detail.mouseIsDown.set(true); 15824 detail.onDragStart(slider, getThumb(slider)); 15825 }; 15826 var onDragEnd = function (slider, simulatedEvent) { 15827 simulatedEvent.stop(); 15828 detail.onDragEnd(slider, getThumb(slider)); 15829 choose(slider); 15830 }; 15831 return { 15832 uid: detail.uid, 15833 dom: detail.dom, 15834 components: components, 15835 behaviours: augment(detail.sliderBehaviours, [ 15836 Keying.config({ 15837 mode: 'special', 15838 focusIn: function (slider) { 15839 return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(always); 15840 } 15841 }), 15842 Representing.config({ 15843 store: { 15844 mode: 'manual', 15845 getValue: function (_) { 15846 return modelDetail.value.get(); 15847 } 15848 } 15849 }), 15850 Receiving.config({ channels: (_a = {}, _a[mouseReleased()] = { onReceive: choose }, _a) }) 15851 ]), 15852 events: derive$2([ 15853 run$1(sliderChangeEvent(), function (slider, simulatedEvent) { 15854 changeValue(slider, simulatedEvent.event.value); 15855 }), 15856 runOnAttached(function (slider, _simulatedEvent) { 15857 var getInitial = modelDetail.getInitialValue(); 15858 modelDetail.value.set(getInitial); 15859 var thumb = getThumb(slider); 15860 refresh(slider, thumb); 15861 var spectrum = getSpectrum(slider); 15862 detail.onInit(slider, thumb, spectrum, modelDetail.value.get()); 15863 }), 15864 run$1(touchstart(), onDragStart), 15865 run$1(touchend(), onDragEnd), 15866 run$1(mousedown(), onDragStart), 15867 run$1(mouseup(), onDragEnd) 15868 ]), 15869 apis: { 15870 resetToMin: resetToMin, 15871 resetToMax: resetToMax, 15872 setValue: setValue, 15873 refresh: refresh 15874 }, 15875 domModification: { styles: { position: 'relative' } } 15876 }; 15877 }; 15878 15879 var Slider = composite({ 15880 name: 'Slider', 15881 configFields: SliderSchema, 15882 partFields: SliderParts, 15883 factory: sketch$2, 15884 apis: { 15885 setValue: function (apis, slider, value) { 15886 apis.setValue(slider, value); 15887 }, 15888 resetToMin: function (apis, slider) { 15889 apis.resetToMin(slider); 15890 }, 15891 resetToMax: function (apis, slider) { 15892 apis.resetToMax(slider); 15893 }, 15894 refresh: function (apis, slider) { 15895 apis.refresh(slider); 15896 } 15897 } 15898 }); 15899 15900 var fieldsUpdate = generate$6('rgb-hex-update'); 15901 var sliderUpdate = generate$6('slider-update'); 15902 var paletteUpdate = generate$6('palette-update'); 15903 15904 var sliderFactory = function (translate, getClass) { 15905 var spectrum = Slider.parts.spectrum({ 15906 dom: { 15907 tag: 'div', 15908 classes: [getClass('hue-slider-spectrum')], 15909 attributes: { role: 'presentation' } 15910 } 15911 }); 15912 var thumb = Slider.parts.thumb({ 15913 dom: { 15914 tag: 'div', 15915 classes: [getClass('hue-slider-thumb')], 15916 attributes: { role: 'presentation' } 15917 } 15918 }); 15919 return Slider.sketch({ 15920 dom: { 15921 tag: 'div', 15922 classes: [getClass('hue-slider')], 15923 attributes: { role: 'presentation' } 15924 }, 15925 rounded: false, 15926 model: { 15927 mode: 'y', 15928 getInitialValue: constant$1({ y: 0 }) 15929 }, 15930 components: [ 15931 spectrum, 15932 thumb 15933 ], 15934 sliderBehaviours: derive$1([Focusing.config({})]), 15935 onChange: function (slider, _thumb, value) { 15936 emitWith(slider, sliderUpdate, { value: value }); 15937 } 15938 }); 15939 }; 15940 15941 var owner$1 = 'form'; 15942 var schema$i = [field('formBehaviours', [Representing])]; 15943 var getPartName$1 = function (name) { 15944 return '<alloy.field.' + name + '>'; 15945 }; 15946 var sketch$1 = function (fSpec) { 15947 var parts = function () { 15948 var record = []; 15949 var field = function (name, config) { 15950 record.push(name); 15951 return generateOne$1(owner$1, getPartName$1(name), config); 15952 }; 15953 return { 15954 field: field, 15955 record: constant$1(record) 15956 }; 15957 }(); 15958 var spec = fSpec(parts); 15959 var partNames = parts.record(); 15960 var fieldParts = map$2(partNames, function (n) { 15961 return required({ 15962 name: n, 15963 pname: getPartName$1(n) 15964 }); 15965 }); 15966 return composite$1(owner$1, schema$i, fieldParts, make$4, spec); 15967 }; 15968 var toResult = function (o, e) { 15969 return o.fold(function () { 15970 return Result.error(e); 15971 }, Result.value); 15972 }; 15973 var make$4 = function (detail, components) { 15974 return { 15975 uid: detail.uid, 15976 dom: detail.dom, 15977 components: components, 15978 behaviours: augment(detail.formBehaviours, [Representing.config({ 15979 store: { 15980 mode: 'manual', 15981 getValue: function (form) { 15982 var resPs = getAllParts(form, detail); 15983 return map$1(resPs, function (resPThunk, pName) { 15984 return resPThunk().bind(function (v) { 15985 var opt = Composing.getCurrent(v); 15986 return toResult(opt, new Error('Cannot find a current component to extract the value from for form part \'' + pName + '\': ' + element(v.element))); 15987 }).map(Representing.getValue); 15988 }); 15989 }, 15990 setValue: function (form, values) { 15991 each(values, function (newValue, key) { 15992 getPart(form, detail, key).each(function (wrapper) { 15993 Composing.getCurrent(wrapper).each(function (field) { 15994 Representing.setValue(field, newValue); 15995 }); 15996 }); 15997 }); 15998 } 15999 } 16000 })]), 16001 apis: { 16002 getField: function (form, key) { 16003 return getPart(form, detail, key).bind(Composing.getCurrent); 16004 } 16005 } 16006 }; 16007 }; 16008 var Form = { 16009 getField: makeApi(function (apis, component, key) { 16010 return apis.getField(component, key); 16011 }), 16012 sketch: sketch$1 16013 }; 16014 16015 var validInput = generate$6('valid-input'); 16016 var invalidInput = generate$6('invalid-input'); 16017 var validatingInput = generate$6('validating-input'); 16018 var translatePrefix = 'colorcustom.rgb.'; 16019 var rgbFormFactory = function (translate, getClass, onValidHexx, onInvalidHexx) { 16020 var invalidation = function (label, isValid) { 16021 return Invalidating.config({ 16022 invalidClass: getClass('invalid'), 16023 notify: { 16024 onValidate: function (comp) { 16025 emitWith(comp, validatingInput, { type: label }); 16026 }, 16027 onValid: function (comp) { 16028 emitWith(comp, validInput, { 16029 type: label, 16030 value: Representing.getValue(comp) 16031 }); 16032 }, 16033 onInvalid: function (comp) { 16034 emitWith(comp, invalidInput, { 16035 type: label, 16036 value: Representing.getValue(comp) 16037 }); 16038 } 16039 }, 16040 validator: { 16041 validate: function (comp) { 16042 var value = Representing.getValue(comp); 16043 var res = isValid(value) ? Result.value(true) : Result.error(translate('aria.input.invalid')); 16044 return Future.pure(res); 16045 }, 16046 validateOnLoad: false 16047 } 16048 }); 16049 }; 16050 var renderTextField = function (isValid, name, label, description, data) { 16051 var helptext = translate(translatePrefix + 'range'); 16052 var pLabel = FormField.parts.label({ 16053 dom: { 16054 tag: 'label', 16055 innerHtml: label, 16056 attributes: { 'aria-label': description } 16057 } 16058 }); 16059 var pField = FormField.parts.field({ 16060 data: data, 16061 factory: Input, 16062 inputAttributes: __assign({ type: 'text' }, name === 'hex' ? { 'aria-live': 'polite' } : {}), 16063 inputClasses: [getClass('textfield')], 16064 inputBehaviours: derive$1([ 16065 invalidation(name, isValid), 16066 Tabstopping.config({}) 16067 ]), 16068 onSetValue: function (input) { 16069 if (Invalidating.isInvalid(input)) { 16070 var run = Invalidating.run(input); 16071 run.get(noop); 16072 } 16073 } 16074 }); 16075 var comps = [ 16076 pLabel, 16077 pField 16078 ]; 16079 var concats = name !== 'hex' ? [FormField.parts['aria-descriptor']({ text: helptext })] : []; 16080 var components = comps.concat(concats); 16081 return { 16082 dom: { 16083 tag: 'div', 16084 attributes: { role: 'presentation' } 16085 }, 16086 components: components 16087 }; 16088 }; 16089 var copyRgbToHex = function (form, rgba) { 16090 var hex = fromRgba(rgba); 16091 Form.getField(form, 'hex').each(function (hexField) { 16092 if (!Focusing.isFocused(hexField)) { 16093 Representing.setValue(form, { hex: hex.value }); 16094 } 16095 }); 16096 return hex; 16097 }; 16098 var copyRgbToForm = function (form, rgb) { 16099 var red = rgb.red; 16100 var green = rgb.green; 16101 var blue = rgb.blue; 16102 Representing.setValue(form, { 16103 red: red, 16104 green: green, 16105 blue: blue 16106 }); 16107 }; 16108 var memPreview = record({ 16109 dom: { 16110 tag: 'div', 16111 classes: [getClass('rgba-preview')], 16112 styles: { 'background-color': 'white' }, 16113 attributes: { role: 'presentation' } 16114 } 16115 }); 16116 var updatePreview = function (anyInSystem, hex) { 16117 memPreview.getOpt(anyInSystem).each(function (preview) { 16118 set$7(preview.element, 'background-color', '#' + hex.value); 16119 }); 16120 }; 16121 var factory = function () { 16122 var state = { 16123 red: Cell(Optional.some(255)), 16124 green: Cell(Optional.some(255)), 16125 blue: Cell(Optional.some(255)), 16126 hex: Cell(Optional.some('ffffff')) 16127 }; 16128 var copyHexToRgb = function (form, hex) { 16129 var rgb = fromHex(hex); 16130 copyRgbToForm(form, rgb); 16131 setValueRgb(rgb); 16132 }; 16133 var get = function (prop) { 16134 return state[prop].get(); 16135 }; 16136 var set = function (prop, value) { 16137 state[prop].set(value); 16138 }; 16139 var getValueRgb = function () { 16140 return get('red').bind(function (red) { 16141 return get('green').bind(function (green) { 16142 return get('blue').map(function (blue) { 16143 return rgbaColour(red, green, blue, 1); 16144 }); 16145 }); 16146 }); 16147 }; 16148 var setValueRgb = function (rgb) { 16149 var red = rgb.red; 16150 var green = rgb.green; 16151 var blue = rgb.blue; 16152 set('red', Optional.some(red)); 16153 set('green', Optional.some(green)); 16154 set('blue', Optional.some(blue)); 16155 }; 16156 var onInvalidInput = function (form, simulatedEvent) { 16157 var data = simulatedEvent.event; 16158 if (data.type !== 'hex') { 16159 set(data.type, Optional.none()); 16160 } else { 16161 onInvalidHexx(form); 16162 } 16163 }; 16164 var onValidHex = function (form, value) { 16165 onValidHexx(form); 16166 var hex = hexColour(value); 16167 set('hex', Optional.some(value)); 16168 var rgb = fromHex(hex); 16169 copyRgbToForm(form, rgb); 16170 setValueRgb(rgb); 16171 emitWith(form, fieldsUpdate, { hex: hex }); 16172 updatePreview(form, hex); 16173 }; 16174 var onValidRgb = function (form, prop, value) { 16175 var val = parseInt(value, 10); 16176 set(prop, Optional.some(val)); 16177 getValueRgb().each(function (rgb) { 16178 var hex = copyRgbToHex(form, rgb); 16179 emitWith(form, fieldsUpdate, { hex: hex }); 16180 updatePreview(form, hex); 16181 }); 16182 }; 16183 var isHexInputEvent = function (data) { 16184 return data.type === 'hex'; 16185 }; 16186 var onValidInput = function (form, simulatedEvent) { 16187 var data = simulatedEvent.event; 16188 if (isHexInputEvent(data)) { 16189 onValidHex(form, data.value); 16190 } else { 16191 onValidRgb(form, data.type, data.value); 16192 } 16193 }; 16194 var formPartStrings = function (key) { 16195 return { 16196 label: translate(translatePrefix + key + '.label'), 16197 description: translate(translatePrefix + key + '.description') 16198 }; 16199 }; 16200 var redStrings = formPartStrings('red'); 16201 var greenStrings = formPartStrings('green'); 16202 var blueStrings = formPartStrings('blue'); 16203 var hexStrings = formPartStrings('hex'); 16204 return deepMerge(Form.sketch(function (parts) { 16205 return { 16206 dom: { 16207 tag: 'form', 16208 classes: [getClass('rgb-form')], 16209 attributes: { 'aria-label': translate('aria.color.picker') } 16210 }, 16211 components: [ 16212 parts.field('red', FormField.sketch(renderTextField(isRgbaComponent, 'red', redStrings.label, redStrings.description, 255))), 16213 parts.field('green', FormField.sketch(renderTextField(isRgbaComponent, 'green', greenStrings.label, greenStrings.description, 255))), 16214 parts.field('blue', FormField.sketch(renderTextField(isRgbaComponent, 'blue', blueStrings.label, blueStrings.description, 255))), 16215 parts.field('hex', FormField.sketch(renderTextField(isHexString, 'hex', hexStrings.label, hexStrings.description, 'ffffff'))), 16216 memPreview.asSpec() 16217 ], 16218 formBehaviours: derive$1([ 16219 Invalidating.config({ invalidClass: getClass('form-invalid') }), 16220 config('rgb-form-events', [ 16221 run$1(validInput, onValidInput), 16222 run$1(invalidInput, onInvalidInput), 16223 run$1(validatingInput, onInvalidInput) 16224 ]) 16225 ]) 16226 }; 16227 }), { 16228 apis: { 16229 updateHex: function (form, hex) { 16230 Representing.setValue(form, { hex: hex.value }); 16231 copyHexToRgb(form, hex); 16232 updatePreview(form, hex); 16233 } 16234 } 16235 }); 16236 }; 16237 var rgbFormSketcher = single({ 16238 factory: factory, 16239 name: 'RgbForm', 16240 configFields: [], 16241 apis: { 16242 updateHex: function (apis, form, hex) { 16243 apis.updateHex(form, hex); 16244 } 16245 }, 16246 extraApis: {} 16247 }); 16248 return rgbFormSketcher; 16249 }; 16250 16251 var paletteFactory = function (_translate, getClass) { 16252 var spectrumPart = Slider.parts.spectrum({ 16253 dom: { 16254 tag: 'canvas', 16255 attributes: { role: 'presentation' }, 16256 classes: [getClass('sv-palette-spectrum')] 16257 } 16258 }); 16259 var thumbPart = Slider.parts.thumb({ 16260 dom: { 16261 tag: 'div', 16262 attributes: { role: 'presentation' }, 16263 classes: [getClass('sv-palette-thumb')], 16264 innerHtml: '<div class=' + getClass('sv-palette-inner-thumb') + ' role="presentation"></div>' 16265 } 16266 }); 16267 var setColour = function (canvas, rgba) { 16268 var width = canvas.width, height = canvas.height; 16269 var ctx = canvas.getContext('2d'); 16270 if (ctx === null) { 16271 return; 16272 } 16273 ctx.fillStyle = rgba; 16274 ctx.fillRect(0, 0, width, height); 16275 var grdWhite = ctx.createLinearGradient(0, 0, width, 0); 16276 grdWhite.addColorStop(0, 'rgba(255,255,255,1)'); 16277 grdWhite.addColorStop(1, 'rgba(255,255,255,0)'); 16278 ctx.fillStyle = grdWhite; 16279 ctx.fillRect(0, 0, width, height); 16280 var grdBlack = ctx.createLinearGradient(0, 0, 0, height); 16281 grdBlack.addColorStop(0, 'rgba(0,0,0,0)'); 16282 grdBlack.addColorStop(1, 'rgba(0,0,0,1)'); 16283 ctx.fillStyle = grdBlack; 16284 ctx.fillRect(0, 0, width, height); 16285 }; 16286 var setPaletteHue = function (slider, hue) { 16287 var canvas = slider.components()[0].element.dom; 16288 var hsv = hsvColour(hue, 100, 100); 16289 var rgba = fromHsv(hsv); 16290 setColour(canvas, toString(rgba)); 16291 }; 16292 var setPaletteThumb = function (slider, hex) { 16293 var hsv = fromRgb(fromHex(hex)); 16294 Slider.setValue(slider, { 16295 x: hsv.saturation, 16296 y: 100 - hsv.value 16297 }); 16298 }; 16299 var factory = function (_detail) { 16300 var getInitialValue = constant$1({ 16301 x: 0, 16302 y: 0 16303 }); 16304 var onChange = function (slider, _thumb, value) { 16305 emitWith(slider, paletteUpdate, { value: value }); 16306 }; 16307 var onInit = function (_slider, _thumb, spectrum, _value) { 16308 setColour(spectrum.element.dom, toString(red)); 16309 }; 16310 var sliderBehaviours = derive$1([ 16311 Composing.config({ find: Optional.some }), 16312 Focusing.config({}) 16313 ]); 16314 return Slider.sketch({ 16315 dom: { 16316 tag: 'div', 16317 attributes: { role: 'presentation' }, 16318 classes: [getClass('sv-palette')] 16319 }, 16320 model: { 16321 mode: 'xy', 16322 getInitialValue: getInitialValue 16323 }, 16324 rounded: false, 16325 components: [ 16326 spectrumPart, 16327 thumbPart 16328 ], 16329 onChange: onChange, 16330 onInit: onInit, 16331 sliderBehaviours: sliderBehaviours 16332 }); 16333 }; 16334 var saturationBrightnessPaletteSketcher = single({ 16335 factory: factory, 16336 name: 'SaturationBrightnessPalette', 16337 configFields: [], 16338 apis: { 16339 setHue: function (_apis, slider, hue) { 16340 setPaletteHue(slider, hue); 16341 }, 16342 setThumb: function (_apis, slider, hex) { 16343 setPaletteThumb(slider, hex); 16344 } 16345 }, 16346 extraApis: {} 16347 }); 16348 return saturationBrightnessPaletteSketcher; 16349 }; 16350 16351 var makeFactory = function (translate, getClass) { 16352 var factory = function (detail) { 16353 var rgbForm = rgbFormFactory(translate, getClass, detail.onValidHex, detail.onInvalidHex); 16354 var sbPalette = paletteFactory(translate, getClass); 16355 var hueSliderToDegrees = function (hue) { 16356 return (100 - hue) / 100 * 360; 16357 }; 16358 var hueDegreesToSlider = function (hue) { 16359 return 100 - hue / 360 * 100; 16360 }; 16361 var state = { 16362 paletteRgba: Cell(red), 16363 paletteHue: Cell(0) 16364 }; 16365 var memSlider = record(sliderFactory(translate, getClass)); 16366 var memPalette = record(sbPalette.sketch({})); 16367 var memRgb = record(rgbForm.sketch({})); 16368 var updatePalette = function (anyInSystem, _hex, hue) { 16369 memPalette.getOpt(anyInSystem).each(function (palette) { 16370 sbPalette.setHue(palette, hue); 16371 }); 16372 }; 16373 var updateFields = function (anyInSystem, hex) { 16374 memRgb.getOpt(anyInSystem).each(function (form) { 16375 rgbForm.updateHex(form, hex); 16376 }); 16377 }; 16378 var updateSlider = function (anyInSystem, _hex, hue) { 16379 memSlider.getOpt(anyInSystem).each(function (slider) { 16380 Slider.setValue(slider, { y: hueDegreesToSlider(hue) }); 16381 }); 16382 }; 16383 var updatePaletteThumb = function (anyInSystem, hex) { 16384 memPalette.getOpt(anyInSystem).each(function (palette) { 16385 sbPalette.setThumb(palette, hex); 16386 }); 16387 }; 16388 var updateState = function (hex, hue) { 16389 var rgba = fromHex(hex); 16390 state.paletteRgba.set(rgba); 16391 state.paletteHue.set(hue); 16392 }; 16393 var runUpdates = function (anyInSystem, hex, hue, updates) { 16394 updateState(hex, hue); 16395 each$1(updates, function (update) { 16396 update(anyInSystem, hex, hue); 16397 }); 16398 }; 16399 var onPaletteUpdate = function () { 16400 var updates = [updateFields]; 16401 return function (form, simulatedEvent) { 16402 var value = simulatedEvent.event.value; 16403 var oldHue = state.paletteHue.get(); 16404 var newHsv = hsvColour(oldHue, value.x, 100 - value.y); 16405 var newHex = hsvToHex(newHsv); 16406 runUpdates(form, newHex, oldHue, updates); 16407 }; 16408 }; 16409 var onSliderUpdate = function () { 16410 var updates = [ 16411 updatePalette, 16412 updateFields 16413 ]; 16414 return function (form, simulatedEvent) { 16415 var hue = hueSliderToDegrees(simulatedEvent.event.value.y); 16416 var oldRgb = state.paletteRgba.get(); 16417 var oldHsv = fromRgb(oldRgb); 16418 var newHsv = hsvColour(hue, oldHsv.saturation, oldHsv.value); 16419 var newHex = hsvToHex(newHsv); 16420 runUpdates(form, newHex, hue, updates); 16421 }; 16422 }; 16423 var onFieldsUpdate = function () { 16424 var updates = [ 16425 updatePalette, 16426 updateSlider, 16427 updatePaletteThumb 16428 ]; 16429 return function (form, simulatedEvent) { 16430 var hex = simulatedEvent.event.hex; 16431 var hsv = hexToHsv(hex); 16432 runUpdates(form, hex, hsv.hue, updates); 16433 }; 16434 }; 16435 return { 16436 uid: detail.uid, 16437 dom: detail.dom, 16438 components: [ 16439 memPalette.asSpec(), 16440 memSlider.asSpec(), 16441 memRgb.asSpec() 16442 ], 16443 behaviours: derive$1([ 16444 config('colour-picker-events', [ 16445 run$1(fieldsUpdate, onFieldsUpdate()), 16446 run$1(paletteUpdate, onPaletteUpdate()), 16447 run$1(sliderUpdate, onSliderUpdate()) 16448 ]), 16449 Composing.config({ 16450 find: function (comp) { 16451 return memRgb.getOpt(comp); 16452 } 16453 }), 16454 Keying.config({ mode: 'acyclic' }) 16455 ]) 16456 }; 16457 }; 16458 var colourPickerSketcher = single({ 16459 name: 'ColourPicker', 16460 configFields: [ 16461 required$1('dom'), 16462 defaulted('onValidHex', noop), 16463 defaulted('onInvalidHex', noop) 16464 ], 16465 factory: factory 16466 }); 16467 return colourPickerSketcher; 16468 }; 16469 16470 var self$1 = function () { 16471 return Composing.config({ find: Optional.some }); 16472 }; 16473 var memento$1 = function (mem) { 16474 return Composing.config({ find: mem.getOpt }); 16475 }; 16476 var childAt = function (index) { 16477 return Composing.config({ 16478 find: function (comp) { 16479 return child$2(comp.element, index).bind(function (element) { 16480 return comp.getSystem().getByDom(element).toOptional(); 16481 }); 16482 } 16483 }); 16484 }; 16485 var ComposingConfigs = { 16486 self: self$1, 16487 memento: memento$1, 16488 childAt: childAt 16489 }; 16490 16491 var english = { 16492 'colorcustom.rgb.red.label': 'R', 16493 'colorcustom.rgb.red.description': 'Red component', 16494 'colorcustom.rgb.green.label': 'G', 16495 'colorcustom.rgb.green.description': 'Green component', 16496 'colorcustom.rgb.blue.label': 'B', 16497 'colorcustom.rgb.blue.description': 'Blue component', 16498 'colorcustom.rgb.hex.label': '#', 16499 'colorcustom.rgb.hex.description': 'Hex color code', 16500 'colorcustom.rgb.range': 'Range 0 to 255', 16501 'colorcustom.sb.saturation': 'Saturation', 16502 'colorcustom.sb.brightness': 'Brightness', 16503 'colorcustom.sb.picker': 'Saturation and Brightness Picker', 16504 'colorcustom.sb.palette': 'Saturation and Brightness Palette', 16505 'colorcustom.sb.instructions': 'Use arrow keys to select saturation and brightness, on x and y axes', 16506 'colorcustom.hue.hue': 'Hue', 16507 'colorcustom.hue.slider': 'Hue Slider', 16508 'colorcustom.hue.palette': 'Hue Palette', 16509 'colorcustom.hue.instructions': 'Use arrow keys to select a hue', 16510 'aria.color.picker': 'Color Picker', 16511 'aria.input.invalid': 'Invalid input' 16512 }; 16513 var getEnglishText = function (key) { 16514 return english[key]; 16515 }; 16516 var translate$1 = function (key) { 16517 return getEnglishText(key); 16518 }; 16519 var renderColorPicker = function (_spec) { 16520 var getClass = function (key) { 16521 return 'tox-' + key; 16522 }; 16523 var colourPickerFactory = makeFactory(translate$1, getClass); 16524 var onValidHex = function (form) { 16525 emitWith(form, formActionEvent, { 16526 name: 'hex-valid', 16527 value: true 16528 }); 16529 }; 16530 var onInvalidHex = function (form) { 16531 emitWith(form, formActionEvent, { 16532 name: 'hex-valid', 16533 value: false 16534 }); 16535 }; 16536 var memPicker = record(colourPickerFactory.sketch({ 16537 dom: { 16538 tag: 'div', 16539 classes: [getClass('color-picker-container')], 16540 attributes: { role: 'presentation' } 16541 }, 16542 onValidHex: onValidHex, 16543 onInvalidHex: onInvalidHex 16544 })); 16545 return { 16546 dom: { tag: 'div' }, 16547 components: [memPicker.asSpec()], 16548 behaviours: derive$1([ 16549 Representing.config({ 16550 store: { 16551 mode: 'manual', 16552 getValue: function (comp) { 16553 var picker = memPicker.get(comp); 16554 var optRgbForm = Composing.getCurrent(picker); 16555 var optHex = optRgbForm.bind(function (rgbForm) { 16556 var formValues = Representing.getValue(rgbForm); 16557 return formValues.hex; 16558 }); 16559 return optHex.map(function (hex) { 16560 return '#' + hex; 16561 }).getOr(''); 16562 }, 16563 setValue: function (comp, newValue) { 16564 var pattern = /^#([a-fA-F0-9]{3}(?:[a-fA-F0-9]{3})?)/; 16565 var m = pattern.exec(newValue); 16566 var picker = memPicker.get(comp); 16567 var optRgbForm = Composing.getCurrent(picker); 16568 optRgbForm.fold(function () { 16569 console.log('Can not find form'); 16570 }, function (rgbForm) { 16571 Representing.setValue(rgbForm, { hex: Optional.from(m[1]).getOr('') }); 16572 Form.getField(rgbForm, 'hex').each(function (hexField) { 16573 emit(hexField, input()); 16574 }); 16575 }); 16576 } 16577 } 16578 }), 16579 ComposingConfigs.self() 16580 ]) 16581 }; 16582 }; 16583 16584 var global$6 = tinymce.util.Tools.resolve('tinymce.Resource'); 16585 16586 var isOldCustomEditor = function (spec) { 16587 return has$2(spec, 'init'); 16588 }; 16589 var renderCustomEditor = function (spec) { 16590 var editorApi = value$1(); 16591 var memReplaced = record({ dom: { tag: spec.tag } }); 16592 var initialValue = value$1(); 16593 return { 16594 dom: { 16595 tag: 'div', 16596 classes: ['tox-custom-editor'] 16597 }, 16598 behaviours: derive$1([ 16599 config('custom-editor-events', [runOnAttached(function (component) { 16600 memReplaced.getOpt(component).each(function (ta) { 16601 (isOldCustomEditor(spec) ? spec.init(ta.element.dom) : global$6.load(spec.scriptId, spec.scriptUrl).then(function (init) { 16602 return init(ta.element.dom, spec.settings); 16603 })).then(function (ea) { 16604 initialValue.on(function (cvalue) { 16605 ea.setValue(cvalue); 16606 }); 16607 initialValue.clear(); 16608 editorApi.set(ea); 16609 }); 16610 }); 16611 })]), 16612 Representing.config({ 16613 store: { 16614 mode: 'manual', 16615 getValue: function () { 16616 return editorApi.get().fold(function () { 16617 return initialValue.get().getOr(''); 16618 }, function (ed) { 16619 return ed.getValue(); 16620 }); 16621 }, 16622 setValue: function (component, value) { 16623 editorApi.get().fold(function () { 16624 initialValue.set(value); 16625 }, function (ed) { 16626 return ed.setValue(value); 16627 }); 16628 } 16629 } 16630 }), 16631 ComposingConfigs.self() 16632 ]), 16633 components: [memReplaced.asSpec()] 16634 }; 16635 }; 16636 16637 var global$5 = tinymce.util.Tools.resolve('tinymce.util.Tools'); 16638 16639 var processors = objOf([ 16640 defaulted('preprocess', identity$1), 16641 defaulted('postprocess', identity$1) 16642 ]); 16643 var memento = function (mem, rawProcessors) { 16644 var ps = asRawOrDie$1('RepresentingConfigs.memento processors', processors, rawProcessors); 16645 return Representing.config({ 16646 store: { 16647 mode: 'manual', 16648 getValue: function (comp) { 16649 var other = mem.get(comp); 16650 var rawValue = Representing.getValue(other); 16651 return ps.postprocess(rawValue); 16652 }, 16653 setValue: function (comp, rawValue) { 16654 var newValue = ps.preprocess(rawValue); 16655 var other = mem.get(comp); 16656 Representing.setValue(other, newValue); 16657 } 16658 } 16659 }); 16660 }; 16661 var withComp = function (optInitialValue, getter, setter) { 16662 return Representing.config(deepMerge({ 16663 store: { 16664 mode: 'manual', 16665 getValue: getter, 16666 setValue: setter 16667 } 16668 }, optInitialValue.map(function (initialValue) { 16669 return { store: { initialValue: initialValue } }; 16670 }).getOr({}))); 16671 }; 16672 var withElement = function (initialValue, getter, setter) { 16673 return withComp(initialValue, function (c) { 16674 return getter(c.element); 16675 }, function (c, v) { 16676 return setter(c.element, v); 16677 }); 16678 }; 16679 var domValue = function (optInitialValue) { 16680 return withElement(optInitialValue, get$5, set$4); 16681 }; 16682 var domHtml = function (optInitialValue) { 16683 return withElement(optInitialValue, get$7, set$5); 16684 }; 16685 var memory = function (initialValue) { 16686 return Representing.config({ 16687 store: { 16688 mode: 'memory', 16689 initialValue: initialValue 16690 } 16691 }); 16692 }; 16693 var RepresentingConfigs = { 16694 memento: memento, 16695 withElement: withElement, 16696 withComp: withComp, 16697 domValue: domValue, 16698 domHtml: domHtml, 16699 memory: memory 16700 }; 16701 16702 var defaultImageFileTypes = 'jpeg,jpg,jpe,jfi,jif,jfif,png,gif,bmp,webp'; 16703 var filterByExtension = function (files, providersBackstage) { 16704 var allowedImageFileTypes = global$5.explode(providersBackstage.getSetting('images_file_types', defaultImageFileTypes, 'string')); 16705 var isFileInAllowedTypes = function (file) { 16706 return exists(allowedImageFileTypes, function (type) { 16707 return endsWith(file.name.toLowerCase(), '.' + type.toLowerCase()); 16708 }); 16709 }; 16710 return filter$2(from(files), isFileInAllowedTypes); 16711 }; 16712 var renderDropZone = function (spec, providersBackstage) { 16713 var stopper = function (_, se) { 16714 se.stop(); 16715 }; 16716 var sequence = function (actions) { 16717 return function (comp, se) { 16718 each$1(actions, function (a) { 16719 a(comp, se); 16720 }); 16721 }; 16722 }; 16723 var onDrop = function (comp, se) { 16724 if (!Disabling.isDisabled(comp)) { 16725 var transferEvent = se.event.raw; 16726 handleFiles(comp, transferEvent.dataTransfer.files); 16727 } 16728 }; 16729 var onSelect = function (component, simulatedEvent) { 16730 var input = simulatedEvent.event.raw.target; 16731 handleFiles(component, input.files); 16732 }; 16733 var handleFiles = function (component, files) { 16734 Representing.setValue(component, filterByExtension(files, providersBackstage)); 16735 emitWith(component, formChangeEvent, { name: spec.name }); 16736 }; 16737 var memInput = record({ 16738 dom: { 16739 tag: 'input', 16740 attributes: { 16741 type: 'file', 16742 accept: 'image/*' 16743 }, 16744 styles: { display: 'none' } 16745 }, 16746 behaviours: derive$1([config('input-file-events', [ 16747 cutter(click()), 16748 cutter(tap()) 16749 ])]) 16750 }); 16751 var renderField = function (s) { 16752 return { 16753 uid: s.uid, 16754 dom: { 16755 tag: 'div', 16756 classes: ['tox-dropzone-container'] 16757 }, 16758 behaviours: derive$1([ 16759 RepresentingConfigs.memory([]), 16760 ComposingConfigs.self(), 16761 Disabling.config({}), 16762 Toggling.config({ 16763 toggleClass: 'dragenter', 16764 toggleOnExecute: false 16765 }), 16766 config('dropzone-events', [ 16767 run$1('dragenter', sequence([ 16768 stopper, 16769 Toggling.toggle 16770 ])), 16771 run$1('dragleave', sequence([ 16772 stopper, 16773 Toggling.toggle 16774 ])), 16775 run$1('dragover', stopper), 16776 run$1('drop', sequence([ 16777 stopper, 16778 onDrop 16779 ])), 16780 run$1(change(), onSelect) 16781 ]) 16782 ]), 16783 components: [{ 16784 dom: { 16785 tag: 'div', 16786 classes: ['tox-dropzone'], 16787 styles: {} 16788 }, 16789 components: [ 16790 { 16791 dom: { 16792 tag: 'p', 16793 innerHtml: providersBackstage.translate('Drop an image here') 16794 } 16795 }, 16796 Button.sketch({ 16797 dom: { 16798 tag: 'button', 16799 innerHtml: providersBackstage.translate('Browse for an image'), 16800 styles: { position: 'relative' }, 16801 classes: [ 16802 'tox-button', 16803 'tox-button--secondary' 16804 ] 16805 }, 16806 components: [memInput.asSpec()], 16807 action: function (comp) { 16808 var inputComp = memInput.get(comp); 16809 inputComp.element.dom.click(); 16810 }, 16811 buttonBehaviours: derive$1([ 16812 Tabstopping.config({}), 16813 DisablingConfigs.button(providersBackstage.isDisabled), 16814 receivingConfig() 16815 ]) 16816 }) 16817 ] 16818 }] 16819 }; 16820 }; 16821 var pLabel = spec.label.map(function (label) { 16822 return renderLabel$2(label, providersBackstage); 16823 }); 16824 var pField = FormField.parts.field({ factory: { sketch: renderField } }); 16825 return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []); 16826 }; 16827 16828 var renderGrid = function (spec, backstage) { 16829 return { 16830 dom: { 16831 tag: 'div', 16832 classes: [ 16833 'tox-form__grid', 16834 'tox-form__grid--' + spec.columns + 'col' 16835 ] 16836 }, 16837 components: map$2(spec.items, backstage.interpreter) 16838 }; 16839 }; 16840 16841 var beforeObject = generate$6('alloy-fake-before-tabstop'); 16842 var afterObject = generate$6('alloy-fake-after-tabstop'); 16843 var craftWithClasses = function (classes) { 16844 return { 16845 dom: { 16846 tag: 'div', 16847 styles: { 16848 width: '1px', 16849 height: '1px', 16850 outline: 'none' 16851 }, 16852 attributes: { tabindex: '0' }, 16853 classes: classes 16854 }, 16855 behaviours: derive$1([ 16856 Focusing.config({ ignore: true }), 16857 Tabstopping.config({}) 16858 ]) 16859 }; 16860 }; 16861 var craft = function (spec) { 16862 return { 16863 dom: { 16864 tag: 'div', 16865 classes: ['tox-navobj'] 16866 }, 16867 components: [ 16868 craftWithClasses([beforeObject]), 16869 spec, 16870 craftWithClasses([afterObject]) 16871 ], 16872 behaviours: derive$1([ComposingConfigs.childAt(1)]) 16873 }; 16874 }; 16875 var triggerTab = function (placeholder, shiftKey) { 16876 emitWith(placeholder, keydown(), { 16877 raw: { 16878 which: 9, 16879 shiftKey: shiftKey 16880 } 16881 }); 16882 }; 16883 var onFocus = function (container, targetComp) { 16884 var target = targetComp.element; 16885 if (has(target, beforeObject)) { 16886 triggerTab(container, true); 16887 } else if (has(target, afterObject)) { 16888 triggerTab(container, false); 16889 } 16890 }; 16891 var isPseudoStop = function (element) { 16892 return closest(element, [ 16893 '.' + beforeObject, 16894 '.' + afterObject 16895 ].join(','), never); 16896 }; 16897 16898 var platformNeedsSandboxing = !(detect$1().browser.isIE() || detect$1().browser.isEdge()); 16899 var getDynamicSource = function (isSandbox) { 16900 var cachedValue = Cell(''); 16901 return { 16902 getValue: function (_frameComponent) { 16903 return cachedValue.get(); 16904 }, 16905 setValue: function (frameComponent, html) { 16906 if (!isSandbox) { 16907 set$8(frameComponent.element, 'src', 'javascript:\'\''); 16908 var doc = frameComponent.element.dom.contentWindow.document; 16909 doc.open(); 16910 doc.write(html); 16911 doc.close(); 16912 } else { 16913 set$8(frameComponent.element, 'srcdoc', html); 16914 } 16915 cachedValue.set(html); 16916 } 16917 }; 16918 }; 16919 var renderIFrame = function (spec, providersBackstage) { 16920 var isSandbox = platformNeedsSandboxing && spec.sandboxed; 16921 var attributes = __assign(__assign({}, spec.label.map(function (title) { 16922 return { title: title }; 16923 }).getOr({})), isSandbox ? { sandbox: 'allow-scripts allow-same-origin' } : {}); 16924 var sourcing = getDynamicSource(isSandbox); 16925 var pLabel = spec.label.map(function (label) { 16926 return renderLabel$2(label, providersBackstage); 16927 }); 16928 var factory = function (newSpec) { 16929 return craft({ 16930 uid: newSpec.uid, 16931 dom: { 16932 tag: 'iframe', 16933 attributes: attributes 16934 }, 16935 behaviours: derive$1([ 16936 Tabstopping.config({}), 16937 Focusing.config({}), 16938 RepresentingConfigs.withComp(Optional.none(), sourcing.getValue, sourcing.setValue) 16939 ]) 16940 }); 16941 }; 16942 var pField = FormField.parts.field({ factory: { sketch: factory } }); 16943 return renderFormFieldWith(pLabel, pField, ['tox-form__group--stretched'], []); 16944 }; 16945 16946 var create$3 = function (width, height) { 16947 return resize$3(document.createElement('canvas'), width, height); 16948 }; 16949 var clone = function (canvas) { 16950 var tCanvas = create$3(canvas.width, canvas.height); 16951 var ctx = get2dContext(tCanvas); 16952 ctx.drawImage(canvas, 0, 0); 16953 return tCanvas; 16954 }; 16955 var get2dContext = function (canvas) { 16956 return canvas.getContext('2d'); 16957 }; 16958 var resize$3 = function (canvas, width, height) { 16959 canvas.width = width; 16960 canvas.height = height; 16961 return canvas; 16962 }; 16963 16964 var getWidth$1 = function (image) { 16965 return image.naturalWidth || image.width; 16966 }; 16967 var getHeight$1 = function (image) { 16968 return image.naturalHeight || image.height; 16969 }; 16970 16971 var blobToImage = function (blob) { 16972 return new Promise$1(function (resolve, reject) { 16973 var blobUrl = URL.createObjectURL(blob); 16974 var image = new Image(); 16975 var removeListeners = function () { 16976 image.removeEventListener('load', loaded); 16977 image.removeEventListener('error', error); 16978 }; 16979 var loaded = function () { 16980 removeListeners(); 16981 resolve(image); 16982 }; 16983 var error = function () { 16984 removeListeners(); 16985 reject('Unable to load data of type ' + blob.type + ': ' + blobUrl); 16986 }; 16987 image.addEventListener('load', loaded); 16988 image.addEventListener('error', error); 16989 image.src = blobUrl; 16990 if (image.complete) { 16991 setTimeout(loaded, 0); 16992 } 16993 }); 16994 }; 16995 var dataUriToBlobSync = function (uri) { 16996 var data = uri.split(','); 16997 var matches = /data:([^;]+)/.exec(data[0]); 16998 if (!matches) { 16999 return Optional.none(); 17000 } 17001 var mimetype = matches[1]; 17002 var base64 = data[1]; 17003 var sliceSize = 1024; 17004 var byteCharacters = atob(base64); 17005 var bytesLength = byteCharacters.length; 17006 var slicesCount = Math.ceil(bytesLength / sliceSize); 17007 var byteArrays = new Array(slicesCount); 17008 for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) { 17009 var begin = sliceIndex * sliceSize; 17010 var end = Math.min(begin + sliceSize, bytesLength); 17011 var bytes = new Array(end - begin); 17012 for (var offset = begin, i = 0; offset < end; ++i, ++offset) { 17013 bytes[i] = byteCharacters[offset].charCodeAt(0); 17014 } 17015 byteArrays[sliceIndex] = new Uint8Array(bytes); 17016 } 17017 return Optional.some(new Blob(byteArrays, { type: mimetype })); 17018 }; 17019 var dataUriToBlob = function (uri) { 17020 return new Promise$1(function (resolve, reject) { 17021 dataUriToBlobSync(uri).fold(function () { 17022 reject('uri is not base64: ' + uri); 17023 }, resolve); 17024 }); 17025 }; 17026 var canvasToBlob = function (canvas, type, quality) { 17027 type = type || 'image/png'; 17028 if (isFunction(HTMLCanvasElement.prototype.toBlob)) { 17029 return new Promise$1(function (resolve, reject) { 17030 canvas.toBlob(function (blob) { 17031 if (blob) { 17032 resolve(blob); 17033 } else { 17034 reject(); 17035 } 17036 }, type, quality); 17037 }); 17038 } else { 17039 return dataUriToBlob(canvas.toDataURL(type, quality)); 17040 } 17041 }; 17042 var canvasToDataURL = function (canvas, type, quality) { 17043 type = type || 'image/png'; 17044 return canvas.toDataURL(type, quality); 17045 }; 17046 var blobToCanvas = function (blob) { 17047 return blobToImage(blob).then(function (image) { 17048 revokeImageUrl(image); 17049 var canvas = create$3(getWidth$1(image), getHeight$1(image)); 17050 var context = get2dContext(canvas); 17051 context.drawImage(image, 0, 0); 17052 return canvas; 17053 }); 17054 }; 17055 var blobToDataUri = function (blob) { 17056 return new Promise$1(function (resolve) { 17057 var reader = new FileReader(); 17058 reader.onloadend = function () { 17059 resolve(reader.result); 17060 }; 17061 reader.readAsDataURL(blob); 17062 }); 17063 }; 17064 var revokeImageUrl = function (image) { 17065 URL.revokeObjectURL(image.src); 17066 }; 17067 17068 var create$2 = function (getCanvas, blob, uri) { 17069 var initialType = blob.type; 17070 var getType = constant$1(initialType); 17071 var toBlob = function () { 17072 return Promise$1.resolve(blob); 17073 }; 17074 var toDataURL = constant$1(uri); 17075 var toBase64 = function () { 17076 return uri.split(',')[1]; 17077 }; 17078 var toAdjustedBlob = function (type, quality) { 17079 return getCanvas.then(function (canvas) { 17080 return canvasToBlob(canvas, type, quality); 17081 }); 17082 }; 17083 var toAdjustedDataURL = function (type, quality) { 17084 return getCanvas.then(function (canvas) { 17085 return canvasToDataURL(canvas, type, quality); 17086 }); 17087 }; 17088 var toAdjustedBase64 = function (type, quality) { 17089 return toAdjustedDataURL(type, quality).then(function (dataurl) { 17090 return dataurl.split(',')[1]; 17091 }); 17092 }; 17093 var toCanvas = function () { 17094 return getCanvas.then(clone); 17095 }; 17096 return { 17097 getType: getType, 17098 toBlob: toBlob, 17099 toDataURL: toDataURL, 17100 toBase64: toBase64, 17101 toAdjustedBlob: toAdjustedBlob, 17102 toAdjustedDataURL: toAdjustedDataURL, 17103 toAdjustedBase64: toAdjustedBase64, 17104 toCanvas: toCanvas 17105 }; 17106 }; 17107 var fromBlob = function (blob) { 17108 return blobToDataUri(blob).then(function (uri) { 17109 return create$2(blobToCanvas(blob), blob, uri); 17110 }); 17111 }; 17112 var fromCanvas = function (canvas, type) { 17113 return canvasToBlob(canvas, type).then(function (blob) { 17114 return create$2(Promise$1.resolve(canvas), blob, canvas.toDataURL()); 17115 }); 17116 }; 17117 17118 var blobToImageResult = function (blob) { 17119 return fromBlob(blob); 17120 }; 17121 17122 var clamp = function (value, min, max) { 17123 var parsedValue = typeof value === 'string' ? parseFloat(value) : value; 17124 if (parsedValue > max) { 17125 parsedValue = max; 17126 } else if (parsedValue < min) { 17127 parsedValue = min; 17128 } 17129 return parsedValue; 17130 }; 17131 var identity = function () { 17132 return [ 17133 1, 17134 0, 17135 0, 17136 0, 17137 0, 17138 0, 17139 1, 17140 0, 17141 0, 17142 0, 17143 0, 17144 0, 17145 1, 17146 0, 17147 0, 17148 0, 17149 0, 17150 0, 17151 1, 17152 0, 17153 0, 17154 0, 17155 0, 17156 0, 17157 1 17158 ]; 17159 }; 17160 var DELTA_INDEX = [ 17161 0, 17162 0.01, 17163 0.02, 17164 0.04, 17165 0.05, 17166 0.06, 17167 0.07, 17168 0.08, 17169 0.1, 17170 0.11, 17171 0.12, 17172 0.14, 17173 0.15, 17174 0.16, 17175 0.17, 17176 0.18, 17177 0.2, 17178 0.21, 17179 0.22, 17180 0.24, 17181 0.25, 17182 0.27, 17183 0.28, 17184 0.3, 17185 0.32, 17186 0.34, 17187 0.36, 17188 0.38, 17189 0.4, 17190 0.42, 17191 0.44, 17192 0.46, 17193 0.48, 17194 0.5, 17195 0.53, 17196 0.56, 17197 0.59, 17198 0.62, 17199 0.65, 17200 0.68, 17201 0.71, 17202 0.74, 17203 0.77, 17204 0.8, 17205 0.83, 17206 0.86, 17207 0.89, 17208 0.92, 17209 0.95, 17210 0.98, 17211 1, 17212 1.06, 17213 1.12, 17214 1.18, 17215 1.24, 17216 1.3, 17217 1.36, 17218 1.42, 17219 1.48, 17220 1.54, 17221 1.6, 17222 1.66, 17223 1.72, 17224 1.78, 17225 1.84, 17226 1.9, 17227 1.96, 17228 2, 17229 2.12, 17230 2.25, 17231 2.37, 17232 2.5, 17233 2.62, 17234 2.75, 17235 2.87, 17236 3, 17237 3.2, 17238 3.4, 17239 3.6, 17240 3.8, 17241 4, 17242 4.3, 17243 4.7, 17244 4.9, 17245 5, 17246 5.5, 17247 6, 17248 6.5, 17249 6.8, 17250 7, 17251 7.3, 17252 7.5, 17253 7.8, 17254 8, 17255 8.4, 17256 8.7, 17257 9, 17258 9.4, 17259 9.6, 17260 9.8, 17261 10 17262 ]; 17263 var multiply = function (matrix1, matrix2) { 17264 var col = []; 17265 var out = new Array(25); 17266 var val; 17267 for (var i = 0; i < 5; i++) { 17268 for (var j = 0; j < 5; j++) { 17269 col[j] = matrix2[j + i * 5]; 17270 } 17271 for (var j = 0; j < 5; j++) { 17272 val = 0; 17273 for (var k = 0; k < 5; k++) { 17274 val += matrix1[j + k * 5] * col[k]; 17275 } 17276 out[j + i * 5] = val; 17277 } 17278 } 17279 return out; 17280 }; 17281 var adjustContrast = function (matrix, value) { 17282 var x; 17283 value = clamp(value, -1, 1); 17284 value *= 100; 17285 if (value < 0) { 17286 x = 127 + value / 100 * 127; 17287 } else { 17288 x = value % 1; 17289 if (x === 0) { 17290 x = DELTA_INDEX[value]; 17291 } else { 17292 x = DELTA_INDEX[Math.floor(value)] * (1 - x) + DELTA_INDEX[Math.floor(value) + 1] * x; 17293 } 17294 x = x * 127 + 127; 17295 } 17296 return multiply(matrix, [ 17297 x / 127, 17298 0, 17299 0, 17300 0, 17301 0.5 * (127 - x), 17302 0, 17303 x / 127, 17304 0, 17305 0, 17306 0.5 * (127 - x), 17307 0, 17308 0, 17309 x / 127, 17310 0, 17311 0.5 * (127 - x), 17312 0, 17313 0, 17314 0, 17315 1, 17316 0, 17317 0, 17318 0, 17319 0, 17320 0, 17321 1 17322 ]); 17323 }; 17324 var adjustBrightness = function (matrix, value) { 17325 value = clamp(255 * value, -255, 255); 17326 return multiply(matrix, [ 17327 1, 17328 0, 17329 0, 17330 0, 17331 value, 17332 0, 17333 1, 17334 0, 17335 0, 17336 value, 17337 0, 17338 0, 17339 1, 17340 0, 17341 value, 17342 0, 17343 0, 17344 0, 17345 1, 17346 0, 17347 0, 17348 0, 17349 0, 17350 0, 17351 1 17352 ]); 17353 }; 17354 var adjustColors = function (matrix, adjustR, adjustG, adjustB) { 17355 adjustR = clamp(adjustR, 0, 2); 17356 adjustG = clamp(adjustG, 0, 2); 17357 adjustB = clamp(adjustB, 0, 2); 17358 return multiply(matrix, [ 17359 adjustR, 17360 0, 17361 0, 17362 0, 17363 0, 17364 0, 17365 adjustG, 17366 0, 17367 0, 17368 0, 17369 0, 17370 0, 17371 adjustB, 17372 0, 17373 0, 17374 0, 17375 0, 17376 0, 17377 1, 17378 0, 17379 0, 17380 0, 17381 0, 17382 0, 17383 1 17384 ]); 17385 }; 17386 17387 var colorFilter = function (ir, matrix) { 17388 return ir.toCanvas().then(function (canvas) { 17389 return applyColorFilter(canvas, ir.getType(), matrix); 17390 }); 17391 }; 17392 var applyColorFilter = function (canvas, type, matrix) { 17393 var context = get2dContext(canvas); 17394 var applyMatrix = function (pixelsData, m) { 17395 var r, g, b, a; 17396 var data = pixelsData.data, m0 = m[0], m1 = m[1], m2 = m[2], m3 = m[3], m4 = m[4], m5 = m[5], m6 = m[6], m7 = m[7], m8 = m[8], m9 = m[9], m10 = m[10], m11 = m[11], m12 = m[12], m13 = m[13], m14 = m[14], m15 = m[15], m16 = m[16], m17 = m[17], m18 = m[18], m19 = m[19]; 17397 for (var i = 0; i < data.length; i += 4) { 17398 r = data[i]; 17399 g = data[i + 1]; 17400 b = data[i + 2]; 17401 a = data[i + 3]; 17402 data[i] = r * m0 + g * m1 + b * m2 + a * m3 + m4; 17403 data[i + 1] = r * m5 + g * m6 + b * m7 + a * m8 + m9; 17404 data[i + 2] = r * m10 + g * m11 + b * m12 + a * m13 + m14; 17405 data[i + 3] = r * m15 + g * m16 + b * m17 + a * m18 + m19; 17406 } 17407 return pixelsData; 17408 }; 17409 var pixels = applyMatrix(context.getImageData(0, 0, canvas.width, canvas.height), matrix); 17410 context.putImageData(pixels, 0, 0); 17411 return fromCanvas(canvas, type); 17412 }; 17413 var convoluteFilter = function (ir, matrix) { 17414 return ir.toCanvas().then(function (canvas) { 17415 return applyConvoluteFilter(canvas, ir.getType(), matrix); 17416 }); 17417 }; 17418 var applyConvoluteFilter = function (canvas, type, matrix) { 17419 var context = get2dContext(canvas); 17420 var applyMatrix = function (pIn, pOut, aMatrix) { 17421 var clamp = function (value, min, max) { 17422 if (value > max) { 17423 value = max; 17424 } else if (value < min) { 17425 value = min; 17426 } 17427 return value; 17428 }; 17429 var side = Math.round(Math.sqrt(aMatrix.length)); 17430 var halfSide = Math.floor(side / 2); 17431 var rgba = pIn.data; 17432 var drgba = pOut.data; 17433 var w = pIn.width; 17434 var h = pIn.height; 17435 for (var y = 0; y < h; y++) { 17436 for (var x = 0; x < w; x++) { 17437 var r = 0; 17438 var g = 0; 17439 var b = 0; 17440 for (var cy = 0; cy < side; cy++) { 17441 for (var cx = 0; cx < side; cx++) { 17442 var scx = clamp(x + cx - halfSide, 0, w - 1); 17443 var scy = clamp(y + cy - halfSide, 0, h - 1); 17444 var innerOffset = (scy * w + scx) * 4; 17445 var wt = aMatrix[cy * side + cx]; 17446 r += rgba[innerOffset] * wt; 17447 g += rgba[innerOffset + 1] * wt; 17448 b += rgba[innerOffset + 2] * wt; 17449 } 17450 } 17451 var offset = (y * w + x) * 4; 17452 drgba[offset] = clamp(r, 0, 255); 17453 drgba[offset + 1] = clamp(g, 0, 255); 17454 drgba[offset + 2] = clamp(b, 0, 255); 17455 } 17456 } 17457 return pOut; 17458 }; 17459 var pixelsIn = context.getImageData(0, 0, canvas.width, canvas.height); 17460 var pixelsOut = context.getImageData(0, 0, canvas.width, canvas.height); 17461 pixelsOut = applyMatrix(pixelsIn, pixelsOut, matrix); 17462 context.putImageData(pixelsOut, 0, 0); 17463 return fromCanvas(canvas, type); 17464 }; 17465 var functionColorFilter = function (colorFn) { 17466 var filterImpl = function (canvas, type, value) { 17467 var context = get2dContext(canvas); 17468 var lookup = new Array(256); 17469 var applyLookup = function (pixelsData, lookupData) { 17470 var data = pixelsData.data; 17471 for (var i = 0; i < data.length; i += 4) { 17472 data[i] = lookupData[data[i]]; 17473 data[i + 1] = lookupData[data[i + 1]]; 17474 data[i + 2] = lookupData[data[i + 2]]; 17475 } 17476 return pixelsData; 17477 }; 17478 for (var i = 0; i < lookup.length; i++) { 17479 lookup[i] = colorFn(i, value); 17480 } 17481 var pixels = applyLookup(context.getImageData(0, 0, canvas.width, canvas.height), lookup); 17482 context.putImageData(pixels, 0, 0); 17483 return fromCanvas(canvas, type); 17484 }; 17485 return function (ir, value) { 17486 return ir.toCanvas().then(function (canvas) { 17487 return filterImpl(canvas, ir.getType(), value); 17488 }); 17489 }; 17490 }; 17491 var complexAdjustableColorFilter = function (matrixAdjustFn) { 17492 return function (ir, adjust) { 17493 return colorFilter(ir, matrixAdjustFn(identity(), adjust)); 17494 }; 17495 }; 17496 var basicColorFilter = function (matrix) { 17497 return function (ir) { 17498 return colorFilter(ir, matrix); 17499 }; 17500 }; 17501 var basicConvolutionFilter = function (kernel) { 17502 return function (ir) { 17503 return convoluteFilter(ir, kernel); 17504 }; 17505 }; 17506 var invert$1 = basicColorFilter([ 17507 -1, 17508 0, 17509 0, 17510 0, 17511 255, 17512 0, 17513 -1, 17514 0, 17515 0, 17516 255, 17517 0, 17518 0, 17519 -1, 17520 0, 17521 255, 17522 0, 17523 0, 17524 0, 17525 1, 17526 0, 17527 0, 17528 0, 17529 0, 17530 0, 17531 1 17532 ]); 17533 var brightness$1 = complexAdjustableColorFilter(adjustBrightness); 17534 var contrast$1 = complexAdjustableColorFilter(adjustContrast); 17535 var colorize$1 = function (ir, adjustR, adjustG, adjustB) { 17536 return colorFilter(ir, adjustColors(identity(), adjustR, adjustG, adjustB)); 17537 }; 17538 var sharpen$1 = basicConvolutionFilter([ 17539 0, 17540 -1, 17541 0, 17542 -1, 17543 5, 17544 -1, 17545 0, 17546 -1, 17547 0 17548 ]); 17549 var gamma$1 = functionColorFilter(function (color, value) { 17550 return Math.pow(color / 255, 1 - value) * 255; 17551 }); 17552 17553 var scale = function (image, dW, dH) { 17554 var sW = getWidth$1(image); 17555 var sH = getHeight$1(image); 17556 var wRatio = dW / sW; 17557 var hRatio = dH / sH; 17558 var scaleCapped = false; 17559 if (wRatio < 0.5 || wRatio > 2) { 17560 wRatio = wRatio < 0.5 ? 0.5 : 2; 17561 scaleCapped = true; 17562 } 17563 if (hRatio < 0.5 || hRatio > 2) { 17564 hRatio = hRatio < 0.5 ? 0.5 : 2; 17565 scaleCapped = true; 17566 } 17567 var scaled = _scale(image, wRatio, hRatio); 17568 return !scaleCapped ? scaled : scaled.then(function (tCanvas) { 17569 return scale(tCanvas, dW, dH); 17570 }); 17571 }; 17572 var _scale = function (image, wRatio, hRatio) { 17573 return new Promise$1(function (resolve) { 17574 var sW = getWidth$1(image); 17575 var sH = getHeight$1(image); 17576 var dW = Math.floor(sW * wRatio); 17577 var dH = Math.floor(sH * hRatio); 17578 var canvas = create$3(dW, dH); 17579 var context = get2dContext(canvas); 17580 context.drawImage(image, 0, 0, sW, sH, 0, 0, dW, dH); 17581 resolve(canvas); 17582 }); 17583 }; 17584 17585 var ceilWithPrecision = function (num, precision) { 17586 if (precision === void 0) { 17587 precision = 2; 17588 } 17589 var mul = Math.pow(10, precision); 17590 var upper = Math.round(num * mul); 17591 return Math.ceil(upper / mul); 17592 }; 17593 var rotate$1 = function (ir, angle) { 17594 return ir.toCanvas().then(function (canvas) { 17595 return applyRotate(canvas, ir.getType(), angle); 17596 }); 17597 }; 17598 var applyRotate = function (image, type, angle) { 17599 var degrees = angle < 0 ? 360 + angle : angle; 17600 var rad = degrees * Math.PI / 180; 17601 var width = image.width; 17602 var height = image.height; 17603 var sin = Math.sin(rad); 17604 var cos = Math.cos(rad); 17605 var newWidth = ceilWithPrecision(Math.abs(width * cos) + Math.abs(height * sin)); 17606 var newHeight = ceilWithPrecision(Math.abs(width * sin) + Math.abs(height * cos)); 17607 var canvas = create$3(newWidth, newHeight); 17608 var context = get2dContext(canvas); 17609 context.translate(newWidth / 2, newHeight / 2); 17610 context.rotate(rad); 17611 context.drawImage(image, -width / 2, -height / 2); 17612 return fromCanvas(canvas, type); 17613 }; 17614 var flip$1 = function (ir, axis) { 17615 return ir.toCanvas().then(function (canvas) { 17616 return applyFlip(canvas, ir.getType(), axis); 17617 }); 17618 }; 17619 var applyFlip = function (image, type, axis) { 17620 var canvas = create$3(image.width, image.height); 17621 var context = get2dContext(canvas); 17622 if (axis === 'v') { 17623 context.scale(1, -1); 17624 context.drawImage(image, 0, -canvas.height); 17625 } else { 17626 context.scale(-1, 1); 17627 context.drawImage(image, -canvas.width, 0); 17628 } 17629 return fromCanvas(canvas, type); 17630 }; 17631 var crop$1 = function (ir, x, y, w, h) { 17632 return ir.toCanvas().then(function (canvas) { 17633 return applyCrop(canvas, ir.getType(), x, y, w, h); 17634 }); 17635 }; 17636 var applyCrop = function (image, type, x, y, w, h) { 17637 var canvas = create$3(w, h); 17638 var context = get2dContext(canvas); 17639 context.drawImage(image, -x, -y); 17640 return fromCanvas(canvas, type); 17641 }; 17642 var resize$2 = function (ir, w, h) { 17643 return ir.toCanvas().then(function (canvas) { 17644 return scale(canvas, w, h).then(function (newCanvas) { 17645 return fromCanvas(newCanvas, ir.getType()); 17646 }); 17647 }); 17648 }; 17649 17650 var invert = function (ir) { 17651 return invert$1(ir); 17652 }; 17653 var sharpen = function (ir) { 17654 return sharpen$1(ir); 17655 }; 17656 var gamma = function (ir, value) { 17657 return gamma$1(ir, value); 17658 }; 17659 var colorize = function (ir, adjustR, adjustG, adjustB) { 17660 return colorize$1(ir, adjustR, adjustG, adjustB); 17661 }; 17662 var brightness = function (ir, adjust) { 17663 return brightness$1(ir, adjust); 17664 }; 17665 var contrast = function (ir, adjust) { 17666 return contrast$1(ir, adjust); 17667 }; 17668 var flip = function (ir, axis) { 17669 return flip$1(ir, axis); 17670 }; 17671 var crop = function (ir, x, y, w, h) { 17672 return crop$1(ir, x, y, w, h); 17673 }; 17674 var resize$1 = function (ir, w, h) { 17675 return resize$2(ir, w, h); 17676 }; 17677 var rotate = function (ir, angle) { 17678 return rotate$1(ir, angle); 17679 }; 17680 17681 var renderIcon = function (iconName, iconsProvider, behaviours) { 17682 return render$3(iconName, { 17683 tag: 'span', 17684 classes: [ 17685 'tox-icon', 17686 'tox-tbtn__icon-wrap' 17687 ], 17688 behaviours: behaviours 17689 }, iconsProvider); 17690 }; 17691 var renderIconFromPack = function (iconName, iconsProvider) { 17692 return renderIcon(iconName, iconsProvider, []); 17693 }; 17694 var renderReplacableIconFromPack = function (iconName, iconsProvider) { 17695 return renderIcon(iconName, iconsProvider, [Replacing.config({})]); 17696 }; 17697 var renderLabel$1 = function (text, prefix, providersBackstage) { 17698 return { 17699 dom: { 17700 tag: 'span', 17701 innerHtml: providersBackstage.translate(text), 17702 classes: [prefix + '__select-label'] 17703 }, 17704 behaviours: derive$1([Replacing.config({})]) 17705 }; 17706 }; 17707 17708 var _a; 17709 var internalToolbarButtonExecute = generate$6('toolbar.button.execute'); 17710 var onToolbarButtonExecute = function (info) { 17711 return runOnExecute$1(function (comp, _simulatedEvent) { 17712 runWithApi(info, comp)(function (itemApi) { 17713 emitWith(comp, internalToolbarButtonExecute, { buttonApi: itemApi }); 17714 info.onAction(itemApi); 17715 }); 17716 }); 17717 }; 17718 var toolbarButtonEventOrder = (_a = {}, _a[execute$5()] = [ 17719 'disabling', 17720 'alloy.base.behaviour', 17721 'toggling', 17722 'toolbar-button-events' 17723 ], _a); 17724 17725 var updateMenuText = generate$6('update-menu-text'); 17726 var updateMenuIcon = generate$6('update-menu-icon'); 17727 var renderCommonDropdown = function (spec, prefix, sharedBackstage) { 17728 var editorOffCell = Cell(noop); 17729 var optMemDisplayText = spec.text.map(function (text) { 17730 return record(renderLabel$1(text, prefix, sharedBackstage.providers)); 17731 }); 17732 var optMemDisplayIcon = spec.icon.map(function (iconName) { 17733 return record(renderReplacableIconFromPack(iconName, sharedBackstage.providers.icons)); 17734 }); 17735 var onLeftOrRightInMenu = function (comp, se) { 17736 var dropdown = Representing.getValue(comp); 17737 Focusing.focus(dropdown); 17738 emitWith(dropdown, 'keydown', { raw: se.event.raw }); 17739 Dropdown.close(dropdown); 17740 return Optional.some(true); 17741 }; 17742 var role = spec.role.fold(function () { 17743 return {}; 17744 }, function (role) { 17745 return { role: role }; 17746 }); 17747 var tooltipAttributes = spec.tooltip.fold(function () { 17748 return {}; 17749 }, function (tooltip) { 17750 var translatedTooltip = sharedBackstage.providers.translate(tooltip); 17751 return { 17752 'title': translatedTooltip, 17753 'aria-label': translatedTooltip 17754 }; 17755 }); 17756 var iconSpec = render$3('chevron-down', { 17757 tag: 'div', 17758 classes: [prefix + '__select-chevron'] 17759 }, sharedBackstage.providers.icons); 17760 var memDropdown = record(Dropdown.sketch(__assign(__assign(__assign({}, spec.uid ? { uid: spec.uid } : {}), role), { 17761 dom: { 17762 tag: 'button', 17763 classes: [ 17764 prefix, 17765 prefix + '--select' 17766 ].concat(map$2(spec.classes, function (c) { 17767 return prefix + '--' + c; 17768 })), 17769 attributes: __assign({}, tooltipAttributes) 17770 }, 17771 components: componentRenderPipeline([ 17772 optMemDisplayIcon.map(function (mem) { 17773 return mem.asSpec(); 17774 }), 17775 optMemDisplayText.map(function (mem) { 17776 return mem.asSpec(); 17777 }), 17778 Optional.some(iconSpec) 17779 ]), 17780 matchWidth: true, 17781 useMinWidth: true, 17782 dropdownBehaviours: derive$1(__spreadArray(__spreadArray([], spec.dropdownBehaviours, true), [ 17783 DisablingConfigs.button(function () { 17784 return spec.disabled || sharedBackstage.providers.isDisabled(); 17785 }), 17786 receivingConfig(), 17787 Unselecting.config({}), 17788 Replacing.config({}), 17789 config('dropdown-events', [ 17790 onControlAttached(spec, editorOffCell), 17791 onControlDetached(spec, editorOffCell) 17792 ]), 17793 config('menubutton-update-display-text', [ 17794 run$1(updateMenuText, function (comp, se) { 17795 optMemDisplayText.bind(function (mem) { 17796 return mem.getOpt(comp); 17797 }).each(function (displayText) { 17798 Replacing.set(displayText, [text(sharedBackstage.providers.translate(se.event.text))]); 17799 }); 17800 }), 17801 run$1(updateMenuIcon, function (comp, se) { 17802 optMemDisplayIcon.bind(function (mem) { 17803 return mem.getOpt(comp); 17804 }).each(function (displayIcon) { 17805 Replacing.set(displayIcon, [renderReplacableIconFromPack(se.event.icon, sharedBackstage.providers.icons)]); 17806 }); 17807 }) 17808 ]) 17809 ], false)), 17810 eventOrder: deepMerge(toolbarButtonEventOrder, { 17811 mousedown: [ 17812 'focusing', 17813 'alloy.base.behaviour', 17814 'item-type-events', 17815 'normal-dropdown-events' 17816 ] 17817 }), 17818 sandboxBehaviours: derive$1([Keying.config({ 17819 mode: 'special', 17820 onLeft: onLeftOrRightInMenu, 17821 onRight: onLeftOrRightInMenu 17822 })]), 17823 lazySink: sharedBackstage.getSink, 17824 toggleClass: prefix + '--active', 17825 parts: { menu: part(false, spec.columns, spec.presets) }, 17826 fetch: function (comp) { 17827 return Future.nu(curry(spec.fetch, comp)); 17828 } 17829 }))); 17830 return memDropdown.asSpec(); 17831 }; 17832 17833 var isMenuItemReference = function (item) { 17834 return isString(item); 17835 }; 17836 var isSeparator$1 = function (item) { 17837 return item.type === 'separator'; 17838 }; 17839 var isExpandingMenuItem = function (item) { 17840 return has$2(item, 'getSubmenuItems'); 17841 }; 17842 var separator$2 = { type: 'separator' }; 17843 var unwrapReferences = function (items, menuItems) { 17844 var realItems = foldl(items, function (acc, item) { 17845 if (isMenuItemReference(item)) { 17846 if (item === '') { 17847 return acc; 17848 } else if (item === '|') { 17849 return acc.length > 0 && !isSeparator$1(acc[acc.length - 1]) ? acc.concat([separator$2]) : acc; 17850 } else if (has$2(menuItems, item.toLowerCase())) { 17851 return acc.concat([menuItems[item.toLowerCase()]]); 17852 } else { 17853 return acc; 17854 } 17855 } else { 17856 return acc.concat([item]); 17857 } 17858 }, []); 17859 if (realItems.length > 0 && isSeparator$1(realItems[realItems.length - 1])) { 17860 realItems.pop(); 17861 } 17862 return realItems; 17863 }; 17864 var getFromExpandingItem = function (item, menuItems) { 17865 var submenuItems = item.getSubmenuItems(); 17866 var rest = expand(submenuItems, menuItems); 17867 var newMenus = deepMerge(rest.menus, wrap$1(item.value, rest.items)); 17868 var newExpansions = deepMerge(rest.expansions, wrap$1(item.value, item.value)); 17869 return { 17870 item: item, 17871 menus: newMenus, 17872 expansions: newExpansions 17873 }; 17874 }; 17875 var getFromItem = function (item, menuItems) { 17876 return isExpandingMenuItem(item) ? getFromExpandingItem(item, menuItems) : { 17877 item: item, 17878 menus: {}, 17879 expansions: {} 17880 }; 17881 }; 17882 var generateValueIfRequired = function (item) { 17883 if (isSeparator$1(item)) { 17884 return item; 17885 } else { 17886 var itemValue = get$e(item, 'value').getOrThunk(function () { 17887 return generate$6('generated-menu-item'); 17888 }); 17889 return deepMerge({ value: itemValue }, item); 17890 } 17891 }; 17892 var expand = function (items, menuItems) { 17893 var realItems = unwrapReferences(isString(items) ? items.split(' ') : items, menuItems); 17894 return foldr(realItems, function (acc, item) { 17895 var itemWithValue = generateValueIfRequired(item); 17896 var newData = getFromItem(itemWithValue, menuItems); 17897 return { 17898 menus: deepMerge(acc.menus, newData.menus), 17899 items: [newData.item].concat(acc.items), 17900 expansions: deepMerge(acc.expansions, newData.expansions) 17901 }; 17902 }, { 17903 menus: {}, 17904 expansions: {}, 17905 items: [] 17906 }); 17907 }; 17908 17909 var build = function (items, itemResponse, backstage, isHorizontalMenu) { 17910 var primary = generate$6('primary-menu'); 17911 var data = expand(items, backstage.shared.providers.menuItems()); 17912 if (data.items.length === 0) { 17913 return Optional.none(); 17914 } 17915 var mainMenu = createPartialMenu(primary, data.items, itemResponse, backstage, isHorizontalMenu); 17916 var submenus = map$1(data.menus, function (menuItems, menuName) { 17917 return createPartialMenu(menuName, menuItems, itemResponse, backstage, false); 17918 }); 17919 var menus = deepMerge(submenus, wrap$1(primary, mainMenu)); 17920 return Optional.from(tieredMenu.tieredData(primary, menus, data.expansions)); 17921 }; 17922 17923 var getMenuButtonApi = function (component) { 17924 return { 17925 isDisabled: function () { 17926 return Disabling.isDisabled(component); 17927 }, 17928 setDisabled: function (state) { 17929 return Disabling.set(component, state); 17930 }, 17931 setActive: function (state) { 17932 var elm = component.element; 17933 if (state) { 17934 add$2(elm, 'tox-tbtn--enabled'); 17935 set$8(elm, 'aria-pressed', true); 17936 } else { 17937 remove$2(elm, 'tox-tbtn--enabled'); 17938 remove$7(elm, 'aria-pressed'); 17939 } 17940 }, 17941 isActive: function () { 17942 return has(component.element, 'tox-tbtn--enabled'); 17943 } 17944 }; 17945 }; 17946 var renderMenuButton = function (spec, prefix, backstage, role) { 17947 return renderCommonDropdown({ 17948 text: spec.text, 17949 icon: spec.icon, 17950 tooltip: spec.tooltip, 17951 role: role, 17952 fetch: function (_comp, callback) { 17953 spec.fetch(function (items) { 17954 callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false)); 17955 }); 17956 }, 17957 onSetup: spec.onSetup, 17958 getApi: getMenuButtonApi, 17959 columns: 1, 17960 presets: 'normal', 17961 classes: [], 17962 dropdownBehaviours: [Tabstopping.config({})] 17963 }, prefix, backstage.shared); 17964 }; 17965 var getFetch = function (items, getButton, backstage) { 17966 var getMenuItemAction = function (item) { 17967 return function (api) { 17968 var newValue = !api.isActive(); 17969 api.setActive(newValue); 17970 item.storage.set(newValue); 17971 backstage.shared.getSink().each(function (sink) { 17972 getButton().getOpt(sink).each(function (orig) { 17973 focus$3(orig.element); 17974 emitWith(orig, formActionEvent, { 17975 name: item.name, 17976 value: item.storage.get() 17977 }); 17978 }); 17979 }); 17980 }; 17981 }; 17982 var getMenuItemSetup = function (item) { 17983 return function (api) { 17984 api.setActive(item.storage.get()); 17985 }; 17986 }; 17987 return function (success) { 17988 success(map$2(items, function (item) { 17989 var text = item.text.fold(function () { 17990 return {}; 17991 }, function (text) { 17992 return { text: text }; 17993 }); 17994 return __assign(__assign({ 17995 type: item.type, 17996 active: false 17997 }, text), { 17998 onAction: getMenuItemAction(item), 17999 onSetup: getMenuItemSetup(item) 18000 }); 18001 })); 18002 }; 18003 }; 18004 18005 var renderCommonSpec = function (spec, actionOpt, extraBehaviours, dom, components, providersBackstage) { 18006 if (extraBehaviours === void 0) { 18007 extraBehaviours = []; 18008 } 18009 var action = actionOpt.fold(function () { 18010 return {}; 18011 }, function (action) { 18012 return { action: action }; 18013 }); 18014 var common = __assign({ 18015 buttonBehaviours: derive$1([ 18016 DisablingConfigs.button(function () { 18017 return spec.disabled || providersBackstage.isDisabled(); 18018 }), 18019 receivingConfig(), 18020 Tabstopping.config({}), 18021 config('button press', [ 18022 preventDefault('click'), 18023 preventDefault('mousedown') 18024 ]) 18025 ].concat(extraBehaviours)), 18026 eventOrder: { 18027 click: [ 18028 'button press', 18029 'alloy.base.behaviour' 18030 ], 18031 mousedown: [ 18032 'button press', 18033 'alloy.base.behaviour' 18034 ] 18035 } 18036 }, action); 18037 var domFinal = deepMerge(common, { dom: dom }); 18038 return deepMerge(domFinal, { components: components }); 18039 }; 18040 var renderIconButtonSpec = function (spec, action, providersBackstage, extraBehaviours) { 18041 if (extraBehaviours === void 0) { 18042 extraBehaviours = []; 18043 } 18044 var tooltipAttributes = spec.tooltip.map(function (tooltip) { 18045 return { 18046 'aria-label': providersBackstage.translate(tooltip), 18047 'title': providersBackstage.translate(tooltip) 18048 }; 18049 }).getOr({}); 18050 var dom = { 18051 tag: 'button', 18052 classes: ['tox-tbtn'], 18053 attributes: tooltipAttributes 18054 }; 18055 var icon = spec.icon.map(function (iconName) { 18056 return renderIconFromPack(iconName, providersBackstage.icons); 18057 }); 18058 var components = componentRenderPipeline([icon]); 18059 return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage); 18060 }; 18061 var renderIconButton = function (spec, action, providersBackstage, extraBehaviours) { 18062 if (extraBehaviours === void 0) { 18063 extraBehaviours = []; 18064 } 18065 var iconButtonSpec = renderIconButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours); 18066 return Button.sketch(iconButtonSpec); 18067 }; 18068 var renderButtonSpec = function (spec, action, providersBackstage, extraBehaviours, extraClasses) { 18069 if (extraBehaviours === void 0) { 18070 extraBehaviours = []; 18071 } 18072 if (extraClasses === void 0) { 18073 extraClasses = []; 18074 } 18075 var translatedText = providersBackstage.translate(spec.text); 18076 var icon = spec.icon ? spec.icon.map(function (iconName) { 18077 return renderIconFromPack(iconName, providersBackstage.icons); 18078 }) : Optional.none(); 18079 var components = icon.isSome() ? componentRenderPipeline([icon]) : []; 18080 var innerHtml = icon.isSome() ? {} : { innerHtml: translatedText }; 18081 var classes = __spreadArray(__spreadArray(__spreadArray(__spreadArray([], !spec.primary && !spec.borderless ? [ 18082 'tox-button', 18083 'tox-button--secondary' 18084 ] : ['tox-button'], true), icon.isSome() ? ['tox-button--icon'] : [], true), spec.borderless ? ['tox-button--naked'] : [], true), extraClasses, true); 18085 var dom = __assign(__assign({ 18086 tag: 'button', 18087 classes: classes 18088 }, innerHtml), { attributes: { title: translatedText } }); 18089 return renderCommonSpec(spec, action, extraBehaviours, dom, components, providersBackstage); 18090 }; 18091 var renderButton = function (spec, action, providersBackstage, extraBehaviours, extraClasses) { 18092 if (extraBehaviours === void 0) { 18093 extraBehaviours = []; 18094 } 18095 if (extraClasses === void 0) { 18096 extraClasses = []; 18097 } 18098 var buttonSpec = renderButtonSpec(spec, Optional.some(action), providersBackstage, extraBehaviours, extraClasses); 18099 return Button.sketch(buttonSpec); 18100 }; 18101 var getAction = function (name, buttonType) { 18102 return function (comp) { 18103 if (buttonType === 'custom') { 18104 emitWith(comp, formActionEvent, { 18105 name: name, 18106 value: {} 18107 }); 18108 } else if (buttonType === 'submit') { 18109 emit(comp, formSubmitEvent); 18110 } else if (buttonType === 'cancel') { 18111 emit(comp, formCancelEvent); 18112 } else { 18113 console.error('Unknown button type: ', buttonType); 18114 } 18115 }; 18116 }; 18117 var isMenuFooterButtonSpec = function (spec, buttonType) { 18118 return buttonType === 'menu'; 18119 }; 18120 var isNormalFooterButtonSpec = function (spec, buttonType) { 18121 return buttonType === 'custom' || buttonType === 'cancel' || buttonType === 'submit'; 18122 }; 18123 var renderFooterButton = function (spec, buttonType, backstage) { 18124 if (isMenuFooterButtonSpec(spec, buttonType)) { 18125 var getButton = function () { 18126 return memButton_1; 18127 }; 18128 var menuButtonSpec = spec; 18129 var fixedSpec = __assign(__assign({}, spec), { 18130 onSetup: function (api) { 18131 api.setDisabled(spec.disabled); 18132 return noop; 18133 }, 18134 fetch: getFetch(menuButtonSpec.items, getButton, backstage) 18135 }); 18136 var memButton_1 = record(renderMenuButton(fixedSpec, 'tox-tbtn', backstage, Optional.none())); 18137 return memButton_1.asSpec(); 18138 } else if (isNormalFooterButtonSpec(spec, buttonType)) { 18139 var action = getAction(spec.name, buttonType); 18140 var buttonSpec = __assign(__assign({}, spec), { borderless: false }); 18141 return renderButton(buttonSpec, action, backstage.shared.providers, []); 18142 } else { 18143 console.error('Unknown footer button type: ', buttonType); 18144 } 18145 }; 18146 var renderDialogButton = function (spec, providersBackstage) { 18147 var action = getAction(spec.name, 'custom'); 18148 return renderFormField(Optional.none(), FormField.parts.field(__assign({ factory: Button }, renderButtonSpec(spec, Optional.some(action), providersBackstage, [ 18149 RepresentingConfigs.memory(''), 18150 ComposingConfigs.self() 18151 ])))); 18152 }; 18153 18154 var schema$h = constant$1([ 18155 defaulted('field1Name', 'field1'), 18156 defaulted('field2Name', 'field2'), 18157 onStrictHandler('onLockedChange'), 18158 markers$1(['lockClass']), 18159 defaulted('locked', false), 18160 SketchBehaviours.field('coupledFieldBehaviours', [ 18161 Composing, 18162 Representing 18163 ]) 18164 ]); 18165 var getField = function (comp, detail, partName) { 18166 return getPart(comp, detail, partName).bind(Composing.getCurrent); 18167 }; 18168 var coupledPart = function (selfName, otherName) { 18169 return required({ 18170 factory: FormField, 18171 name: selfName, 18172 overrides: function (detail) { 18173 return { 18174 fieldBehaviours: derive$1([config('coupled-input-behaviour', [run$1(input(), function (me) { 18175 getField(me, detail, otherName).each(function (other) { 18176 getPart(me, detail, 'lock').each(function (lock) { 18177 if (Toggling.isOn(lock)) { 18178 detail.onLockedChange(me, other, lock); 18179 } 18180 }); 18181 }); 18182 })])]) 18183 }; 18184 } 18185 }); 18186 }; 18187 var parts$c = constant$1([ 18188 coupledPart('field1', 'field2'), 18189 coupledPart('field2', 'field1'), 18190 required({ 18191 factory: Button, 18192 schema: [required$1('dom')], 18193 name: 'lock', 18194 overrides: function (detail) { 18195 return { 18196 buttonBehaviours: derive$1([Toggling.config({ 18197 selected: detail.locked, 18198 toggleClass: detail.markers.lockClass, 18199 aria: { mode: 'pressed' } 18200 })]) 18201 }; 18202 } 18203 }) 18204 ]); 18205 18206 var factory$f = function (detail, components, _spec, _externals) { 18207 return { 18208 uid: detail.uid, 18209 dom: detail.dom, 18210 components: components, 18211 behaviours: SketchBehaviours.augment(detail.coupledFieldBehaviours, [ 18212 Composing.config({ find: Optional.some }), 18213 Representing.config({ 18214 store: { 18215 mode: 'manual', 18216 getValue: function (comp) { 18217 var _a; 18218 var parts = getPartsOrDie(comp, detail, [ 18219 'field1', 18220 'field2' 18221 ]); 18222 return _a = {}, _a[detail.field1Name] = Representing.getValue(parts.field1()), _a[detail.field2Name] = Representing.getValue(parts.field2()), _a; 18223 }, 18224 setValue: function (comp, value) { 18225 var parts = getPartsOrDie(comp, detail, [ 18226 'field1', 18227 'field2' 18228 ]); 18229 if (hasNonNullableKey(value, detail.field1Name)) { 18230 Representing.setValue(parts.field1(), value[detail.field1Name]); 18231 } 18232 if (hasNonNullableKey(value, detail.field2Name)) { 18233 Representing.setValue(parts.field2(), value[detail.field2Name]); 18234 } 18235 } 18236 } 18237 }) 18238 ]), 18239 apis: { 18240 getField1: function (component) { 18241 return getPart(component, detail, 'field1'); 18242 }, 18243 getField2: function (component) { 18244 return getPart(component, detail, 'field2'); 18245 }, 18246 getLock: function (component) { 18247 return getPart(component, detail, 'lock'); 18248 } 18249 } 18250 }; 18251 }; 18252 var FormCoupledInputs = composite({ 18253 name: 'FormCoupledInputs', 18254 configFields: schema$h(), 18255 partFields: parts$c(), 18256 factory: factory$f, 18257 apis: { 18258 getField1: function (apis, component) { 18259 return apis.getField1(component); 18260 }, 18261 getField2: function (apis, component) { 18262 return apis.getField2(component); 18263 }, 18264 getLock: function (apis, component) { 18265 return apis.getLock(component); 18266 } 18267 } 18268 }); 18269 18270 var formatSize = function (size) { 18271 var unitDec = { 18272 '': 0, 18273 'px': 0, 18274 'pt': 1, 18275 'mm': 1, 18276 'pc': 2, 18277 'ex': 2, 18278 'em': 2, 18279 'ch': 2, 18280 'rem': 2, 18281 'cm': 3, 18282 'in': 4, 18283 '%': 4 18284 }; 18285 var maxDecimal = function (unit) { 18286 return unit in unitDec ? unitDec[unit] : 1; 18287 }; 18288 var numText = size.value.toFixed(maxDecimal(size.unit)); 18289 if (numText.indexOf('.') !== -1) { 18290 numText = numText.replace(/\.?0*$/, ''); 18291 } 18292 return numText + size.unit; 18293 }; 18294 var parseSize = function (sizeText) { 18295 var numPattern = /^\s*(\d+(?:\.\d+)?)\s*(|cm|mm|in|px|pt|pc|em|ex|ch|rem|vw|vh|vmin|vmax|%)\s*$/; 18296 var match = numPattern.exec(sizeText); 18297 if (match !== null) { 18298 var value = parseFloat(match[1]); 18299 var unit = match[2]; 18300 return Result.value({ 18301 value: value, 18302 unit: unit 18303 }); 18304 } else { 18305 return Result.error(sizeText); 18306 } 18307 }; 18308 var convertUnit = function (size, unit) { 18309 var inInch = { 18310 '': 96, 18311 'px': 96, 18312 'pt': 72, 18313 'cm': 2.54, 18314 'pc': 12, 18315 'mm': 25.4, 18316 'in': 1 18317 }; 18318 var supported = function (u) { 18319 return has$2(inInch, u); 18320 }; 18321 if (size.unit === unit) { 18322 return Optional.some(size.value); 18323 } else if (supported(size.unit) && supported(unit)) { 18324 if (inInch[size.unit] === inInch[unit]) { 18325 return Optional.some(size.value); 18326 } else { 18327 return Optional.some(size.value / inInch[size.unit] * inInch[unit]); 18328 } 18329 } else { 18330 return Optional.none(); 18331 } 18332 }; 18333 var noSizeConversion = function (_input) { 18334 return Optional.none(); 18335 }; 18336 var ratioSizeConversion = function (scale, unit) { 18337 return function (size) { 18338 return convertUnit(size, unit).map(function (value) { 18339 return { 18340 value: value * scale, 18341 unit: unit 18342 }; 18343 }); 18344 }; 18345 }; 18346 var makeRatioConverter = function (currentFieldText, otherFieldText) { 18347 var cValue = parseSize(currentFieldText).toOptional(); 18348 var oValue = parseSize(otherFieldText).toOptional(); 18349 return lift2(cValue, oValue, function (cSize, oSize) { 18350 return convertUnit(cSize, oSize.unit).map(function (val) { 18351 return oSize.value / val; 18352 }).map(function (r) { 18353 return ratioSizeConversion(r, oSize.unit); 18354 }).getOr(noSizeConversion); 18355 }).getOr(noSizeConversion); 18356 }; 18357 18358 var renderSizeInput = function (spec, providersBackstage) { 18359 var converter = noSizeConversion; 18360 var ratioEvent = generate$6('ratio-event'); 18361 var makeIcon = function (iconName) { 18362 return render$3(iconName, { 18363 tag: 'span', 18364 classes: [ 18365 'tox-icon', 18366 'tox-lock-icon__' + iconName 18367 ] 18368 }, providersBackstage.icons); 18369 }; 18370 var pLock = FormCoupledInputs.parts.lock({ 18371 dom: { 18372 tag: 'button', 18373 classes: [ 18374 'tox-lock', 18375 'tox-button', 18376 'tox-button--naked', 18377 'tox-button--icon' 18378 ], 18379 attributes: { title: providersBackstage.translate(spec.label.getOr('Constrain proportions')) } 18380 }, 18381 components: [ 18382 makeIcon('lock'), 18383 makeIcon('unlock') 18384 ], 18385 buttonBehaviours: derive$1([ 18386 Disabling.config({ 18387 disabled: function () { 18388 return spec.disabled || providersBackstage.isDisabled(); 18389 } 18390 }), 18391 receivingConfig(), 18392 Tabstopping.config({}) 18393 ]) 18394 }); 18395 var formGroup = function (components) { 18396 return { 18397 dom: { 18398 tag: 'div', 18399 classes: ['tox-form__group'] 18400 }, 18401 components: components 18402 }; 18403 }; 18404 var getFieldPart = function (isField1) { 18405 return FormField.parts.field({ 18406 factory: Input, 18407 inputClasses: ['tox-textfield'], 18408 inputBehaviours: derive$1([ 18409 Disabling.config({ 18410 disabled: function () { 18411 return spec.disabled || providersBackstage.isDisabled(); 18412 } 18413 }), 18414 receivingConfig(), 18415 Tabstopping.config({}), 18416 config('size-input-events', [ 18417 run$1(focusin(), function (component, _simulatedEvent) { 18418 emitWith(component, ratioEvent, { isField1: isField1 }); 18419 }), 18420 run$1(change(), function (component, _simulatedEvent) { 18421 emitWith(component, formChangeEvent, { name: spec.name }); 18422 }) 18423 ]) 18424 ]), 18425 selectOnFocus: false 18426 }); 18427 }; 18428 var getLabel = function (label) { 18429 return { 18430 dom: { 18431 tag: 'label', 18432 classes: ['tox-label'], 18433 innerHtml: providersBackstage.translate(label) 18434 } 18435 }; 18436 }; 18437 var widthField = FormCoupledInputs.parts.field1(formGroup([ 18438 FormField.parts.label(getLabel('Width')), 18439 getFieldPart(true) 18440 ])); 18441 var heightField = FormCoupledInputs.parts.field2(formGroup([ 18442 FormField.parts.label(getLabel('Height')), 18443 getFieldPart(false) 18444 ])); 18445 return FormCoupledInputs.sketch({ 18446 dom: { 18447 tag: 'div', 18448 classes: ['tox-form__group'] 18449 }, 18450 components: [{ 18451 dom: { 18452 tag: 'div', 18453 classes: ['tox-form__controls-h-stack'] 18454 }, 18455 components: [ 18456 widthField, 18457 heightField, 18458 formGroup([ 18459 getLabel(' '), 18460 pLock 18461 ]) 18462 ] 18463 }], 18464 field1Name: 'width', 18465 field2Name: 'height', 18466 locked: true, 18467 markers: { lockClass: 'tox-locked' }, 18468 onLockedChange: function (current, other, _lock) { 18469 parseSize(Representing.getValue(current)).each(function (size) { 18470 converter(size).each(function (newSize) { 18471 Representing.setValue(other, formatSize(newSize)); 18472 }); 18473 }); 18474 }, 18475 coupledFieldBehaviours: derive$1([ 18476 Disabling.config({ 18477 disabled: function () { 18478 return spec.disabled || providersBackstage.isDisabled(); 18479 }, 18480 onDisabled: function (comp) { 18481 FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.disable); 18482 FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.disable); 18483 FormCoupledInputs.getLock(comp).each(Disabling.disable); 18484 }, 18485 onEnabled: function (comp) { 18486 FormCoupledInputs.getField1(comp).bind(FormField.getField).each(Disabling.enable); 18487 FormCoupledInputs.getField2(comp).bind(FormField.getField).each(Disabling.enable); 18488 FormCoupledInputs.getLock(comp).each(Disabling.enable); 18489 } 18490 }), 18491 receivingConfig(), 18492 config('size-input-events2', [run$1(ratioEvent, function (component, simulatedEvent) { 18493 var isField1 = simulatedEvent.event.isField1; 18494 var optCurrent = isField1 ? FormCoupledInputs.getField1(component) : FormCoupledInputs.getField2(component); 18495 var optOther = isField1 ? FormCoupledInputs.getField2(component) : FormCoupledInputs.getField1(component); 18496 var value1 = optCurrent.map(Representing.getValue).getOr(''); 18497 var value2 = optOther.map(Representing.getValue).getOr(''); 18498 converter = makeRatioConverter(value1, value2); 18499 })]) 18500 ]) 18501 }); 18502 }; 18503 18504 var undo = constant$1(generate$6('undo')); 18505 var redo = constant$1(generate$6('redo')); 18506 var zoom = constant$1(generate$6('zoom')); 18507 var back = constant$1(generate$6('back')); 18508 var apply = constant$1(generate$6('apply')); 18509 var swap = constant$1(generate$6('swap')); 18510 var transform$1 = constant$1(generate$6('transform')); 18511 var tempTransform = constant$1(generate$6('temp-transform')); 18512 var transformApply = constant$1(generate$6('transform-apply')); 18513 var internal = { 18514 undo: undo, 18515 redo: redo, 18516 zoom: zoom, 18517 back: back, 18518 apply: apply, 18519 swap: swap, 18520 transform: transform$1, 18521 tempTransform: tempTransform, 18522 transformApply: transformApply 18523 }; 18524 var saveState = constant$1('save-state'); 18525 var disable = constant$1('disable'); 18526 var enable = constant$1('enable'); 18527 var external = { 18528 formActionEvent: formActionEvent, 18529 saveState: saveState, 18530 disable: disable, 18531 enable: enable 18532 }; 18533 18534 var renderEditPanel = function (imagePanel, providersBackstage) { 18535 var createButton = function (text, action, disabled, primary) { 18536 return record(renderButton({ 18537 name: text, 18538 text: text, 18539 disabled: disabled, 18540 primary: primary, 18541 icon: Optional.none(), 18542 borderless: false 18543 }, action, providersBackstage)); 18544 }; 18545 var createIconButton = function (icon, tooltip, action, disabled) { 18546 return record(renderIconButton({ 18547 name: icon, 18548 icon: Optional.some(icon), 18549 tooltip: Optional.some(tooltip), 18550 disabled: disabled, 18551 primary: false, 18552 borderless: false 18553 }, action, providersBackstage)); 18554 }; 18555 var disableAllComponents = function (comps, eventcomp) { 18556 comps.map(function (mem) { 18557 var component = mem.get(eventcomp); 18558 if (component.hasConfigured(Disabling)) { 18559 Disabling.disable(component); 18560 } 18561 }); 18562 }; 18563 var enableAllComponents = function (comps, eventcomp) { 18564 comps.map(function (mem) { 18565 var component = mem.get(eventcomp); 18566 if (component.hasConfigured(Disabling)) { 18567 Disabling.enable(component); 18568 } 18569 }); 18570 }; 18571 var panelDom = { 18572 tag: 'div', 18573 classes: [ 18574 'tox-image-tools__toolbar', 18575 'tox-image-tools-edit-panel' 18576 ] 18577 }; 18578 var noop$1 = noop; 18579 var emit$1 = function (comp, event, data) { 18580 emitWith(comp, event, data); 18581 }; 18582 var emitDisable = function (component) { 18583 return emit(component, external.disable()); 18584 }; 18585 var emitEnable = function (component) { 18586 return emit(component, external.enable()); 18587 }; 18588 var emitTransform = function (comp, transform) { 18589 emitDisable(comp); 18590 emit$1(comp, internal.transform(), { transform: transform }); 18591 emitEnable(comp); 18592 }; 18593 var emitTempTransform = function (comp, transform) { 18594 emitDisable(comp); 18595 emit$1(comp, internal.tempTransform(), { transform: transform }); 18596 emitEnable(comp); 18597 }; 18598 var getBackSwap = function (anyInSystem) { 18599 return function () { 18600 memContainer.getOpt(anyInSystem).each(function (container) { 18601 Replacing.set(container, [ButtonPanel]); 18602 }); 18603 }; 18604 }; 18605 var emitTransformApply = function (comp, transform) { 18606 emitDisable(comp); 18607 emit$1(comp, internal.transformApply(), { 18608 transform: transform, 18609 swap: getBackSwap(comp) 18610 }); 18611 emitEnable(comp); 18612 }; 18613 var createBackButton = function () { 18614 return createButton('Back', function (button) { 18615 return emit$1(button, internal.back(), { swap: getBackSwap(button) }); 18616 }, false, false); 18617 }; 18618 var createSpacer = function () { 18619 return record({ 18620 dom: { 18621 tag: 'div', 18622 classes: ['tox-spacer'] 18623 }, 18624 behaviours: derive$1([Disabling.config({})]) 18625 }); 18626 }; 18627 var createApplyButton = function () { 18628 return createButton('Apply', function (button) { 18629 return emit$1(button, internal.apply(), { swap: getBackSwap(button) }); 18630 }, true, true); 18631 }; 18632 var makeCropTransform = function () { 18633 return function (ir) { 18634 var rect = imagePanel.getRect(); 18635 return crop(ir, rect.x, rect.y, rect.w, rect.h); 18636 }; 18637 }; 18638 var cropPanelComponents = [ 18639 createBackButton(), 18640 createSpacer(), 18641 createButton('Apply', function (button) { 18642 var transform = makeCropTransform(); 18643 emitTransformApply(button, transform); 18644 imagePanel.hideCrop(); 18645 }, false, true) 18646 ]; 18647 var CropPanel = Container.sketch({ 18648 dom: panelDom, 18649 components: cropPanelComponents.map(function (mem) { 18650 return mem.asSpec(); 18651 }), 18652 containerBehaviours: derive$1([config('image-tools-crop-buttons-events', [ 18653 run$1(external.disable(), function (comp, _se) { 18654 disableAllComponents(cropPanelComponents, comp); 18655 }), 18656 run$1(external.enable(), function (comp, _se) { 18657 enableAllComponents(cropPanelComponents, comp); 18658 }) 18659 ])]) 18660 }); 18661 var memSize = record(renderSizeInput({ 18662 name: 'size', 18663 label: Optional.none(), 18664 constrain: true, 18665 disabled: false 18666 }, providersBackstage)); 18667 var makeResizeTransform = function (width, height) { 18668 return function (ir) { 18669 return resize$1(ir, width, height); 18670 }; 18671 }; 18672 var resizePanelComponents = [ 18673 createBackButton(), 18674 createSpacer(), 18675 memSize, 18676 createSpacer(), 18677 createButton('Apply', function (button) { 18678 memSize.getOpt(button).each(function (sizeInput) { 18679 var value = Representing.getValue(sizeInput); 18680 var width = parseInt(value.width, 10); 18681 var height = parseInt(value.height, 10); 18682 var transform = makeResizeTransform(width, height); 18683 emitTransformApply(button, transform); 18684 }); 18685 }, false, true) 18686 ]; 18687 var ResizePanel = Container.sketch({ 18688 dom: panelDom, 18689 components: resizePanelComponents.map(function (mem) { 18690 return mem.asSpec(); 18691 }), 18692 containerBehaviours: derive$1([config('image-tools-resize-buttons-events', [ 18693 run$1(external.disable(), function (comp, _se) { 18694 disableAllComponents(resizePanelComponents, comp); 18695 }), 18696 run$1(external.enable(), function (comp, _se) { 18697 enableAllComponents(resizePanelComponents, comp); 18698 }) 18699 ])]) 18700 }); 18701 var makeValueTransform = function (transform, value) { 18702 return function (ir) { 18703 return transform(ir, value); 18704 }; 18705 }; 18706 var horizontalFlip = makeValueTransform(flip, 'h'); 18707 var verticalFlip = makeValueTransform(flip, 'v'); 18708 var counterclockwiseRotate = makeValueTransform(rotate, -90); 18709 var clockwiseRotate = makeValueTransform(rotate, 90); 18710 var flipRotateOnAction = function (comp, operation) { 18711 emitTempTransform(comp, operation); 18712 }; 18713 var flipRotateComponents = [ 18714 createBackButton(), 18715 createSpacer(), 18716 createIconButton('flip-horizontally', 'Flip horizontally', function (button) { 18717 flipRotateOnAction(button, horizontalFlip); 18718 }, false), 18719 createIconButton('flip-vertically', 'Flip vertically', function (button) { 18720 flipRotateOnAction(button, verticalFlip); 18721 }, false), 18722 createIconButton('rotate-left', 'Rotate counterclockwise', function (button) { 18723 flipRotateOnAction(button, counterclockwiseRotate); 18724 }, false), 18725 createIconButton('rotate-right', 'Rotate clockwise', function (button) { 18726 flipRotateOnAction(button, clockwiseRotate); 18727 }, false), 18728 createSpacer(), 18729 createApplyButton() 18730 ]; 18731 var FlipRotatePanel = Container.sketch({ 18732 dom: panelDom, 18733 components: flipRotateComponents.map(function (mem) { 18734 return mem.asSpec(); 18735 }), 18736 containerBehaviours: derive$1([config('image-tools-fliprotate-buttons-events', [ 18737 run$1(external.disable(), function (comp, _se) { 18738 disableAllComponents(flipRotateComponents, comp); 18739 }), 18740 run$1(external.enable(), function (comp, _se) { 18741 enableAllComponents(flipRotateComponents, comp); 18742 }) 18743 ])]) 18744 }); 18745 var makeSlider = function (label, onChoose, min, value, max) { 18746 var labelPart = Slider.parts.label({ 18747 dom: { 18748 tag: 'label', 18749 classes: ['tox-label'], 18750 innerHtml: providersBackstage.translate(label) 18751 } 18752 }); 18753 var spectrum = Slider.parts.spectrum({ 18754 dom: { 18755 tag: 'div', 18756 classes: ['tox-slider__rail'], 18757 attributes: { role: 'presentation' } 18758 } 18759 }); 18760 var thumb = Slider.parts.thumb({ 18761 dom: { 18762 tag: 'div', 18763 classes: ['tox-slider__handle'], 18764 attributes: { role: 'presentation' } 18765 } 18766 }); 18767 return record(Slider.sketch({ 18768 dom: { 18769 tag: 'div', 18770 classes: ['tox-slider'], 18771 attributes: { role: 'presentation' } 18772 }, 18773 model: { 18774 mode: 'x', 18775 minX: min, 18776 maxX: max, 18777 getInitialValue: constant$1({ x: value }) 18778 }, 18779 components: [ 18780 labelPart, 18781 spectrum, 18782 thumb 18783 ], 18784 sliderBehaviours: derive$1([Focusing.config({})]), 18785 onChoose: onChoose 18786 })); 18787 }; 18788 var makeVariableSlider = function (label, transform, min, value, max) { 18789 var onChoose = function (slider, _thumb, value) { 18790 var valTransform = makeValueTransform(transform, value.x / 100); 18791 emitTransform(slider, valTransform); 18792 }; 18793 return makeSlider(label, onChoose, min, value, max); 18794 }; 18795 var variableFilterPanelComponents = function (label, transform, min, value, max) { 18796 return [ 18797 createBackButton(), 18798 makeVariableSlider(label, transform, min, value, max), 18799 createApplyButton() 18800 ]; 18801 }; 18802 var createVariableFilterPanel = function (label, transform, min, value, max) { 18803 var filterPanelComponents = variableFilterPanelComponents(label, transform, min, value, max); 18804 return Container.sketch({ 18805 dom: panelDom, 18806 components: filterPanelComponents.map(function (mem) { 18807 return mem.asSpec(); 18808 }), 18809 containerBehaviours: derive$1([config('image-tools-filter-panel-buttons-events', [ 18810 run$1(external.disable(), function (comp, _se) { 18811 disableAllComponents(filterPanelComponents, comp); 18812 }), 18813 run$1(external.enable(), function (comp, _se) { 18814 enableAllComponents(filterPanelComponents, comp); 18815 }) 18816 ])]) 18817 }); 18818 }; 18819 var filterPanelComponents = [ 18820 createBackButton(), 18821 createSpacer(), 18822 createApplyButton() 18823 ]; 18824 var FilterPanel = Container.sketch({ 18825 dom: panelDom, 18826 components: filterPanelComponents.map(function (mem) { 18827 return mem.asSpec(); 18828 }) 18829 }); 18830 var BrightnessPanel = createVariableFilterPanel('Brightness', brightness, -100, 0, 100); 18831 var ContrastPanel = createVariableFilterPanel('Contrast', contrast, -100, 0, 100); 18832 var GammaPanel = createVariableFilterPanel('Gamma', gamma, -100, 0, 100); 18833 var makeColorTransform = function (red, green, blue) { 18834 return function (ir) { 18835 return colorize(ir, red, green, blue); 18836 }; 18837 }; 18838 var makeColorSlider = function (label) { 18839 var onChoose = function (slider, _thumb, _value) { 18840 var redOpt = memRed.getOpt(slider); 18841 var blueOpt = memBlue.getOpt(slider); 18842 var greenOpt = memGreen.getOpt(slider); 18843 redOpt.each(function (red) { 18844 blueOpt.each(function (blue) { 18845 greenOpt.each(function (green) { 18846 var r = Representing.getValue(red).x / 100; 18847 var g = Representing.getValue(green).x / 100; 18848 var b = Representing.getValue(blue).x / 100; 18849 var transform = makeColorTransform(r, g, b); 18850 emitTransform(slider, transform); 18851 }); 18852 }); 18853 }); 18854 }; 18855 return makeSlider(label, onChoose, 0, 100, 200); 18856 }; 18857 var memRed = makeColorSlider('R'); 18858 var memGreen = makeColorSlider('G'); 18859 var memBlue = makeColorSlider('B'); 18860 var colorizePanelComponents = [ 18861 createBackButton(), 18862 memRed, 18863 memGreen, 18864 memBlue, 18865 createApplyButton() 18866 ]; 18867 var ColorizePanel = Container.sketch({ 18868 dom: panelDom, 18869 components: colorizePanelComponents.map(function (mem) { 18870 return mem.asSpec(); 18871 }) 18872 }); 18873 var getTransformPanelEvent = function (panel, transform, update) { 18874 return function (button) { 18875 var swap = function () { 18876 memContainer.getOpt(button).each(function (container) { 18877 Replacing.set(container, [panel]); 18878 update(container); 18879 }); 18880 }; 18881 emit$1(button, internal.swap(), { 18882 transform: transform, 18883 swap: swap 18884 }); 18885 }; 18886 }; 18887 var cropPanelUpdate = function (_anyInSystem) { 18888 imagePanel.showCrop(); 18889 }; 18890 var resizePanelUpdate = function (anyInSystem) { 18891 memSize.getOpt(anyInSystem).each(function (sizeInput) { 18892 var measurements = imagePanel.getMeasurements(); 18893 var width = measurements.width; 18894 var height = measurements.height; 18895 Representing.setValue(sizeInput, { 18896 width: width, 18897 height: height 18898 }); 18899 }); 18900 }; 18901 var sharpenTransform = Optional.some(sharpen); 18902 var invertTransform = Optional.some(invert); 18903 var buttonPanelComponents = [ 18904 createIconButton('crop', 'Crop', getTransformPanelEvent(CropPanel, Optional.none(), cropPanelUpdate), false), 18905 createIconButton('resize', 'Resize', getTransformPanelEvent(ResizePanel, Optional.none(), resizePanelUpdate), false), 18906 createIconButton('orientation', 'Orientation', getTransformPanelEvent(FlipRotatePanel, Optional.none(), noop$1), false), 18907 createIconButton('brightness', 'Brightness', getTransformPanelEvent(BrightnessPanel, Optional.none(), noop$1), false), 18908 createIconButton('sharpen', 'Sharpen', getTransformPanelEvent(FilterPanel, sharpenTransform, noop$1), false), 18909 createIconButton('contrast', 'Contrast', getTransformPanelEvent(ContrastPanel, Optional.none(), noop$1), false), 18910 createIconButton('color-levels', 'Color levels', getTransformPanelEvent(ColorizePanel, Optional.none(), noop$1), false), 18911 createIconButton('gamma', 'Gamma', getTransformPanelEvent(GammaPanel, Optional.none(), noop$1), false), 18912 createIconButton('invert', 'Invert', getTransformPanelEvent(FilterPanel, invertTransform, noop$1), false) 18913 ]; 18914 var ButtonPanel = Container.sketch({ 18915 dom: panelDom, 18916 components: buttonPanelComponents.map(function (mem) { 18917 return mem.asSpec(); 18918 }) 18919 }); 18920 var container = Container.sketch({ 18921 dom: { tag: 'div' }, 18922 components: [ButtonPanel], 18923 containerBehaviours: derive$1([Replacing.config({})]) 18924 }); 18925 var memContainer = record(container); 18926 var getApplyButton = function (anyInSystem) { 18927 return memContainer.getOpt(anyInSystem).map(function (container) { 18928 var panel = container.components()[0]; 18929 return panel.components()[panel.components().length - 1]; 18930 }); 18931 }; 18932 return { 18933 memContainer: memContainer, 18934 getApplyButton: getApplyButton 18935 }; 18936 }; 18937 18938 var global$4 = tinymce.util.Tools.resolve('tinymce.geom.Rect'); 18939 18940 var global$3 = tinymce.util.Tools.resolve('tinymce.util.Observable'); 18941 18942 var global$2 = tinymce.util.Tools.resolve('tinymce.util.VK'); 18943 18944 var getDocumentSize = function (doc) { 18945 var max = Math.max; 18946 var documentElement = doc.documentElement; 18947 var body = doc.body; 18948 var scrollWidth = max(documentElement.scrollWidth, body.scrollWidth); 18949 var clientWidth = max(documentElement.clientWidth, body.clientWidth); 18950 var offsetWidth = max(documentElement.offsetWidth, body.offsetWidth); 18951 var scrollHeight = max(documentElement.scrollHeight, body.scrollHeight); 18952 var clientHeight = max(documentElement.clientHeight, body.clientHeight); 18953 var offsetHeight = max(documentElement.offsetHeight, body.offsetHeight); 18954 return { 18955 width: scrollWidth < offsetWidth ? clientWidth : scrollWidth, 18956 height: scrollHeight < offsetHeight ? clientHeight : scrollHeight 18957 }; 18958 }; 18959 var isTouchEvent$1 = function (e) { 18960 return isNonNullable(e.changedTouches); 18961 }; 18962 var updateWithTouchData = function (e) { 18963 if (isTouchEvent$1(e)) { 18964 var keys = 'screenX screenY pageX pageY clientX clientY'.split(' '); 18965 for (var i = 0; i < keys.length; i++) { 18966 e[keys[i]] = e.changedTouches[0][keys[i]]; 18967 } 18968 } 18969 }; 18970 function DragHelper (id, settings) { 18971 var _a, _b, _c; 18972 var eventOverlay; 18973 var handleEvents = []; 18974 var overlayEvents = []; 18975 var doc = (_a = settings.document) !== null && _a !== void 0 ? _a : document; 18976 var root = (_b = settings.root) !== null && _b !== void 0 ? _b : doc; 18977 var sugarDoc = SugarElement.fromDom(doc); 18978 var downButton; 18979 var startX; 18980 var startY; 18981 var handleElement = SugarElement.fromDom(root.getElementById((_c = settings.handle) !== null && _c !== void 0 ? _c : id)); 18982 var start = function (e) { 18983 var rawEvent = e.raw; 18984 var docSize = getDocumentSize(doc); 18985 updateWithTouchData(rawEvent); 18986 e.prevent(); 18987 downButton = rawEvent.button; 18988 startX = rawEvent.screenX; 18989 startY = rawEvent.screenY; 18990 var cursor = get$c(handleElement, 'cursor'); 18991 eventOverlay = SugarElement.fromTag('div', doc); 18992 setAll(eventOverlay, { 18993 'position': 'absolute', 18994 'top': '0', 18995 'left': '0', 18996 'width': docSize.width + 'px', 18997 'height': docSize.height + 'px', 18998 'z-index': 2147483647 + '', 18999 'opacity': '0.0001', 19000 cursor: cursor 19001 }); 19002 append$2(getBody(sugarDoc), eventOverlay); 19003 overlayEvents.push(bind(sugarDoc, 'mousemove', drag), bind(sugarDoc, 'touchmove', drag), bind(sugarDoc, 'mouseup', stop), bind(sugarDoc, 'touchend', stop)); 19004 settings.start(rawEvent); 19005 }; 19006 var drag = function (e) { 19007 var rawEvent = e.raw; 19008 updateWithTouchData(rawEvent); 19009 if (rawEvent.button !== downButton) { 19010 return stop(e); 19011 } 19012 rawEvent.deltaX = rawEvent.screenX - startX; 19013 rawEvent.deltaY = rawEvent.screenY - startY; 19014 e.prevent(); 19015 settings.drag(rawEvent); 19016 }; 19017 var stop = function (e) { 19018 updateWithTouchData(e.raw); 19019 each$1(overlayEvents, function (e) { 19020 return e.unbind(); 19021 }); 19022 overlayEvents = []; 19023 remove$5(eventOverlay); 19024 if (settings.stop) { 19025 settings.stop(e.raw); 19026 } 19027 }; 19028 var destroy = function () { 19029 each$1(overlayEvents.concat(handleEvents), function (e) { 19030 return e.unbind(); 19031 }); 19032 overlayEvents = []; 19033 handleEvents = []; 19034 if (isNonNullable(eventOverlay)) { 19035 remove$5(eventOverlay); 19036 } 19037 }; 19038 handleEvents.push(bind(handleElement, 'mousedown', start), bind(handleElement, 'touchstart', start)); 19039 return { destroy: destroy }; 19040 } 19041 19042 var count = 0; 19043 var create$1 = function (currentRect, viewPortRect, clampRect, containerElm, action) { 19044 var dragHelpers; 19045 var events = []; 19046 var prefix = 'tox-'; 19047 var id = prefix + 'crid-' + count++; 19048 var container = SugarElement.fromDom(containerElm); 19049 var handles = [ 19050 { 19051 name: 'move', 19052 xMul: 0, 19053 yMul: 0, 19054 deltaX: 1, 19055 deltaY: 1, 19056 deltaW: 0, 19057 deltaH: 0, 19058 label: 'Crop Mask' 19059 }, 19060 { 19061 name: 'nw', 19062 xMul: 0, 19063 yMul: 0, 19064 deltaX: 1, 19065 deltaY: 1, 19066 deltaW: -1, 19067 deltaH: -1, 19068 label: 'Top Left Crop Handle' 19069 }, 19070 { 19071 name: 'ne', 19072 xMul: 1, 19073 yMul: 0, 19074 deltaX: 0, 19075 deltaY: 1, 19076 deltaW: 1, 19077 deltaH: -1, 19078 label: 'Top Right Crop Handle' 19079 }, 19080 { 19081 name: 'sw', 19082 xMul: 0, 19083 yMul: 1, 19084 deltaX: 1, 19085 deltaY: 0, 19086 deltaW: -1, 19087 deltaH: 1, 19088 label: 'Bottom Left Crop Handle' 19089 }, 19090 { 19091 name: 'se', 19092 xMul: 1, 19093 yMul: 1, 19094 deltaX: 0, 19095 deltaY: 0, 19096 deltaW: 1, 19097 deltaH: 1, 19098 label: 'Bottom Right Crop Handle' 19099 } 19100 ]; 19101 var blockers = [ 19102 'top', 19103 'right', 19104 'bottom', 19105 'left' 19106 ]; 19107 var getAbsoluteRect = function (outerRect, relativeRect) { 19108 return { 19109 x: relativeRect.x + outerRect.x, 19110 y: relativeRect.y + outerRect.y, 19111 w: relativeRect.w, 19112 h: relativeRect.h 19113 }; 19114 }; 19115 var getRelativeRect = function (outerRect, innerRect) { 19116 return { 19117 x: innerRect.x - outerRect.x, 19118 y: innerRect.y - outerRect.y, 19119 w: innerRect.w, 19120 h: innerRect.h 19121 }; 19122 }; 19123 var getInnerRect = function () { 19124 return getRelativeRect(clampRect, currentRect); 19125 }; 19126 var moveRect = function (handle, startRect, deltaX, deltaY) { 19127 var x = startRect.x + deltaX * handle.deltaX; 19128 var y = startRect.y + deltaY * handle.deltaY; 19129 var w = Math.max(20, startRect.w + deltaX * handle.deltaW); 19130 var h = Math.max(20, startRect.h + deltaY * handle.deltaH); 19131 var rect = currentRect = global$4.clamp({ 19132 x: x, 19133 y: y, 19134 w: w, 19135 h: h 19136 }, clampRect, handle.name === 'move'); 19137 rect = getRelativeRect(clampRect, rect); 19138 instance.fire('updateRect', { rect: rect }); 19139 setInnerRect(rect); 19140 }; 19141 var render = function () { 19142 var createDragHelper = function (handle) { 19143 var startRect; 19144 return DragHelper(id, { 19145 document: containerElm.ownerDocument, 19146 root: getRootNode(container).dom, 19147 handle: id + '-' + handle.name, 19148 start: function () { 19149 startRect = currentRect; 19150 }, 19151 drag: function (e) { 19152 moveRect(handle, startRect, e.deltaX, e.deltaY); 19153 } 19154 }); 19155 }; 19156 var cropContainer = SugarElement.fromTag('div'); 19157 setAll$1(cropContainer, { 19158 id: id, 19159 'class': prefix + 'croprect-container', 19160 'role': 'grid', 19161 'aria-dropeffect': 'execute' 19162 }); 19163 append$2(container, cropContainer); 19164 each$1(blockers, function (blocker) { 19165 descendant(container, '#' + id).each(function (blockerElm) { 19166 var cropBlocker = SugarElement.fromTag('div'); 19167 setAll$1(cropBlocker, { 19168 'id': id + '-' + blocker, 19169 'class': prefix + 'croprect-block', 19170 'data-mce-bogus': 'all' 19171 }); 19172 set$7(cropBlocker, 'display', 'none'); 19173 append$2(blockerElm, cropBlocker); 19174 }); 19175 }); 19176 each$1(handles, function (handle) { 19177 descendant(container, '#' + id).each(function (handleElm) { 19178 var cropHandle = SugarElement.fromTag('div'); 19179 setAll$1(cropHandle, { 19180 'id': id + '-' + handle.name, 19181 'aria-label': handle.label, 19182 'aria-grabbed': 'false', 19183 'data-mce-bogus': 'all', 19184 'role': 'gridcell', 19185 'tabindex': '-1', 19186 'title': handle.label 19187 }); 19188 add$1(cropHandle, [ 19189 prefix + 'croprect-handle', 19190 prefix + 'croprect-handle-' + handle.name 19191 ]); 19192 set$7(cropHandle, 'display', 'none'); 19193 append$2(handleElm, cropHandle); 19194 }); 19195 }); 19196 dragHelpers = map$2(handles, createDragHelper); 19197 repaint(currentRect); 19198 var handleFocus = function (e) { 19199 set$8(e.target, 'aria-grabbed', e.raw.type === 'focus' ? 'true' : 'false'); 19200 }; 19201 var handleKeydown = function (e) { 19202 var activeHandle; 19203 each$1(handles, function (handle) { 19204 if (get$d(e.target, 'id') === id + '-' + handle.name) { 19205 activeHandle = handle; 19206 return false; 19207 } 19208 }); 19209 var moveAndBlock = function (evt, handle, startRect, deltaX, deltaY) { 19210 evt.stopPropagation(); 19211 evt.preventDefault(); 19212 moveRect(activeHandle, startRect, deltaX, deltaY); 19213 }; 19214 switch (e.raw.keyCode) { 19215 case global$2.LEFT: 19216 moveAndBlock(e, activeHandle, currentRect, -10, 0); 19217 break; 19218 case global$2.RIGHT: 19219 moveAndBlock(e, activeHandle, currentRect, 10, 0); 19220 break; 19221 case global$2.UP: 19222 moveAndBlock(e, activeHandle, currentRect, 0, -10); 19223 break; 19224 case global$2.DOWN: 19225 moveAndBlock(e, activeHandle, currentRect, 0, 10); 19226 break; 19227 case global$2.ENTER: 19228 case global$2.SPACEBAR: 19229 e.prevent(); 19230 action(); 19231 break; 19232 } 19233 }; 19234 events.push(bind(container, 'focusin', handleFocus), bind(container, 'focusout', handleFocus), bind(container, 'keydown', handleKeydown)); 19235 }; 19236 var toggleVisibility = function (state) { 19237 var selectors = __spreadArray(__spreadArray([], map$2(handles, function (handle) { 19238 return '#' + id + '-' + handle.name; 19239 }), true), map$2(blockers, function (blocker) { 19240 return '#' + id + '-' + blocker; 19241 }), true).join(','); 19242 var elems = descendants(container, selectors); 19243 if (state) { 19244 each$1(elems, function (elm) { 19245 return remove$6(elm, 'display'); 19246 }); 19247 } else { 19248 each$1(elems, function (elm) { 19249 return set$7(elm, 'display', 'none'); 19250 }); 19251 } 19252 }; 19253 var repaint = function (rect) { 19254 var updateElementRect = function (name, newRect) { 19255 descendant(container, '#' + id + '-' + name).each(function (elm) { 19256 setAll(elm, { 19257 left: newRect.x + 'px', 19258 top: newRect.y + 'px', 19259 width: Math.max(0, newRect.w) + 'px', 19260 height: Math.max(0, newRect.h) + 'px' 19261 }); 19262 }); 19263 }; 19264 each$1(handles, function (handle) { 19265 descendant(container, '#' + id + '-' + handle.name).each(function (elm) { 19266 setAll(elm, { 19267 left: rect.w * handle.xMul + rect.x + 'px', 19268 top: rect.h * handle.yMul + rect.y + 'px' 19269 }); 19270 }); 19271 }); 19272 updateElementRect('top', { 19273 x: viewPortRect.x, 19274 y: viewPortRect.y, 19275 w: viewPortRect.w, 19276 h: rect.y - viewPortRect.y 19277 }); 19278 updateElementRect('right', { 19279 x: rect.x + rect.w, 19280 y: rect.y, 19281 w: viewPortRect.w - rect.x - rect.w + viewPortRect.x, 19282 h: rect.h 19283 }); 19284 updateElementRect('bottom', { 19285 x: viewPortRect.x, 19286 y: rect.y + rect.h, 19287 w: viewPortRect.w, 19288 h: viewPortRect.h - rect.y - rect.h + viewPortRect.y 19289 }); 19290 updateElementRect('left', { 19291 x: viewPortRect.x, 19292 y: rect.y, 19293 w: rect.x - viewPortRect.x, 19294 h: rect.h 19295 }); 19296 updateElementRect('move', rect); 19297 }; 19298 var setRect = function (rect) { 19299 currentRect = rect; 19300 repaint(currentRect); 19301 }; 19302 var setViewPortRect = function (rect) { 19303 viewPortRect = rect; 19304 repaint(currentRect); 19305 }; 19306 var setInnerRect = function (rect) { 19307 setRect(getAbsoluteRect(clampRect, rect)); 19308 }; 19309 var setClampRect = function (rect) { 19310 clampRect = rect; 19311 repaint(currentRect); 19312 }; 19313 var destroy = function () { 19314 each$1(dragHelpers, function (helper) { 19315 return helper.destroy(); 19316 }); 19317 dragHelpers = []; 19318 each$1(events, function (e) { 19319 return e.unbind(); 19320 }); 19321 events = []; 19322 }; 19323 render(); 19324 var instance = __assign(__assign({}, global$3), { 19325 toggleVisibility: toggleVisibility, 19326 setClampRect: setClampRect, 19327 setRect: setRect, 19328 getInnerRect: getInnerRect, 19329 setInnerRect: setInnerRect, 19330 setViewPortRect: setViewPortRect, 19331 destroy: destroy 19332 }); 19333 return instance; 19334 }; 19335 var CropRect = { create: create$1 }; 19336 19337 var loadImage = function (image) { 19338 return new global$c(function (resolve) { 19339 var loaded = function () { 19340 image.removeEventListener('load', loaded); 19341 resolve(image); 19342 }; 19343 if (image.complete) { 19344 resolve(image); 19345 } else { 19346 image.addEventListener('load', loaded); 19347 } 19348 }); 19349 }; 19350 var renderImagePanel = function (initialUrl) { 19351 var memBg = record({ 19352 dom: { 19353 tag: 'div', 19354 classes: ['tox-image-tools__image-bg'], 19355 attributes: { role: 'presentation' } 19356 } 19357 }); 19358 var zoomState = Cell(1); 19359 var cropRect = api$1(); 19360 var rectState = Cell({ 19361 x: 0, 19362 y: 0, 19363 w: 1, 19364 h: 1 19365 }); 19366 var viewRectState = Cell({ 19367 x: 0, 19368 y: 0, 19369 w: 1, 19370 h: 1 19371 }); 19372 var repaintImg = function (anyInSystem, img) { 19373 memContainer.getOpt(anyInSystem).each(function (panel) { 19374 var zoom = zoomState.get(); 19375 var panelW = get$a(panel.element); 19376 var panelH = get$b(panel.element); 19377 var width = img.dom.naturalWidth * zoom; 19378 var height = img.dom.naturalHeight * zoom; 19379 var left = Math.max(0, panelW / 2 - width / 2); 19380 var top = Math.max(0, panelH / 2 - height / 2); 19381 var css = { 19382 left: left.toString() + 'px', 19383 top: top.toString() + 'px', 19384 width: width.toString() + 'px', 19385 height: height.toString() + 'px', 19386 position: 'absolute' 19387 }; 19388 setAll(img, css); 19389 memBg.getOpt(panel).each(function (bg) { 19390 setAll(bg.element, css); 19391 }); 19392 cropRect.run(function (cRect) { 19393 var rect = rectState.get(); 19394 cRect.setRect({ 19395 x: rect.x * zoom + left, 19396 y: rect.y * zoom + top, 19397 w: rect.w * zoom, 19398 h: rect.h * zoom 19399 }); 19400 cRect.setClampRect({ 19401 x: left, 19402 y: top, 19403 w: width, 19404 h: height 19405 }); 19406 cRect.setViewPortRect({ 19407 x: 0, 19408 y: 0, 19409 w: panelW, 19410 h: panelH 19411 }); 19412 }); 19413 }); 19414 }; 19415 var zoomFit = function (anyInSystem, img) { 19416 memContainer.getOpt(anyInSystem).each(function (panel) { 19417 var panelW = get$a(panel.element); 19418 var panelH = get$b(panel.element); 19419 var width = img.dom.naturalWidth; 19420 var height = img.dom.naturalHeight; 19421 var zoom = Math.min(panelW / width, panelH / height); 19422 if (zoom >= 1) { 19423 zoomState.set(1); 19424 } else { 19425 zoomState.set(zoom); 19426 } 19427 }); 19428 }; 19429 var updateSrc = function (anyInSystem, url) { 19430 var img = SugarElement.fromTag('img'); 19431 set$8(img, 'src', url); 19432 return loadImage(img.dom).then(function () { 19433 if (anyInSystem.getSystem().isConnected()) { 19434 memContainer.getOpt(anyInSystem).map(function (panel) { 19435 var aImg = external$2({ element: img }); 19436 Replacing.replaceAt(panel, 1, Optional.some(aImg)); 19437 var lastViewRect = viewRectState.get(); 19438 var viewRect = { 19439 x: 0, 19440 y: 0, 19441 w: img.dom.naturalWidth, 19442 h: img.dom.naturalHeight 19443 }; 19444 viewRectState.set(viewRect); 19445 var rect = global$4.inflate(viewRect, -20, -20); 19446 rectState.set(rect); 19447 if (lastViewRect.w !== viewRect.w || lastViewRect.h !== viewRect.h) { 19448 zoomFit(panel, img); 19449 } 19450 repaintImg(panel, img); 19451 }); 19452 } 19453 }); 19454 }; 19455 var zoom = function (anyInSystem, direction) { 19456 var currentZoom = zoomState.get(); 19457 var newZoom = direction > 0 ? Math.min(2, currentZoom + 0.1) : Math.max(0.1, currentZoom - 0.1); 19458 zoomState.set(newZoom); 19459 memContainer.getOpt(anyInSystem).each(function (panel) { 19460 var img = panel.components()[1].element; 19461 repaintImg(panel, img); 19462 }); 19463 }; 19464 var showCrop = function () { 19465 cropRect.run(function (cRect) { 19466 cRect.toggleVisibility(true); 19467 }); 19468 }; 19469 var hideCrop = function () { 19470 cropRect.run(function (cRect) { 19471 cRect.toggleVisibility(false); 19472 }); 19473 }; 19474 var getRect = function () { 19475 return rectState.get(); 19476 }; 19477 var container = Container.sketch({ 19478 dom: { 19479 tag: 'div', 19480 classes: ['tox-image-tools__image'] 19481 }, 19482 components: [ 19483 memBg.asSpec(), 19484 { 19485 dom: { 19486 tag: 'img', 19487 attributes: { src: initialUrl } 19488 } 19489 }, 19490 { 19491 dom: { tag: 'div' }, 19492 behaviours: derive$1([config('image-panel-crop-events', [ 19493 runOnAttached(function (comp) { 19494 memContainer.getOpt(comp).each(function (container) { 19495 var el = container.element.dom; 19496 var cRect = CropRect.create({ 19497 x: 10, 19498 y: 10, 19499 w: 100, 19500 h: 100 19501 }, { 19502 x: 0, 19503 y: 0, 19504 w: 200, 19505 h: 200 19506 }, { 19507 x: 0, 19508 y: 0, 19509 w: 200, 19510 h: 200 19511 }, el, noop); 19512 cRect.toggleVisibility(false); 19513 cRect.on('updateRect', function (e) { 19514 var rect = e.rect; 19515 var zoom = zoomState.get(); 19516 var newRect = { 19517 x: Math.round(rect.x / zoom), 19518 y: Math.round(rect.y / zoom), 19519 w: Math.round(rect.w / zoom), 19520 h: Math.round(rect.h / zoom) 19521 }; 19522 rectState.set(newRect); 19523 }); 19524 cropRect.set(cRect); 19525 }); 19526 }), 19527 runOnDetached(function () { 19528 cropRect.clear(); 19529 }) 19530 ])]) 19531 } 19532 ], 19533 containerBehaviours: derive$1([ 19534 Replacing.config({}), 19535 config('image-panel-events', [runOnAttached(function (comp) { 19536 updateSrc(comp, initialUrl); 19537 })]) 19538 ]) 19539 }); 19540 var memContainer = record(container); 19541 var getMeasurements = function () { 19542 var viewRect = viewRectState.get(); 19543 return { 19544 width: viewRect.w, 19545 height: viewRect.h 19546 }; 19547 }; 19548 return { 19549 memContainer: memContainer, 19550 updateSrc: updateSrc, 19551 zoom: zoom, 19552 showCrop: showCrop, 19553 hideCrop: hideCrop, 19554 getRect: getRect, 19555 getMeasurements: getMeasurements 19556 }; 19557 }; 19558 19559 var createButton = function (innerHtml, icon, disabled, action, providersBackstage) { 19560 return renderIconButton({ 19561 name: innerHtml, 19562 icon: Optional.some(icon), 19563 disabled: disabled, 19564 tooltip: Optional.some(innerHtml), 19565 primary: false, 19566 borderless: false 19567 }, action, providersBackstage); 19568 }; 19569 var setButtonEnabled = function (button, enabled) { 19570 if (enabled) { 19571 Disabling.enable(button); 19572 } else { 19573 Disabling.disable(button); 19574 } 19575 }; 19576 var renderSideBar = function (providersBackstage) { 19577 var updateButtonUndoStates = function (anyInSystem, undoEnabled, redoEnabled) { 19578 memUndo.getOpt(anyInSystem).each(function (undo) { 19579 setButtonEnabled(undo, undoEnabled); 19580 }); 19581 memRedo.getOpt(anyInSystem).each(function (redo) { 19582 setButtonEnabled(redo, redoEnabled); 19583 }); 19584 }; 19585 var memUndo = record(createButton('Undo', 'undo', true, function (button) { 19586 emitWith(button, internal.undo(), { direction: 1 }); 19587 }, providersBackstage)); 19588 var memRedo = record(createButton('Redo', 'redo', true, function (button) { 19589 emitWith(button, internal.redo(), { direction: 1 }); 19590 }, providersBackstage)); 19591 var container = Container.sketch({ 19592 dom: { 19593 tag: 'div', 19594 classes: [ 19595 'tox-image-tools__toolbar', 19596 'tox-image-tools__sidebar' 19597 ] 19598 }, 19599 components: [ 19600 memUndo.asSpec(), 19601 memRedo.asSpec(), 19602 createButton('Zoom in', 'zoom-in', false, function (button) { 19603 emitWith(button, internal.zoom(), { direction: 1 }); 19604 }, providersBackstage), 19605 createButton('Zoom out', 'zoom-out', false, function (button) { 19606 emitWith(button, internal.zoom(), { direction: -1 }); 19607 }, providersBackstage) 19608 ] 19609 }); 19610 return { 19611 container: container, 19612 updateButtonUndoStates: updateButtonUndoStates 19613 }; 19614 }; 19615 19616 function UndoStack () { 19617 var data = []; 19618 var index = -1; 19619 var add = function (state) { 19620 var removed = data.splice(++index); 19621 data.push(state); 19622 return { 19623 state: state, 19624 removed: removed 19625 }; 19626 }; 19627 var undo = function () { 19628 if (canUndo()) { 19629 return data[--index]; 19630 } 19631 }; 19632 var redo = function () { 19633 if (canRedo()) { 19634 return data[++index]; 19635 } 19636 }; 19637 var canUndo = function () { 19638 return index > 0; 19639 }; 19640 var canRedo = function () { 19641 return index !== -1 && index < data.length - 1; 19642 }; 19643 return { 19644 data: data, 19645 add: add, 19646 undo: undo, 19647 redo: redo, 19648 canUndo: canUndo, 19649 canRedo: canRedo 19650 }; 19651 } 19652 19653 var makeState = function (initialState) { 19654 var blobState = Cell(initialState); 19655 var tempState = value$1(); 19656 var undoStack = UndoStack(); 19657 undoStack.add(initialState); 19658 var getBlobState = function () { 19659 return blobState.get(); 19660 }; 19661 var setBlobState = function (state) { 19662 blobState.set(state); 19663 }; 19664 var getTempState = function () { 19665 return tempState.get().getOrThunk(blobState.get); 19666 }; 19667 var updateTempState = function (blob) { 19668 var newTempState = createState(blob); 19669 destroyTempState(); 19670 tempState.set(newTempState); 19671 return newTempState.url; 19672 }; 19673 var createState = function (blob) { 19674 return { 19675 blob: blob, 19676 url: URL.createObjectURL(blob) 19677 }; 19678 }; 19679 var destroyState = function (state) { 19680 URL.revokeObjectURL(state.url); 19681 }; 19682 var destroyStates = function (states) { 19683 global$5.each(states, destroyState); 19684 }; 19685 var destroyTempState = function () { 19686 tempState.on(destroyState); 19687 tempState.clear(); 19688 }; 19689 var addBlobState = function (blob) { 19690 var newState = createState(blob); 19691 setBlobState(newState); 19692 var removed = undoStack.add(newState).removed; 19693 destroyStates(removed); 19694 return newState.url; 19695 }; 19696 var addTempState = function (blob) { 19697 var newState = createState(blob); 19698 tempState.set(newState); 19699 return newState.url; 19700 }; 19701 var applyTempState = function (postApply) { 19702 return tempState.get().fold(noop, function (temp) { 19703 addBlobState(temp.blob); 19704 postApply(); 19705 }); 19706 }; 19707 var undo = function () { 19708 var currentState = undoStack.undo(); 19709 setBlobState(currentState); 19710 return currentState.url; 19711 }; 19712 var redo = function () { 19713 var currentState = undoStack.redo(); 19714 setBlobState(currentState); 19715 return currentState.url; 19716 }; 19717 var getHistoryStates = function () { 19718 var undoEnabled = undoStack.canUndo(); 19719 var redoEnabled = undoStack.canRedo(); 19720 return { 19721 undoEnabled: undoEnabled, 19722 redoEnabled: redoEnabled 19723 }; 19724 }; 19725 return { 19726 getBlobState: getBlobState, 19727 setBlobState: setBlobState, 19728 addBlobState: addBlobState, 19729 getTempState: getTempState, 19730 updateTempState: updateTempState, 19731 addTempState: addTempState, 19732 applyTempState: applyTempState, 19733 destroyTempState: destroyTempState, 19734 undo: undo, 19735 redo: redo, 19736 getHistoryStates: getHistoryStates 19737 }; 19738 }; 19739 19740 var renderImageTools = function (detail, providersBackstage) { 19741 var state = makeState(detail.currentState); 19742 var zoom = function (anyInSystem, simulatedEvent) { 19743 var direction = simulatedEvent.event.direction; 19744 imagePanel.zoom(anyInSystem, direction); 19745 }; 19746 var updateButtonUndoStates = function (anyInSystem) { 19747 var historyStates = state.getHistoryStates(); 19748 sideBar.updateButtonUndoStates(anyInSystem, historyStates.undoEnabled, historyStates.redoEnabled); 19749 emitWith(anyInSystem, external.formActionEvent, { 19750 name: external.saveState(), 19751 value: historyStates.undoEnabled 19752 }); 19753 }; 19754 var disableUndoRedo = function (anyInSystem) { 19755 sideBar.updateButtonUndoStates(anyInSystem, false, false); 19756 }; 19757 var undo = function (anyInSystem, _simulatedEvent) { 19758 var url = state.undo(); 19759 updateSrc(anyInSystem, url).then(function (_oImg) { 19760 unblock(anyInSystem); 19761 updateButtonUndoStates(anyInSystem); 19762 }); 19763 }; 19764 var redo = function (anyInSystem, _simulatedEvent) { 19765 var url = state.redo(); 19766 updateSrc(anyInSystem, url).then(function (_oImg) { 19767 unblock(anyInSystem); 19768 updateButtonUndoStates(anyInSystem); 19769 }); 19770 }; 19771 var imageResultToBlob = function (ir) { 19772 return ir.toBlob(); 19773 }; 19774 var block = function (anyInSystem) { 19775 emitWith(anyInSystem, external.formActionEvent, { 19776 name: external.disable(), 19777 value: {} 19778 }); 19779 }; 19780 var unblock = function (anyInSystem) { 19781 editPanel.getApplyButton(anyInSystem).each(function (applyButton) { 19782 Disabling.enable(applyButton); 19783 }); 19784 emitWith(anyInSystem, external.formActionEvent, { 19785 name: external.enable(), 19786 value: {} 19787 }); 19788 }; 19789 var updateSrc = function (anyInSystem, src) { 19790 block(anyInSystem); 19791 return imagePanel.updateSrc(anyInSystem, src); 19792 }; 19793 var blobManipulate = function (anyInSystem, blob, filter, action, swap) { 19794 block(anyInSystem); 19795 blobToImageResult(blob).then(filter).then(imageResultToBlob).then(action).then(function (url) { 19796 return updateSrc(anyInSystem, url); 19797 }).then(function () { 19798 updateButtonUndoStates(anyInSystem); 19799 swap(); 19800 unblock(anyInSystem); 19801 }).catch(function (err) { 19802 console.log(err); 19803 if (anyInSystem.getSystem().isConnected()) { 19804 unblock(anyInSystem); 19805 } 19806 }); 19807 }; 19808 var manipulate = function (anyInSystem, filter, swap) { 19809 var blob = state.getBlobState().blob; 19810 var action = function (blob) { 19811 return state.updateTempState(blob); 19812 }; 19813 blobManipulate(anyInSystem, blob, filter, action, swap); 19814 }; 19815 var tempManipulate = function (anyInSystem, filter) { 19816 var blob = state.getTempState().blob; 19817 var action = function (blob) { 19818 return state.addTempState(blob); 19819 }; 19820 blobManipulate(anyInSystem, blob, filter, action, noop); 19821 }; 19822 var manipulateApply = function (anyInSystem, filter, swap) { 19823 var blob = state.getBlobState().blob; 19824 var action = function (blob) { 19825 var url = state.addBlobState(blob); 19826 destroyTempState(anyInSystem); 19827 return url; 19828 }; 19829 blobManipulate(anyInSystem, blob, filter, action, swap); 19830 }; 19831 var apply = function (anyInSystem, simulatedEvent) { 19832 var postApply = function () { 19833 destroyTempState(anyInSystem); 19834 var swap = simulatedEvent.event.swap; 19835 swap(); 19836 }; 19837 state.applyTempState(postApply); 19838 }; 19839 var destroyTempState = function (anyInSystem) { 19840 var currentUrl = state.getBlobState().url; 19841 state.destroyTempState(); 19842 updateButtonUndoStates(anyInSystem); 19843 return currentUrl; 19844 }; 19845 var cancel = function (anyInSystem) { 19846 var currentUrl = destroyTempState(anyInSystem); 19847 updateSrc(anyInSystem, currentUrl).then(function (_oImg) { 19848 unblock(anyInSystem); 19849 }); 19850 }; 19851 var back = function (anyInSystem, simulatedEvent) { 19852 cancel(anyInSystem); 19853 var swap = simulatedEvent.event.swap; 19854 swap(); 19855 imagePanel.hideCrop(); 19856 }; 19857 var transform = function (anyInSystem, simulatedEvent) { 19858 return manipulate(anyInSystem, simulatedEvent.event.transform, noop); 19859 }; 19860 var tempTransform = function (anyInSystem, simulatedEvent) { 19861 return tempManipulate(anyInSystem, simulatedEvent.event.transform); 19862 }; 19863 var transformApply = function (anyInSystem, simulatedEvent) { 19864 return manipulateApply(anyInSystem, simulatedEvent.event.transform, simulatedEvent.event.swap); 19865 }; 19866 var imagePanel = renderImagePanel(detail.currentState.url); 19867 var sideBar = renderSideBar(providersBackstage); 19868 var editPanel = renderEditPanel(imagePanel, providersBackstage); 19869 var swap = function (anyInSystem, simulatedEvent) { 19870 disableUndoRedo(anyInSystem); 19871 var transform = simulatedEvent.event.transform; 19872 var swap = simulatedEvent.event.swap; 19873 transform.fold(function () { 19874 swap(); 19875 }, function (transform) { 19876 manipulate(anyInSystem, transform, swap); 19877 }); 19878 }; 19879 return { 19880 dom: { 19881 tag: 'div', 19882 attributes: { role: 'presentation' } 19883 }, 19884 components: [ 19885 editPanel.memContainer.asSpec(), 19886 imagePanel.memContainer.asSpec(), 19887 sideBar.container 19888 ], 19889 behaviours: derive$1([ 19890 Representing.config({ 19891 store: { 19892 mode: 'manual', 19893 getValue: function () { 19894 return state.getBlobState(); 19895 } 19896 } 19897 }), 19898 config('image-tools-events', [ 19899 run$1(internal.undo(), undo), 19900 run$1(internal.redo(), redo), 19901 run$1(internal.zoom(), zoom), 19902 run$1(internal.back(), back), 19903 run$1(internal.apply(), apply), 19904 run$1(internal.transform(), transform), 19905 run$1(internal.tempTransform(), tempTransform), 19906 run$1(internal.transformApply(), transformApply), 19907 run$1(internal.swap(), swap) 19908 ]), 19909 ComposingConfigs.self() 19910 ]) 19911 }; 19912 }; 19913 19914 var renderLabel = function (spec, backstageShared) { 19915 var label = { 19916 dom: { 19917 tag: 'label', 19918 innerHtml: backstageShared.providers.translate(spec.label), 19919 classes: ['tox-label'] 19920 } 19921 }; 19922 var comps = map$2(spec.items, backstageShared.interpreter); 19923 return { 19924 dom: { 19925 tag: 'div', 19926 classes: ['tox-form__group'] 19927 }, 19928 components: [label].concat(comps), 19929 behaviours: derive$1([ 19930 ComposingConfigs.self(), 19931 Replacing.config({}), 19932 RepresentingConfigs.domHtml(Optional.none()), 19933 Keying.config({ mode: 'acyclic' }) 19934 ]) 19935 }; 19936 }; 19937 19938 var isSingleListItem = function (item) { 19939 return !has$2(item, 'items'); 19940 }; 19941 var dataAttribute = 'data-value'; 19942 var fetchItems = function (dropdownComp, name, items, selectedValue) { 19943 return map$2(items, function (item) { 19944 if (!isSingleListItem(item)) { 19945 return { 19946 type: 'nestedmenuitem', 19947 text: item.text, 19948 getSubmenuItems: function () { 19949 return fetchItems(dropdownComp, name, item.items, selectedValue); 19950 } 19951 }; 19952 } else { 19953 return { 19954 type: 'togglemenuitem', 19955 text: item.text, 19956 value: item.value, 19957 active: item.value === selectedValue, 19958 onAction: function () { 19959 Representing.setValue(dropdownComp, item.value); 19960 emitWith(dropdownComp, formChangeEvent, { name: name }); 19961 Focusing.focus(dropdownComp); 19962 } 19963 }; 19964 } 19965 }); 19966 }; 19967 var findItemByValue = function (items, value) { 19968 return findMap(items, function (item) { 19969 if (!isSingleListItem(item)) { 19970 return findItemByValue(item.items, value); 19971 } else { 19972 return someIf(item.value === value, item); 19973 } 19974 }); 19975 }; 19976 var renderListBox = function (spec, backstage) { 19977 var providersBackstage = backstage.shared.providers; 19978 var initialItem = head(spec.items).filter(isSingleListItem); 19979 var pLabel = spec.label.map(function (label) { 19980 return renderLabel$2(label, providersBackstage); 19981 }); 19982 var pField = FormField.parts.field({ 19983 dom: {}, 19984 factory: { 19985 sketch: function (sketchSpec) { 19986 return renderCommonDropdown({ 19987 uid: sketchSpec.uid, 19988 text: initialItem.map(function (item) { 19989 return item.text; 19990 }), 19991 icon: Optional.none(), 19992 tooltip: spec.label, 19993 role: Optional.none(), 19994 fetch: function (comp, callback) { 19995 var items = fetchItems(comp, spec.name, spec.items, Representing.getValue(comp)); 19996 callback(build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false)); 19997 }, 19998 onSetup: constant$1(noop), 19999 getApi: constant$1({}), 20000 columns: 1, 20001 presets: 'normal', 20002 classes: [], 20003 dropdownBehaviours: [ 20004 Tabstopping.config({}), 20005 Representing.config({ 20006 store: { 20007 mode: 'manual', 20008 initialValue: initialItem.map(function (item) { 20009 return item.value; 20010 }).getOr(''), 20011 getValue: function (comp) { 20012 return get$d(comp.element, dataAttribute); 20013 }, 20014 setValue: function (comp, data) { 20015 findItemByValue(spec.items, data).each(function (item) { 20016 set$8(comp.element, dataAttribute, item.value); 20017 emitWith(comp, updateMenuText, { text: item.text }); 20018 }); 20019 } 20020 } 20021 }) 20022 ] 20023 }, 'tox-listbox', backstage.shared); 20024 } 20025 } 20026 }); 20027 var listBoxWrap = { 20028 dom: { 20029 tag: 'div', 20030 classes: ['tox-listboxfield'] 20031 }, 20032 components: [pField] 20033 }; 20034 return FormField.sketch({ 20035 dom: { 20036 tag: 'div', 20037 classes: ['tox-form__group'] 20038 }, 20039 components: flatten([ 20040 pLabel.toArray(), 20041 [listBoxWrap] 20042 ]), 20043 fieldBehaviours: derive$1([Disabling.config({ 20044 disabled: constant$1(spec.disabled), 20045 onDisabled: function (comp) { 20046 FormField.getField(comp).each(Disabling.disable); 20047 }, 20048 onEnabled: function (comp) { 20049 FormField.getField(comp).each(Disabling.enable); 20050 } 20051 })]) 20052 }); 20053 }; 20054 20055 var renderPanel = function (spec, backstage) { 20056 return { 20057 dom: { 20058 tag: 'div', 20059 classes: spec.classes 20060 }, 20061 components: map$2(spec.items, backstage.shared.interpreter) 20062 }; 20063 }; 20064 20065 var factory$e = function (detail, _spec) { 20066 var options = map$2(detail.options, function (option) { 20067 return { 20068 dom: { 20069 tag: 'option', 20070 value: option.value, 20071 innerHtml: option.text 20072 } 20073 }; 20074 }); 20075 var initialValues = detail.data.map(function (v) { 20076 return wrap$1('initialValue', v); 20077 }).getOr({}); 20078 return { 20079 uid: detail.uid, 20080 dom: { 20081 tag: 'select', 20082 classes: detail.selectClasses, 20083 attributes: detail.selectAttributes 20084 }, 20085 components: options, 20086 behaviours: augment(detail.selectBehaviours, [ 20087 Focusing.config({}), 20088 Representing.config({ 20089 store: __assign({ 20090 mode: 'manual', 20091 getValue: function (select) { 20092 return get$5(select.element); 20093 }, 20094 setValue: function (select, newValue) { 20095 var found = find$5(detail.options, function (opt) { 20096 return opt.value === newValue; 20097 }); 20098 if (found.isSome()) { 20099 set$4(select.element, newValue); 20100 } 20101 } 20102 }, initialValues) 20103 }) 20104 ]) 20105 }; 20106 }; 20107 var HtmlSelect = single({ 20108 name: 'HtmlSelect', 20109 configFields: [ 20110 required$1('options'), 20111 field('selectBehaviours', [ 20112 Focusing, 20113 Representing 20114 ]), 20115 defaulted('selectClasses', []), 20116 defaulted('selectAttributes', {}), 20117 option('data') 20118 ], 20119 factory: factory$e 20120 }); 20121 20122 var renderSelectBox = function (spec, providersBackstage) { 20123 var translatedOptions = map$2(spec.items, function (item) { 20124 return { 20125 text: providersBackstage.translate(item.text), 20126 value: item.value 20127 }; 20128 }); 20129 var pLabel = spec.label.map(function (label) { 20130 return renderLabel$2(label, providersBackstage); 20131 }); 20132 var pField = FormField.parts.field({ 20133 dom: {}, 20134 selectAttributes: { size: spec.size }, 20135 options: translatedOptions, 20136 factory: HtmlSelect, 20137 selectBehaviours: derive$1([ 20138 Disabling.config({ 20139 disabled: function () { 20140 return spec.disabled || providersBackstage.isDisabled(); 20141 } 20142 }), 20143 Tabstopping.config({}), 20144 config('selectbox-change', [run$1(change(), function (component, _) { 20145 emitWith(component, formChangeEvent, { name: spec.name }); 20146 })]) 20147 ]) 20148 }); 20149 var chevron = spec.size > 1 ? Optional.none() : Optional.some(render$3('chevron-down', { 20150 tag: 'div', 20151 classes: ['tox-selectfield__icon-js'] 20152 }, providersBackstage.icons)); 20153 var selectWrap = { 20154 dom: { 20155 tag: 'div', 20156 classes: ['tox-selectfield'] 20157 }, 20158 components: flatten([ 20159 [pField], 20160 chevron.toArray() 20161 ]) 20162 }; 20163 return FormField.sketch({ 20164 dom: { 20165 tag: 'div', 20166 classes: ['tox-form__group'] 20167 }, 20168 components: flatten([ 20169 pLabel.toArray(), 20170 [selectWrap] 20171 ]), 20172 fieldBehaviours: derive$1([ 20173 Disabling.config({ 20174 disabled: function () { 20175 return spec.disabled || providersBackstage.isDisabled(); 20176 }, 20177 onDisabled: function (comp) { 20178 FormField.getField(comp).each(Disabling.disable); 20179 }, 20180 onEnabled: function (comp) { 20181 FormField.getField(comp).each(Disabling.enable); 20182 } 20183 }), 20184 receivingConfig() 20185 ]) 20186 }); 20187 }; 20188 20189 var renderTable = function (spec, providersBackstage) { 20190 var renderTh = function (text) { 20191 return { 20192 dom: { 20193 tag: 'th', 20194 innerHtml: providersBackstage.translate(text) 20195 } 20196 }; 20197 }; 20198 var renderHeader = function (header) { 20199 return { 20200 dom: { tag: 'thead' }, 20201 components: [{ 20202 dom: { tag: 'tr' }, 20203 components: map$2(header, renderTh) 20204 }] 20205 }; 20206 }; 20207 var renderTd = function (text) { 20208 return { 20209 dom: { 20210 tag: 'td', 20211 innerHtml: providersBackstage.translate(text) 20212 } 20213 }; 20214 }; 20215 var renderTr = function (row) { 20216 return { 20217 dom: { tag: 'tr' }, 20218 components: map$2(row, renderTd) 20219 }; 20220 }; 20221 var renderRows = function (rows) { 20222 return { 20223 dom: { tag: 'tbody' }, 20224 components: map$2(rows, renderTr) 20225 }; 20226 }; 20227 return { 20228 dom: { 20229 tag: 'table', 20230 classes: ['tox-dialog__table'] 20231 }, 20232 components: [ 20233 renderHeader(spec.header), 20234 renderRows(spec.cells) 20235 ], 20236 behaviours: derive$1([ 20237 Tabstopping.config({}), 20238 Focusing.config({}) 20239 ]) 20240 }; 20241 }; 20242 20243 var renderTextField = function (spec, providersBackstage) { 20244 var pLabel = spec.label.map(function (label) { 20245 return renderLabel$2(label, providersBackstage); 20246 }); 20247 var baseInputBehaviours = [ 20248 Disabling.config({ 20249 disabled: function () { 20250 return spec.disabled || providersBackstage.isDisabled(); 20251 } 20252 }), 20253 receivingConfig(), 20254 Keying.config({ 20255 mode: 'execution', 20256 useEnter: spec.multiline !== true, 20257 useControlEnter: spec.multiline === true, 20258 execute: function (comp) { 20259 emit(comp, formSubmitEvent); 20260 return Optional.some(true); 20261 } 20262 }), 20263 config('textfield-change', [ 20264 run$1(input(), function (component, _) { 20265 emitWith(component, formChangeEvent, { name: spec.name }); 20266 }), 20267 run$1(postPaste(), function (component, _) { 20268 emitWith(component, formChangeEvent, { name: spec.name }); 20269 }) 20270 ]), 20271 Tabstopping.config({}) 20272 ]; 20273 var validatingBehaviours = spec.validation.map(function (vl) { 20274 return Invalidating.config({ 20275 getRoot: function (input) { 20276 return parent(input.element); 20277 }, 20278 invalidClass: 'tox-invalid', 20279 validator: { 20280 validate: function (input) { 20281 var v = Representing.getValue(input); 20282 var result = vl.validator(v); 20283 return Future.pure(result === true ? Result.value(v) : Result.error(result)); 20284 }, 20285 validateOnLoad: vl.validateOnLoad 20286 } 20287 }); 20288 }).toArray(); 20289 var placeholder = spec.placeholder.fold(constant$1({}), function (p) { 20290 return { placeholder: providersBackstage.translate(p) }; 20291 }); 20292 var inputMode = spec.inputMode.fold(constant$1({}), function (mode) { 20293 return { inputmode: mode }; 20294 }); 20295 var inputAttributes = __assign(__assign({}, placeholder), inputMode); 20296 var pField = FormField.parts.field({ 20297 tag: spec.multiline === true ? 'textarea' : 'input', 20298 inputAttributes: inputAttributes, 20299 inputClasses: [spec.classname], 20300 inputBehaviours: derive$1(flatten([ 20301 baseInputBehaviours, 20302 validatingBehaviours 20303 ])), 20304 selectOnFocus: false, 20305 factory: Input 20306 }); 20307 var extraClasses = spec.flex ? ['tox-form__group--stretched'] : []; 20308 var extraClasses2 = extraClasses.concat(spec.maximized ? ['tox-form-group--maximize'] : []); 20309 var extraBehaviours = [ 20310 Disabling.config({ 20311 disabled: function () { 20312 return spec.disabled || providersBackstage.isDisabled(); 20313 }, 20314 onDisabled: function (comp) { 20315 FormField.getField(comp).each(Disabling.disable); 20316 }, 20317 onEnabled: function (comp) { 20318 FormField.getField(comp).each(Disabling.enable); 20319 } 20320 }), 20321 receivingConfig() 20322 ]; 20323 return renderFormFieldWith(pLabel, pField, extraClasses2, extraBehaviours); 20324 }; 20325 var renderInput = function (spec, providersBackstage) { 20326 return renderTextField({ 20327 name: spec.name, 20328 multiline: false, 20329 label: spec.label, 20330 inputMode: spec.inputMode, 20331 placeholder: spec.placeholder, 20332 flex: false, 20333 disabled: spec.disabled, 20334 classname: 'tox-textfield', 20335 validation: Optional.none(), 20336 maximized: spec.maximized 20337 }, providersBackstage); 20338 }; 20339 var renderTextarea = function (spec, providersBackstage) { 20340 return renderTextField({ 20341 name: spec.name, 20342 multiline: true, 20343 label: spec.label, 20344 inputMode: Optional.none(), 20345 placeholder: spec.placeholder, 20346 flex: true, 20347 disabled: spec.disabled, 20348 classname: 'tox-textarea', 20349 validation: Optional.none(), 20350 maximized: spec.maximized 20351 }, providersBackstage); 20352 }; 20353 20354 var events$6 = function (streamConfig, streamState) { 20355 var streams = streamConfig.stream.streams; 20356 var processor = streams.setup(streamConfig, streamState); 20357 return derive$2([ 20358 run$1(streamConfig.event, processor), 20359 runOnDetached(function () { 20360 return streamState.cancel(); 20361 }) 20362 ].concat(streamConfig.cancelEvent.map(function (e) { 20363 return [run$1(e, function () { 20364 return streamState.cancel(); 20365 })]; 20366 }).getOr([]))); 20367 }; 20368 20369 var ActiveStreaming = /*#__PURE__*/Object.freeze({ 20370 __proto__: null, 20371 events: events$6 20372 }); 20373 20374 var throttle = function (_config) { 20375 var state = Cell(null); 20376 var readState = function () { 20377 return { timer: state.get() !== null ? 'set' : 'unset' }; 20378 }; 20379 var setTimer = function (t) { 20380 state.set(t); 20381 }; 20382 var cancel = function () { 20383 var t = state.get(); 20384 if (t !== null) { 20385 t.cancel(); 20386 } 20387 }; 20388 return nu$8({ 20389 readState: readState, 20390 setTimer: setTimer, 20391 cancel: cancel 20392 }); 20393 }; 20394 var init$9 = function (spec) { 20395 return spec.stream.streams.state(spec); 20396 }; 20397 20398 var StreamingState = /*#__PURE__*/Object.freeze({ 20399 __proto__: null, 20400 throttle: throttle, 20401 init: init$9 20402 }); 20403 20404 var setup$c = function (streamInfo, streamState) { 20405 var sInfo = streamInfo.stream; 20406 var throttler = last(streamInfo.onStream, sInfo.delay); 20407 streamState.setTimer(throttler); 20408 return function (component, simulatedEvent) { 20409 throttler.throttle(component, simulatedEvent); 20410 if (sInfo.stopEvent) { 20411 simulatedEvent.stop(); 20412 } 20413 }; 20414 }; 20415 var StreamingSchema = [ 20416 requiredOf('stream', choose$1('mode', { 20417 throttle: [ 20418 required$1('delay'), 20419 defaulted('stopEvent', true), 20420 output$1('streams', { 20421 setup: setup$c, 20422 state: throttle 20423 }) 20424 ] 20425 })), 20426 defaulted('event', 'input'), 20427 option('cancelEvent'), 20428 onStrictHandler('onStream') 20429 ]; 20430 20431 var Streaming = create$7({ 20432 fields: StreamingSchema, 20433 name: 'streaming', 20434 active: ActiveStreaming, 20435 state: StreamingState 20436 }); 20437 20438 var setValueFromItem = function (model, input, item) { 20439 var itemData = Representing.getValue(item); 20440 Representing.setValue(input, itemData); 20441 setCursorAtEnd(input); 20442 }; 20443 var setSelectionOn = function (input, f) { 20444 var el = input.element; 20445 var value = get$5(el); 20446 var node = el.dom; 20447 if (get$d(el, 'type') !== 'number') { 20448 f(node, value); 20449 } 20450 }; 20451 var setCursorAtEnd = function (input) { 20452 setSelectionOn(input, function (node, value) { 20453 return node.setSelectionRange(value.length, value.length); 20454 }); 20455 }; 20456 var setSelectionToEnd = function (input, startOffset) { 20457 setSelectionOn(input, function (node, value) { 20458 return node.setSelectionRange(startOffset, value.length); 20459 }); 20460 }; 20461 var attemptSelectOver = function (model, input, item) { 20462 if (!model.selectsOver) { 20463 return Optional.none(); 20464 } else { 20465 var currentValue = Representing.getValue(input); 20466 var inputDisplay_1 = model.getDisplayText(currentValue); 20467 var itemValue = Representing.getValue(item); 20468 var itemDisplay = model.getDisplayText(itemValue); 20469 return itemDisplay.indexOf(inputDisplay_1) === 0 ? Optional.some(function () { 20470 setValueFromItem(model, input, item); 20471 setSelectionToEnd(input, inputDisplay_1.length); 20472 }) : Optional.none(); 20473 } 20474 }; 20475 20476 var itemExecute = constant$1('alloy.typeahead.itemexecute'); 20477 20478 var make$3 = function (detail, components, spec, externals) { 20479 var navigateList = function (comp, simulatedEvent, highlighter) { 20480 detail.previewing.set(false); 20481 var sandbox = Coupling.getCoupled(comp, 'sandbox'); 20482 if (Sandboxing.isOpen(sandbox)) { 20483 Composing.getCurrent(sandbox).each(function (menu) { 20484 Highlighting.getHighlighted(menu).fold(function () { 20485 highlighter(menu); 20486 }, function () { 20487 dispatchEvent(sandbox, menu.element, 'keydown', simulatedEvent); 20488 }); 20489 }); 20490 } else { 20491 var onOpenSync = function (sandbox) { 20492 Composing.getCurrent(sandbox).each(highlighter); 20493 }; 20494 open(detail, mapFetch(comp), comp, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop); 20495 } 20496 }; 20497 var focusBehaviours$1 = focusBehaviours(detail); 20498 var mapFetch = function (comp) { 20499 return function (tdata) { 20500 return tdata.map(function (data) { 20501 var menus = values(data.menus); 20502 var items = bind$3(menus, function (menu) { 20503 return filter$2(menu.items, function (item) { 20504 return item.type === 'item'; 20505 }); 20506 }); 20507 var repState = Representing.getState(comp); 20508 repState.update(map$2(items, function (item) { 20509 return item.data; 20510 })); 20511 return data; 20512 }); 20513 }; 20514 }; 20515 var behaviours = [ 20516 Focusing.config({}), 20517 Representing.config({ 20518 onSetValue: detail.onSetValue, 20519 store: __assign({ 20520 mode: 'dataset', 20521 getDataKey: function (comp) { 20522 return get$5(comp.element); 20523 }, 20524 getFallbackEntry: function (itemString) { 20525 return { 20526 value: itemString, 20527 meta: {} 20528 }; 20529 }, 20530 setValue: function (comp, data) { 20531 set$4(comp.element, detail.model.getDisplayText(data)); 20532 } 20533 }, detail.initialData.map(function (d) { 20534 return wrap$1('initialValue', d); 20535 }).getOr({})) 20536 }), 20537 Streaming.config({ 20538 stream: { 20539 mode: 'throttle', 20540 delay: detail.responseTime, 20541 stopEvent: false 20542 }, 20543 onStream: function (component, _simulatedEvent) { 20544 var sandbox = Coupling.getCoupled(component, 'sandbox'); 20545 var focusInInput = Focusing.isFocused(component); 20546 if (focusInInput) { 20547 if (get$5(component.element).length >= detail.minChars) { 20548 var previousValue_1 = Composing.getCurrent(sandbox).bind(function (menu) { 20549 return Highlighting.getHighlighted(menu).map(Representing.getValue); 20550 }); 20551 detail.previewing.set(true); 20552 var onOpenSync = function (_sandbox) { 20553 Composing.getCurrent(sandbox).each(function (menu) { 20554 previousValue_1.fold(function () { 20555 if (detail.model.selectsOver) { 20556 Highlighting.highlightFirst(menu); 20557 } 20558 }, function (pv) { 20559 Highlighting.highlightBy(menu, function (item) { 20560 var itemData = Representing.getValue(item); 20561 return itemData.value === pv.value; 20562 }); 20563 Highlighting.getHighlighted(menu).orThunk(function () { 20564 Highlighting.highlightFirst(menu); 20565 return Optional.none(); 20566 }); 20567 }); 20568 }); 20569 }; 20570 open(detail, mapFetch(component), component, sandbox, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop); 20571 } 20572 } 20573 }, 20574 cancelEvent: typeaheadCancel() 20575 }), 20576 Keying.config({ 20577 mode: 'special', 20578 onDown: function (comp, simulatedEvent) { 20579 navigateList(comp, simulatedEvent, Highlighting.highlightFirst); 20580 return Optional.some(true); 20581 }, 20582 onEscape: function (comp) { 20583 var sandbox = Coupling.getCoupled(comp, 'sandbox'); 20584 if (Sandboxing.isOpen(sandbox)) { 20585 Sandboxing.close(sandbox); 20586 return Optional.some(true); 20587 } 20588 return Optional.none(); 20589 }, 20590 onUp: function (comp, simulatedEvent) { 20591 navigateList(comp, simulatedEvent, Highlighting.highlightLast); 20592 return Optional.some(true); 20593 }, 20594 onEnter: function (comp) { 20595 var sandbox = Coupling.getCoupled(comp, 'sandbox'); 20596 var sandboxIsOpen = Sandboxing.isOpen(sandbox); 20597 if (sandboxIsOpen && !detail.previewing.get()) { 20598 return Composing.getCurrent(sandbox).bind(function (menu) { 20599 return Highlighting.getHighlighted(menu); 20600 }).map(function (item) { 20601 emitWith(comp, itemExecute(), { item: item }); 20602 return true; 20603 }); 20604 } else { 20605 var currentValue = Representing.getValue(comp); 20606 emit(comp, typeaheadCancel()); 20607 detail.onExecute(sandbox, comp, currentValue); 20608 if (sandboxIsOpen) { 20609 Sandboxing.close(sandbox); 20610 } 20611 return Optional.some(true); 20612 } 20613 } 20614 }), 20615 Toggling.config({ 20616 toggleClass: detail.markers.openClass, 20617 aria: { mode: 'expanded' } 20618 }), 20619 Coupling.config({ 20620 others: { 20621 sandbox: function (hotspot) { 20622 return makeSandbox$1(detail, hotspot, { 20623 onOpen: function () { 20624 return Toggling.on(hotspot); 20625 }, 20626 onClose: function () { 20627 return Toggling.off(hotspot); 20628 } 20629 }); 20630 } 20631 } 20632 }), 20633 config('typeaheadevents', [ 20634 runOnExecute$1(function (comp) { 20635 var onOpenSync = noop; 20636 togglePopup(detail, mapFetch(comp), comp, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop); 20637 }), 20638 run$1(itemExecute(), function (comp, se) { 20639 var sandbox = Coupling.getCoupled(comp, 'sandbox'); 20640 setValueFromItem(detail.model, comp, se.event.item); 20641 emit(comp, typeaheadCancel()); 20642 detail.onItemExecute(comp, sandbox, se.event.item, Representing.getValue(comp)); 20643 Sandboxing.close(sandbox); 20644 setCursorAtEnd(comp); 20645 }) 20646 ].concat(detail.dismissOnBlur ? [run$1(postBlur(), function (typeahead) { 20647 var sandbox = Coupling.getCoupled(typeahead, 'sandbox'); 20648 if (search(sandbox.element).isNone()) { 20649 Sandboxing.close(sandbox); 20650 } 20651 })] : [])) 20652 ]; 20653 return { 20654 uid: detail.uid, 20655 dom: dom(deepMerge(detail, { 20656 inputAttributes: { 20657 'role': 'combobox', 20658 'aria-autocomplete': 'list', 20659 'aria-haspopup': 'true' 20660 } 20661 })), 20662 behaviours: __assign(__assign({}, focusBehaviours$1), augment(detail.typeaheadBehaviours, behaviours)), 20663 eventOrder: detail.eventOrder 20664 }; 20665 }; 20666 20667 var schema$g = constant$1([ 20668 option('lazySink'), 20669 required$1('fetch'), 20670 defaulted('minChars', 5), 20671 defaulted('responseTime', 1000), 20672 onHandler('onOpen'), 20673 defaulted('getHotspot', Optional.some), 20674 defaulted('getAnchorOverrides', constant$1({})), 20675 defaulted('layouts', Optional.none()), 20676 defaulted('eventOrder', {}), 20677 defaultedObjOf('model', {}, [ 20678 defaulted('getDisplayText', function (itemData) { 20679 return itemData.meta !== undefined && itemData.meta.text !== undefined ? itemData.meta.text : itemData.value; 20680 }), 20681 defaulted('selectsOver', true), 20682 defaulted('populateFromBrowse', true) 20683 ]), 20684 onHandler('onSetValue'), 20685 onKeyboardHandler('onExecute'), 20686 onHandler('onItemExecute'), 20687 defaulted('inputClasses', []), 20688 defaulted('inputAttributes', {}), 20689 defaulted('inputStyles', {}), 20690 defaulted('matchWidth', true), 20691 defaulted('useMinWidth', false), 20692 defaulted('dismissOnBlur', true), 20693 markers$1(['openClass']), 20694 option('initialData'), 20695 field('typeaheadBehaviours', [ 20696 Focusing, 20697 Representing, 20698 Streaming, 20699 Keying, 20700 Toggling, 20701 Coupling 20702 ]), 20703 customField('previewing', function () { 20704 return Cell(true); 20705 }) 20706 ].concat(schema$k()).concat(sandboxFields())); 20707 var parts$b = constant$1([external$1({ 20708 schema: [tieredMenuMarkers()], 20709 name: 'menu', 20710 overrides: function (detail) { 20711 return { 20712 fakeFocus: true, 20713 onHighlight: function (menu, item) { 20714 if (!detail.previewing.get()) { 20715 menu.getSystem().getByUid(detail.uid).each(function (input) { 20716 if (detail.model.populateFromBrowse) { 20717 setValueFromItem(detail.model, input, item); 20718 } 20719 }); 20720 } else { 20721 menu.getSystem().getByUid(detail.uid).each(function (input) { 20722 attemptSelectOver(detail.model, input, item).fold(function () { 20723 return Highlighting.dehighlight(menu, item); 20724 }, function (fn) { 20725 return fn(); 20726 }); 20727 }); 20728 } 20729 detail.previewing.set(false); 20730 }, 20731 onExecute: function (menu, item) { 20732 return menu.getSystem().getByUid(detail.uid).toOptional().map(function (typeahead) { 20733 emitWith(typeahead, itemExecute(), { item: item }); 20734 return true; 20735 }); 20736 }, 20737 onHover: function (menu, item) { 20738 detail.previewing.set(false); 20739 menu.getSystem().getByUid(detail.uid).each(function (input) { 20740 if (detail.model.populateFromBrowse) { 20741 setValueFromItem(detail.model, input, item); 20742 } 20743 }); 20744 } 20745 }; 20746 } 20747 })]); 20748 20749 var Typeahead = composite({ 20750 name: 'Typeahead', 20751 configFields: schema$g(), 20752 partFields: parts$b(), 20753 factory: make$3 20754 }); 20755 20756 var wrap = function (delegate) { 20757 var toCached = function () { 20758 return wrap(delegate.toCached()); 20759 }; 20760 var bindFuture = function (f) { 20761 return wrap(delegate.bind(function (resA) { 20762 return resA.fold(function (err) { 20763 return Future.pure(Result.error(err)); 20764 }, function (a) { 20765 return f(a); 20766 }); 20767 })); 20768 }; 20769 var bindResult = function (f) { 20770 return wrap(delegate.map(function (resA) { 20771 return resA.bind(f); 20772 })); 20773 }; 20774 var mapResult = function (f) { 20775 return wrap(delegate.map(function (resA) { 20776 return resA.map(f); 20777 })); 20778 }; 20779 var mapError = function (f) { 20780 return wrap(delegate.map(function (resA) { 20781 return resA.mapError(f); 20782 })); 20783 }; 20784 var foldResult = function (whenError, whenValue) { 20785 return delegate.map(function (res) { 20786 return res.fold(whenError, whenValue); 20787 }); 20788 }; 20789 var withTimeout = function (timeout, errorThunk) { 20790 return wrap(Future.nu(function (callback) { 20791 var timedOut = false; 20792 var timer = setTimeout(function () { 20793 timedOut = true; 20794 callback(Result.error(errorThunk())); 20795 }, timeout); 20796 delegate.get(function (result) { 20797 if (!timedOut) { 20798 clearTimeout(timer); 20799 callback(result); 20800 } 20801 }); 20802 })); 20803 }; 20804 return __assign(__assign({}, delegate), { 20805 toCached: toCached, 20806 bindFuture: bindFuture, 20807 bindResult: bindResult, 20808 mapResult: mapResult, 20809 mapError: mapError, 20810 foldResult: foldResult, 20811 withTimeout: withTimeout 20812 }); 20813 }; 20814 var nu$1 = function (worker) { 20815 return wrap(Future.nu(worker)); 20816 }; 20817 var value = function (value) { 20818 return wrap(Future.pure(Result.value(value))); 20819 }; 20820 var error = function (error) { 20821 return wrap(Future.pure(Result.error(error))); 20822 }; 20823 var fromResult = function (result) { 20824 return wrap(Future.pure(result)); 20825 }; 20826 var fromFuture = function (future) { 20827 return wrap(future.map(Result.value)); 20828 }; 20829 var fromPromise = function (promise) { 20830 return nu$1(function (completer) { 20831 promise.then(function (value) { 20832 completer(Result.value(value)); 20833 }, function (error) { 20834 completer(Result.error(error)); 20835 }); 20836 }); 20837 }; 20838 var FutureResult = { 20839 nu: nu$1, 20840 wrap: wrap, 20841 pure: value, 20842 value: value, 20843 error: error, 20844 fromResult: fromResult, 20845 fromFuture: fromFuture, 20846 fromPromise: fromPromise 20847 }; 20848 20849 var separator$1 = { type: 'separator' }; 20850 var toMenuItem = function (target) { 20851 return { 20852 type: 'menuitem', 20853 value: target.url, 20854 text: target.title, 20855 meta: { attach: target.attach }, 20856 onAction: noop 20857 }; 20858 }; 20859 var staticMenuItem = function (title, url) { 20860 return { 20861 type: 'menuitem', 20862 value: url, 20863 text: title, 20864 meta: { attach: undefined }, 20865 onAction: noop 20866 }; 20867 }; 20868 var toMenuItems = function (targets) { 20869 return map$2(targets, toMenuItem); 20870 }; 20871 var filterLinkTargets = function (type, targets) { 20872 return filter$2(targets, function (target) { 20873 return target.type === type; 20874 }); 20875 }; 20876 var filteredTargets = function (type, targets) { 20877 return toMenuItems(filterLinkTargets(type, targets)); 20878 }; 20879 var headerTargets = function (linkInfo) { 20880 return filteredTargets('header', linkInfo.targets); 20881 }; 20882 var anchorTargets = function (linkInfo) { 20883 return filteredTargets('anchor', linkInfo.targets); 20884 }; 20885 var anchorTargetTop = function (linkInfo) { 20886 return Optional.from(linkInfo.anchorTop).map(function (url) { 20887 return staticMenuItem('<top>', url); 20888 }).toArray(); 20889 }; 20890 var anchorTargetBottom = function (linkInfo) { 20891 return Optional.from(linkInfo.anchorBottom).map(function (url) { 20892 return staticMenuItem('<bottom>', url); 20893 }).toArray(); 20894 }; 20895 var historyTargets = function (history) { 20896 return map$2(history, function (url) { 20897 return staticMenuItem(url, url); 20898 }); 20899 }; 20900 var joinMenuLists = function (items) { 20901 return foldl(items, function (a, b) { 20902 var bothEmpty = a.length === 0 || b.length === 0; 20903 return bothEmpty ? a.concat(b) : a.concat(separator$1, b); 20904 }, []); 20905 }; 20906 var filterByQuery = function (term, menuItems) { 20907 var lowerCaseTerm = term.toLowerCase(); 20908 return filter$2(menuItems, function (item) { 20909 var text = item.meta !== undefined && item.meta.text !== undefined ? item.meta.text : item.text; 20910 return contains$1(text.toLowerCase(), lowerCaseTerm) || contains$1(item.value.toLowerCase(), lowerCaseTerm); 20911 }); 20912 }; 20913 20914 var getItems = function (fileType, input, urlBackstage) { 20915 var urlInputValue = Representing.getValue(input); 20916 var term = urlInputValue.meta.text !== undefined ? urlInputValue.meta.text : urlInputValue.value; 20917 var info = urlBackstage.getLinkInformation(); 20918 return info.fold(function () { 20919 return []; 20920 }, function (linkInfo) { 20921 var history = filterByQuery(term, historyTargets(urlBackstage.getHistory(fileType))); 20922 return fileType === 'file' ? joinMenuLists([ 20923 history, 20924 filterByQuery(term, headerTargets(linkInfo)), 20925 filterByQuery(term, flatten([ 20926 anchorTargetTop(linkInfo), 20927 anchorTargets(linkInfo), 20928 anchorTargetBottom(linkInfo) 20929 ])) 20930 ]) : history; 20931 }); 20932 }; 20933 var errorId = generate$6('aria-invalid'); 20934 var renderUrlInput = function (spec, backstage, urlBackstage) { 20935 var _a; 20936 var providersBackstage = backstage.shared.providers; 20937 var updateHistory = function (component) { 20938 var urlEntry = Representing.getValue(component); 20939 urlBackstage.addToHistory(urlEntry.value, spec.filetype); 20940 }; 20941 var pField = FormField.parts.field({ 20942 factory: Typeahead, 20943 dismissOnBlur: true, 20944 inputClasses: ['tox-textfield'], 20945 sandboxClasses: ['tox-dialog__popups'], 20946 inputAttributes: { 20947 'aria-errormessage': errorId, 20948 'type': 'url' 20949 }, 20950 minChars: 0, 20951 responseTime: 0, 20952 fetch: function (input) { 20953 var items = getItems(spec.filetype, input, urlBackstage); 20954 var tdata = build(items, ItemResponse$1.BUBBLE_TO_SANDBOX, backstage, false); 20955 return Future.pure(tdata); 20956 }, 20957 getHotspot: function (comp) { 20958 return memUrlBox.getOpt(comp); 20959 }, 20960 onSetValue: function (comp, _newValue) { 20961 if (comp.hasConfigured(Invalidating)) { 20962 Invalidating.run(comp).get(noop); 20963 } 20964 }, 20965 typeaheadBehaviours: derive$1(flatten([ 20966 urlBackstage.getValidationHandler().map(function (handler) { 20967 return Invalidating.config({ 20968 getRoot: function (comp) { 20969 return parent(comp.element); 20970 }, 20971 invalidClass: 'tox-control-wrap--status-invalid', 20972 notify: { 20973 onInvalid: function (comp, err) { 20974 memInvalidIcon.getOpt(comp).each(function (invalidComp) { 20975 set$8(invalidComp.element, 'title', providersBackstage.translate(err)); 20976 }); 20977 } 20978 }, 20979 validator: { 20980 validate: function (input) { 20981 var urlEntry = Representing.getValue(input); 20982 return FutureResult.nu(function (completer) { 20983 handler({ 20984 type: spec.filetype, 20985 url: urlEntry.value 20986 }, function (validation) { 20987 if (validation.status === 'invalid') { 20988 var err = Result.error(validation.message); 20989 completer(err); 20990 } else { 20991 var val = Result.value(validation.message); 20992 completer(val); 20993 } 20994 }); 20995 }); 20996 }, 20997 validateOnLoad: false 20998 } 20999 }); 21000 }).toArray(), 21001 [ 21002 Disabling.config({ 21003 disabled: function () { 21004 return spec.disabled || providersBackstage.isDisabled(); 21005 } 21006 }), 21007 Tabstopping.config({}), 21008 config('urlinput-events', flatten([ 21009 spec.filetype === 'file' ? [run$1(input(), function (comp) { 21010 emitWith(comp, formChangeEvent, { name: spec.name }); 21011 })] : [], 21012 [ 21013 run$1(change(), function (comp) { 21014 emitWith(comp, formChangeEvent, { name: spec.name }); 21015 updateHistory(comp); 21016 }), 21017 run$1(postPaste(), function (comp) { 21018 emitWith(comp, formChangeEvent, { name: spec.name }); 21019 updateHistory(comp); 21020 }) 21021 ] 21022 ])) 21023 ] 21024 ])), 21025 eventOrder: (_a = {}, _a[input()] = [ 21026 'streaming', 21027 'urlinput-events', 21028 'invalidating' 21029 ], _a), 21030 model: { 21031 getDisplayText: function (itemData) { 21032 return itemData.value; 21033 }, 21034 selectsOver: false, 21035 populateFromBrowse: false 21036 }, 21037 markers: { openClass: 'tox-textfield--popup-open' }, 21038 lazySink: backstage.shared.getSink, 21039 parts: { menu: part(false, 1, 'normal') }, 21040 onExecute: function (_menu, component, _entry) { 21041 emitWith(component, formSubmitEvent, {}); 21042 }, 21043 onItemExecute: function (typeahead, _sandbox, _item, _value) { 21044 updateHistory(typeahead); 21045 emitWith(typeahead, formChangeEvent, { name: spec.name }); 21046 } 21047 }); 21048 var pLabel = spec.label.map(function (label) { 21049 return renderLabel$2(label, providersBackstage); 21050 }); 21051 var makeIcon = function (name, errId, icon, label) { 21052 if (icon === void 0) { 21053 icon = name; 21054 } 21055 if (label === void 0) { 21056 label = name; 21057 } 21058 return render$3(icon, { 21059 tag: 'div', 21060 classes: [ 21061 'tox-icon', 21062 'tox-control-wrap__status-icon-' + name 21063 ], 21064 attributes: __assign({ 21065 'title': providersBackstage.translate(label), 21066 'aria-live': 'polite' 21067 }, errId.fold(function () { 21068 return {}; 21069 }, function (id) { 21070 return { id: id }; 21071 })) 21072 }, providersBackstage.icons); 21073 }; 21074 var memInvalidIcon = record(makeIcon('invalid', Optional.some(errorId), 'warning')); 21075 var memStatus = record({ 21076 dom: { 21077 tag: 'div', 21078 classes: ['tox-control-wrap__status-icon-wrap'] 21079 }, 21080 components: [memInvalidIcon.asSpec()] 21081 }); 21082 var optUrlPicker = urlBackstage.getUrlPicker(spec.filetype); 21083 var browseUrlEvent = generate$6('browser.url.event'); 21084 var memUrlBox = record({ 21085 dom: { 21086 tag: 'div', 21087 classes: ['tox-control-wrap'] 21088 }, 21089 components: [ 21090 pField, 21091 memStatus.asSpec() 21092 ], 21093 behaviours: derive$1([Disabling.config({ 21094 disabled: function () { 21095 return spec.disabled || providersBackstage.isDisabled(); 21096 } 21097 })]) 21098 }); 21099 var memUrlPickerButton = record(renderButton({ 21100 name: spec.name, 21101 icon: Optional.some('browse'), 21102 text: spec.label.getOr(''), 21103 disabled: spec.disabled, 21104 primary: false, 21105 borderless: true 21106 }, function (component) { 21107 return emit(component, browseUrlEvent); 21108 }, providersBackstage, [], ['tox-browse-url'])); 21109 var controlHWrapper = function () { 21110 return { 21111 dom: { 21112 tag: 'div', 21113 classes: ['tox-form__controls-h-stack'] 21114 }, 21115 components: flatten([ 21116 [memUrlBox.asSpec()], 21117 optUrlPicker.map(function () { 21118 return memUrlPickerButton.asSpec(); 21119 }).toArray() 21120 ]) 21121 }; 21122 }; 21123 var openUrlPicker = function (comp) { 21124 Composing.getCurrent(comp).each(function (field) { 21125 var componentData = Representing.getValue(field); 21126 var urlData = __assign({ fieldname: spec.name }, componentData); 21127 optUrlPicker.each(function (picker) { 21128 picker(urlData).get(function (chosenData) { 21129 Representing.setValue(field, chosenData); 21130 emitWith(comp, formChangeEvent, { name: spec.name }); 21131 }); 21132 }); 21133 }); 21134 }; 21135 return FormField.sketch({ 21136 dom: renderFormFieldDom(), 21137 components: pLabel.toArray().concat([controlHWrapper()]), 21138 fieldBehaviours: derive$1([ 21139 Disabling.config({ 21140 disabled: function () { 21141 return spec.disabled || providersBackstage.isDisabled(); 21142 }, 21143 onDisabled: function (comp) { 21144 FormField.getField(comp).each(Disabling.disable); 21145 memUrlPickerButton.getOpt(comp).each(Disabling.disable); 21146 }, 21147 onEnabled: function (comp) { 21148 FormField.getField(comp).each(Disabling.enable); 21149 memUrlPickerButton.getOpt(comp).each(Disabling.enable); 21150 } 21151 }), 21152 receivingConfig(), 21153 config('url-input-events', [run$1(browseUrlEvent, openUrlPicker)]) 21154 ]) 21155 }); 21156 }; 21157 21158 var renderAlertBanner = function (spec, providersBackstage) { 21159 return Container.sketch({ 21160 dom: { 21161 tag: 'div', 21162 attributes: { role: 'alert' }, 21163 classes: [ 21164 'tox-notification', 21165 'tox-notification--in', 21166 'tox-notification--' + spec.level 21167 ] 21168 }, 21169 components: [ 21170 { 21171 dom: { 21172 tag: 'div', 21173 classes: ['tox-notification__icon'] 21174 }, 21175 components: [Button.sketch({ 21176 dom: { 21177 tag: 'button', 21178 classes: [ 21179 'tox-button', 21180 'tox-button--naked', 21181 'tox-button--icon' 21182 ], 21183 innerHtml: get$1(spec.icon, providersBackstage.icons), 21184 attributes: { title: providersBackstage.translate(spec.iconTooltip) } 21185 }, 21186 action: function (comp) { 21187 emitWith(comp, formActionEvent, { 21188 name: 'alert-banner', 21189 value: spec.url 21190 }); 21191 }, 21192 buttonBehaviours: derive$1([addFocusableBehaviour()]) 21193 })] 21194 }, 21195 { 21196 dom: { 21197 tag: 'div', 21198 classes: ['tox-notification__body'], 21199 innerHtml: providersBackstage.translate(spec.text) 21200 } 21201 } 21202 ] 21203 }); 21204 }; 21205 21206 var renderCheckbox = function (spec, providerBackstage) { 21207 var repBehaviour = Representing.config({ 21208 store: { 21209 mode: 'manual', 21210 getValue: function (comp) { 21211 var el = comp.element.dom; 21212 return el.checked; 21213 }, 21214 setValue: function (comp, value) { 21215 var el = comp.element.dom; 21216 el.checked = value; 21217 } 21218 } 21219 }); 21220 var toggleCheckboxHandler = function (comp) { 21221 comp.element.dom.click(); 21222 return Optional.some(true); 21223 }; 21224 var pField = FormField.parts.field({ 21225 factory: { sketch: identity$1 }, 21226 dom: { 21227 tag: 'input', 21228 classes: ['tox-checkbox__input'], 21229 attributes: { type: 'checkbox' } 21230 }, 21231 behaviours: derive$1([ 21232 ComposingConfigs.self(), 21233 Disabling.config({ 21234 disabled: function () { 21235 return spec.disabled || providerBackstage.isDisabled(); 21236 } 21237 }), 21238 Tabstopping.config({}), 21239 Focusing.config({}), 21240 repBehaviour, 21241 Keying.config({ 21242 mode: 'special', 21243 onEnter: toggleCheckboxHandler, 21244 onSpace: toggleCheckboxHandler, 21245 stopSpaceKeyup: true 21246 }), 21247 config('checkbox-events', [run$1(change(), function (component, _) { 21248 emitWith(component, formChangeEvent, { name: spec.name }); 21249 })]) 21250 ]) 21251 }); 21252 var pLabel = FormField.parts.label({ 21253 dom: { 21254 tag: 'span', 21255 classes: ['tox-checkbox__label'], 21256 innerHtml: providerBackstage.translate(spec.label) 21257 }, 21258 behaviours: derive$1([Unselecting.config({})]) 21259 }); 21260 var makeIcon = function (className) { 21261 var iconName = className === 'checked' ? 'selected' : 'unselected'; 21262 return render$3(iconName, { 21263 tag: 'span', 21264 classes: [ 21265 'tox-icon', 21266 'tox-checkbox-icon__' + className 21267 ] 21268 }, providerBackstage.icons); 21269 }; 21270 var memIcons = record({ 21271 dom: { 21272 tag: 'div', 21273 classes: ['tox-checkbox__icons'] 21274 }, 21275 components: [ 21276 makeIcon('checked'), 21277 makeIcon('unchecked') 21278 ] 21279 }); 21280 return FormField.sketch({ 21281 dom: { 21282 tag: 'label', 21283 classes: ['tox-checkbox'] 21284 }, 21285 components: [ 21286 pField, 21287 memIcons.asSpec(), 21288 pLabel 21289 ], 21290 fieldBehaviours: derive$1([ 21291 Disabling.config({ 21292 disabled: function () { 21293 return spec.disabled || providerBackstage.isDisabled(); 21294 }, 21295 disableClass: 'tox-checkbox--disabled', 21296 onDisabled: function (comp) { 21297 FormField.getField(comp).each(Disabling.disable); 21298 }, 21299 onEnabled: function (comp) { 21300 FormField.getField(comp).each(Disabling.enable); 21301 } 21302 }), 21303 receivingConfig() 21304 ]) 21305 }); 21306 }; 21307 21308 var renderHtmlPanel = function (spec) { 21309 if (spec.presets === 'presentation') { 21310 return Container.sketch({ 21311 dom: { 21312 tag: 'div', 21313 classes: ['tox-form__group'], 21314 innerHtml: spec.html 21315 } 21316 }); 21317 } else { 21318 return Container.sketch({ 21319 dom: { 21320 tag: 'div', 21321 classes: ['tox-form__group'], 21322 innerHtml: spec.html, 21323 attributes: { role: 'document' } 21324 }, 21325 containerBehaviours: derive$1([ 21326 Tabstopping.config({}), 21327 Focusing.config({}) 21328 ]) 21329 }); 21330 } 21331 }; 21332 21333 var make$2 = function (render) { 21334 return function (parts, spec, backstage) { 21335 return get$e(spec, 'name').fold(function () { 21336 return render(spec, backstage); 21337 }, function (fieldName) { 21338 return parts.field(fieldName, render(spec, backstage)); 21339 }); 21340 }; 21341 }; 21342 var makeIframe = function (render) { 21343 return function (parts, spec, backstage) { 21344 var iframeSpec = deepMerge(spec, { source: 'dynamic' }); 21345 return make$2(render)(parts, iframeSpec, backstage); 21346 }; 21347 }; 21348 var factories = { 21349 bar: make$2(function (spec, backstage) { 21350 return renderBar(spec, backstage.shared); 21351 }), 21352 collection: make$2(function (spec, backstage) { 21353 return renderCollection(spec, backstage.shared.providers); 21354 }), 21355 alertbanner: make$2(function (spec, backstage) { 21356 return renderAlertBanner(spec, backstage.shared.providers); 21357 }), 21358 input: make$2(function (spec, backstage) { 21359 return renderInput(spec, backstage.shared.providers); 21360 }), 21361 textarea: make$2(function (spec, backstage) { 21362 return renderTextarea(spec, backstage.shared.providers); 21363 }), 21364 label: make$2(function (spec, backstage) { 21365 return renderLabel(spec, backstage.shared); 21366 }), 21367 iframe: makeIframe(function (spec, backstage) { 21368 return renderIFrame(spec, backstage.shared.providers); 21369 }), 21370 button: make$2(function (spec, backstage) { 21371 return renderDialogButton(spec, backstage.shared.providers); 21372 }), 21373 checkbox: make$2(function (spec, backstage) { 21374 return renderCheckbox(spec, backstage.shared.providers); 21375 }), 21376 colorinput: make$2(function (spec, backstage) { 21377 return renderColorInput(spec, backstage.shared, backstage.colorinput); 21378 }), 21379 colorpicker: make$2(renderColorPicker), 21380 dropzone: make$2(function (spec, backstage) { 21381 return renderDropZone(spec, backstage.shared.providers); 21382 }), 21383 grid: make$2(function (spec, backstage) { 21384 return renderGrid(spec, backstage.shared); 21385 }), 21386 listbox: make$2(function (spec, backstage) { 21387 return renderListBox(spec, backstage); 21388 }), 21389 selectbox: make$2(function (spec, backstage) { 21390 return renderSelectBox(spec, backstage.shared.providers); 21391 }), 21392 sizeinput: make$2(function (spec, backstage) { 21393 return renderSizeInput(spec, backstage.shared.providers); 21394 }), 21395 urlinput: make$2(function (spec, backstage) { 21396 return renderUrlInput(spec, backstage, backstage.urlinput); 21397 }), 21398 customeditor: make$2(renderCustomEditor), 21399 htmlpanel: make$2(renderHtmlPanel), 21400 imagetools: make$2(function (spec, backstage) { 21401 return renderImageTools(spec, backstage.shared.providers); 21402 }), 21403 table: make$2(function (spec, backstage) { 21404 return renderTable(spec, backstage.shared.providers); 21405 }), 21406 panel: make$2(function (spec, backstage) { 21407 return renderPanel(spec, backstage); 21408 }) 21409 }; 21410 var noFormParts = { 21411 field: function (_name, spec) { 21412 return spec; 21413 } 21414 }; 21415 var interpretInForm = function (parts, spec, oldBackstage) { 21416 var newBackstage = deepMerge(oldBackstage, { 21417 shared: { 21418 interpreter: function (childSpec) { 21419 return interpretParts(parts, childSpec, newBackstage); 21420 } 21421 } 21422 }); 21423 return interpretParts(parts, spec, newBackstage); 21424 }; 21425 var interpretParts = function (parts, spec, backstage) { 21426 return get$e(factories, spec.type).fold(function () { 21427 console.error('Unknown factory type "' + spec.type + '", defaulting to container: ', spec); 21428 return spec; 21429 }, function (factory) { 21430 return factory(parts, spec, backstage); 21431 }); 21432 }; 21433 var interpretWithoutForm = function (spec, backstage) { 21434 var parts = noFormParts; 21435 return interpretParts(parts, spec, backstage); 21436 }; 21437 21438 var bubbleAlignments$2 = { 21439 valignCentre: [], 21440 alignCentre: [], 21441 alignLeft: [], 21442 alignRight: [], 21443 right: [], 21444 left: [], 21445 bottom: [], 21446 top: [] 21447 }; 21448 var getInlineDialogAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) { 21449 var bubbleSize = 12; 21450 var overrides = { maxHeightFunction: expandable$1() }; 21451 var editableAreaAnchor = function () { 21452 return { 21453 type: 'node', 21454 root: getContentContainer(contentAreaElement()), 21455 node: Optional.from(contentAreaElement()), 21456 bubble: nu$5(bubbleSize, bubbleSize, bubbleAlignments$2), 21457 layouts: { 21458 onRtl: function () { 21459 return [northeast]; 21460 }, 21461 onLtr: function () { 21462 return [northwest]; 21463 } 21464 }, 21465 overrides: overrides 21466 }; 21467 }; 21468 var standardAnchor = function () { 21469 return { 21470 type: 'hotspot', 21471 hotspot: lazyAnchorbar(), 21472 bubble: nu$5(-bubbleSize, bubbleSize, bubbleAlignments$2), 21473 layouts: { 21474 onRtl: function () { 21475 return [southeast$2]; 21476 }, 21477 onLtr: function () { 21478 return [southwest$2]; 21479 } 21480 }, 21481 overrides: overrides 21482 }; 21483 }; 21484 return function () { 21485 return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor(); 21486 }; 21487 }; 21488 var getBannerAnchor = function (contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor) { 21489 var editableAreaAnchor = function () { 21490 return { 21491 type: 'node', 21492 root: getContentContainer(contentAreaElement()), 21493 node: Optional.from(contentAreaElement()), 21494 layouts: { 21495 onRtl: function () { 21496 return [north]; 21497 }, 21498 onLtr: function () { 21499 return [north]; 21500 } 21501 } 21502 }; 21503 }; 21504 var standardAnchor = function () { 21505 return { 21506 type: 'hotspot', 21507 hotspot: lazyAnchorbar(), 21508 layouts: { 21509 onRtl: function () { 21510 return [south$2]; 21511 }, 21512 onLtr: function () { 21513 return [south$2]; 21514 } 21515 } 21516 }; 21517 }; 21518 return function () { 21519 return lazyUseEditableAreaAnchor() ? editableAreaAnchor() : standardAnchor(); 21520 }; 21521 }; 21522 var getCursorAnchor = function (editor, bodyElement) { 21523 return function () { 21524 return { 21525 type: 'selection', 21526 root: bodyElement(), 21527 getSelection: function () { 21528 var rng = editor.selection.getRng(); 21529 return Optional.some(SimSelection.range(SugarElement.fromDom(rng.startContainer), rng.startOffset, SugarElement.fromDom(rng.endContainer), rng.endOffset)); 21530 } 21531 }; 21532 }; 21533 }; 21534 var getNodeAnchor$1 = function (bodyElement) { 21535 return function (element) { 21536 return { 21537 type: 'node', 21538 root: bodyElement(), 21539 node: element 21540 }; 21541 }; 21542 }; 21543 var getAnchors = function (editor, lazyAnchorbar, isToolbarTop) { 21544 var useFixedToolbarContainer = useFixedContainer(editor); 21545 var bodyElement = function () { 21546 return SugarElement.fromDom(editor.getBody()); 21547 }; 21548 var contentAreaElement = function () { 21549 return SugarElement.fromDom(editor.getContentAreaContainer()); 21550 }; 21551 var lazyUseEditableAreaAnchor = function () { 21552 return useFixedToolbarContainer || !isToolbarTop(); 21553 }; 21554 return { 21555 inlineDialog: getInlineDialogAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor), 21556 banner: getBannerAnchor(contentAreaElement, lazyAnchorbar, lazyUseEditableAreaAnchor), 21557 cursor: getCursorAnchor(editor, bodyElement), 21558 node: getNodeAnchor$1(bodyElement) 21559 }; 21560 }; 21561 21562 var colorPicker = function (editor) { 21563 return function (callback, value) { 21564 var dialog = colorPickerDialog(editor); 21565 dialog(callback, value); 21566 }; 21567 }; 21568 var hasCustomColors = function (editor) { 21569 return function () { 21570 return hasCustomColors$1(editor); 21571 }; 21572 }; 21573 var getColors = function (editor) { 21574 return function () { 21575 return getColors$2(editor); 21576 }; 21577 }; 21578 var getColorCols = function (editor) { 21579 return function () { 21580 return getColorCols$1(editor); 21581 }; 21582 }; 21583 var ColorInputBackstage = function (editor) { 21584 return { 21585 colorPicker: colorPicker(editor), 21586 hasCustomColors: hasCustomColors(editor), 21587 getColors: getColors(editor), 21588 getColorCols: getColorCols(editor) 21589 }; 21590 }; 21591 21592 var isDraggableModal = function (editor) { 21593 return function () { 21594 return isDraggableModal$1(editor); 21595 }; 21596 }; 21597 var DialogBackstage = function (editor) { 21598 return { isDraggableModal: isDraggableModal(editor) }; 21599 }; 21600 21601 var HeaderBackstage = function (editor) { 21602 var mode = Cell(isToolbarLocationBottom(editor) ? 'bottom' : 'top'); 21603 return { 21604 isPositionedAtTop: function () { 21605 return mode.get() === 'top'; 21606 }, 21607 getDockingMode: mode.get, 21608 setDockingMode: mode.set 21609 }; 21610 }; 21611 21612 var defaultStyleFormats = [ 21613 { 21614 title: 'Headings', 21615 items: [ 21616 { 21617 title: 'Heading 1', 21618 format: 'h1' 21619 }, 21620 { 21621 title: 'Heading 2', 21622 format: 'h2' 21623 }, 21624 { 21625 title: 'Heading 3', 21626 format: 'h3' 21627 }, 21628 { 21629 title: 'Heading 4', 21630 format: 'h4' 21631 }, 21632 { 21633 title: 'Heading 5', 21634 format: 'h5' 21635 }, 21636 { 21637 title: 'Heading 6', 21638 format: 'h6' 21639 } 21640 ] 21641 }, 21642 { 21643 title: 'Inline', 21644 items: [ 21645 { 21646 title: 'Bold', 21647 format: 'bold' 21648 }, 21649 { 21650 title: 'Italic', 21651 format: 'italic' 21652 }, 21653 { 21654 title: 'Underline', 21655 format: 'underline' 21656 }, 21657 { 21658 title: 'Strikethrough', 21659 format: 'strikethrough' 21660 }, 21661 { 21662 title: 'Superscript', 21663 format: 'superscript' 21664 }, 21665 { 21666 title: 'Subscript', 21667 format: 'subscript' 21668 }, 21669 { 21670 title: 'Code', 21671 format: 'code' 21672 } 21673 ] 21674 }, 21675 { 21676 title: 'Blocks', 21677 items: [ 21678 { 21679 title: 'Paragraph', 21680 format: 'p' 21681 }, 21682 { 21683 title: 'Blockquote', 21684 format: 'blockquote' 21685 }, 21686 { 21687 title: 'Div', 21688 format: 'div' 21689 }, 21690 { 21691 title: 'Pre', 21692 format: 'pre' 21693 } 21694 ] 21695 }, 21696 { 21697 title: 'Align', 21698 items: [ 21699 { 21700 title: 'Left', 21701 format: 'alignleft' 21702 }, 21703 { 21704 title: 'Center', 21705 format: 'aligncenter' 21706 }, 21707 { 21708 title: 'Right', 21709 format: 'alignright' 21710 }, 21711 { 21712 title: 'Justify', 21713 format: 'alignjustify' 21714 } 21715 ] 21716 } 21717 ]; 21718 var isNestedFormat = function (format) { 21719 return has$2(format, 'items'); 21720 }; 21721 var isBlockFormat = function (format) { 21722 return has$2(format, 'block'); 21723 }; 21724 var isInlineFormat = function (format) { 21725 return has$2(format, 'inline'); 21726 }; 21727 var isSelectorFormat = function (format) { 21728 return has$2(format, 'selector'); 21729 }; 21730 var mapFormats = function (userFormats) { 21731 return foldl(userFormats, function (acc, fmt) { 21732 if (isNestedFormat(fmt)) { 21733 var result = mapFormats(fmt.items); 21734 return { 21735 customFormats: acc.customFormats.concat(result.customFormats), 21736 formats: acc.formats.concat([{ 21737 title: fmt.title, 21738 items: result.formats 21739 }]) 21740 }; 21741 } else if (isInlineFormat(fmt) || isBlockFormat(fmt) || isSelectorFormat(fmt)) { 21742 var formatName = isString(fmt.name) ? fmt.name : fmt.title.toLowerCase(); 21743 var formatNameWithPrefix = 'custom-' + formatName; 21744 return { 21745 customFormats: acc.customFormats.concat([{ 21746 name: formatNameWithPrefix, 21747 format: fmt 21748 }]), 21749 formats: acc.formats.concat([{ 21750 title: fmt.title, 21751 format: formatNameWithPrefix, 21752 icon: fmt.icon 21753 }]) 21754 }; 21755 } else { 21756 return __assign(__assign({}, acc), { formats: acc.formats.concat(fmt) }); 21757 } 21758 }, { 21759 customFormats: [], 21760 formats: [] 21761 }); 21762 }; 21763 var registerCustomFormats = function (editor, userFormats) { 21764 var result = mapFormats(userFormats); 21765 var registerFormats = function (customFormats) { 21766 each$1(customFormats, function (fmt) { 21767 if (!editor.formatter.has(fmt.name)) { 21768 editor.formatter.register(fmt.name, fmt.format); 21769 } 21770 }); 21771 }; 21772 if (editor.formatter) { 21773 registerFormats(result.customFormats); 21774 } else { 21775 editor.on('init', function () { 21776 registerFormats(result.customFormats); 21777 }); 21778 } 21779 return result.formats; 21780 }; 21781 var getStyleFormats = function (editor) { 21782 return getUserStyleFormats(editor).map(function (userFormats) { 21783 var registeredUserFormats = registerCustomFormats(editor, userFormats); 21784 return isMergeStyleFormats(editor) ? defaultStyleFormats.concat(registeredUserFormats) : registeredUserFormats; 21785 }).getOr(defaultStyleFormats); 21786 }; 21787 21788 var processBasic = function (item, isSelectedFor, getPreviewFor) { 21789 var formatterSpec = { 21790 type: 'formatter', 21791 isSelected: isSelectedFor(item.format), 21792 getStylePreview: getPreviewFor(item.format) 21793 }; 21794 return deepMerge(item, formatterSpec); 21795 }; 21796 var register$8 = function (editor, formats, isSelectedFor, getPreviewFor) { 21797 var enrichSupported = function (item) { 21798 return processBasic(item, isSelectedFor, getPreviewFor); 21799 }; 21800 var enrichMenu = function (item) { 21801 var submenuSpec = { type: 'submenu' }; 21802 return deepMerge(item, submenuSpec); 21803 }; 21804 var enrichCustom = function (item) { 21805 var formatName = isString(item.name) ? item.name : generate$6(item.title); 21806 var formatNameWithPrefix = 'custom-' + formatName; 21807 var customSpec = { 21808 type: 'formatter', 21809 format: formatNameWithPrefix, 21810 isSelected: isSelectedFor(formatNameWithPrefix), 21811 getStylePreview: getPreviewFor(formatNameWithPrefix) 21812 }; 21813 var newItem = deepMerge(item, customSpec); 21814 editor.formatter.register(formatName, newItem); 21815 return newItem; 21816 }; 21817 var doEnrich = function (items) { 21818 return map$2(items, function (item) { 21819 var keys$1 = keys(item); 21820 if (hasNonNullableKey(item, 'items')) { 21821 var newItems = doEnrich(item.items); 21822 return deepMerge(enrichMenu(item), { getStyleItems: constant$1(newItems) }); 21823 } else if (hasNonNullableKey(item, 'format')) { 21824 return enrichSupported(item); 21825 } else if (keys$1.length === 1 && contains$2(keys$1, 'title')) { 21826 return deepMerge(item, { type: 'separator' }); 21827 } else { 21828 return enrichCustom(item); 21829 } 21830 }); 21831 }; 21832 return doEnrich(formats); 21833 }; 21834 21835 var init$8 = function (editor) { 21836 var isSelectedFor = function (format) { 21837 return function () { 21838 return editor.formatter.match(format); 21839 }; 21840 }; 21841 var getPreviewFor = function (format) { 21842 return function () { 21843 var fmt = editor.formatter.get(format); 21844 return fmt !== undefined ? Optional.some({ 21845 tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div', 21846 styles: editor.dom.parseStyle(editor.formatter.getCssText(format)) 21847 }) : Optional.none(); 21848 }; 21849 }; 21850 var flatten = function (fmt) { 21851 var subs = fmt.items; 21852 return subs !== undefined && subs.length > 0 ? bind$3(subs, flatten) : [fmt.format]; 21853 }; 21854 var settingsFormats = Cell([]); 21855 var settingsFlattenedFormats = Cell([]); 21856 var eventsFormats = Cell([]); 21857 var eventsFlattenedFormats = Cell([]); 21858 var replaceSettings = Cell(false); 21859 editor.on('PreInit', function (_e) { 21860 var formats = getStyleFormats(editor); 21861 var enriched = register$8(editor, formats, isSelectedFor, getPreviewFor); 21862 settingsFormats.set(enriched); 21863 settingsFlattenedFormats.set(bind$3(enriched, flatten)); 21864 }); 21865 editor.on('addStyleModifications', function (e) { 21866 var modifications = register$8(editor, e.items, isSelectedFor, getPreviewFor); 21867 eventsFormats.set(modifications); 21868 replaceSettings.set(e.replace); 21869 eventsFlattenedFormats.set(bind$3(modifications, flatten)); 21870 }); 21871 var getData = function () { 21872 var fromSettings = replaceSettings.get() ? [] : settingsFormats.get(); 21873 var fromEvents = eventsFormats.get(); 21874 return fromSettings.concat(fromEvents); 21875 }; 21876 var getFlattenedKeys = function () { 21877 var fromSettings = replaceSettings.get() ? [] : settingsFlattenedFormats.get(); 21878 var fromEvents = eventsFlattenedFormats.get(); 21879 return fromSettings.concat(fromEvents); 21880 }; 21881 return { 21882 getData: getData, 21883 getFlattenedKeys: getFlattenedKeys 21884 }; 21885 }; 21886 21887 var isElement = function (node) { 21888 return isNonNullable(node) && node.nodeType === 1; 21889 }; 21890 var trim = global$5.trim; 21891 var hasContentEditableState = function (value) { 21892 return function (node) { 21893 if (isElement(node)) { 21894 if (node.contentEditable === value) { 21895 return true; 21896 } 21897 if (node.getAttribute('data-mce-contenteditable') === value) { 21898 return true; 21899 } 21900 } 21901 return false; 21902 }; 21903 }; 21904 var isContentEditableTrue = hasContentEditableState('true'); 21905 var isContentEditableFalse = hasContentEditableState('false'); 21906 var create = function (type, title, url, level, attach) { 21907 return { 21908 type: type, 21909 title: title, 21910 url: url, 21911 level: level, 21912 attach: attach 21913 }; 21914 }; 21915 var isChildOfContentEditableTrue = function (node) { 21916 while (node = node.parentNode) { 21917 var value = node.contentEditable; 21918 if (value && value !== 'inherit') { 21919 return isContentEditableTrue(node); 21920 } 21921 } 21922 return false; 21923 }; 21924 var select = function (selector, root) { 21925 return map$2(descendants(SugarElement.fromDom(root), selector), function (element) { 21926 return element.dom; 21927 }); 21928 }; 21929 var getElementText = function (elm) { 21930 return elm.innerText || elm.textContent; 21931 }; 21932 var getOrGenerateId = function (elm) { 21933 return elm.id ? elm.id : generate$6('h'); 21934 }; 21935 var isAnchor = function (elm) { 21936 return elm && elm.nodeName === 'A' && (elm.id || elm.name) !== undefined; 21937 }; 21938 var isValidAnchor = function (elm) { 21939 return isAnchor(elm) && isEditable(elm); 21940 }; 21941 var isHeader = function (elm) { 21942 return elm && /^(H[1-6])$/.test(elm.nodeName); 21943 }; 21944 var isEditable = function (elm) { 21945 return isChildOfContentEditableTrue(elm) && !isContentEditableFalse(elm); 21946 }; 21947 var isValidHeader = function (elm) { 21948 return isHeader(elm) && isEditable(elm); 21949 }; 21950 var getLevel = function (elm) { 21951 return isHeader(elm) ? parseInt(elm.nodeName.substr(1), 10) : 0; 21952 }; 21953 var headerTarget = function (elm) { 21954 var headerId = getOrGenerateId(elm); 21955 var attach = function () { 21956 elm.id = headerId; 21957 }; 21958 return create('header', getElementText(elm), '#' + headerId, getLevel(elm), attach); 21959 }; 21960 var anchorTarget = function (elm) { 21961 var anchorId = elm.id || elm.name; 21962 var anchorText = getElementText(elm); 21963 return create('anchor', anchorText ? anchorText : '#' + anchorId, '#' + anchorId, 0, noop); 21964 }; 21965 var getHeaderTargets = function (elms) { 21966 return map$2(filter$2(elms, isValidHeader), headerTarget); 21967 }; 21968 var getAnchorTargets = function (elms) { 21969 return map$2(filter$2(elms, isValidAnchor), anchorTarget); 21970 }; 21971 var getTargetElements = function (elm) { 21972 var elms = select('h1,h2,h3,h4,h5,h6,a:not([href])', elm); 21973 return elms; 21974 }; 21975 var hasTitle = function (target) { 21976 return trim(target.title).length > 0; 21977 }; 21978 var find = function (elm) { 21979 var elms = getTargetElements(elm); 21980 return filter$2(getHeaderTargets(elms).concat(getAnchorTargets(elms)), hasTitle); 21981 }; 21982 var LinkTargets = { find: find }; 21983 21984 var STORAGE_KEY = 'tinymce-url-history'; 21985 var HISTORY_LENGTH = 5; 21986 var isHttpUrl = function (url) { 21987 return isString(url) && /^https?/.test(url); 21988 }; 21989 var isArrayOfUrl = function (a) { 21990 return isArray(a) && a.length <= HISTORY_LENGTH && forall(a, isHttpUrl); 21991 }; 21992 var isRecordOfUrlArray = function (r) { 21993 return isObject(r) && find$4(r, function (value) { 21994 return !isArrayOfUrl(value); 21995 }).isNone(); 21996 }; 21997 var getAllHistory = function () { 21998 var unparsedHistory = global$8.getItem(STORAGE_KEY); 21999 if (unparsedHistory === null) { 22000 return {}; 22001 } 22002 var history; 22003 try { 22004 history = JSON.parse(unparsedHistory); 22005 } catch (e) { 22006 if (e instanceof SyntaxError) { 22007 console.log('Local storage ' + STORAGE_KEY + ' was not valid JSON', e); 22008 return {}; 22009 } 22010 throw e; 22011 } 22012 if (!isRecordOfUrlArray(history)) { 22013 console.log('Local storage ' + STORAGE_KEY + ' was not valid format', history); 22014 return {}; 22015 } 22016 return history; 22017 }; 22018 var setAllHistory = function (history) { 22019 if (!isRecordOfUrlArray(history)) { 22020 throw new Error('Bad format for history:\n' + JSON.stringify(history)); 22021 } 22022 global$8.setItem(STORAGE_KEY, JSON.stringify(history)); 22023 }; 22024 var getHistory = function (fileType) { 22025 var history = getAllHistory(); 22026 return get$e(history, fileType).getOr([]); 22027 }; 22028 var addToHistory = function (url, fileType) { 22029 if (!isHttpUrl(url)) { 22030 return; 22031 } 22032 var history = getAllHistory(); 22033 var items = get$e(history, fileType).getOr([]); 22034 var itemsWithoutUrl = filter$2(items, function (item) { 22035 return item !== url; 22036 }); 22037 history[fileType] = [url].concat(itemsWithoutUrl).slice(0, HISTORY_LENGTH); 22038 setAllHistory(history); 22039 }; 22040 22041 var isTruthy = function (value) { 22042 return !!value; 22043 }; 22044 var makeMap = function (value) { 22045 return map$1(global$5.makeMap(value, /[, ]/), isTruthy); 22046 }; 22047 var getPicker = function (editor) { 22048 return Optional.from(getFilePickerCallback(editor)).filter(isFunction); 22049 }; 22050 var getPickerTypes = function (editor) { 22051 var optFileTypes = Optional.some(getFilePickerTypes(editor)).filter(isTruthy); 22052 var optLegacyTypes = Optional.some(getFileBrowserCallbackTypes(editor)).filter(isTruthy); 22053 var optTypes = optFileTypes.or(optLegacyTypes).map(makeMap); 22054 return getPicker(editor).fold(never, function (_picker) { 22055 return optTypes.fold(always, function (types) { 22056 return keys(types).length > 0 ? types : false; 22057 }); 22058 }); 22059 }; 22060 var getPickerSetting = function (editor, filetype) { 22061 var pickerTypes = getPickerTypes(editor); 22062 if (isBoolean(pickerTypes)) { 22063 return pickerTypes ? getPicker(editor) : Optional.none(); 22064 } else { 22065 return pickerTypes[filetype] ? getPicker(editor) : Optional.none(); 22066 } 22067 }; 22068 var getUrlPicker = function (editor, filetype) { 22069 return getPickerSetting(editor, filetype).map(function (picker) { 22070 return function (entry) { 22071 return Future.nu(function (completer) { 22072 var handler = function (value, meta) { 22073 if (!isString(value)) { 22074 throw new Error('Expected value to be string'); 22075 } 22076 if (meta !== undefined && !isObject(meta)) { 22077 throw new Error('Expected meta to be a object'); 22078 } 22079 var r = { 22080 value: value, 22081 meta: meta 22082 }; 22083 completer(r); 22084 }; 22085 var meta = __assign({ 22086 filetype: filetype, 22087 fieldname: entry.fieldname 22088 }, Optional.from(entry.meta).getOr({})); 22089 picker.call(editor, handler, entry.value, meta); 22090 }); 22091 }; 22092 }); 22093 }; 22094 var getTextSetting = function (value) { 22095 return Optional.from(value).filter(isString).getOrUndefined(); 22096 }; 22097 var getLinkInformation = function (editor) { 22098 if (noTypeaheadUrls(editor)) { 22099 return Optional.none(); 22100 } 22101 return Optional.some({ 22102 targets: LinkTargets.find(editor.getBody()), 22103 anchorTop: getTextSetting(getAnchorTop(editor)), 22104 anchorBottom: getTextSetting(getAnchorBottom(editor)) 22105 }); 22106 }; 22107 var getValidationHandler = function (editor) { 22108 return Optional.from(getFilePickerValidatorHandler(editor)); 22109 }; 22110 var UrlInputBackstage = function (editor) { 22111 return { 22112 getHistory: getHistory, 22113 addToHistory: addToHistory, 22114 getLinkInformation: function () { 22115 return getLinkInformation(editor); 22116 }, 22117 getValidationHandler: function () { 22118 return getValidationHandler(editor); 22119 }, 22120 getUrlPicker: function (filetype) { 22121 return getUrlPicker(editor, filetype); 22122 } 22123 }; 22124 }; 22125 22126 var init$7 = function (sink, editor, lazyAnchorbar) { 22127 var contextMenuState = Cell(false); 22128 var toolbar = HeaderBackstage(editor); 22129 var backstage = { 22130 shared: { 22131 providers: { 22132 icons: function () { 22133 return editor.ui.registry.getAll().icons; 22134 }, 22135 menuItems: function () { 22136 return editor.ui.registry.getAll().menuItems; 22137 }, 22138 translate: global$e.translate, 22139 isDisabled: function () { 22140 return editor.mode.isReadOnly() || editor.ui.isDisabled(); 22141 }, 22142 getSetting: editor.getParam.bind(editor) 22143 }, 22144 interpreter: function (s) { 22145 return interpretWithoutForm(s, backstage); 22146 }, 22147 anchors: getAnchors(editor, lazyAnchorbar, toolbar.isPositionedAtTop), 22148 header: toolbar, 22149 getSink: function () { 22150 return Result.value(sink); 22151 } 22152 }, 22153 urlinput: UrlInputBackstage(editor), 22154 styleselect: init$8(editor), 22155 colorinput: ColorInputBackstage(editor), 22156 dialog: DialogBackstage(editor), 22157 isContextMenuOpen: function () { 22158 return contextMenuState.get(); 22159 }, 22160 setContextMenuState: function (state) { 22161 return contextMenuState.set(state); 22162 } 22163 }; 22164 return backstage; 22165 }; 22166 22167 var setup$b = function (editor, mothership, uiMothership) { 22168 var broadcastEvent = function (name, evt) { 22169 each$1([ 22170 mothership, 22171 uiMothership 22172 ], function (ship) { 22173 ship.broadcastEvent(name, evt); 22174 }); 22175 }; 22176 var broadcastOn = function (channel, message) { 22177 each$1([ 22178 mothership, 22179 uiMothership 22180 ], function (ship) { 22181 ship.broadcastOn([channel], message); 22182 }); 22183 }; 22184 var fireDismissPopups = function (evt) { 22185 return broadcastOn(dismissPopups(), { target: evt.target }); 22186 }; 22187 var doc = getDocument(); 22188 var onTouchstart = bind(doc, 'touchstart', fireDismissPopups); 22189 var onTouchmove = bind(doc, 'touchmove', function (evt) { 22190 return broadcastEvent(documentTouchmove(), evt); 22191 }); 22192 var onTouchend = bind(doc, 'touchend', function (evt) { 22193 return broadcastEvent(documentTouchend(), evt); 22194 }); 22195 var onMousedown = bind(doc, 'mousedown', fireDismissPopups); 22196 var onMouseup = bind(doc, 'mouseup', function (evt) { 22197 if (evt.raw.button === 0) { 22198 broadcastOn(mouseReleased(), { target: evt.target }); 22199 } 22200 }); 22201 var onContentClick = function (raw) { 22202 return broadcastOn(dismissPopups(), { target: SugarElement.fromDom(raw.target) }); 22203 }; 22204 var onContentMouseup = function (raw) { 22205 if (raw.button === 0) { 22206 broadcastOn(mouseReleased(), { target: SugarElement.fromDom(raw.target) }); 22207 } 22208 }; 22209 var onContentMousedown = function () { 22210 each$1(editor.editorManager.get(), function (loopEditor) { 22211 if (editor !== loopEditor) { 22212 loopEditor.fire('DismissPopups', { relatedTarget: editor }); 22213 } 22214 }); 22215 }; 22216 var onWindowScroll = function (evt) { 22217 return broadcastEvent(windowScroll(), fromRawEvent(evt)); 22218 }; 22219 var onWindowResize = function (evt) { 22220 broadcastOn(repositionPopups(), {}); 22221 broadcastEvent(windowResize(), fromRawEvent(evt)); 22222 }; 22223 var onEditorResize = function () { 22224 return broadcastOn(repositionPopups(), {}); 22225 }; 22226 var onEditorProgress = function (evt) { 22227 if (evt.state) { 22228 broadcastOn(dismissPopups(), { target: SugarElement.fromDom(editor.getContainer()) }); 22229 } 22230 }; 22231 var onDismissPopups = function (event) { 22232 broadcastOn(dismissPopups(), { target: SugarElement.fromDom(event.relatedTarget.getContainer()) }); 22233 }; 22234 editor.on('PostRender', function () { 22235 editor.on('click', onContentClick); 22236 editor.on('tap', onContentClick); 22237 editor.on('mouseup', onContentMouseup); 22238 editor.on('mousedown', onContentMousedown); 22239 editor.on('ScrollWindow', onWindowScroll); 22240 editor.on('ResizeWindow', onWindowResize); 22241 editor.on('ResizeEditor', onEditorResize); 22242 editor.on('AfterProgressState', onEditorProgress); 22243 editor.on('DismissPopups', onDismissPopups); 22244 }); 22245 editor.on('remove', function () { 22246 editor.off('click', onContentClick); 22247 editor.off('tap', onContentClick); 22248 editor.off('mouseup', onContentMouseup); 22249 editor.off('mousedown', onContentMousedown); 22250 editor.off('ScrollWindow', onWindowScroll); 22251 editor.off('ResizeWindow', onWindowResize); 22252 editor.off('ResizeEditor', onEditorResize); 22253 editor.off('AfterProgressState', onEditorProgress); 22254 editor.off('DismissPopups', onDismissPopups); 22255 onMousedown.unbind(); 22256 onTouchstart.unbind(); 22257 onTouchmove.unbind(); 22258 onTouchend.unbind(); 22259 onMouseup.unbind(); 22260 }); 22261 editor.on('detach', function () { 22262 detachSystem(mothership); 22263 detachSystem(uiMothership); 22264 mothership.destroy(); 22265 uiMothership.destroy(); 22266 }); 22267 }; 22268 22269 var parts$a = AlloyParts; 22270 var partType = PartType; 22271 22272 var schema$f = constant$1([ 22273 defaulted('shell', false), 22274 required$1('makeItem'), 22275 defaulted('setupItem', noop), 22276 SketchBehaviours.field('listBehaviours', [Replacing]) 22277 ]); 22278 var customListDetail = function () { 22279 return { behaviours: derive$1([Replacing.config({})]) }; 22280 }; 22281 var itemsPart = optional({ 22282 name: 'items', 22283 overrides: customListDetail 22284 }); 22285 var parts$9 = constant$1([itemsPart]); 22286 var name = constant$1('CustomList'); 22287 22288 var factory$d = function (detail, components, _spec, _external) { 22289 var setItems = function (list, items) { 22290 getListContainer(list).fold(function () { 22291 console.error('Custom List was defined to not be a shell, but no item container was specified in components'); 22292 throw new Error('Custom List was defined to not be a shell, but no item container was specified in components'); 22293 }, function (container) { 22294 var itemComps = Replacing.contents(container); 22295 var numListsRequired = items.length; 22296 var numListsToAdd = numListsRequired - itemComps.length; 22297 var itemsToAdd = numListsToAdd > 0 ? range$2(numListsToAdd, function () { 22298 return detail.makeItem(); 22299 }) : []; 22300 var itemsToRemove = itemComps.slice(numListsRequired); 22301 each$1(itemsToRemove, function (item) { 22302 return Replacing.remove(container, item); 22303 }); 22304 each$1(itemsToAdd, function (item) { 22305 return Replacing.append(container, item); 22306 }); 22307 var builtLists = Replacing.contents(container); 22308 each$1(builtLists, function (item, i) { 22309 detail.setupItem(list, item, items[i], i); 22310 }); 22311 }); 22312 }; 22313 var extra = detail.shell ? { 22314 behaviours: [Replacing.config({})], 22315 components: [] 22316 } : { 22317 behaviours: [], 22318 components: components 22319 }; 22320 var getListContainer = function (component) { 22321 return detail.shell ? Optional.some(component) : getPart(component, detail, 'items'); 22322 }; 22323 return { 22324 uid: detail.uid, 22325 dom: detail.dom, 22326 components: extra.components, 22327 behaviours: augment(detail.listBehaviours, extra.behaviours), 22328 apis: { setItems: setItems } 22329 }; 22330 }; 22331 var CustomList = composite({ 22332 name: name(), 22333 configFields: schema$f(), 22334 partFields: parts$9(), 22335 factory: factory$d, 22336 apis: { 22337 setItems: function (apis, list, items) { 22338 apis.setItems(list, items); 22339 } 22340 } 22341 }); 22342 22343 var schema$e = constant$1([ 22344 required$1('dom'), 22345 defaulted('shell', true), 22346 field('toolbarBehaviours', [Replacing]) 22347 ]); 22348 var enhanceGroups = function () { 22349 return { behaviours: derive$1([Replacing.config({})]) }; 22350 }; 22351 var parts$8 = constant$1([optional({ 22352 name: 'groups', 22353 overrides: enhanceGroups 22354 })]); 22355 22356 var factory$c = function (detail, components, _spec, _externals) { 22357 var setGroups = function (toolbar, groups) { 22358 getGroupContainer(toolbar).fold(function () { 22359 console.error('Toolbar was defined to not be a shell, but no groups container was specified in components'); 22360 throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components'); 22361 }, function (container) { 22362 Replacing.set(container, groups); 22363 }); 22364 }; 22365 var getGroupContainer = function (component) { 22366 return detail.shell ? Optional.some(component) : getPart(component, detail, 'groups'); 22367 }; 22368 var extra = detail.shell ? { 22369 behaviours: [Replacing.config({})], 22370 components: [] 22371 } : { 22372 behaviours: [], 22373 components: components 22374 }; 22375 return { 22376 uid: detail.uid, 22377 dom: detail.dom, 22378 components: extra.components, 22379 behaviours: augment(detail.toolbarBehaviours, extra.behaviours), 22380 apis: { setGroups: setGroups }, 22381 domModification: { attributes: { role: 'group' } } 22382 }; 22383 }; 22384 var Toolbar = composite({ 22385 name: 'Toolbar', 22386 configFields: schema$e(), 22387 partFields: parts$8(), 22388 factory: factory$c, 22389 apis: { 22390 setGroups: function (apis, toolbar, groups) { 22391 apis.setGroups(toolbar, groups); 22392 } 22393 } 22394 }); 22395 22396 var setup$a = noop; 22397 var isDocked$2 = never; 22398 var getBehaviours$1 = constant$1([]); 22399 22400 var StaticHeader = /*#__PURE__*/Object.freeze({ 22401 __proto__: null, 22402 setup: setup$a, 22403 isDocked: isDocked$2, 22404 getBehaviours: getBehaviours$1 22405 }); 22406 22407 var getOffsetParent = function (element) { 22408 var isFixed = is$1(getRaw(element, 'position'), 'fixed'); 22409 var offsetParent$1 = isFixed ? Optional.none() : offsetParent(element); 22410 return offsetParent$1.orThunk(function () { 22411 var marker = SugarElement.fromTag('span'); 22412 return parent(element).bind(function (parent) { 22413 append$2(parent, marker); 22414 var offsetParent$1 = offsetParent(marker); 22415 remove$5(marker); 22416 return offsetParent$1; 22417 }); 22418 }); 22419 }; 22420 var getOrigin = function (element) { 22421 return getOffsetParent(element).map(absolute$3).getOrThunk(function () { 22422 return SugarPosition(0, 0); 22423 }); 22424 }; 22425 22426 var morphAdt = Adt.generate([ 22427 { static: [] }, 22428 { absolute: ['positionCss'] }, 22429 { fixed: ['positionCss'] } 22430 ]); 22431 var appear = function (component, contextualInfo) { 22432 var elem = component.element; 22433 add$2(elem, contextualInfo.transitionClass); 22434 remove$2(elem, contextualInfo.fadeOutClass); 22435 add$2(elem, contextualInfo.fadeInClass); 22436 contextualInfo.onShow(component); 22437 }; 22438 var disappear = function (component, contextualInfo) { 22439 var elem = component.element; 22440 add$2(elem, contextualInfo.transitionClass); 22441 remove$2(elem, contextualInfo.fadeInClass); 22442 add$2(elem, contextualInfo.fadeOutClass); 22443 contextualInfo.onHide(component); 22444 }; 22445 var isPartiallyVisible = function (box, viewport) { 22446 return box.y < viewport.bottom && box.bottom > viewport.y; 22447 }; 22448 var isTopCompletelyVisible = function (box, viewport) { 22449 return box.y >= viewport.y; 22450 }; 22451 var isBottomCompletelyVisible = function (box, viewport) { 22452 return box.bottom <= viewport.bottom; 22453 }; 22454 var isVisibleForModes = function (modes, box, viewport) { 22455 return forall(modes, function (mode) { 22456 switch (mode) { 22457 case 'bottom': 22458 return isBottomCompletelyVisible(box, viewport); 22459 case 'top': 22460 return isTopCompletelyVisible(box, viewport); 22461 } 22462 }); 22463 }; 22464 var getPrior = function (elem, state) { 22465 return state.getInitialPos().map(function (pos) { 22466 return bounds(pos.bounds.x, pos.bounds.y, get$a(elem), get$b(elem)); 22467 }); 22468 }; 22469 var storePrior = function (elem, box, state) { 22470 state.setInitialPos({ 22471 style: getAllRaw(elem), 22472 position: get$c(elem, 'position') || 'static', 22473 bounds: box 22474 }); 22475 }; 22476 var revertToOriginal = function (elem, box, state) { 22477 return state.getInitialPos().bind(function (position) { 22478 state.clearInitialPos(); 22479 switch (position.position) { 22480 case 'static': 22481 return Optional.some(morphAdt.static()); 22482 case 'absolute': 22483 var offsetBox_1 = getOffsetParent(elem).map(box$1).getOrThunk(function () { 22484 return box$1(body()); 22485 }); 22486 return Optional.some(morphAdt.absolute(NuPositionCss('absolute', get$e(position.style, 'left').map(function (_left) { 22487 return box.x - offsetBox_1.x; 22488 }), get$e(position.style, 'top').map(function (_top) { 22489 return box.y - offsetBox_1.y; 22490 }), get$e(position.style, 'right').map(function (_right) { 22491 return offsetBox_1.right - box.right; 22492 }), get$e(position.style, 'bottom').map(function (_bottom) { 22493 return offsetBox_1.bottom - box.bottom; 22494 })))); 22495 default: 22496 return Optional.none(); 22497 } 22498 }); 22499 }; 22500 var morphToOriginal = function (elem, viewport, state) { 22501 return getPrior(elem, state).filter(function (box) { 22502 return isVisibleForModes(state.getModes(), box, viewport); 22503 }).bind(function (box) { 22504 return revertToOriginal(elem, box, state); 22505 }); 22506 }; 22507 var morphToFixed = function (elem, viewport, state) { 22508 var box = box$1(elem); 22509 if (!isVisibleForModes(state.getModes(), box, viewport)) { 22510 storePrior(elem, box, state); 22511 var winBox = win(); 22512 var left = box.x - winBox.x; 22513 var top_1 = viewport.y - winBox.y; 22514 var bottom = winBox.bottom - viewport.bottom; 22515 var isTop = box.y <= viewport.y; 22516 return Optional.some(morphAdt.fixed(NuPositionCss('fixed', Optional.some(left), isTop ? Optional.some(top_1) : Optional.none(), Optional.none(), !isTop ? Optional.some(bottom) : Optional.none()))); 22517 } else { 22518 return Optional.none(); 22519 } 22520 }; 22521 var getMorph = function (component, viewport, state) { 22522 var elem = component.element; 22523 var isDocked = is$1(getRaw(elem, 'position'), 'fixed'); 22524 return isDocked ? morphToOriginal(elem, viewport, state) : morphToFixed(elem, viewport, state); 22525 }; 22526 var getMorphToOriginal = function (component, state) { 22527 var elem = component.element; 22528 return getPrior(elem, state).bind(function (box) { 22529 return revertToOriginal(elem, box, state); 22530 }); 22531 }; 22532 22533 var morphToStatic = function (component, config, state) { 22534 state.setDocked(false); 22535 each$1([ 22536 'left', 22537 'right', 22538 'top', 22539 'bottom', 22540 'position' 22541 ], function (prop) { 22542 return remove$6(component.element, prop); 22543 }); 22544 config.onUndocked(component); 22545 }; 22546 var morphToCoord = function (component, config, state, position) { 22547 var isDocked = position.position === 'fixed'; 22548 state.setDocked(isDocked); 22549 applyPositionCss(component.element, position); 22550 var method = isDocked ? config.onDocked : config.onUndocked; 22551 method(component); 22552 }; 22553 var updateVisibility = function (component, config, state, viewport, morphToDocked) { 22554 if (morphToDocked === void 0) { 22555 morphToDocked = false; 22556 } 22557 config.contextual.each(function (contextInfo) { 22558 contextInfo.lazyContext(component).each(function (box) { 22559 var isVisible = isPartiallyVisible(box, viewport); 22560 if (isVisible !== state.isVisible()) { 22561 state.setVisible(isVisible); 22562 if (morphToDocked && !isVisible) { 22563 add$1(component.element, [contextInfo.fadeOutClass]); 22564 contextInfo.onHide(component); 22565 } else { 22566 var method = isVisible ? appear : disappear; 22567 method(component, contextInfo); 22568 } 22569 } 22570 }); 22571 }); 22572 }; 22573 var refreshInternal = function (component, config, state) { 22574 var viewport = config.lazyViewport(component); 22575 var isDocked = state.isDocked(); 22576 if (isDocked) { 22577 updateVisibility(component, config, state, viewport); 22578 } 22579 getMorph(component, viewport, state).each(function (morph) { 22580 morph.fold(function () { 22581 return morphToStatic(component, config, state); 22582 }, function (position) { 22583 return morphToCoord(component, config, state, position); 22584 }, function (position) { 22585 updateVisibility(component, config, state, viewport, true); 22586 morphToCoord(component, config, state, position); 22587 }); 22588 }); 22589 }; 22590 var resetInternal = function (component, config, state) { 22591 var elem = component.element; 22592 state.setDocked(false); 22593 getMorphToOriginal(component, state).each(function (morph) { 22594 morph.fold(function () { 22595 return morphToStatic(component, config, state); 22596 }, function (position) { 22597 return morphToCoord(component, config, state, position); 22598 }, noop); 22599 }); 22600 state.setVisible(true); 22601 config.contextual.each(function (contextInfo) { 22602 remove$1(elem, [ 22603 contextInfo.fadeInClass, 22604 contextInfo.fadeOutClass, 22605 contextInfo.transitionClass 22606 ]); 22607 contextInfo.onShow(component); 22608 }); 22609 refresh$4(component, config, state); 22610 }; 22611 var refresh$4 = function (component, config, state) { 22612 if (component.getSystem().isConnected()) { 22613 refreshInternal(component, config, state); 22614 } 22615 }; 22616 var reset = function (component, config, state) { 22617 if (state.isDocked()) { 22618 resetInternal(component, config, state); 22619 } 22620 }; 22621 var isDocked$1 = function (component, config, state) { 22622 return state.isDocked(); 22623 }; 22624 var setModes = function (component, config, state, modes) { 22625 return state.setModes(modes); 22626 }; 22627 var getModes = function (component, config, state) { 22628 return state.getModes(); 22629 }; 22630 22631 var DockingApis = /*#__PURE__*/Object.freeze({ 22632 __proto__: null, 22633 refresh: refresh$4, 22634 reset: reset, 22635 isDocked: isDocked$1, 22636 getModes: getModes, 22637 setModes: setModes 22638 }); 22639 22640 var events$5 = function (dockInfo, dockState) { 22641 return derive$2([ 22642 runOnSource(transitionend(), function (component, simulatedEvent) { 22643 dockInfo.contextual.each(function (contextInfo) { 22644 if (has(component.element, contextInfo.transitionClass)) { 22645 remove$1(component.element, [ 22646 contextInfo.transitionClass, 22647 contextInfo.fadeInClass 22648 ]); 22649 var notify = dockState.isVisible() ? contextInfo.onShown : contextInfo.onHidden; 22650 notify(component); 22651 } 22652 simulatedEvent.stop(); 22653 }); 22654 }), 22655 run$1(windowScroll(), function (component, _) { 22656 refresh$4(component, dockInfo, dockState); 22657 }), 22658 run$1(windowResize(), function (component, _) { 22659 reset(component, dockInfo, dockState); 22660 }) 22661 ]); 22662 }; 22663 22664 var ActiveDocking = /*#__PURE__*/Object.freeze({ 22665 __proto__: null, 22666 events: events$5 22667 }); 22668 22669 var DockingSchema = [ 22670 optionObjOf('contextual', [ 22671 requiredString('fadeInClass'), 22672 requiredString('fadeOutClass'), 22673 requiredString('transitionClass'), 22674 requiredFunction('lazyContext'), 22675 onHandler('onShow'), 22676 onHandler('onShown'), 22677 onHandler('onHide'), 22678 onHandler('onHidden') 22679 ]), 22680 defaultedFunction('lazyViewport', win), 22681 defaultedArrayOf('modes', [ 22682 'top', 22683 'bottom' 22684 ], string), 22685 onHandler('onDocked'), 22686 onHandler('onUndocked') 22687 ]; 22688 22689 var init$6 = function (spec) { 22690 var docked = Cell(false); 22691 var visible = Cell(true); 22692 var initialBounds = value$1(); 22693 var modes = Cell(spec.modes); 22694 var readState = function () { 22695 return 'docked: ' + docked.get() + ', visible: ' + visible.get() + ', modes: ' + modes.get().join(','); 22696 }; 22697 return nu$8({ 22698 isDocked: docked.get, 22699 setDocked: docked.set, 22700 getInitialPos: initialBounds.get, 22701 setInitialPos: initialBounds.set, 22702 clearInitialPos: initialBounds.clear, 22703 isVisible: visible.get, 22704 setVisible: visible.set, 22705 getModes: modes.get, 22706 setModes: modes.set, 22707 readState: readState 22708 }); 22709 }; 22710 22711 var DockingState = /*#__PURE__*/Object.freeze({ 22712 __proto__: null, 22713 init: init$6 22714 }); 22715 22716 var Docking = create$7({ 22717 fields: DockingSchema, 22718 name: 'docking', 22719 active: ActiveDocking, 22720 apis: DockingApis, 22721 state: DockingState 22722 }); 22723 22724 var toolbarHeightChange = constant$1(generate$6('toolbar-height-change')); 22725 22726 var visibility = { 22727 fadeInClass: 'tox-editor-dock-fadein', 22728 fadeOutClass: 'tox-editor-dock-fadeout', 22729 transitionClass: 'tox-editor-dock-transition' 22730 }; 22731 var editorStickyOnClass = 'tox-tinymce--toolbar-sticky-on'; 22732 var editorStickyOffClass = 'tox-tinymce--toolbar-sticky-off'; 22733 var scrollFromBehindHeader = function (e, containerHeader) { 22734 var doc = owner$4(containerHeader); 22735 var viewHeight = doc.dom.defaultView.innerHeight; 22736 var scrollPos = get$9(doc); 22737 var markerElement = SugarElement.fromDom(e.elm); 22738 var markerPos = absolute$2(markerElement); 22739 var markerHeight = get$b(markerElement); 22740 var markerTop = markerPos.y; 22741 var markerBottom = markerTop + markerHeight; 22742 var editorHeaderPos = absolute$3(containerHeader); 22743 var editorHeaderHeight = get$b(containerHeader); 22744 var editorHeaderTop = editorHeaderPos.top; 22745 var editorHeaderBottom = editorHeaderTop + editorHeaderHeight; 22746 var editorHeaderDockedAtTop = Math.abs(editorHeaderTop - scrollPos.top) < 2; 22747 var editorHeaderDockedAtBottom = Math.abs(editorHeaderBottom - (scrollPos.top + viewHeight)) < 2; 22748 if (editorHeaderDockedAtTop && markerTop < editorHeaderBottom) { 22749 to(scrollPos.left, markerTop - editorHeaderHeight, doc); 22750 } else if (editorHeaderDockedAtBottom && markerBottom > editorHeaderTop) { 22751 var y = markerTop - viewHeight + markerHeight + editorHeaderHeight; 22752 to(scrollPos.left, y, doc); 22753 } 22754 }; 22755 var isDockedMode = function (header, mode) { 22756 return contains$2(Docking.getModes(header), mode); 22757 }; 22758 var updateIframeContentFlow = function (header) { 22759 var getOccupiedHeight = function (elm) { 22760 return getOuter$2(elm) + (parseInt(get$c(elm, 'margin-top'), 10) || 0) + (parseInt(get$c(elm, 'margin-bottom'), 10) || 0); 22761 }; 22762 var elm = header.element; 22763 parent(elm).each(function (parentElem) { 22764 var padding = 'padding-' + Docking.getModes(header)[0]; 22765 if (Docking.isDocked(header)) { 22766 var parentWidth = get$a(parentElem); 22767 set$7(elm, 'width', parentWidth + 'px'); 22768 set$7(parentElem, padding, getOccupiedHeight(elm) + 'px'); 22769 } else { 22770 remove$6(elm, 'width'); 22771 remove$6(parentElem, padding); 22772 } 22773 }); 22774 }; 22775 var updateSinkVisibility = function (sinkElem, visible) { 22776 if (visible) { 22777 remove$2(sinkElem, visibility.fadeOutClass); 22778 add$1(sinkElem, [ 22779 visibility.transitionClass, 22780 visibility.fadeInClass 22781 ]); 22782 } else { 22783 remove$2(sinkElem, visibility.fadeInClass); 22784 add$1(sinkElem, [ 22785 visibility.fadeOutClass, 22786 visibility.transitionClass 22787 ]); 22788 } 22789 }; 22790 var updateEditorClasses = function (editor, docked) { 22791 var editorContainer = SugarElement.fromDom(editor.getContainer()); 22792 if (docked) { 22793 add$2(editorContainer, editorStickyOnClass); 22794 remove$2(editorContainer, editorStickyOffClass); 22795 } else { 22796 add$2(editorContainer, editorStickyOffClass); 22797 remove$2(editorContainer, editorStickyOnClass); 22798 } 22799 }; 22800 var restoreFocus = function (headerElem, focusedElem) { 22801 var ownerDoc = owner$4(focusedElem); 22802 active(ownerDoc).filter(function (activeElm) { 22803 return !eq(focusedElem, activeElm); 22804 }).filter(function (activeElm) { 22805 return eq(activeElm, SugarElement.fromDom(ownerDoc.dom.body)) || contains(headerElem, activeElm); 22806 }).each(function () { 22807 return focus$3(focusedElem); 22808 }); 22809 }; 22810 var findFocusedElem = function (rootElm, lazySink) { 22811 return search(rootElm).orThunk(function () { 22812 return lazySink().toOptional().bind(function (sink) { 22813 return search(sink.element); 22814 }); 22815 }); 22816 }; 22817 var setup$9 = function (editor, sharedBackstage, lazyHeader) { 22818 if (!editor.inline) { 22819 if (!sharedBackstage.header.isPositionedAtTop()) { 22820 editor.on('ResizeEditor', function () { 22821 lazyHeader().each(Docking.reset); 22822 }); 22823 } 22824 editor.on('ResizeWindow ResizeEditor', function () { 22825 lazyHeader().each(updateIframeContentFlow); 22826 }); 22827 editor.on('SkinLoaded', function () { 22828 lazyHeader().each(function (comp) { 22829 Docking.isDocked(comp) ? Docking.reset(comp) : Docking.refresh(comp); 22830 }); 22831 }); 22832 editor.on('FullscreenStateChanged', function () { 22833 lazyHeader().each(Docking.reset); 22834 }); 22835 } 22836 editor.on('AfterScrollIntoView', function (e) { 22837 lazyHeader().each(function (header) { 22838 Docking.refresh(header); 22839 var headerElem = header.element; 22840 if (isVisible(headerElem)) { 22841 scrollFromBehindHeader(e, headerElem); 22842 } 22843 }); 22844 }); 22845 editor.on('PostRender', function () { 22846 updateEditorClasses(editor, false); 22847 }); 22848 }; 22849 var isDocked = function (lazyHeader) { 22850 return lazyHeader().map(Docking.isDocked).getOr(false); 22851 }; 22852 var getIframeBehaviours = function () { 22853 var _a; 22854 return [Receiving.config({ channels: (_a = {}, _a[toolbarHeightChange()] = { onReceive: updateIframeContentFlow }, _a) })]; 22855 }; 22856 var getBehaviours = function (editor, sharedBackstage) { 22857 var focusedElm = value$1(); 22858 var lazySink = sharedBackstage.getSink; 22859 var runOnSinkElement = function (f) { 22860 lazySink().each(function (sink) { 22861 return f(sink.element); 22862 }); 22863 }; 22864 var onDockingSwitch = function (comp) { 22865 if (!editor.inline) { 22866 updateIframeContentFlow(comp); 22867 } 22868 updateEditorClasses(editor, Docking.isDocked(comp)); 22869 comp.getSystem().broadcastOn([repositionPopups()], {}); 22870 lazySink().each(function (sink) { 22871 return sink.getSystem().broadcastOn([repositionPopups()], {}); 22872 }); 22873 }; 22874 var additionalBehaviours = editor.inline ? [] : getIframeBehaviours(); 22875 return __spreadArray([ 22876 Focusing.config({}), 22877 Docking.config({ 22878 contextual: __assign({ 22879 lazyContext: function (comp) { 22880 var headerHeight = getOuter$2(comp.element); 22881 var container = editor.inline ? editor.getContentAreaContainer() : editor.getContainer(); 22882 var box = box$1(SugarElement.fromDom(container)); 22883 var boxHeight = box.height - headerHeight; 22884 var topBound = box.y + (isDockedMode(comp, 'top') ? 0 : headerHeight); 22885 return Optional.some(bounds(box.x, topBound, box.width, boxHeight)); 22886 }, 22887 onShow: function () { 22888 runOnSinkElement(function (elem) { 22889 return updateSinkVisibility(elem, true); 22890 }); 22891 }, 22892 onShown: function (comp) { 22893 runOnSinkElement(function (elem) { 22894 return remove$1(elem, [ 22895 visibility.transitionClass, 22896 visibility.fadeInClass 22897 ]); 22898 }); 22899 focusedElm.get().each(function (elem) { 22900 restoreFocus(comp.element, elem); 22901 focusedElm.clear(); 22902 }); 22903 }, 22904 onHide: function (comp) { 22905 findFocusedElem(comp.element, lazySink).fold(focusedElm.clear, focusedElm.set); 22906 runOnSinkElement(function (elem) { 22907 return updateSinkVisibility(elem, false); 22908 }); 22909 }, 22910 onHidden: function () { 22911 runOnSinkElement(function (elem) { 22912 return remove$1(elem, [visibility.transitionClass]); 22913 }); 22914 } 22915 }, visibility), 22916 lazyViewport: function (comp) { 22917 var win$1 = win(); 22918 var offset = getStickyToolbarOffset(editor); 22919 var top = win$1.y + (isDockedMode(comp, 'top') ? offset : 0); 22920 var height = win$1.height - (isDockedMode(comp, 'bottom') ? offset : 0); 22921 return bounds(win$1.x, top, win$1.width, height); 22922 }, 22923 modes: [sharedBackstage.header.getDockingMode()], 22924 onDocked: onDockingSwitch, 22925 onUndocked: onDockingSwitch 22926 }) 22927 ], additionalBehaviours, true); 22928 }; 22929 22930 var StickyHeader = /*#__PURE__*/Object.freeze({ 22931 __proto__: null, 22932 setup: setup$9, 22933 isDocked: isDocked, 22934 getBehaviours: getBehaviours 22935 }); 22936 22937 var renderHeader = function (spec) { 22938 var editor = spec.editor; 22939 var getBehaviours$2 = spec.sticky ? getBehaviours : getBehaviours$1; 22940 return { 22941 uid: spec.uid, 22942 dom: spec.dom, 22943 components: spec.components, 22944 behaviours: derive$1(getBehaviours$2(editor, spec.sharedBackstage)) 22945 }; 22946 }; 22947 22948 var groupToolbarButtonSchema = objOf([ 22949 requiredString('type'), 22950 requiredOf('items', oneOf([ 22951 arrOfObj([ 22952 requiredString('name'), 22953 requiredArrayOf('items', string) 22954 ]), 22955 string 22956 ])) 22957 ].concat(baseToolbarButtonFields)); 22958 var createGroupToolbarButton = function (spec) { 22959 return asRaw('GroupToolbarButton', groupToolbarButtonSchema, spec); 22960 }; 22961 22962 var baseMenuButtonFields = [ 22963 optionString('text'), 22964 optionString('tooltip'), 22965 optionString('icon'), 22966 requiredFunction('fetch'), 22967 defaultedFunction('onSetup', function () { 22968 return noop; 22969 }) 22970 ]; 22971 22972 var MenuButtonSchema = objOf(__spreadArray([requiredString('type')], baseMenuButtonFields, true)); 22973 var createMenuButton = function (spec) { 22974 return asRaw('menubutton', MenuButtonSchema, spec); 22975 }; 22976 22977 var splitButtonSchema = objOf([ 22978 requiredString('type'), 22979 optionString('tooltip'), 22980 optionString('icon'), 22981 optionString('text'), 22982 optionFunction('select'), 22983 requiredFunction('fetch'), 22984 defaultedFunction('onSetup', function () { 22985 return noop; 22986 }), 22987 defaultedStringEnum('presets', 'normal', [ 22988 'normal', 22989 'color', 22990 'listpreview' 22991 ]), 22992 defaulted('columns', 1), 22993 requiredFunction('onAction'), 22994 requiredFunction('onItemAction') 22995 ]); 22996 var createSplitButton = function (spec) { 22997 return asRaw('SplitButton', splitButtonSchema, spec); 22998 }; 22999 23000 var factory$b = function (detail, spec) { 23001 var setMenus = function (comp, menus) { 23002 var newMenus = map$2(menus, function (m) { 23003 var buttonSpec = { 23004 type: 'menubutton', 23005 text: m.text, 23006 fetch: function (callback) { 23007 callback(m.getItems()); 23008 } 23009 }; 23010 var internal = createMenuButton(buttonSpec).mapError(function (errInfo) { 23011 return formatError(errInfo); 23012 }).getOrDie(); 23013 return renderMenuButton(internal, 'tox-mbtn', spec.backstage, Optional.some('menuitem')); 23014 }); 23015 Replacing.set(comp, newMenus); 23016 }; 23017 var apis = { 23018 focus: Keying.focusIn, 23019 setMenus: setMenus 23020 }; 23021 return { 23022 uid: detail.uid, 23023 dom: detail.dom, 23024 components: [], 23025 behaviours: derive$1([ 23026 Replacing.config({}), 23027 config('menubar-events', [ 23028 runOnAttached(function (component) { 23029 detail.onSetup(component); 23030 }), 23031 run$1(mouseover(), function (comp, se) { 23032 descendant(comp.element, '.' + 'tox-mbtn--active').each(function (activeButton) { 23033 closest$1(se.event.target, '.' + 'tox-mbtn').each(function (hoveredButton) { 23034 if (!eq(activeButton, hoveredButton)) { 23035 comp.getSystem().getByDom(activeButton).each(function (activeComp) { 23036 comp.getSystem().getByDom(hoveredButton).each(function (hoveredComp) { 23037 Dropdown.expand(hoveredComp); 23038 Dropdown.close(activeComp); 23039 Focusing.focus(hoveredComp); 23040 }); 23041 }); 23042 } 23043 }); 23044 }); 23045 }), 23046 run$1(focusShifted(), function (comp, se) { 23047 se.event.prevFocus.bind(function (prev) { 23048 return comp.getSystem().getByDom(prev).toOptional(); 23049 }).each(function (prev) { 23050 se.event.newFocus.bind(function (nu) { 23051 return comp.getSystem().getByDom(nu).toOptional(); 23052 }).each(function (nu) { 23053 if (Dropdown.isOpen(prev)) { 23054 Dropdown.expand(nu); 23055 Dropdown.close(prev); 23056 } 23057 }); 23058 }); 23059 }) 23060 ]), 23061 Keying.config({ 23062 mode: 'flow', 23063 selector: '.' + 'tox-mbtn', 23064 onEscape: function (comp) { 23065 detail.onEscape(comp); 23066 return Optional.some(true); 23067 } 23068 }), 23069 Tabstopping.config({}) 23070 ]), 23071 apis: apis, 23072 domModification: { attributes: { role: 'menubar' } } 23073 }; 23074 }; 23075 var SilverMenubar = single({ 23076 factory: factory$b, 23077 name: 'silver.Menubar', 23078 configFields: [ 23079 required$1('dom'), 23080 required$1('uid'), 23081 required$1('onEscape'), 23082 required$1('backstage'), 23083 defaulted('onSetup', noop) 23084 ], 23085 apis: { 23086 focus: function (apis, comp) { 23087 apis.focus(comp); 23088 }, 23089 setMenus: function (apis, comp, menus) { 23090 apis.setMenus(comp, menus); 23091 } 23092 } 23093 }); 23094 23095 var getAnimationRoot = function (component, slideConfig) { 23096 return slideConfig.getAnimationRoot.fold(function () { 23097 return component.element; 23098 }, function (get) { 23099 return get(component); 23100 }); 23101 }; 23102 23103 var getDimensionProperty = function (slideConfig) { 23104 return slideConfig.dimension.property; 23105 }; 23106 var getDimension = function (slideConfig, elem) { 23107 return slideConfig.dimension.getDimension(elem); 23108 }; 23109 var disableTransitions = function (component, slideConfig) { 23110 var root = getAnimationRoot(component, slideConfig); 23111 remove$1(root, [ 23112 slideConfig.shrinkingClass, 23113 slideConfig.growingClass 23114 ]); 23115 }; 23116 var setShrunk = function (component, slideConfig) { 23117 remove$2(component.element, slideConfig.openClass); 23118 add$2(component.element, slideConfig.closedClass); 23119 set$7(component.element, getDimensionProperty(slideConfig), '0px'); 23120 reflow(component.element); 23121 }; 23122 var setGrown = function (component, slideConfig) { 23123 remove$2(component.element, slideConfig.closedClass); 23124 add$2(component.element, slideConfig.openClass); 23125 remove$6(component.element, getDimensionProperty(slideConfig)); 23126 }; 23127 var doImmediateShrink = function (component, slideConfig, slideState, _calculatedSize) { 23128 slideState.setCollapsed(); 23129 set$7(component.element, getDimensionProperty(slideConfig), getDimension(slideConfig, component.element)); 23130 reflow(component.element); 23131 disableTransitions(component, slideConfig); 23132 setShrunk(component, slideConfig); 23133 slideConfig.onStartShrink(component); 23134 slideConfig.onShrunk(component); 23135 }; 23136 var doStartShrink = function (component, slideConfig, slideState, calculatedSize) { 23137 var size = calculatedSize.getOrThunk(function () { 23138 return getDimension(slideConfig, component.element); 23139 }); 23140 slideState.setCollapsed(); 23141 set$7(component.element, getDimensionProperty(slideConfig), size); 23142 reflow(component.element); 23143 var root = getAnimationRoot(component, slideConfig); 23144 remove$2(root, slideConfig.growingClass); 23145 add$2(root, slideConfig.shrinkingClass); 23146 setShrunk(component, slideConfig); 23147 slideConfig.onStartShrink(component); 23148 }; 23149 var doStartSmartShrink = function (component, slideConfig, slideState) { 23150 var size = getDimension(slideConfig, component.element); 23151 var shrinker = size === '0px' ? doImmediateShrink : doStartShrink; 23152 shrinker(component, slideConfig, slideState, Optional.some(size)); 23153 }; 23154 var doStartGrow = function (component, slideConfig, slideState) { 23155 var root = getAnimationRoot(component, slideConfig); 23156 var wasShrinking = has(root, slideConfig.shrinkingClass); 23157 var beforeSize = getDimension(slideConfig, component.element); 23158 setGrown(component, slideConfig); 23159 var fullSize = getDimension(slideConfig, component.element); 23160 var startPartialGrow = function () { 23161 set$7(component.element, getDimensionProperty(slideConfig), beforeSize); 23162 reflow(component.element); 23163 }; 23164 var startCompleteGrow = function () { 23165 setShrunk(component, slideConfig); 23166 }; 23167 var setStartSize = wasShrinking ? startPartialGrow : startCompleteGrow; 23168 setStartSize(); 23169 remove$2(root, slideConfig.shrinkingClass); 23170 add$2(root, slideConfig.growingClass); 23171 setGrown(component, slideConfig); 23172 set$7(component.element, getDimensionProperty(slideConfig), fullSize); 23173 slideState.setExpanded(); 23174 slideConfig.onStartGrow(component); 23175 }; 23176 var refresh$3 = function (component, slideConfig, slideState) { 23177 if (slideState.isExpanded()) { 23178 remove$6(component.element, getDimensionProperty(slideConfig)); 23179 var fullSize = getDimension(slideConfig, component.element); 23180 set$7(component.element, getDimensionProperty(slideConfig), fullSize); 23181 } 23182 }; 23183 var grow = function (component, slideConfig, slideState) { 23184 if (!slideState.isExpanded()) { 23185 doStartGrow(component, slideConfig, slideState); 23186 } 23187 }; 23188 var shrink = function (component, slideConfig, slideState) { 23189 if (slideState.isExpanded()) { 23190 doStartSmartShrink(component, slideConfig, slideState); 23191 } 23192 }; 23193 var immediateShrink = function (component, slideConfig, slideState) { 23194 if (slideState.isExpanded()) { 23195 doImmediateShrink(component, slideConfig, slideState); 23196 } 23197 }; 23198 var hasGrown = function (component, slideConfig, slideState) { 23199 return slideState.isExpanded(); 23200 }; 23201 var hasShrunk = function (component, slideConfig, slideState) { 23202 return slideState.isCollapsed(); 23203 }; 23204 var isGrowing = function (component, slideConfig, _slideState) { 23205 var root = getAnimationRoot(component, slideConfig); 23206 return has(root, slideConfig.growingClass) === true; 23207 }; 23208 var isShrinking = function (component, slideConfig, _slideState) { 23209 var root = getAnimationRoot(component, slideConfig); 23210 return has(root, slideConfig.shrinkingClass) === true; 23211 }; 23212 var isTransitioning = function (component, slideConfig, slideState) { 23213 return isGrowing(component, slideConfig) || isShrinking(component, slideConfig); 23214 }; 23215 var toggleGrow = function (component, slideConfig, slideState) { 23216 var f = slideState.isExpanded() ? doStartSmartShrink : doStartGrow; 23217 f(component, slideConfig, slideState); 23218 }; 23219 23220 var SlidingApis = /*#__PURE__*/Object.freeze({ 23221 __proto__: null, 23222 refresh: refresh$3, 23223 grow: grow, 23224 shrink: shrink, 23225 immediateShrink: immediateShrink, 23226 hasGrown: hasGrown, 23227 hasShrunk: hasShrunk, 23228 isGrowing: isGrowing, 23229 isShrinking: isShrinking, 23230 isTransitioning: isTransitioning, 23231 toggleGrow: toggleGrow, 23232 disableTransitions: disableTransitions 23233 }); 23234 23235 var exhibit = function (base, slideConfig, _slideState) { 23236 var expanded = slideConfig.expanded; 23237 return expanded ? nu$7({ 23238 classes: [slideConfig.openClass], 23239 styles: {} 23240 }) : nu$7({ 23241 classes: [slideConfig.closedClass], 23242 styles: wrap$1(slideConfig.dimension.property, '0px') 23243 }); 23244 }; 23245 var events$4 = function (slideConfig, slideState) { 23246 return derive$2([runOnSource(transitionend(), function (component, simulatedEvent) { 23247 var raw = simulatedEvent.event.raw; 23248 if (raw.propertyName === slideConfig.dimension.property) { 23249 disableTransitions(component, slideConfig); 23250 if (slideState.isExpanded()) { 23251 remove$6(component.element, slideConfig.dimension.property); 23252 } 23253 var notify = slideState.isExpanded() ? slideConfig.onGrown : slideConfig.onShrunk; 23254 notify(component); 23255 } 23256 })]); 23257 }; 23258 23259 var ActiveSliding = /*#__PURE__*/Object.freeze({ 23260 __proto__: null, 23261 exhibit: exhibit, 23262 events: events$4 23263 }); 23264 23265 var SlidingSchema = [ 23266 required$1('closedClass'), 23267 required$1('openClass'), 23268 required$1('shrinkingClass'), 23269 required$1('growingClass'), 23270 option('getAnimationRoot'), 23271 onHandler('onShrunk'), 23272 onHandler('onStartShrink'), 23273 onHandler('onGrown'), 23274 onHandler('onStartGrow'), 23275 defaulted('expanded', false), 23276 requiredOf('dimension', choose$1('property', { 23277 width: [ 23278 output$1('property', 'width'), 23279 output$1('getDimension', function (elem) { 23280 return get$a(elem) + 'px'; 23281 }) 23282 ], 23283 height: [ 23284 output$1('property', 'height'), 23285 output$1('getDimension', function (elem) { 23286 return get$b(elem) + 'px'; 23287 }) 23288 ] 23289 })) 23290 ]; 23291 23292 var init$5 = function (spec) { 23293 var state = Cell(spec.expanded); 23294 var readState = function () { 23295 return 'expanded: ' + state.get(); 23296 }; 23297 return nu$8({ 23298 isExpanded: function () { 23299 return state.get() === true; 23300 }, 23301 isCollapsed: function () { 23302 return state.get() === false; 23303 }, 23304 setCollapsed: curry(state.set, false), 23305 setExpanded: curry(state.set, true), 23306 readState: readState 23307 }); 23308 }; 23309 23310 var SlidingState = /*#__PURE__*/Object.freeze({ 23311 __proto__: null, 23312 init: init$5 23313 }); 23314 23315 var Sliding = create$7({ 23316 fields: SlidingSchema, 23317 name: 'sliding', 23318 active: ActiveSliding, 23319 apis: SlidingApis, 23320 state: SlidingState 23321 }); 23322 23323 var owner = 'container'; 23324 var schema$d = [field('slotBehaviours', [])]; 23325 var getPartName = function (name) { 23326 return '<alloy.field.' + name + '>'; 23327 }; 23328 var sketch = function (sSpec) { 23329 var parts = function () { 23330 var record = []; 23331 var slot = function (name, config) { 23332 record.push(name); 23333 return generateOne$1(owner, getPartName(name), config); 23334 }; 23335 return { 23336 slot: slot, 23337 record: constant$1(record) 23338 }; 23339 }(); 23340 var spec = sSpec(parts); 23341 var partNames = parts.record(); 23342 var fieldParts = map$2(partNames, function (n) { 23343 return required({ 23344 name: n, 23345 pname: getPartName(n) 23346 }); 23347 }); 23348 return composite$1(owner, schema$d, fieldParts, make$1, spec); 23349 }; 23350 var make$1 = function (detail, components) { 23351 var getSlotNames = function (_) { 23352 return getAllPartNames(detail); 23353 }; 23354 var getSlot = function (container, key) { 23355 return getPart(container, detail, key); 23356 }; 23357 var onSlot = function (f, def) { 23358 return function (container, key) { 23359 return getPart(container, detail, key).map(function (slot) { 23360 return f(slot, key); 23361 }).getOr(def); 23362 }; 23363 }; 23364 var onSlots = function (f) { 23365 return function (container, keys) { 23366 each$1(keys, function (key) { 23367 return f(container, key); 23368 }); 23369 }; 23370 }; 23371 var doShowing = function (comp, _key) { 23372 return get$d(comp.element, 'aria-hidden') !== 'true'; 23373 }; 23374 var doShow = function (comp, key) { 23375 if (!doShowing(comp)) { 23376 var element = comp.element; 23377 remove$6(element, 'display'); 23378 remove$7(element, 'aria-hidden'); 23379 emitWith(comp, slotVisibility(), { 23380 name: key, 23381 visible: true 23382 }); 23383 } 23384 }; 23385 var doHide = function (comp, key) { 23386 if (doShowing(comp)) { 23387 var element = comp.element; 23388 set$7(element, 'display', 'none'); 23389 set$8(element, 'aria-hidden', 'true'); 23390 emitWith(comp, slotVisibility(), { 23391 name: key, 23392 visible: false 23393 }); 23394 } 23395 }; 23396 var isShowing = onSlot(doShowing, false); 23397 var hideSlot = onSlot(doHide); 23398 var hideSlots = onSlots(hideSlot); 23399 var hideAllSlots = function (container) { 23400 return hideSlots(container, getSlotNames()); 23401 }; 23402 var showSlot = onSlot(doShow); 23403 var apis = { 23404 getSlotNames: getSlotNames, 23405 getSlot: getSlot, 23406 isShowing: isShowing, 23407 hideSlot: hideSlot, 23408 hideAllSlots: hideAllSlots, 23409 showSlot: showSlot 23410 }; 23411 return { 23412 uid: detail.uid, 23413 dom: detail.dom, 23414 components: components, 23415 behaviours: get$2(detail.slotBehaviours), 23416 apis: apis 23417 }; 23418 }; 23419 var slotApis = map$1({ 23420 getSlotNames: function (apis, c) { 23421 return apis.getSlotNames(c); 23422 }, 23423 getSlot: function (apis, c, key) { 23424 return apis.getSlot(c, key); 23425 }, 23426 isShowing: function (apis, c, key) { 23427 return apis.isShowing(c, key); 23428 }, 23429 hideSlot: function (apis, c, key) { 23430 return apis.hideSlot(c, key); 23431 }, 23432 hideAllSlots: function (apis, c) { 23433 return apis.hideAllSlots(c); 23434 }, 23435 showSlot: function (apis, c, key) { 23436 return apis.showSlot(c, key); 23437 } 23438 }, function (value) { 23439 return makeApi(value); 23440 }); 23441 var SlotContainer = __assign(__assign({}, slotApis), { sketch: sketch }); 23442 23443 var sidebarSchema = objOf([ 23444 optionString('icon'), 23445 optionString('tooltip'), 23446 defaultedFunction('onShow', noop), 23447 defaultedFunction('onHide', noop), 23448 defaultedFunction('onSetup', function () { 23449 return noop; 23450 }) 23451 ]); 23452 var createSidebar = function (spec) { 23453 return asRaw('sidebar', sidebarSchema, spec); 23454 }; 23455 23456 var setup$8 = function (editor) { 23457 var sidebars = editor.ui.registry.getAll().sidebars; 23458 each$1(keys(sidebars), function (name) { 23459 var spec = sidebars[name]; 23460 var isActive = function () { 23461 return is$1(Optional.from(editor.queryCommandValue('ToggleSidebar')), name); 23462 }; 23463 editor.ui.registry.addToggleButton(name, { 23464 icon: spec.icon, 23465 tooltip: spec.tooltip, 23466 onAction: function (buttonApi) { 23467 editor.execCommand('ToggleSidebar', false, name); 23468 buttonApi.setActive(isActive()); 23469 }, 23470 onSetup: function (buttonApi) { 23471 var handleToggle = function () { 23472 return buttonApi.setActive(isActive()); 23473 }; 23474 editor.on('ToggleSidebar', handleToggle); 23475 return function () { 23476 editor.off('ToggleSidebar', handleToggle); 23477 }; 23478 } 23479 }); 23480 }); 23481 }; 23482 var getApi = function (comp) { 23483 return { 23484 element: function () { 23485 return comp.element.dom; 23486 } 23487 }; 23488 }; 23489 var makePanels = function (parts, panelConfigs) { 23490 var specs = map$2(keys(panelConfigs), function (name) { 23491 var spec = panelConfigs[name]; 23492 var bridged = getOrDie(createSidebar(spec)); 23493 return { 23494 name: name, 23495 getApi: getApi, 23496 onSetup: bridged.onSetup, 23497 onShow: bridged.onShow, 23498 onHide: bridged.onHide 23499 }; 23500 }); 23501 return map$2(specs, function (spec) { 23502 var editorOffCell = Cell(noop); 23503 return parts.slot(spec.name, { 23504 dom: { 23505 tag: 'div', 23506 classes: ['tox-sidebar__pane'] 23507 }, 23508 behaviours: SimpleBehaviours.unnamedEvents([ 23509 onControlAttached(spec, editorOffCell), 23510 onControlDetached(spec, editorOffCell), 23511 run$1(slotVisibility(), function (sidepanel, se) { 23512 var data = se.event; 23513 var optSidePanelSpec = find$5(specs, function (config) { 23514 return config.name === data.name; 23515 }); 23516 optSidePanelSpec.each(function (sidePanelSpec) { 23517 var handler = data.visible ? sidePanelSpec.onShow : sidePanelSpec.onHide; 23518 handler(sidePanelSpec.getApi(sidepanel)); 23519 }); 23520 }) 23521 ]) 23522 }); 23523 }); 23524 }; 23525 var makeSidebar = function (panelConfigs) { 23526 return SlotContainer.sketch(function (parts) { 23527 return { 23528 dom: { 23529 tag: 'div', 23530 classes: ['tox-sidebar__pane-container'] 23531 }, 23532 components: makePanels(parts, panelConfigs), 23533 slotBehaviours: SimpleBehaviours.unnamedEvents([runOnAttached(function (slotContainer) { 23534 return SlotContainer.hideAllSlots(slotContainer); 23535 })]) 23536 }; 23537 }); 23538 }; 23539 var setSidebar = function (sidebar, panelConfigs) { 23540 var optSlider = Composing.getCurrent(sidebar); 23541 optSlider.each(function (slider) { 23542 return Replacing.set(slider, [makeSidebar(panelConfigs)]); 23543 }); 23544 }; 23545 var toggleSidebar = function (sidebar, name) { 23546 var optSlider = Composing.getCurrent(sidebar); 23547 optSlider.each(function (slider) { 23548 var optSlotContainer = Composing.getCurrent(slider); 23549 optSlotContainer.each(function (slotContainer) { 23550 if (Sliding.hasGrown(slider)) { 23551 if (SlotContainer.isShowing(slotContainer, name)) { 23552 Sliding.shrink(slider); 23553 } else { 23554 SlotContainer.hideAllSlots(slotContainer); 23555 SlotContainer.showSlot(slotContainer, name); 23556 } 23557 } else { 23558 SlotContainer.hideAllSlots(slotContainer); 23559 SlotContainer.showSlot(slotContainer, name); 23560 Sliding.grow(slider); 23561 } 23562 }); 23563 }); 23564 }; 23565 var whichSidebar = function (sidebar) { 23566 var optSlider = Composing.getCurrent(sidebar); 23567 return optSlider.bind(function (slider) { 23568 var sidebarOpen = Sliding.isGrowing(slider) || Sliding.hasGrown(slider); 23569 if (sidebarOpen) { 23570 var optSlotContainer = Composing.getCurrent(slider); 23571 return optSlotContainer.bind(function (slotContainer) { 23572 return find$5(SlotContainer.getSlotNames(slotContainer), function (name) { 23573 return SlotContainer.isShowing(slotContainer, name); 23574 }); 23575 }); 23576 } else { 23577 return Optional.none(); 23578 } 23579 }); 23580 }; 23581 var fixSize = generate$6('FixSizeEvent'); 23582 var autoSize = generate$6('AutoSizeEvent'); 23583 var renderSidebar = function (spec) { 23584 return { 23585 uid: spec.uid, 23586 dom: { 23587 tag: 'div', 23588 classes: ['tox-sidebar'], 23589 attributes: { role: 'complementary' } 23590 }, 23591 components: [{ 23592 dom: { 23593 tag: 'div', 23594 classes: ['tox-sidebar__slider'] 23595 }, 23596 components: [], 23597 behaviours: derive$1([ 23598 Tabstopping.config({}), 23599 Focusing.config({}), 23600 Sliding.config({ 23601 dimension: { property: 'width' }, 23602 closedClass: 'tox-sidebar--sliding-closed', 23603 openClass: 'tox-sidebar--sliding-open', 23604 shrinkingClass: 'tox-sidebar--sliding-shrinking', 23605 growingClass: 'tox-sidebar--sliding-growing', 23606 onShrunk: function (slider) { 23607 var optSlotContainer = Composing.getCurrent(slider); 23608 optSlotContainer.each(SlotContainer.hideAllSlots); 23609 emit(slider, autoSize); 23610 }, 23611 onGrown: function (slider) { 23612 emit(slider, autoSize); 23613 }, 23614 onStartGrow: function (slider) { 23615 emitWith(slider, fixSize, { width: getRaw(slider.element, 'width').getOr('') }); 23616 }, 23617 onStartShrink: function (slider) { 23618 emitWith(slider, fixSize, { width: get$a(slider.element) + 'px' }); 23619 } 23620 }), 23621 Replacing.config({}), 23622 Composing.config({ 23623 find: function (comp) { 23624 var children = Replacing.contents(comp); 23625 return head(children); 23626 } 23627 }) 23628 ]) 23629 }], 23630 behaviours: derive$1([ 23631 ComposingConfigs.childAt(0), 23632 config('sidebar-sliding-events', [ 23633 run$1(fixSize, function (comp, se) { 23634 set$7(comp.element, 'width', se.event.width); 23635 }), 23636 run$1(autoSize, function (comp, _se) { 23637 remove$6(comp.element, 'width'); 23638 }) 23639 ]) 23640 ]) 23641 }; 23642 }; 23643 23644 var block = function (component, config, state, getBusySpec) { 23645 set$8(component.element, 'aria-busy', true); 23646 var root = config.getRoot(component).getOr(component); 23647 var blockerBehaviours = derive$1([ 23648 Keying.config({ 23649 mode: 'special', 23650 onTab: function () { 23651 return Optional.some(true); 23652 }, 23653 onShiftTab: function () { 23654 return Optional.some(true); 23655 } 23656 }), 23657 Focusing.config({}) 23658 ]); 23659 var blockSpec = getBusySpec(root, blockerBehaviours); 23660 var blocker = root.getSystem().build(blockSpec); 23661 Replacing.append(root, premade(blocker)); 23662 if (blocker.hasConfigured(Keying) && config.focus) { 23663 Keying.focusIn(blocker); 23664 } 23665 if (!state.isBlocked()) { 23666 config.onBlock(component); 23667 } 23668 state.blockWith(function () { 23669 return Replacing.remove(root, blocker); 23670 }); 23671 }; 23672 var unblock = function (component, config, state) { 23673 remove$7(component.element, 'aria-busy'); 23674 if (state.isBlocked()) { 23675 config.onUnblock(component); 23676 } 23677 state.clear(); 23678 }; 23679 23680 var BlockingApis = /*#__PURE__*/Object.freeze({ 23681 __proto__: null, 23682 block: block, 23683 unblock: unblock 23684 }); 23685 23686 var BlockingSchema = [ 23687 defaultedFunction('getRoot', Optional.none), 23688 defaultedBoolean('focus', true), 23689 onHandler('onBlock'), 23690 onHandler('onUnblock') 23691 ]; 23692 23693 var init$4 = function () { 23694 var blocker = destroyable(); 23695 var blockWith = function (destroy) { 23696 blocker.set({ destroy: destroy }); 23697 }; 23698 return nu$8({ 23699 readState: blocker.isSet, 23700 blockWith: blockWith, 23701 clear: blocker.clear, 23702 isBlocked: blocker.isSet 23703 }); 23704 }; 23705 23706 var BlockingState = /*#__PURE__*/Object.freeze({ 23707 __proto__: null, 23708 init: init$4 23709 }); 23710 23711 var Blocking = create$7({ 23712 fields: BlockingSchema, 23713 name: 'blocking', 23714 apis: BlockingApis, 23715 state: BlockingState 23716 }); 23717 23718 var getAttrs = function (elem) { 23719 var attributes = elem.dom.attributes !== undefined ? elem.dom.attributes : []; 23720 return foldl(attributes, function (b, attr) { 23721 var _a; 23722 if (attr.name === 'class') { 23723 return b; 23724 } else { 23725 return __assign(__assign({}, b), (_a = {}, _a[attr.name] = attr.value, _a)); 23726 } 23727 }, {}); 23728 }; 23729 var getClasses = function (elem) { 23730 return Array.prototype.slice.call(elem.dom.classList, 0); 23731 }; 23732 var fromHtml = function (html) { 23733 var elem = SugarElement.fromHtml(html); 23734 var children$1 = children(elem); 23735 var attrs = getAttrs(elem); 23736 var classes = getClasses(elem); 23737 var contents = children$1.length === 0 ? {} : { innerHtml: get$7(elem) }; 23738 return __assign({ 23739 tag: name$2(elem), 23740 classes: classes, 23741 attributes: attrs 23742 }, contents); 23743 }; 23744 23745 var getBusySpec$1 = function (providerBackstage) { 23746 return function (_root, _behaviours) { 23747 return { 23748 dom: { 23749 tag: 'div', 23750 attributes: { 23751 'aria-label': providerBackstage.translate('Loading...'), 23752 'tabindex': '0' 23753 }, 23754 classes: ['tox-throbber__busy-spinner'] 23755 }, 23756 components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }] 23757 }; 23758 }; 23759 }; 23760 var focusBusyComponent = function (throbber) { 23761 return Composing.getCurrent(throbber).each(function (comp) { 23762 return focus$3(comp.element); 23763 }); 23764 }; 23765 var toggleEditorTabIndex = function (editor, state) { 23766 var tabIndexAttr = 'tabindex'; 23767 var dataTabIndexAttr = 'data-mce-' + tabIndexAttr; 23768 Optional.from(editor.iframeElement).map(SugarElement.fromDom).each(function (iframe) { 23769 if (state) { 23770 getOpt(iframe, tabIndexAttr).each(function (tabIndex) { 23771 return set$8(iframe, dataTabIndexAttr, tabIndex); 23772 }); 23773 set$8(iframe, tabIndexAttr, -1); 23774 } else { 23775 remove$7(iframe, tabIndexAttr); 23776 getOpt(iframe, dataTabIndexAttr).each(function (tabIndex) { 23777 set$8(iframe, tabIndexAttr, tabIndex); 23778 remove$7(iframe, dataTabIndexAttr); 23779 }); 23780 } 23781 }); 23782 }; 23783 var toggleThrobber = function (editor, comp, state, providerBackstage) { 23784 var element = comp.element; 23785 toggleEditorTabIndex(editor, state); 23786 if (state) { 23787 Blocking.block(comp, getBusySpec$1(providerBackstage)); 23788 remove$6(element, 'display'); 23789 remove$7(element, 'aria-hidden'); 23790 if (editor.hasFocus()) { 23791 focusBusyComponent(comp); 23792 } 23793 } else { 23794 var throbberFocus = Composing.getCurrent(comp).exists(function (busyComp) { 23795 return hasFocus(busyComp.element); 23796 }); 23797 Blocking.unblock(comp); 23798 set$7(element, 'display', 'none'); 23799 set$8(element, 'aria-hidden', 'true'); 23800 if (throbberFocus) { 23801 editor.focus(); 23802 } 23803 } 23804 }; 23805 var renderThrobber = function (spec) { 23806 return { 23807 uid: spec.uid, 23808 dom: { 23809 tag: 'div', 23810 attributes: { 'aria-hidden': 'true' }, 23811 classes: ['tox-throbber'], 23812 styles: { display: 'none' } 23813 }, 23814 behaviours: derive$1([ 23815 Replacing.config({}), 23816 Blocking.config({ focus: false }), 23817 Composing.config({ 23818 find: function (comp) { 23819 return head(comp.components()); 23820 } 23821 }) 23822 ]), 23823 components: [] 23824 }; 23825 }; 23826 var isFocusEvent = function (event) { 23827 return event.type === 'focusin'; 23828 }; 23829 var isPasteBinTarget = function (event) { 23830 if (isFocusEvent(event)) { 23831 var node = event.composed ? head(event.composedPath()) : Optional.from(event.target); 23832 return node.map(SugarElement.fromDom).filter(isElement$2).exists(function (targetElm) { 23833 return has(targetElm, 'mce-pastebin'); 23834 }); 23835 } else { 23836 return false; 23837 } 23838 }; 23839 var setup$7 = function (editor, lazyThrobber, sharedBackstage) { 23840 var throbberState = Cell(false); 23841 var timer = value$1(); 23842 var stealFocus = function (e) { 23843 if (throbberState.get() && !isPasteBinTarget(e)) { 23844 e.preventDefault(); 23845 focusBusyComponent(lazyThrobber()); 23846 editor.editorManager.setActive(editor); 23847 } 23848 }; 23849 if (!editor.inline) { 23850 editor.on('PreInit', function () { 23851 editor.dom.bind(editor.getWin(), 'focusin', stealFocus); 23852 editor.on('BeforeExecCommand', function (e) { 23853 if (e.command.toLowerCase() === 'mcefocus' && e.value !== true) { 23854 stealFocus(e); 23855 } 23856 }); 23857 }); 23858 } 23859 var toggle = function (state) { 23860 if (state !== throbberState.get()) { 23861 throbberState.set(state); 23862 toggleThrobber(editor, lazyThrobber(), state, sharedBackstage.providers); 23863 editor.fire('AfterProgressState', { state: state }); 23864 } 23865 }; 23866 editor.on('ProgressState', function (e) { 23867 timer.on(global$f.clearTimeout); 23868 if (isNumber(e.time)) { 23869 var timerId = global$f.setEditorTimeout(editor, function () { 23870 return toggle(e.state); 23871 }, e.time); 23872 timer.set(timerId); 23873 } else { 23874 toggle(e.state); 23875 timer.clear(); 23876 } 23877 }); 23878 }; 23879 23880 var generate$1 = function (xs, f) { 23881 var init = { 23882 len: 0, 23883 list: [] 23884 }; 23885 var r = foldl(xs, function (b, a) { 23886 var value = f(a, b.len); 23887 return value.fold(constant$1(b), function (v) { 23888 return { 23889 len: v.finish, 23890 list: b.list.concat([v]) 23891 }; 23892 }); 23893 }, init); 23894 return r.list; 23895 }; 23896 23897 var output = function (within, extra, withinWidth) { 23898 return { 23899 within: within, 23900 extra: extra, 23901 withinWidth: withinWidth 23902 }; 23903 }; 23904 var apportion = function (units, total, len) { 23905 var parray = generate$1(units, function (unit, current) { 23906 var width = len(unit); 23907 return Optional.some({ 23908 element: unit, 23909 start: current, 23910 finish: current + width, 23911 width: width 23912 }); 23913 }); 23914 var within = filter$2(parray, function (unit) { 23915 return unit.finish <= total; 23916 }); 23917 var withinWidth = foldr(within, function (acc, el) { 23918 return acc + el.width; 23919 }, 0); 23920 var extra = parray.slice(within.length); 23921 return { 23922 within: within, 23923 extra: extra, 23924 withinWidth: withinWidth 23925 }; 23926 }; 23927 var toUnit = function (parray) { 23928 return map$2(parray, function (unit) { 23929 return unit.element; 23930 }); 23931 }; 23932 var fitLast = function (within, extra, withinWidth) { 23933 var fits = toUnit(within.concat(extra)); 23934 return output(fits, [], withinWidth); 23935 }; 23936 var overflow = function (within, extra, overflower, withinWidth) { 23937 var fits = toUnit(within).concat([overflower]); 23938 return output(fits, toUnit(extra), withinWidth); 23939 }; 23940 var fitAll = function (within, extra, withinWidth) { 23941 return output(toUnit(within), [], withinWidth); 23942 }; 23943 var tryFit = function (total, units, len) { 23944 var divide = apportion(units, total, len); 23945 return divide.extra.length === 0 ? Optional.some(divide) : Optional.none(); 23946 }; 23947 var partition = function (total, units, len, overflower) { 23948 var divide = tryFit(total, units, len).getOrThunk(function () { 23949 return apportion(units, total - len(overflower), len); 23950 }); 23951 var within = divide.within; 23952 var extra = divide.extra; 23953 var withinWidth = divide.withinWidth; 23954 if (extra.length === 1 && extra[0].width <= len(overflower)) { 23955 return fitLast(within, extra, withinWidth); 23956 } else if (extra.length >= 1) { 23957 return overflow(within, extra, overflower, withinWidth); 23958 } else { 23959 return fitAll(within, extra, withinWidth); 23960 } 23961 }; 23962 23963 var setGroups$1 = function (toolbar, storedGroups) { 23964 var bGroups = map$2(storedGroups, function (g) { 23965 return premade(g); 23966 }); 23967 Toolbar.setGroups(toolbar, bGroups); 23968 }; 23969 var findFocusedComp = function (comps) { 23970 return findMap(comps, function (comp) { 23971 return search(comp.element).bind(function (focusedElm) { 23972 return comp.getSystem().getByDom(focusedElm).toOptional(); 23973 }); 23974 }); 23975 }; 23976 var refresh$2 = function (toolbar, detail, setOverflow) { 23977 var builtGroups = detail.builtGroups.get(); 23978 if (builtGroups.length === 0) { 23979 return; 23980 } 23981 var primary = getPartOrDie(toolbar, detail, 'primary'); 23982 var overflowGroup = Coupling.getCoupled(toolbar, 'overflowGroup'); 23983 set$7(primary.element, 'visibility', 'hidden'); 23984 var groups = builtGroups.concat([overflowGroup]); 23985 var focusedComp = findFocusedComp(groups); 23986 setOverflow([]); 23987 setGroups$1(primary, groups); 23988 var availableWidth = get$a(primary.element); 23989 var overflows = partition(availableWidth, detail.builtGroups.get(), function (comp) { 23990 return get$a(comp.element); 23991 }, overflowGroup); 23992 if (overflows.extra.length === 0) { 23993 Replacing.remove(primary, overflowGroup); 23994 setOverflow([]); 23995 } else { 23996 setGroups$1(primary, overflows.within); 23997 setOverflow(overflows.extra); 23998 } 23999 remove$6(primary.element, 'visibility'); 24000 reflow(primary.element); 24001 focusedComp.each(Focusing.focus); 24002 }; 24003 24004 var schema$c = constant$1([ 24005 field('splitToolbarBehaviours', [Coupling]), 24006 customField('builtGroups', function () { 24007 return Cell([]); 24008 }) 24009 ]); 24010 24011 var schema$b = constant$1([ 24012 markers$1(['overflowToggledClass']), 24013 optionFunction('getOverflowBounds'), 24014 required$1('lazySink'), 24015 customField('overflowGroups', function () { 24016 return Cell([]); 24017 }) 24018 ].concat(schema$c())); 24019 var parts$7 = constant$1([ 24020 required({ 24021 factory: Toolbar, 24022 schema: schema$e(), 24023 name: 'primary' 24024 }), 24025 external$1({ 24026 schema: schema$e(), 24027 name: 'overflow' 24028 }), 24029 external$1({ name: 'overflow-button' }), 24030 external$1({ name: 'overflow-group' }) 24031 ]); 24032 24033 var expandable = constant$1(function (element, available) { 24034 setMax(element, Math.floor(available)); 24035 }); 24036 24037 var schema$a = constant$1([ 24038 markers$1(['toggledClass']), 24039 required$1('lazySink'), 24040 requiredFunction('fetch'), 24041 optionFunction('getBounds'), 24042 optionObjOf('fireDismissalEventInstead', [defaulted('event', dismissRequested())]), 24043 schema$y() 24044 ]); 24045 var parts$6 = constant$1([ 24046 external$1({ 24047 name: 'button', 24048 overrides: function (detail) { 24049 return { 24050 dom: { attributes: { 'aria-haspopup': 'true' } }, 24051 buttonBehaviours: derive$1([Toggling.config({ 24052 toggleClass: detail.markers.toggledClass, 24053 aria: { mode: 'expanded' }, 24054 toggleOnExecute: false 24055 })]) 24056 }; 24057 } 24058 }), 24059 external$1({ 24060 factory: Toolbar, 24061 schema: schema$e(), 24062 name: 'toolbar', 24063 overrides: function (detail) { 24064 return { 24065 toolbarBehaviours: derive$1([Keying.config({ 24066 mode: 'cyclic', 24067 onEscape: function (comp) { 24068 getPart(comp, detail, 'button').each(Focusing.focus); 24069 return Optional.none(); 24070 } 24071 })]) 24072 }; 24073 } 24074 }) 24075 ]); 24076 24077 var toggle = function (button, externals) { 24078 var toolbarSandbox = Coupling.getCoupled(button, 'toolbarSandbox'); 24079 if (Sandboxing.isOpen(toolbarSandbox)) { 24080 Sandboxing.close(toolbarSandbox); 24081 } else { 24082 Sandboxing.open(toolbarSandbox, externals.toolbar()); 24083 } 24084 }; 24085 var position = function (button, toolbar, detail, layouts) { 24086 var bounds = detail.getBounds.map(function (bounder) { 24087 return bounder(); 24088 }); 24089 var sink = detail.lazySink(button).getOrDie(); 24090 Positioning.positionWithinBounds(sink, toolbar, { 24091 anchor: { 24092 type: 'hotspot', 24093 hotspot: button, 24094 layouts: layouts, 24095 overrides: { maxWidthFunction: expandable() } 24096 } 24097 }, bounds); 24098 }; 24099 var setGroups = function (button, toolbar, detail, layouts, groups) { 24100 Toolbar.setGroups(toolbar, groups); 24101 position(button, toolbar, detail, layouts); 24102 Toggling.on(button); 24103 }; 24104 var makeSandbox = function (button, spec, detail) { 24105 var ariaOwner = manager(); 24106 var onOpen = function (sandbox, toolbar) { 24107 detail.fetch().get(function (groups) { 24108 setGroups(button, toolbar, detail, spec.layouts, groups); 24109 ariaOwner.link(button.element); 24110 Keying.focusIn(toolbar); 24111 }); 24112 }; 24113 var onClose = function () { 24114 Toggling.off(button); 24115 Focusing.focus(button); 24116 ariaOwner.unlink(button.element); 24117 }; 24118 return { 24119 dom: { 24120 tag: 'div', 24121 attributes: { id: ariaOwner.id } 24122 }, 24123 behaviours: derive$1([ 24124 Keying.config({ 24125 mode: 'special', 24126 onEscape: function (comp) { 24127 Sandboxing.close(comp); 24128 return Optional.some(true); 24129 } 24130 }), 24131 Sandboxing.config({ 24132 onOpen: onOpen, 24133 onClose: onClose, 24134 isPartOf: function (container, data, queryElem) { 24135 return isPartOf$1(data, queryElem) || isPartOf$1(button, queryElem); 24136 }, 24137 getAttachPoint: function () { 24138 return detail.lazySink(button).getOrDie(); 24139 } 24140 }), 24141 Receiving.config({ 24142 channels: __assign(__assign({}, receivingChannel$1(__assign({ isExtraPart: never }, detail.fireDismissalEventInstead.map(function (fe) { 24143 return { fireEventInstead: { event: fe.event } }; 24144 }).getOr({})))), receivingChannel({ 24145 doReposition: function () { 24146 Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) { 24147 position(button, toolbar, detail, spec.layouts); 24148 }); 24149 } 24150 })) 24151 }) 24152 ]) 24153 }; 24154 }; 24155 var factory$a = function (detail, components, spec, externals) { 24156 return __assign(__assign({}, Button.sketch(__assign(__assign({}, externals.button()), { 24157 action: function (button) { 24158 toggle(button, externals); 24159 }, 24160 buttonBehaviours: SketchBehaviours.augment({ dump: externals.button().buttonBehaviours }, [Coupling.config({ 24161 others: { 24162 toolbarSandbox: function (button) { 24163 return makeSandbox(button, spec, detail); 24164 } 24165 } 24166 })]) 24167 }))), { 24168 apis: { 24169 setGroups: function (button, groups) { 24170 Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) { 24171 setGroups(button, toolbar, detail, spec.layouts, groups); 24172 }); 24173 }, 24174 reposition: function (button) { 24175 Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')).each(function (toolbar) { 24176 position(button, toolbar, detail, spec.layouts); 24177 }); 24178 }, 24179 toggle: function (button) { 24180 toggle(button, externals); 24181 }, 24182 getToolbar: function (button) { 24183 return Sandboxing.getState(Coupling.getCoupled(button, 'toolbarSandbox')); 24184 }, 24185 isOpen: function (button) { 24186 return Sandboxing.isOpen(Coupling.getCoupled(button, 'toolbarSandbox')); 24187 } 24188 } 24189 }); 24190 }; 24191 var FloatingToolbarButton = composite({ 24192 name: 'FloatingToolbarButton', 24193 factory: factory$a, 24194 configFields: schema$a(), 24195 partFields: parts$6(), 24196 apis: { 24197 setGroups: function (apis, button, groups) { 24198 apis.setGroups(button, groups); 24199 }, 24200 reposition: function (apis, button) { 24201 apis.reposition(button); 24202 }, 24203 toggle: function (apis, button) { 24204 apis.toggle(button); 24205 }, 24206 getToolbar: function (apis, button) { 24207 return apis.getToolbar(button); 24208 }, 24209 isOpen: function (apis, button) { 24210 return apis.isOpen(button); 24211 } 24212 } 24213 }); 24214 24215 var schema$9 = constant$1([ 24216 required$1('items'), 24217 markers$1(['itemSelector']), 24218 field('tgroupBehaviours', [Keying]) 24219 ]); 24220 var parts$5 = constant$1([group({ 24221 name: 'items', 24222 unit: 'item' 24223 })]); 24224 24225 var factory$9 = function (detail, components, _spec, _externals) { 24226 return { 24227 uid: detail.uid, 24228 dom: detail.dom, 24229 components: components, 24230 behaviours: augment(detail.tgroupBehaviours, [Keying.config({ 24231 mode: 'flow', 24232 selector: detail.markers.itemSelector 24233 })]), 24234 domModification: { attributes: { role: 'toolbar' } } 24235 }; 24236 }; 24237 var ToolbarGroup = composite({ 24238 name: 'ToolbarGroup', 24239 configFields: schema$9(), 24240 partFields: parts$5(), 24241 factory: factory$9 24242 }); 24243 24244 var buildGroups = function (comps) { 24245 return map$2(comps, function (g) { 24246 return premade(g); 24247 }); 24248 }; 24249 var refresh$1 = function (toolbar, memFloatingToolbarButton, detail) { 24250 refresh$2(toolbar, detail, function (overflowGroups) { 24251 detail.overflowGroups.set(overflowGroups); 24252 memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) { 24253 FloatingToolbarButton.setGroups(floatingToolbarButton, buildGroups(overflowGroups)); 24254 }); 24255 }); 24256 }; 24257 var factory$8 = function (detail, components, spec, externals) { 24258 var memFloatingToolbarButton = record(FloatingToolbarButton.sketch({ 24259 fetch: function () { 24260 return Future.nu(function (resolve) { 24261 resolve(buildGroups(detail.overflowGroups.get())); 24262 }); 24263 }, 24264 layouts: { 24265 onLtr: function () { 24266 return [ 24267 southwest$2, 24268 southeast$2 24269 ]; 24270 }, 24271 onRtl: function () { 24272 return [ 24273 southeast$2, 24274 southwest$2 24275 ]; 24276 }, 24277 onBottomLtr: function () { 24278 return [ 24279 northwest$2, 24280 northeast$2 24281 ]; 24282 }, 24283 onBottomRtl: function () { 24284 return [ 24285 northeast$2, 24286 northwest$2 24287 ]; 24288 } 24289 }, 24290 getBounds: spec.getOverflowBounds, 24291 lazySink: detail.lazySink, 24292 fireDismissalEventInstead: {}, 24293 markers: { toggledClass: detail.markers.overflowToggledClass }, 24294 parts: { 24295 button: externals['overflow-button'](), 24296 toolbar: externals.overflow() 24297 } 24298 })); 24299 return { 24300 uid: detail.uid, 24301 dom: detail.dom, 24302 components: components, 24303 behaviours: augment(detail.splitToolbarBehaviours, [Coupling.config({ 24304 others: { 24305 overflowGroup: function () { 24306 return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { items: [memFloatingToolbarButton.asSpec()] })); 24307 } 24308 } 24309 })]), 24310 apis: { 24311 setGroups: function (toolbar, groups) { 24312 detail.builtGroups.set(map$2(groups, toolbar.getSystem().build)); 24313 refresh$1(toolbar, memFloatingToolbarButton, detail); 24314 }, 24315 refresh: function (toolbar) { 24316 return refresh$1(toolbar, memFloatingToolbarButton, detail); 24317 }, 24318 toggle: function (toolbar) { 24319 memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) { 24320 FloatingToolbarButton.toggle(floatingToolbarButton); 24321 }); 24322 }, 24323 isOpen: function (toolbar) { 24324 return memFloatingToolbarButton.getOpt(toolbar).map(FloatingToolbarButton.isOpen).getOr(false); 24325 }, 24326 reposition: function (toolbar) { 24327 memFloatingToolbarButton.getOpt(toolbar).each(function (floatingToolbarButton) { 24328 FloatingToolbarButton.reposition(floatingToolbarButton); 24329 }); 24330 }, 24331 getOverflow: function (toolbar) { 24332 return memFloatingToolbarButton.getOpt(toolbar).bind(FloatingToolbarButton.getToolbar); 24333 } 24334 }, 24335 domModification: { attributes: { role: 'group' } } 24336 }; 24337 }; 24338 var SplitFloatingToolbar = composite({ 24339 name: 'SplitFloatingToolbar', 24340 configFields: schema$b(), 24341 partFields: parts$7(), 24342 factory: factory$8, 24343 apis: { 24344 setGroups: function (apis, toolbar, groups) { 24345 apis.setGroups(toolbar, groups); 24346 }, 24347 refresh: function (apis, toolbar) { 24348 apis.refresh(toolbar); 24349 }, 24350 reposition: function (apis, toolbar) { 24351 apis.reposition(toolbar); 24352 }, 24353 toggle: function (apis, toolbar) { 24354 apis.toggle(toolbar); 24355 }, 24356 isOpen: function (apis, toolbar) { 24357 return apis.isOpen(toolbar); 24358 }, 24359 getOverflow: function (apis, toolbar) { 24360 return apis.getOverflow(toolbar); 24361 } 24362 } 24363 }); 24364 24365 var schema$8 = constant$1([ 24366 markers$1([ 24367 'closedClass', 24368 'openClass', 24369 'shrinkingClass', 24370 'growingClass', 24371 'overflowToggledClass' 24372 ]), 24373 onHandler('onOpened'), 24374 onHandler('onClosed') 24375 ].concat(schema$c())); 24376 var parts$4 = constant$1([ 24377 required({ 24378 factory: Toolbar, 24379 schema: schema$e(), 24380 name: 'primary' 24381 }), 24382 required({ 24383 factory: Toolbar, 24384 schema: schema$e(), 24385 name: 'overflow', 24386 overrides: function (detail) { 24387 return { 24388 toolbarBehaviours: derive$1([ 24389 Sliding.config({ 24390 dimension: { property: 'height' }, 24391 closedClass: detail.markers.closedClass, 24392 openClass: detail.markers.openClass, 24393 shrinkingClass: detail.markers.shrinkingClass, 24394 growingClass: detail.markers.growingClass, 24395 onShrunk: function (comp) { 24396 getPart(comp, detail, 'overflow-button').each(function (button) { 24397 Toggling.off(button); 24398 Focusing.focus(button); 24399 }); 24400 detail.onClosed(comp); 24401 }, 24402 onGrown: function (comp) { 24403 Keying.focusIn(comp); 24404 detail.onOpened(comp); 24405 }, 24406 onStartGrow: function (comp) { 24407 getPart(comp, detail, 'overflow-button').each(Toggling.on); 24408 } 24409 }), 24410 Keying.config({ 24411 mode: 'acyclic', 24412 onEscape: function (comp) { 24413 getPart(comp, detail, 'overflow-button').each(Focusing.focus); 24414 return Optional.some(true); 24415 } 24416 }) 24417 ]) 24418 }; 24419 } 24420 }), 24421 external$1({ 24422 name: 'overflow-button', 24423 overrides: function (detail) { 24424 return { 24425 buttonBehaviours: derive$1([Toggling.config({ 24426 toggleClass: detail.markers.overflowToggledClass, 24427 aria: { mode: 'pressed' }, 24428 toggleOnExecute: false 24429 })]) 24430 }; 24431 } 24432 }), 24433 external$1({ name: 'overflow-group' }) 24434 ]); 24435 24436 var isOpen = function (toolbar, detail) { 24437 return getPart(toolbar, detail, 'overflow').map(Sliding.hasGrown).getOr(false); 24438 }; 24439 var toggleToolbar = function (toolbar, detail) { 24440 getPart(toolbar, detail, 'overflow-button').bind(function () { 24441 return getPart(toolbar, detail, 'overflow'); 24442 }).each(function (overf) { 24443 refresh(toolbar, detail); 24444 Sliding.toggleGrow(overf); 24445 }); 24446 }; 24447 var refresh = function (toolbar, detail) { 24448 getPart(toolbar, detail, 'overflow').each(function (overflow) { 24449 refresh$2(toolbar, detail, function (groups) { 24450 var builtGroups = map$2(groups, function (g) { 24451 return premade(g); 24452 }); 24453 Toolbar.setGroups(overflow, builtGroups); 24454 }); 24455 getPart(toolbar, detail, 'overflow-button').each(function (button) { 24456 if (Sliding.hasGrown(overflow)) { 24457 Toggling.on(button); 24458 } 24459 }); 24460 Sliding.refresh(overflow); 24461 }); 24462 }; 24463 var factory$7 = function (detail, components, spec, externals) { 24464 var toolbarToggleEvent = 'alloy.toolbar.toggle'; 24465 var doSetGroups = function (toolbar, groups) { 24466 var built = map$2(groups, toolbar.getSystem().build); 24467 detail.builtGroups.set(built); 24468 }; 24469 return { 24470 uid: detail.uid, 24471 dom: detail.dom, 24472 components: components, 24473 behaviours: augment(detail.splitToolbarBehaviours, [ 24474 Coupling.config({ 24475 others: { 24476 overflowGroup: function (toolbar) { 24477 return ToolbarGroup.sketch(__assign(__assign({}, externals['overflow-group']()), { 24478 items: [Button.sketch(__assign(__assign({}, externals['overflow-button']()), { 24479 action: function (_button) { 24480 emit(toolbar, toolbarToggleEvent); 24481 } 24482 }))] 24483 })); 24484 } 24485 } 24486 }), 24487 config('toolbar-toggle-events', [run$1(toolbarToggleEvent, function (toolbar) { 24488 toggleToolbar(toolbar, detail); 24489 })]) 24490 ]), 24491 apis: { 24492 setGroups: function (toolbar, groups) { 24493 doSetGroups(toolbar, groups); 24494 refresh(toolbar, detail); 24495 }, 24496 refresh: function (toolbar) { 24497 return refresh(toolbar, detail); 24498 }, 24499 toggle: function (toolbar) { 24500 return toggleToolbar(toolbar, detail); 24501 }, 24502 isOpen: function (toolbar) { 24503 return isOpen(toolbar, detail); 24504 } 24505 }, 24506 domModification: { attributes: { role: 'group' } } 24507 }; 24508 }; 24509 var SplitSlidingToolbar = composite({ 24510 name: 'SplitSlidingToolbar', 24511 configFields: schema$8(), 24512 partFields: parts$4(), 24513 factory: factory$7, 24514 apis: { 24515 setGroups: function (apis, toolbar, groups) { 24516 apis.setGroups(toolbar, groups); 24517 }, 24518 refresh: function (apis, toolbar) { 24519 apis.refresh(toolbar); 24520 }, 24521 toggle: function (apis, toolbar) { 24522 apis.toggle(toolbar); 24523 }, 24524 isOpen: function (apis, toolbar) { 24525 return apis.isOpen(toolbar); 24526 } 24527 } 24528 }); 24529 24530 var renderToolbarGroupCommon = function (toolbarGroup) { 24531 var attributes = toolbarGroup.title.fold(function () { 24532 return {}; 24533 }, function (title) { 24534 return { attributes: { title: title } }; 24535 }); 24536 return { 24537 dom: __assign({ 24538 tag: 'div', 24539 classes: ['tox-toolbar__group'] 24540 }, attributes), 24541 components: [ToolbarGroup.parts.items({})], 24542 items: toolbarGroup.items, 24543 markers: { itemSelector: '*:not(.tox-split-button) > .tox-tbtn:not([disabled]), ' + '.tox-split-button:not([disabled]), ' + '.tox-toolbar-nav-js:not([disabled])' }, 24544 tgroupBehaviours: derive$1([ 24545 Tabstopping.config({}), 24546 Focusing.config({}) 24547 ]) 24548 }; 24549 }; 24550 var renderToolbarGroup = function (toolbarGroup) { 24551 return ToolbarGroup.sketch(renderToolbarGroupCommon(toolbarGroup)); 24552 }; 24553 var getToolbarbehaviours = function (toolbarSpec, modeName) { 24554 var onAttached = runOnAttached(function (component) { 24555 var groups = map$2(toolbarSpec.initGroups, renderToolbarGroup); 24556 Toolbar.setGroups(component, groups); 24557 }); 24558 return derive$1([ 24559 DisablingConfigs.toolbarButton(toolbarSpec.providers.isDisabled), 24560 receivingConfig(), 24561 Keying.config({ 24562 mode: modeName, 24563 onEscape: toolbarSpec.onEscape, 24564 selector: '.tox-toolbar__group' 24565 }), 24566 config('toolbar-events', [onAttached]) 24567 ]); 24568 }; 24569 var renderMoreToolbarCommon = function (toolbarSpec) { 24570 var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic'; 24571 return { 24572 uid: toolbarSpec.uid, 24573 dom: { 24574 tag: 'div', 24575 classes: ['tox-toolbar-overlord'] 24576 }, 24577 parts: { 24578 'overflow-group': renderToolbarGroupCommon({ 24579 title: Optional.none(), 24580 items: [] 24581 }), 24582 'overflow-button': renderIconButtonSpec({ 24583 name: 'more', 24584 icon: Optional.some('more-drawer'), 24585 disabled: false, 24586 tooltip: Optional.some('More...'), 24587 primary: false, 24588 borderless: false 24589 }, Optional.none(), toolbarSpec.providers) 24590 }, 24591 splitToolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName) 24592 }; 24593 }; 24594 var renderFloatingMoreToolbar = function (toolbarSpec) { 24595 var baseSpec = renderMoreToolbarCommon(toolbarSpec); 24596 var overflowXOffset = 4; 24597 var primary = SplitFloatingToolbar.parts.primary({ 24598 dom: { 24599 tag: 'div', 24600 classes: ['tox-toolbar__primary'] 24601 } 24602 }); 24603 return SplitFloatingToolbar.sketch(__assign(__assign({}, baseSpec), { 24604 lazySink: toolbarSpec.getSink, 24605 getOverflowBounds: function () { 24606 var headerElem = toolbarSpec.moreDrawerData.lazyHeader().element; 24607 var headerBounds = absolute$2(headerElem); 24608 var docElem = documentElement(headerElem); 24609 var docBounds = absolute$2(docElem); 24610 var height = Math.max(docElem.dom.scrollHeight, docBounds.height); 24611 return bounds(headerBounds.x + overflowXOffset, docBounds.y, headerBounds.width - overflowXOffset * 2, height); 24612 }, 24613 parts: __assign(__assign({}, baseSpec.parts), { 24614 overflow: { 24615 dom: { 24616 tag: 'div', 24617 classes: ['tox-toolbar__overflow'], 24618 attributes: toolbarSpec.attributes 24619 } 24620 } 24621 }), 24622 components: [primary], 24623 markers: { overflowToggledClass: 'tox-tbtn--enabled' } 24624 })); 24625 }; 24626 var renderSlidingMoreToolbar = function (toolbarSpec) { 24627 var primary = SplitSlidingToolbar.parts.primary({ 24628 dom: { 24629 tag: 'div', 24630 classes: ['tox-toolbar__primary'] 24631 } 24632 }); 24633 var overflow = SplitSlidingToolbar.parts.overflow({ 24634 dom: { 24635 tag: 'div', 24636 classes: ['tox-toolbar__overflow'] 24637 } 24638 }); 24639 var baseSpec = renderMoreToolbarCommon(toolbarSpec); 24640 return SplitSlidingToolbar.sketch(__assign(__assign({}, baseSpec), { 24641 components: [ 24642 primary, 24643 overflow 24644 ], 24645 markers: { 24646 openClass: 'tox-toolbar__overflow--open', 24647 closedClass: 'tox-toolbar__overflow--closed', 24648 growingClass: 'tox-toolbar__overflow--growing', 24649 shrinkingClass: 'tox-toolbar__overflow--shrinking', 24650 overflowToggledClass: 'tox-tbtn--enabled' 24651 }, 24652 onOpened: function (comp) { 24653 comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'opened' }); 24654 }, 24655 onClosed: function (comp) { 24656 comp.getSystem().broadcastOn([toolbarHeightChange()], { type: 'closed' }); 24657 } 24658 })); 24659 }; 24660 var renderToolbar = function (toolbarSpec) { 24661 var modeName = toolbarSpec.cyclicKeying ? 'cyclic' : 'acyclic'; 24662 return Toolbar.sketch({ 24663 uid: toolbarSpec.uid, 24664 dom: { 24665 tag: 'div', 24666 classes: ['tox-toolbar'].concat(toolbarSpec.type === ToolbarMode.scrolling ? ['tox-toolbar--scrolling'] : []) 24667 }, 24668 components: [Toolbar.parts.groups({})], 24669 toolbarBehaviours: getToolbarbehaviours(toolbarSpec, modeName) 24670 }); 24671 }; 24672 24673 var factory$6 = function (detail, components, _spec) { 24674 var apis = { 24675 getSocket: function (comp) { 24676 return parts$a.getPart(comp, detail, 'socket'); 24677 }, 24678 setSidebar: function (comp, panelConfigs) { 24679 parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) { 24680 return setSidebar(sidebar, panelConfigs); 24681 }); 24682 }, 24683 toggleSidebar: function (comp, name) { 24684 parts$a.getPart(comp, detail, 'sidebar').each(function (sidebar) { 24685 return toggleSidebar(sidebar, name); 24686 }); 24687 }, 24688 whichSidebar: function (comp) { 24689 return parts$a.getPart(comp, detail, 'sidebar').bind(whichSidebar).getOrNull(); 24690 }, 24691 getHeader: function (comp) { 24692 return parts$a.getPart(comp, detail, 'header'); 24693 }, 24694 getToolbar: function (comp) { 24695 return parts$a.getPart(comp, detail, 'toolbar'); 24696 }, 24697 setToolbar: function (comp, groups) { 24698 parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) { 24699 toolbar.getApis().setGroups(toolbar, groups); 24700 }); 24701 }, 24702 setToolbars: function (comp, toolbars) { 24703 parts$a.getPart(comp, detail, 'multiple-toolbar').each(function (mToolbar) { 24704 CustomList.setItems(mToolbar, toolbars); 24705 }); 24706 }, 24707 refreshToolbar: function (comp) { 24708 var toolbar = parts$a.getPart(comp, detail, 'toolbar'); 24709 toolbar.each(function (toolbar) { 24710 return toolbar.getApis().refresh(toolbar); 24711 }); 24712 }, 24713 toggleToolbarDrawer: function (comp) { 24714 parts$a.getPart(comp, detail, 'toolbar').each(function (toolbar) { 24715 mapFrom(toolbar.getApis().toggle, function (toggle) { 24716 return toggle(toolbar); 24717 }); 24718 }); 24719 }, 24720 isToolbarDrawerToggled: function (comp) { 24721 return parts$a.getPart(comp, detail, 'toolbar').bind(function (toolbar) { 24722 return Optional.from(toolbar.getApis().isOpen).map(function (isOpen) { 24723 return isOpen(toolbar); 24724 }); 24725 }).getOr(false); 24726 }, 24727 getThrobber: function (comp) { 24728 return parts$a.getPart(comp, detail, 'throbber'); 24729 }, 24730 focusToolbar: function (comp) { 24731 var optToolbar = parts$a.getPart(comp, detail, 'toolbar').orThunk(function () { 24732 return parts$a.getPart(comp, detail, 'multiple-toolbar'); 24733 }); 24734 optToolbar.each(function (toolbar) { 24735 Keying.focusIn(toolbar); 24736 }); 24737 }, 24738 setMenubar: function (comp, menus) { 24739 parts$a.getPart(comp, detail, 'menubar').each(function (menubar) { 24740 SilverMenubar.setMenus(menubar, menus); 24741 }); 24742 }, 24743 focusMenubar: function (comp) { 24744 parts$a.getPart(comp, detail, 'menubar').each(function (menubar) { 24745 SilverMenubar.focus(menubar); 24746 }); 24747 } 24748 }; 24749 return { 24750 uid: detail.uid, 24751 dom: detail.dom, 24752 components: components, 24753 apis: apis, 24754 behaviours: detail.behaviours 24755 }; 24756 }; 24757 var partMenubar = partType.optional({ 24758 factory: SilverMenubar, 24759 name: 'menubar', 24760 schema: [required$1('backstage')] 24761 }); 24762 var toolbarFactory = function (spec) { 24763 if (spec.type === ToolbarMode.sliding) { 24764 return renderSlidingMoreToolbar; 24765 } else if (spec.type === ToolbarMode.floating) { 24766 return renderFloatingMoreToolbar; 24767 } else { 24768 return renderToolbar; 24769 } 24770 }; 24771 var partMultipleToolbar = partType.optional({ 24772 factory: { 24773 sketch: function (spec) { 24774 return CustomList.sketch({ 24775 uid: spec.uid, 24776 dom: spec.dom, 24777 listBehaviours: derive$1([Keying.config({ 24778 mode: 'acyclic', 24779 selector: '.tox-toolbar' 24780 })]), 24781 makeItem: function () { 24782 return renderToolbar({ 24783 type: spec.type, 24784 uid: generate$6('multiple-toolbar-item'), 24785 cyclicKeying: false, 24786 initGroups: [], 24787 providers: spec.providers, 24788 onEscape: function () { 24789 spec.onEscape(); 24790 return Optional.some(true); 24791 } 24792 }); 24793 }, 24794 setupItem: function (_mToolbar, tc, data, _index) { 24795 Toolbar.setGroups(tc, data); 24796 }, 24797 shell: true 24798 }); 24799 } 24800 }, 24801 name: 'multiple-toolbar', 24802 schema: [ 24803 required$1('dom'), 24804 required$1('onEscape') 24805 ] 24806 }); 24807 var partToolbar = partType.optional({ 24808 factory: { 24809 sketch: function (spec) { 24810 var renderer = toolbarFactory(spec); 24811 var toolbarSpec = { 24812 type: spec.type, 24813 uid: spec.uid, 24814 onEscape: function () { 24815 spec.onEscape(); 24816 return Optional.some(true); 24817 }, 24818 cyclicKeying: false, 24819 initGroups: [], 24820 getSink: spec.getSink, 24821 providers: spec.providers, 24822 moreDrawerData: { 24823 lazyToolbar: spec.lazyToolbar, 24824 lazyMoreButton: spec.lazyMoreButton, 24825 lazyHeader: spec.lazyHeader 24826 }, 24827 attributes: spec.attributes 24828 }; 24829 return renderer(toolbarSpec); 24830 } 24831 }, 24832 name: 'toolbar', 24833 schema: [ 24834 required$1('dom'), 24835 required$1('onEscape'), 24836 required$1('getSink') 24837 ] 24838 }); 24839 var partHeader = partType.optional({ 24840 factory: { sketch: renderHeader }, 24841 name: 'header', 24842 schema: [required$1('dom')] 24843 }); 24844 var partSocket = partType.optional({ 24845 name: 'socket', 24846 schema: [required$1('dom')] 24847 }); 24848 var partSidebar = partType.optional({ 24849 factory: { sketch: renderSidebar }, 24850 name: 'sidebar', 24851 schema: [required$1('dom')] 24852 }); 24853 var partThrobber = partType.optional({ 24854 factory: { sketch: renderThrobber }, 24855 name: 'throbber', 24856 schema: [required$1('dom')] 24857 }); 24858 var OuterContainer = composite({ 24859 name: 'OuterContainer', 24860 factory: factory$6, 24861 configFields: [ 24862 required$1('dom'), 24863 required$1('behaviours') 24864 ], 24865 partFields: [ 24866 partHeader, 24867 partMenubar, 24868 partToolbar, 24869 partMultipleToolbar, 24870 partSocket, 24871 partSidebar, 24872 partThrobber 24873 ], 24874 apis: { 24875 getSocket: function (apis, comp) { 24876 return apis.getSocket(comp); 24877 }, 24878 setSidebar: function (apis, comp, panelConfigs) { 24879 apis.setSidebar(comp, panelConfigs); 24880 }, 24881 toggleSidebar: function (apis, comp, name) { 24882 apis.toggleSidebar(comp, name); 24883 }, 24884 whichSidebar: function (apis, comp) { 24885 return apis.whichSidebar(comp); 24886 }, 24887 getHeader: function (apis, comp) { 24888 return apis.getHeader(comp); 24889 }, 24890 getToolbar: function (apis, comp) { 24891 return apis.getToolbar(comp); 24892 }, 24893 setToolbar: function (apis, comp, grps) { 24894 var groups = map$2(grps, function (grp) { 24895 return renderToolbarGroup(grp); 24896 }); 24897 apis.setToolbar(comp, groups); 24898 }, 24899 setToolbars: function (apis, comp, ts) { 24900 var renderedToolbars = map$2(ts, function (g) { 24901 return map$2(g, renderToolbarGroup); 24902 }); 24903 apis.setToolbars(comp, renderedToolbars); 24904 }, 24905 refreshToolbar: function (apis, comp) { 24906 return apis.refreshToolbar(comp); 24907 }, 24908 toggleToolbarDrawer: function (apis, comp) { 24909 apis.toggleToolbarDrawer(comp); 24910 }, 24911 isToolbarDrawerToggled: function (apis, comp) { 24912 return apis.isToolbarDrawerToggled(comp); 24913 }, 24914 getThrobber: function (apis, comp) { 24915 return apis.getThrobber(comp); 24916 }, 24917 setMenubar: function (apis, comp, menus) { 24918 apis.setMenubar(comp, menus); 24919 }, 24920 focusMenubar: function (apis, comp) { 24921 apis.focusMenubar(comp); 24922 }, 24923 focusToolbar: function (apis, comp) { 24924 apis.focusToolbar(comp); 24925 } 24926 } 24927 }); 24928 24929 var defaultMenubar = 'file edit view insert format tools table help'; 24930 var defaultMenus = { 24931 file: { 24932 title: 'File', 24933 items: 'newdocument restoredraft | preview | export print | deleteallconversations' 24934 }, 24935 edit: { 24936 title: 'Edit', 24937 items: 'undo redo | cut copy paste pastetext | selectall | searchreplace' 24938 }, 24939 view: { 24940 title: 'View', 24941 items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen | showcomments' 24942 }, 24943 insert: { 24944 title: 'Insert', 24945 items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime' 24946 }, 24947 format: { 24948 title: 'Format', 24949 items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | language | removeformat' 24950 }, 24951 tools: { 24952 title: 'Tools', 24953 items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount' 24954 }, 24955 table: { 24956 title: 'Table', 24957 items: 'inserttable | cell row column | advtablesort | tableprops deletetable' 24958 }, 24959 help: { 24960 title: 'Help', 24961 items: 'help' 24962 } 24963 }; 24964 var make = function (menu, registry, editor) { 24965 var removedMenuItems = getRemovedMenuItems(editor).split(/[ ,]/); 24966 return { 24967 text: menu.title, 24968 getItems: function () { 24969 return bind$3(menu.items, function (i) { 24970 var itemName = i.toLowerCase(); 24971 if (itemName.trim().length === 0) { 24972 return []; 24973 } else if (exists(removedMenuItems, function (removedMenuItem) { 24974 return removedMenuItem === itemName; 24975 })) { 24976 return []; 24977 } else if (itemName === 'separator' || itemName === '|') { 24978 return [{ type: 'separator' }]; 24979 } else if (registry.menuItems[itemName]) { 24980 return [registry.menuItems[itemName]]; 24981 } else { 24982 return []; 24983 } 24984 }); 24985 } 24986 }; 24987 }; 24988 var parseItemsString = function (items) { 24989 if (typeof items === 'string') { 24990 return items.split(' '); 24991 } 24992 return items; 24993 }; 24994 var identifyMenus = function (editor, registry) { 24995 var rawMenuData = __assign(__assign({}, defaultMenus), registry.menus); 24996 var userDefinedMenus = keys(registry.menus).length > 0; 24997 var menubar = registry.menubar === undefined || registry.menubar === true ? parseItemsString(defaultMenubar) : parseItemsString(registry.menubar === false ? '' : registry.menubar); 24998 var validMenus = filter$2(menubar, function (menuName) { 24999 var isDefaultMenu = has$2(defaultMenus, menuName); 25000 if (userDefinedMenus) { 25001 return isDefaultMenu || get$e(registry.menus, menuName).exists(function (menu) { 25002 return has$2(menu, 'items'); 25003 }); 25004 } else { 25005 return isDefaultMenu; 25006 } 25007 }); 25008 var menus = map$2(validMenus, function (menuName) { 25009 var menuData = rawMenuData[menuName]; 25010 return make({ 25011 title: menuData.title, 25012 items: parseItemsString(menuData.items) 25013 }, registry, editor); 25014 }); 25015 return filter$2(menus, function (menu) { 25016 var isNotSeparator = function (item) { 25017 return item.type !== 'separator'; 25018 }; 25019 return menu.getItems().length > 0 && exists(menu.getItems(), isNotSeparator); 25020 }); 25021 }; 25022 25023 var fireSkinLoaded = function (editor) { 25024 var done = function () { 25025 editor._skinLoaded = true; 25026 fireSkinLoaded$1(editor); 25027 }; 25028 return function () { 25029 if (editor.initialized) { 25030 done(); 25031 } else { 25032 editor.on('init', done); 25033 } 25034 }; 25035 }; 25036 var fireSkinLoadError = function (editor, err) { 25037 return function () { 25038 return fireSkinLoadError$1(editor, { message: err }); 25039 }; 25040 }; 25041 25042 var loadStylesheet = function (editor, stylesheetUrl, styleSheetLoader) { 25043 return new global$c(function (resolve, reject) { 25044 styleSheetLoader.load(stylesheetUrl, resolve, reject); 25045 editor.on('remove', function () { 25046 return styleSheetLoader.unload(stylesheetUrl); 25047 }); 25048 }); 25049 }; 25050 var loadUiSkins = function (editor, skinUrl) { 25051 var skinUiCss = skinUrl + '/skin.min.css'; 25052 return loadStylesheet(editor, skinUiCss, editor.ui.styleSheetLoader); 25053 }; 25054 var loadShadowDomUiSkins = function (editor, skinUrl) { 25055 var isInShadowRoot$1 = isInShadowRoot(SugarElement.fromDom(editor.getElement())); 25056 if (isInShadowRoot$1) { 25057 var shadowDomSkinCss = skinUrl + '/skin.shadowdom.min.css'; 25058 return loadStylesheet(editor, shadowDomSkinCss, global$b.DOM.styleSheetLoader); 25059 } else { 25060 return global$c.resolve(); 25061 } 25062 }; 25063 var loadSkin = function (isInline, editor) { 25064 var skinUrl = getSkinUrl(editor); 25065 if (skinUrl) { 25066 editor.contentCSS.push(skinUrl + (isInline ? '/content.inline' : '/content') + '.min.css'); 25067 } 25068 if (isSkinDisabled(editor) === false && isString(skinUrl)) { 25069 global$c.all([ 25070 loadUiSkins(editor, skinUrl), 25071 loadShadowDomUiSkins(editor, skinUrl) 25072 ]).then(fireSkinLoaded(editor), fireSkinLoadError(editor, 'Skin could not be loaded')); 25073 } else { 25074 fireSkinLoaded(editor)(); 25075 } 25076 }; 25077 var iframe = curry(loadSkin, false); 25078 var inline = curry(loadSkin, true); 25079 25080 var onSetupFormatToggle = function (editor, name) { 25081 return function (api) { 25082 var boundCallback = unbindable(); 25083 var init = function () { 25084 api.setActive(editor.formatter.match(name)); 25085 var binding = editor.formatter.formatChanged(name, api.setActive); 25086 boundCallback.set(binding); 25087 }; 25088 editor.initialized ? init() : editor.once('init', init); 25089 return function () { 25090 editor.off('init', init); 25091 boundCallback.clear(); 25092 }; 25093 }; 25094 }; 25095 var onSetupEvent = function (editor, event, f) { 25096 return function (api) { 25097 var handleEvent = function () { 25098 return f(api); 25099 }; 25100 var init = function () { 25101 f(api); 25102 editor.on(event, handleEvent); 25103 }; 25104 editor.initialized ? init() : editor.once('init', init); 25105 return function () { 25106 editor.off('init', init); 25107 editor.off(event, handleEvent); 25108 }; 25109 }; 25110 }; 25111 var onActionToggleFormat$1 = function (editor) { 25112 return function (rawItem) { 25113 return function () { 25114 editor.undoManager.transact(function () { 25115 editor.focus(); 25116 editor.execCommand('mceToggleFormat', false, rawItem.format); 25117 }); 25118 }; 25119 }; 25120 }; 25121 var onActionExecCommand = function (editor, command) { 25122 return function () { 25123 return editor.execCommand(command); 25124 }; 25125 }; 25126 25127 var generateSelectItems = function (_editor, backstage, spec) { 25128 var generateItem = function (rawItem, response, disabled, value) { 25129 var translatedText = backstage.shared.providers.translate(rawItem.title); 25130 if (rawItem.type === 'separator') { 25131 return Optional.some({ 25132 type: 'separator', 25133 text: translatedText 25134 }); 25135 } else if (rawItem.type === 'submenu') { 25136 var items = bind$3(rawItem.getStyleItems(), function (si) { 25137 return validate(si, response, value); 25138 }); 25139 if (response === 0 && items.length <= 0) { 25140 return Optional.none(); 25141 } else { 25142 return Optional.some({ 25143 type: 'nestedmenuitem', 25144 text: translatedText, 25145 disabled: items.length <= 0, 25146 getSubmenuItems: function () { 25147 return bind$3(rawItem.getStyleItems(), function (si) { 25148 return validate(si, response, value); 25149 }); 25150 } 25151 }); 25152 } 25153 } else { 25154 return Optional.some(__assign({ 25155 type: 'togglemenuitem', 25156 text: translatedText, 25157 icon: rawItem.icon, 25158 active: rawItem.isSelected(value), 25159 disabled: disabled, 25160 onAction: spec.onAction(rawItem) 25161 }, rawItem.getStylePreview().fold(function () { 25162 return {}; 25163 }, function (preview) { 25164 return { meta: { style: preview } }; 25165 }))); 25166 } 25167 }; 25168 var validate = function (item, response, value) { 25169 var invalid = item.type === 'formatter' && spec.isInvalid(item); 25170 if (response === 0) { 25171 return invalid ? [] : generateItem(item, response, false, value).toArray(); 25172 } else { 25173 return generateItem(item, response, invalid, value).toArray(); 25174 } 25175 }; 25176 var validateItems = function (preItems) { 25177 var value = spec.getCurrentValue(); 25178 var response = spec.shouldHide ? 0 : 1; 25179 return bind$3(preItems, function (item) { 25180 return validate(item, response, value); 25181 }); 25182 }; 25183 var getFetch = function (backstage, getStyleItems) { 25184 return function (comp, callback) { 25185 var preItems = getStyleItems(); 25186 var items = validateItems(preItems); 25187 var menu = build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false); 25188 callback(menu); 25189 }; 25190 }; 25191 return { 25192 validateItems: validateItems, 25193 getFetch: getFetch 25194 }; 25195 }; 25196 var createMenuItems = function (editor, backstage, spec) { 25197 var dataset = spec.dataset; 25198 var getStyleItems = dataset.type === 'basic' ? function () { 25199 return map$2(dataset.data, function (d) { 25200 return processBasic(d, spec.isSelectedFor, spec.getPreviewFor); 25201 }); 25202 } : dataset.getData; 25203 return { 25204 items: generateSelectItems(editor, backstage, spec), 25205 getStyleItems: getStyleItems 25206 }; 25207 }; 25208 var createSelectButton = function (editor, backstage, spec) { 25209 var _a = createMenuItems(editor, backstage, spec), items = _a.items, getStyleItems = _a.getStyleItems; 25210 var getApi = function (comp) { 25211 return { getComponent: constant$1(comp) }; 25212 }; 25213 var onSetup = onSetupEvent(editor, 'NodeChange', function (api) { 25214 var comp = api.getComponent(); 25215 spec.updateText(comp); 25216 }); 25217 return renderCommonDropdown({ 25218 text: spec.icon.isSome() ? Optional.none() : spec.text, 25219 icon: spec.icon, 25220 tooltip: Optional.from(spec.tooltip), 25221 role: Optional.none(), 25222 fetch: items.getFetch(backstage, getStyleItems), 25223 onSetup: onSetup, 25224 getApi: getApi, 25225 columns: 1, 25226 presets: 'normal', 25227 classes: spec.icon.isSome() ? [] : ['bespoke'], 25228 dropdownBehaviours: [] 25229 }, 'tox-tbtn', backstage.shared); 25230 }; 25231 25232 var process = function (rawFormats) { 25233 return map$2(rawFormats, function (item) { 25234 var title = item, format = item; 25235 var values = item.split('='); 25236 if (values.length > 1) { 25237 title = values[0]; 25238 format = values[1]; 25239 } 25240 return { 25241 title: title, 25242 format: format 25243 }; 25244 }); 25245 }; 25246 var buildBasicStaticDataset = function (data) { 25247 return { 25248 type: 'basic', 25249 data: data 25250 }; 25251 }; 25252 var Delimiter; 25253 (function (Delimiter) { 25254 Delimiter[Delimiter['SemiColon'] = 0] = 'SemiColon'; 25255 Delimiter[Delimiter['Space'] = 1] = 'Space'; 25256 }(Delimiter || (Delimiter = {}))); 25257 var split = function (rawFormats, delimiter) { 25258 if (delimiter === Delimiter.SemiColon) { 25259 return rawFormats.replace(/;$/, '').split(';'); 25260 } else { 25261 return rawFormats.split(' '); 25262 } 25263 }; 25264 var buildBasicSettingsDataset = function (editor, settingName, defaults, delimiter) { 25265 var rawFormats = editor.getParam(settingName, defaults, 'string'); 25266 var data = process(split(rawFormats, delimiter)); 25267 return { 25268 type: 'basic', 25269 data: data 25270 }; 25271 }; 25272 25273 var alignMenuItems = [ 25274 { 25275 title: 'Left', 25276 icon: 'align-left', 25277 format: 'alignleft', 25278 command: 'JustifyLeft' 25279 }, 25280 { 25281 title: 'Center', 25282 icon: 'align-center', 25283 format: 'aligncenter', 25284 command: 'JustifyCenter' 25285 }, 25286 { 25287 title: 'Right', 25288 icon: 'align-right', 25289 format: 'alignright', 25290 command: 'JustifyRight' 25291 }, 25292 { 25293 title: 'Justify', 25294 icon: 'align-justify', 25295 format: 'alignjustify', 25296 command: 'JustifyFull' 25297 } 25298 ]; 25299 var getSpec$4 = function (editor) { 25300 var getMatchingValue = function () { 25301 return find$5(alignMenuItems, function (item) { 25302 return editor.formatter.match(item.format); 25303 }); 25304 }; 25305 var isSelectedFor = function (format) { 25306 return function () { 25307 return editor.formatter.match(format); 25308 }; 25309 }; 25310 var getPreviewFor = function (_format) { 25311 return Optional.none; 25312 }; 25313 var updateSelectMenuIcon = function (comp) { 25314 var match = getMatchingValue(); 25315 var alignment = match.fold(constant$1('left'), function (item) { 25316 return item.title.toLowerCase(); 25317 }); 25318 emitWith(comp, updateMenuIcon, { icon: 'align-' + alignment }); 25319 }; 25320 var dataset = buildBasicStaticDataset(alignMenuItems); 25321 var onAction = function (rawItem) { 25322 return function () { 25323 return find$5(alignMenuItems, function (item) { 25324 return item.format === rawItem.format; 25325 }).each(function (item) { 25326 return editor.execCommand(item.command); 25327 }); 25328 }; 25329 }; 25330 return { 25331 tooltip: 'Align', 25332 text: Optional.none(), 25333 icon: Optional.some('align-left'), 25334 isSelectedFor: isSelectedFor, 25335 getCurrentValue: Optional.none, 25336 getPreviewFor: getPreviewFor, 25337 onAction: onAction, 25338 updateText: updateSelectMenuIcon, 25339 dataset: dataset, 25340 shouldHide: false, 25341 isInvalid: function (item) { 25342 return !editor.formatter.canApply(item.format); 25343 } 25344 }; 25345 }; 25346 var createAlignSelect = function (editor, backstage) { 25347 return createSelectButton(editor, backstage, getSpec$4(editor)); 25348 }; 25349 var alignSelectMenu = function (editor, backstage) { 25350 var menuItems = createMenuItems(editor, backstage, getSpec$4(editor)); 25351 editor.ui.registry.addNestedMenuItem('align', { 25352 text: backstage.shared.providers.translate('Align'), 25353 getSubmenuItems: function () { 25354 return menuItems.items.validateItems(menuItems.getStyleItems()); 25355 } 25356 }); 25357 }; 25358 25359 var defaultFontsFormats = 'Andale Mono=andale mono,monospace;' + 'Arial=arial,helvetica,sans-serif;' + 'Arial Black=arial black,sans-serif;' + 'Book Antiqua=book antiqua,palatino,serif;' + 'Comic Sans MS=comic sans ms,sans-serif;' + 'Courier New=courier new,courier,monospace;' + 'Georgia=georgia,palatino,serif;' + 'Helvetica=helvetica,arial,sans-serif;' + 'Impact=impact,sans-serif;' + 'Symbol=symbol;' + 'Tahoma=tahoma,arial,helvetica,sans-serif;' + 'Terminal=terminal,monaco,monospace;' + 'Times New Roman=times new roman,times,serif;' + 'Trebuchet MS=trebuchet ms,geneva,sans-serif;' + 'Verdana=verdana,geneva,sans-serif;' + 'Webdings=webdings;' + 'Wingdings=wingdings,zapf dingbats'; 25360 var systemStackFonts = [ 25361 '-apple-system', 25362 'Segoe UI', 25363 'Roboto', 25364 'Helvetica Neue', 25365 'sans-serif' 25366 ]; 25367 var splitFonts = function (fontFamily) { 25368 var fonts = fontFamily.split(/\s*,\s*/); 25369 return map$2(fonts, function (font) { 25370 return font.replace(/^['"]+|['"]+$/g, ''); 25371 }); 25372 }; 25373 var isSystemFontStack = function (fontFamily) { 25374 var matchesSystemStack = function () { 25375 var fonts = splitFonts(fontFamily.toLowerCase()); 25376 return forall(systemStackFonts, function (font) { 25377 return fonts.indexOf(font.toLowerCase()) > -1; 25378 }); 25379 }; 25380 return fontFamily.indexOf('-apple-system') === 0 && matchesSystemStack(); 25381 }; 25382 var getSpec$3 = function (editor) { 25383 var systemFont = 'System Font'; 25384 var getMatchingValue = function () { 25385 var getFirstFont = function (fontFamily) { 25386 return fontFamily ? splitFonts(fontFamily)[0] : ''; 25387 }; 25388 var fontFamily = editor.queryCommandValue('FontName'); 25389 var items = dataset.data; 25390 var font = fontFamily ? fontFamily.toLowerCase() : ''; 25391 var matchOpt = find$5(items, function (item) { 25392 var format = item.format; 25393 return format.toLowerCase() === font || getFirstFont(format).toLowerCase() === getFirstFont(font).toLowerCase(); 25394 }).orThunk(function () { 25395 return someIf(isSystemFontStack(font), { 25396 title: systemFont, 25397 format: font 25398 }); 25399 }); 25400 return { 25401 matchOpt: matchOpt, 25402 font: fontFamily 25403 }; 25404 }; 25405 var isSelectedFor = function (item) { 25406 return function (valueOpt) { 25407 return valueOpt.exists(function (value) { 25408 return value.format === item; 25409 }); 25410 }; 25411 }; 25412 var getCurrentValue = function () { 25413 var matchOpt = getMatchingValue().matchOpt; 25414 return matchOpt; 25415 }; 25416 var getPreviewFor = function (item) { 25417 return function () { 25418 return Optional.some({ 25419 tag: 'div', 25420 styles: item.indexOf('dings') === -1 ? { 'font-family': item } : {} 25421 }); 25422 }; 25423 }; 25424 var onAction = function (rawItem) { 25425 return function () { 25426 editor.undoManager.transact(function () { 25427 editor.focus(); 25428 editor.execCommand('FontName', false, rawItem.format); 25429 }); 25430 }; 25431 }; 25432 var updateSelectMenuText = function (comp) { 25433 var _a = getMatchingValue(), matchOpt = _a.matchOpt, font = _a.font; 25434 var text = matchOpt.fold(constant$1(font), function (item) { 25435 return item.title; 25436 }); 25437 emitWith(comp, updateMenuText, { text: text }); 25438 }; 25439 var dataset = buildBasicSettingsDataset(editor, 'font_formats', defaultFontsFormats, Delimiter.SemiColon); 25440 return { 25441 tooltip: 'Fonts', 25442 text: Optional.some(systemFont), 25443 icon: Optional.none(), 25444 isSelectedFor: isSelectedFor, 25445 getCurrentValue: getCurrentValue, 25446 getPreviewFor: getPreviewFor, 25447 onAction: onAction, 25448 updateText: updateSelectMenuText, 25449 dataset: dataset, 25450 shouldHide: false, 25451 isInvalid: never 25452 }; 25453 }; 25454 var createFontSelect = function (editor, backstage) { 25455 return createSelectButton(editor, backstage, getSpec$3(editor)); 25456 }; 25457 var fontSelectMenu = function (editor, backstage) { 25458 var menuItems = createMenuItems(editor, backstage, getSpec$3(editor)); 25459 editor.ui.registry.addNestedMenuItem('fontformats', { 25460 text: backstage.shared.providers.translate('Fonts'), 25461 getSubmenuItems: function () { 25462 return menuItems.items.validateItems(menuItems.getStyleItems()); 25463 } 25464 }); 25465 }; 25466 25467 var defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt'; 25468 var legacyFontSizes = { 25469 '8pt': '1', 25470 '10pt': '2', 25471 '12pt': '3', 25472 '14pt': '4', 25473 '18pt': '5', 25474 '24pt': '6', 25475 '36pt': '7' 25476 }; 25477 var keywordFontSizes = { 25478 'xx-small': '7pt', 25479 'x-small': '8pt', 25480 'small': '10pt', 25481 'medium': '12pt', 25482 'large': '14pt', 25483 'x-large': '18pt', 25484 'xx-large': '24pt' 25485 }; 25486 var round = function (number, precision) { 25487 var factor = Math.pow(10, precision); 25488 return Math.round(number * factor) / factor; 25489 }; 25490 var toPt = function (fontSize, precision) { 25491 if (/[0-9.]+px$/.test(fontSize)) { 25492 return round(parseInt(fontSize, 10) * 72 / 96, precision || 0) + 'pt'; 25493 } else { 25494 return get$e(keywordFontSizes, fontSize).getOr(fontSize); 25495 } 25496 }; 25497 var toLegacy = function (fontSize) { 25498 return get$e(legacyFontSizes, fontSize).getOr(''); 25499 }; 25500 var getSpec$2 = function (editor) { 25501 var getMatchingValue = function () { 25502 var matchOpt = Optional.none(); 25503 var items = dataset.data; 25504 var fontSize = editor.queryCommandValue('FontSize'); 25505 if (fontSize) { 25506 var _loop_1 = function (precision) { 25507 var pt = toPt(fontSize, precision); 25508 var legacy = toLegacy(pt); 25509 matchOpt = find$5(items, function (item) { 25510 return item.format === fontSize || item.format === pt || item.format === legacy; 25511 }); 25512 }; 25513 for (var precision = 3; matchOpt.isNone() && precision >= 0; precision--) { 25514 _loop_1(precision); 25515 } 25516 } 25517 return { 25518 matchOpt: matchOpt, 25519 size: fontSize 25520 }; 25521 }; 25522 var isSelectedFor = function (item) { 25523 return function (valueOpt) { 25524 return valueOpt.exists(function (value) { 25525 return value.format === item; 25526 }); 25527 }; 25528 }; 25529 var getCurrentValue = function () { 25530 var matchOpt = getMatchingValue().matchOpt; 25531 return matchOpt; 25532 }; 25533 var getPreviewFor = constant$1(Optional.none); 25534 var onAction = function (rawItem) { 25535 return function () { 25536 editor.undoManager.transact(function () { 25537 editor.focus(); 25538 editor.execCommand('FontSize', false, rawItem.format); 25539 }); 25540 }; 25541 }; 25542 var updateSelectMenuText = function (comp) { 25543 var _a = getMatchingValue(), matchOpt = _a.matchOpt, size = _a.size; 25544 var text = matchOpt.fold(constant$1(size), function (match) { 25545 return match.title; 25546 }); 25547 emitWith(comp, updateMenuText, { text: text }); 25548 }; 25549 var dataset = buildBasicSettingsDataset(editor, 'fontsize_formats', defaultFontsizeFormats, Delimiter.Space); 25550 return { 25551 tooltip: 'Font sizes', 25552 text: Optional.some('12pt'), 25553 icon: Optional.none(), 25554 isSelectedFor: isSelectedFor, 25555 getPreviewFor: getPreviewFor, 25556 getCurrentValue: getCurrentValue, 25557 onAction: onAction, 25558 updateText: updateSelectMenuText, 25559 dataset: dataset, 25560 shouldHide: false, 25561 isInvalid: never 25562 }; 25563 }; 25564 var createFontsizeSelect = function (editor, backstage) { 25565 return createSelectButton(editor, backstage, getSpec$2(editor)); 25566 }; 25567 var fontsizeSelectMenu = function (editor, backstage) { 25568 var menuItems = createMenuItems(editor, backstage, getSpec$2(editor)); 25569 editor.ui.registry.addNestedMenuItem('fontsizes', { 25570 text: 'Font sizes', 25571 getSubmenuItems: function () { 25572 return menuItems.items.validateItems(menuItems.getStyleItems()); 25573 } 25574 }); 25575 }; 25576 25577 var findNearest = function (editor, getStyles) { 25578 var styles = getStyles(); 25579 var formats = map$2(styles, function (style) { 25580 return style.format; 25581 }); 25582 return Optional.from(editor.formatter.closest(formats)).bind(function (fmt) { 25583 return find$5(styles, function (data) { 25584 return data.format === fmt; 25585 }); 25586 }).orThunk(function () { 25587 return someIf(editor.formatter.match('p'), { 25588 title: 'Paragraph', 25589 format: 'p' 25590 }); 25591 }); 25592 }; 25593 25594 var defaultBlocks = 'Paragraph=p;' + 'Heading 1=h1;' + 'Heading 2=h2;' + 'Heading 3=h3;' + 'Heading 4=h4;' + 'Heading 5=h5;' + 'Heading 6=h6;' + 'Preformatted=pre'; 25595 var getSpec$1 = function (editor) { 25596 var fallbackFormat = 'Paragraph'; 25597 var isSelectedFor = function (format) { 25598 return function () { 25599 return editor.formatter.match(format); 25600 }; 25601 }; 25602 var getPreviewFor = function (format) { 25603 return function () { 25604 var fmt = editor.formatter.get(format); 25605 return Optional.some({ 25606 tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div', 25607 styles: editor.dom.parseStyle(editor.formatter.getCssText(format)) 25608 }); 25609 }; 25610 }; 25611 var updateSelectMenuText = function (comp) { 25612 var detectedFormat = findNearest(editor, function () { 25613 return dataset.data; 25614 }); 25615 var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) { 25616 return fmt.title; 25617 }); 25618 emitWith(comp, updateMenuText, { text: text }); 25619 }; 25620 var dataset = buildBasicSettingsDataset(editor, 'block_formats', defaultBlocks, Delimiter.SemiColon); 25621 return { 25622 tooltip: 'Blocks', 25623 text: Optional.some(fallbackFormat), 25624 icon: Optional.none(), 25625 isSelectedFor: isSelectedFor, 25626 getCurrentValue: Optional.none, 25627 getPreviewFor: getPreviewFor, 25628 onAction: onActionToggleFormat$1(editor), 25629 updateText: updateSelectMenuText, 25630 dataset: dataset, 25631 shouldHide: false, 25632 isInvalid: function (item) { 25633 return !editor.formatter.canApply(item.format); 25634 } 25635 }; 25636 }; 25637 var createFormatSelect = function (editor, backstage) { 25638 return createSelectButton(editor, backstage, getSpec$1(editor)); 25639 }; 25640 var formatSelectMenu = function (editor, backstage) { 25641 var menuItems = createMenuItems(editor, backstage, getSpec$1(editor)); 25642 editor.ui.registry.addNestedMenuItem('blockformats', { 25643 text: 'Blocks', 25644 getSubmenuItems: function () { 25645 return menuItems.items.validateItems(menuItems.getStyleItems()); 25646 } 25647 }); 25648 }; 25649 25650 var getSpec = function (editor, dataset) { 25651 var fallbackFormat = 'Paragraph'; 25652 var isSelectedFor = function (format) { 25653 return function () { 25654 return editor.formatter.match(format); 25655 }; 25656 }; 25657 var getPreviewFor = function (format) { 25658 return function () { 25659 var fmt = editor.formatter.get(format); 25660 return fmt !== undefined ? Optional.some({ 25661 tag: fmt.length > 0 ? fmt[0].inline || fmt[0].block || 'div' : 'div', 25662 styles: editor.dom.parseStyle(editor.formatter.getCssText(format)) 25663 }) : Optional.none(); 25664 }; 25665 }; 25666 var updateSelectMenuText = function (comp) { 25667 var getFormatItems = function (fmt) { 25668 var subs = fmt.items; 25669 return subs !== undefined && subs.length > 0 ? bind$3(subs, getFormatItems) : [{ 25670 title: fmt.title, 25671 format: fmt.format 25672 }]; 25673 }; 25674 var flattenedItems = bind$3(getStyleFormats(editor), getFormatItems); 25675 var detectedFormat = findNearest(editor, constant$1(flattenedItems)); 25676 var text = detectedFormat.fold(constant$1(fallbackFormat), function (fmt) { 25677 return fmt.title; 25678 }); 25679 emitWith(comp, updateMenuText, { text: text }); 25680 }; 25681 return { 25682 tooltip: 'Formats', 25683 text: Optional.some(fallbackFormat), 25684 icon: Optional.none(), 25685 isSelectedFor: isSelectedFor, 25686 getCurrentValue: Optional.none, 25687 getPreviewFor: getPreviewFor, 25688 onAction: onActionToggleFormat$1(editor), 25689 updateText: updateSelectMenuText, 25690 shouldHide: editor.getParam('style_formats_autohide', false, 'boolean'), 25691 isInvalid: function (item) { 25692 return !editor.formatter.canApply(item.format); 25693 }, 25694 dataset: dataset 25695 }; 25696 }; 25697 var createStyleSelect = function (editor, backstage) { 25698 var dataset = __assign({ type: 'advanced' }, backstage.styleselect); 25699 return createSelectButton(editor, backstage, getSpec(editor, dataset)); 25700 }; 25701 var styleSelectMenu = function (editor, backstage) { 25702 var dataset = __assign({ type: 'advanced' }, backstage.styleselect); 25703 var menuItems = createMenuItems(editor, backstage, getSpec(editor, dataset)); 25704 editor.ui.registry.addNestedMenuItem('formats', { 25705 text: 'Formats', 25706 getSubmenuItems: function () { 25707 return menuItems.items.validateItems(menuItems.getStyleItems()); 25708 } 25709 }); 25710 }; 25711 25712 var events$3 = function (reflectingConfig, reflectingState) { 25713 var update = function (component, data) { 25714 reflectingConfig.updateState.each(function (updateState) { 25715 var newState = updateState(component, data); 25716 reflectingState.set(newState); 25717 }); 25718 reflectingConfig.renderComponents.each(function (renderComponents) { 25719 var newComponents = renderComponents(data, reflectingState.get()); 25720 var newChildren = map$2(newComponents, component.getSystem().build); 25721 replaceChildren(component, newChildren); 25722 }); 25723 }; 25724 return derive$2([ 25725 run$1(receive(), function (component, message) { 25726 var receivingData = message; 25727 if (!receivingData.universal) { 25728 var channel = reflectingConfig.channel; 25729 if (contains$2(receivingData.channels, channel)) { 25730 update(component, receivingData.data); 25731 } 25732 } 25733 }), 25734 runOnAttached(function (comp, _se) { 25735 reflectingConfig.initialData.each(function (rawData) { 25736 update(comp, rawData); 25737 }); 25738 }) 25739 ]); 25740 }; 25741 25742 var ActiveReflecting = /*#__PURE__*/Object.freeze({ 25743 __proto__: null, 25744 events: events$3 25745 }); 25746 25747 var getState = function (component, replaceConfig, reflectState) { 25748 return reflectState; 25749 }; 25750 25751 var ReflectingApis = /*#__PURE__*/Object.freeze({ 25752 __proto__: null, 25753 getState: getState 25754 }); 25755 25756 var ReflectingSchema = [ 25757 required$1('channel'), 25758 option('renderComponents'), 25759 option('updateState'), 25760 option('initialData') 25761 ]; 25762 25763 var init$3 = function () { 25764 var cell = Cell(Optional.none()); 25765 var clear = function () { 25766 return cell.set(Optional.none()); 25767 }; 25768 var readState = function () { 25769 return cell.get().getOr('none'); 25770 }; 25771 return { 25772 readState: readState, 25773 get: cell.get, 25774 set: cell.set, 25775 clear: clear 25776 }; 25777 }; 25778 25779 var ReflectingState = /*#__PURE__*/Object.freeze({ 25780 __proto__: null, 25781 init: init$3 25782 }); 25783 25784 var Reflecting = create$7({ 25785 fields: ReflectingSchema, 25786 name: 'reflecting', 25787 active: ActiveReflecting, 25788 apis: ReflectingApis, 25789 state: ReflectingState 25790 }); 25791 25792 var schema$7 = constant$1([ 25793 required$1('toggleClass'), 25794 required$1('fetch'), 25795 onStrictHandler('onExecute'), 25796 defaulted('getHotspot', Optional.some), 25797 defaulted('getAnchorOverrides', constant$1({})), 25798 schema$y(), 25799 onStrictHandler('onItemExecute'), 25800 option('lazySink'), 25801 required$1('dom'), 25802 onHandler('onOpen'), 25803 field('splitDropdownBehaviours', [ 25804 Coupling, 25805 Keying, 25806 Focusing 25807 ]), 25808 defaulted('matchWidth', false), 25809 defaulted('useMinWidth', false), 25810 defaulted('eventOrder', {}), 25811 option('role') 25812 ].concat(sandboxFields())); 25813 var arrowPart = required({ 25814 factory: Button, 25815 schema: [required$1('dom')], 25816 name: 'arrow', 25817 defaults: function () { 25818 return { buttonBehaviours: derive$1([Focusing.revoke()]) }; 25819 }, 25820 overrides: function (detail) { 25821 return { 25822 dom: { 25823 tag: 'span', 25824 attributes: { role: 'presentation' } 25825 }, 25826 action: function (arrow) { 25827 arrow.getSystem().getByUid(detail.uid).each(emitExecute); 25828 }, 25829 buttonBehaviours: derive$1([Toggling.config({ 25830 toggleOnExecute: false, 25831 toggleClass: detail.toggleClass 25832 })]) 25833 }; 25834 } 25835 }); 25836 var buttonPart = required({ 25837 factory: Button, 25838 schema: [required$1('dom')], 25839 name: 'button', 25840 defaults: function () { 25841 return { buttonBehaviours: derive$1([Focusing.revoke()]) }; 25842 }, 25843 overrides: function (detail) { 25844 return { 25845 dom: { 25846 tag: 'span', 25847 attributes: { role: 'presentation' } 25848 }, 25849 action: function (btn) { 25850 btn.getSystem().getByUid(detail.uid).each(function (splitDropdown) { 25851 detail.onExecute(splitDropdown, btn); 25852 }); 25853 } 25854 }; 25855 } 25856 }); 25857 var parts$3 = constant$1([ 25858 arrowPart, 25859 buttonPart, 25860 optional({ 25861 factory: { 25862 sketch: function (spec) { 25863 return { 25864 uid: spec.uid, 25865 dom: { 25866 tag: 'span', 25867 styles: { display: 'none' }, 25868 attributes: { 'aria-hidden': 'true' }, 25869 innerHtml: spec.text 25870 } 25871 }; 25872 } 25873 }, 25874 schema: [required$1('text')], 25875 name: 'aria-descriptor' 25876 }), 25877 external$1({ 25878 schema: [tieredMenuMarkers()], 25879 name: 'menu', 25880 defaults: function (detail) { 25881 return { 25882 onExecute: function (tmenu, item) { 25883 tmenu.getSystem().getByUid(detail.uid).each(function (splitDropdown) { 25884 detail.onItemExecute(splitDropdown, tmenu, item); 25885 }); 25886 } 25887 }; 25888 } 25889 }), 25890 partType$1() 25891 ]); 25892 25893 var factory$5 = function (detail, components, spec, externals) { 25894 var _a; 25895 var switchToMenu = function (sandbox) { 25896 Composing.getCurrent(sandbox).each(function (current) { 25897 Highlighting.highlightFirst(current); 25898 Keying.focusIn(current); 25899 }); 25900 }; 25901 var action = function (component) { 25902 var onOpenSync = switchToMenu; 25903 togglePopup(detail, identity$1, component, externals, onOpenSync, HighlightOnOpen.HighlightFirst).get(noop); 25904 }; 25905 var openMenu = function (comp) { 25906 action(comp); 25907 return Optional.some(true); 25908 }; 25909 var executeOnButton = function (comp) { 25910 var button = getPartOrDie(comp, detail, 'button'); 25911 emitExecute(button); 25912 return Optional.some(true); 25913 }; 25914 var buttonEvents = __assign(__assign({}, derive$2([runOnAttached(function (component, _simulatedEvent) { 25915 var ariaDescriptor = getPart(component, detail, 'aria-descriptor'); 25916 ariaDescriptor.each(function (descriptor) { 25917 var descriptorId = generate$6('aria'); 25918 set$8(descriptor.element, 'id', descriptorId); 25919 set$8(component.element, 'aria-describedby', descriptorId); 25920 }); 25921 })])), events$a(Optional.some(action))); 25922 var apis = { 25923 repositionMenus: function (comp) { 25924 if (Toggling.isOn(comp)) { 25925 repositionMenus(comp); 25926 } 25927 } 25928 }; 25929 return { 25930 uid: detail.uid, 25931 dom: detail.dom, 25932 components: components, 25933 apis: apis, 25934 eventOrder: __assign(__assign({}, detail.eventOrder), (_a = {}, _a[execute$5()] = [ 25935 'disabling', 25936 'toggling', 25937 'alloy.base.behaviour' 25938 ], _a)), 25939 events: buttonEvents, 25940 behaviours: augment(detail.splitDropdownBehaviours, [ 25941 Coupling.config({ 25942 others: { 25943 sandbox: function (hotspot) { 25944 var arrow = getPartOrDie(hotspot, detail, 'arrow'); 25945 var extras = { 25946 onOpen: function () { 25947 Toggling.on(arrow); 25948 Toggling.on(hotspot); 25949 }, 25950 onClose: function () { 25951 Toggling.off(arrow); 25952 Toggling.off(hotspot); 25953 } 25954 }; 25955 return makeSandbox$1(detail, hotspot, extras); 25956 } 25957 } 25958 }), 25959 Keying.config({ 25960 mode: 'special', 25961 onSpace: executeOnButton, 25962 onEnter: executeOnButton, 25963 onDown: openMenu 25964 }), 25965 Focusing.config({}), 25966 Toggling.config({ 25967 toggleOnExecute: false, 25968 aria: { mode: 'expanded' } 25969 }) 25970 ]), 25971 domModification: { 25972 attributes: { 25973 'role': detail.role.getOr('button'), 25974 'aria-haspopup': true 25975 } 25976 } 25977 }; 25978 }; 25979 var SplitDropdown = composite({ 25980 name: 'SplitDropdown', 25981 configFields: schema$7(), 25982 partFields: parts$3(), 25983 factory: factory$5, 25984 apis: { 25985 repositionMenus: function (apis, comp) { 25986 return apis.repositionMenus(comp); 25987 } 25988 } 25989 }); 25990 25991 var getButtonApi = function (component) { 25992 return { 25993 isDisabled: function () { 25994 return Disabling.isDisabled(component); 25995 }, 25996 setDisabled: function (state) { 25997 return Disabling.set(component, state); 25998 } 25999 }; 26000 }; 26001 var getToggleApi = function (component) { 26002 return { 26003 setActive: function (state) { 26004 Toggling.set(component, state); 26005 }, 26006 isActive: function () { 26007 return Toggling.isOn(component); 26008 }, 26009 isDisabled: function () { 26010 return Disabling.isDisabled(component); 26011 }, 26012 setDisabled: function (state) { 26013 return Disabling.set(component, state); 26014 } 26015 }; 26016 }; 26017 var getTooltipAttributes = function (tooltip, providersBackstage) { 26018 return tooltip.map(function (tooltip) { 26019 return { 26020 'aria-label': providersBackstage.translate(tooltip), 26021 'title': providersBackstage.translate(tooltip) 26022 }; 26023 }).getOr({}); 26024 }; 26025 var focusButtonEvent = generate$6('focus-button'); 26026 var renderCommonStructure = function (icon, text, tooltip, receiver, behaviours, providersBackstage) { 26027 var _d; 26028 return { 26029 dom: { 26030 tag: 'button', 26031 classes: ['tox-tbtn'].concat(text.isSome() ? ['tox-tbtn--select'] : []), 26032 attributes: getTooltipAttributes(tooltip, providersBackstage) 26033 }, 26034 components: componentRenderPipeline([ 26035 icon.map(function (iconName) { 26036 return renderIconFromPack(iconName, providersBackstage.icons); 26037 }), 26038 text.map(function (text) { 26039 return renderLabel$1(text, 'tox-tbtn', providersBackstage); 26040 }) 26041 ]), 26042 eventOrder: (_d = {}, _d[mousedown()] = [ 26043 'focusing', 26044 'alloy.base.behaviour', 26045 'common-button-display-events' 26046 ], _d), 26047 buttonBehaviours: derive$1([ 26048 DisablingConfigs.toolbarButton(providersBackstage.isDisabled), 26049 receivingConfig(), 26050 config('common-button-display-events', [run$1(mousedown(), function (button, se) { 26051 se.event.prevent(); 26052 emit(button, focusButtonEvent); 26053 })]) 26054 ].concat(receiver.map(function (r) { 26055 return Reflecting.config({ 26056 channel: r, 26057 initialData: { 26058 icon: icon, 26059 text: text 26060 }, 26061 renderComponents: function (data, _state) { 26062 return componentRenderPipeline([ 26063 data.icon.map(function (iconName) { 26064 return renderIconFromPack(iconName, providersBackstage.icons); 26065 }), 26066 data.text.map(function (text) { 26067 return renderLabel$1(text, 'tox-tbtn', providersBackstage); 26068 }) 26069 ]); 26070 } 26071 }); 26072 }).toArray()).concat(behaviours.getOr([]))) 26073 }; 26074 }; 26075 var renderFloatingToolbarButton = function (spec, backstage, identifyButtons, attributes) { 26076 var sharedBackstage = backstage.shared; 26077 return FloatingToolbarButton.sketch({ 26078 lazySink: sharedBackstage.getSink, 26079 fetch: function () { 26080 return Future.nu(function (resolve) { 26081 resolve(map$2(identifyButtons(spec.items), renderToolbarGroup)); 26082 }); 26083 }, 26084 markers: { toggledClass: 'tox-tbtn--enabled' }, 26085 parts: { 26086 button: renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), sharedBackstage.providers), 26087 toolbar: { 26088 dom: { 26089 tag: 'div', 26090 classes: ['tox-toolbar__overflow'], 26091 attributes: attributes 26092 } 26093 } 26094 } 26095 }); 26096 }; 26097 var renderCommonToolbarButton = function (spec, specialisation, providersBackstage) { 26098 var editorOffCell = Cell(noop); 26099 var structure = renderCommonStructure(spec.icon, spec.text, spec.tooltip, Optional.none(), Optional.none(), providersBackstage); 26100 return Button.sketch({ 26101 dom: structure.dom, 26102 components: structure.components, 26103 eventOrder: toolbarButtonEventOrder, 26104 buttonBehaviours: derive$1([ 26105 config('toolbar-button-events', [ 26106 onToolbarButtonExecute({ 26107 onAction: spec.onAction, 26108 getApi: specialisation.getApi 26109 }), 26110 onControlAttached(specialisation, editorOffCell), 26111 onControlDetached(specialisation, editorOffCell) 26112 ]), 26113 DisablingConfigs.toolbarButton(function () { 26114 return spec.disabled || providersBackstage.isDisabled(); 26115 }), 26116 receivingConfig() 26117 ].concat(specialisation.toolbarButtonBehaviours)) 26118 }); 26119 }; 26120 var renderToolbarButton = function (spec, providersBackstage) { 26121 return renderToolbarButtonWith(spec, providersBackstage, []); 26122 }; 26123 var renderToolbarButtonWith = function (spec, providersBackstage, bonusEvents) { 26124 return renderCommonToolbarButton(spec, { 26125 toolbarButtonBehaviours: [].concat(bonusEvents.length > 0 ? [config('toolbarButtonWith', bonusEvents)] : []), 26126 getApi: getButtonApi, 26127 onSetup: spec.onSetup 26128 }, providersBackstage); 26129 }; 26130 var renderToolbarToggleButton = function (spec, providersBackstage) { 26131 return renderToolbarToggleButtonWith(spec, providersBackstage, []); 26132 }; 26133 var renderToolbarToggleButtonWith = function (spec, providersBackstage, bonusEvents) { 26134 return deepMerge(renderCommonToolbarButton(spec, { 26135 toolbarButtonBehaviours: [ 26136 Replacing.config({}), 26137 Toggling.config({ 26138 toggleClass: 'tox-tbtn--enabled', 26139 aria: { mode: 'pressed' }, 26140 toggleOnExecute: false 26141 }) 26142 ].concat(bonusEvents.length > 0 ? [config('toolbarToggleButtonWith', bonusEvents)] : []), 26143 getApi: getToggleApi, 26144 onSetup: spec.onSetup 26145 }, providersBackstage)); 26146 }; 26147 var fetchChoices = function (getApi, spec, providersBackstage) { 26148 return function (comp) { 26149 return Future.nu(function (callback) { 26150 return spec.fetch(callback); 26151 }).map(function (items) { 26152 return Optional.from(createTieredDataFrom(deepMerge(createPartialChoiceMenu(generate$6('menu-value'), items, function (value) { 26153 spec.onItemAction(getApi(comp), value); 26154 }, spec.columns, spec.presets, ItemResponse$1.CLOSE_ON_EXECUTE, spec.select.getOr(never), providersBackstage), { 26155 movement: deriveMenuMovement(spec.columns, spec.presets), 26156 menuBehaviours: SimpleBehaviours.unnamedEvents(spec.columns !== 'auto' ? [] : [runOnAttached(function (comp, _se) { 26157 detectSize(comp, 4, classForPreset(spec.presets)).each(function (_d) { 26158 var numRows = _d.numRows, numColumns = _d.numColumns; 26159 Keying.setGridSize(comp, numRows, numColumns); 26160 }); 26161 })]) 26162 }))); 26163 }); 26164 }; 26165 }; 26166 var renderSplitButton = function (spec, sharedBackstage) { 26167 var _d; 26168 var displayChannel = generate$6('channel-update-split-dropdown-display'); 26169 var getApi = function (comp) { 26170 return { 26171 isDisabled: function () { 26172 return Disabling.isDisabled(comp); 26173 }, 26174 setDisabled: function (state) { 26175 return Disabling.set(comp, state); 26176 }, 26177 setIconFill: function (id, value) { 26178 descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) { 26179 set$8(underlinePath, 'fill', value); 26180 }); 26181 }, 26182 setIconStroke: function (id, value) { 26183 descendant(comp.element, 'svg path[id="' + id + '"], rect[id="' + id + '"]').each(function (underlinePath) { 26184 set$8(underlinePath, 'stroke', value); 26185 }); 26186 }, 26187 setActive: function (state) { 26188 set$8(comp.element, 'aria-pressed', state); 26189 descendant(comp.element, 'span').each(function (button) { 26190 comp.getSystem().getByDom(button).each(function (buttonComp) { 26191 return Toggling.set(buttonComp, state); 26192 }); 26193 }); 26194 }, 26195 isActive: function () { 26196 return descendant(comp.element, 'span').exists(function (button) { 26197 return comp.getSystem().getByDom(button).exists(Toggling.isOn); 26198 }); 26199 } 26200 }; 26201 }; 26202 var editorOffCell = Cell(noop); 26203 var specialisation = { 26204 getApi: getApi, 26205 onSetup: spec.onSetup 26206 }; 26207 return SplitDropdown.sketch({ 26208 dom: { 26209 tag: 'div', 26210 classes: ['tox-split-button'], 26211 attributes: __assign({ 'aria-pressed': false }, getTooltipAttributes(spec.tooltip, sharedBackstage.providers)) 26212 }, 26213 onExecute: function (button) { 26214 spec.onAction(getApi(button)); 26215 }, 26216 onItemExecute: function (_a, _b, _c) { 26217 }, 26218 splitDropdownBehaviours: derive$1([ 26219 DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled), 26220 receivingConfig(), 26221 config('split-dropdown-events', [ 26222 run$1(focusButtonEvent, Focusing.focus), 26223 onControlAttached(specialisation, editorOffCell), 26224 onControlDetached(specialisation, editorOffCell) 26225 ]), 26226 Unselecting.config({}) 26227 ]), 26228 eventOrder: (_d = {}, _d[attachedToDom()] = [ 26229 'alloy.base.behaviour', 26230 'split-dropdown-events' 26231 ], _d), 26232 toggleClass: 'tox-tbtn--enabled', 26233 lazySink: sharedBackstage.getSink, 26234 fetch: fetchChoices(getApi, spec, sharedBackstage.providers), 26235 parts: { menu: part(false, spec.columns, spec.presets) }, 26236 components: [ 26237 SplitDropdown.parts.button(renderCommonStructure(spec.icon, spec.text, Optional.none(), Optional.some(displayChannel), Optional.some([Toggling.config({ 26238 toggleClass: 'tox-tbtn--enabled', 26239 toggleOnExecute: false 26240 })]), sharedBackstage.providers)), 26241 SplitDropdown.parts.arrow({ 26242 dom: { 26243 tag: 'button', 26244 classes: [ 26245 'tox-tbtn', 26246 'tox-split-button__chevron' 26247 ], 26248 innerHtml: get$1('chevron-down', sharedBackstage.providers.icons) 26249 }, 26250 buttonBehaviours: derive$1([ 26251 DisablingConfigs.splitButton(sharedBackstage.providers.isDisabled), 26252 receivingConfig(), 26253 addFocusableBehaviour() 26254 ]) 26255 }), 26256 SplitDropdown.parts['aria-descriptor']({ text: sharedBackstage.providers.translate('To open the popup, press Shift+Enter') }) 26257 ] 26258 }); 26259 }; 26260 26261 var defaultToolbar = [ 26262 { 26263 name: 'history', 26264 items: [ 26265 'undo', 26266 'redo' 26267 ] 26268 }, 26269 { 26270 name: 'styles', 26271 items: ['styleselect'] 26272 }, 26273 { 26274 name: 'formatting', 26275 items: [ 26276 'bold', 26277 'italic' 26278 ] 26279 }, 26280 { 26281 name: 'alignment', 26282 items: [ 26283 'alignleft', 26284 'aligncenter', 26285 'alignright', 26286 'alignjustify' 26287 ] 26288 }, 26289 { 26290 name: 'indentation', 26291 items: [ 26292 'outdent', 26293 'indent' 26294 ] 26295 }, 26296 { 26297 name: 'permanent pen', 26298 items: ['permanentpen'] 26299 }, 26300 { 26301 name: 'comments', 26302 items: ['addcomment'] 26303 } 26304 ]; 26305 var renderFromBridge = function (bridgeBuilder, render) { 26306 return function (spec, extras, editor) { 26307 var internal = bridgeBuilder(spec).mapError(function (errInfo) { 26308 return formatError(errInfo); 26309 }).getOrDie(); 26310 return render(internal, extras, editor); 26311 }; 26312 }; 26313 var types = { 26314 button: renderFromBridge(createToolbarButton, function (s, extras) { 26315 return renderToolbarButton(s, extras.backstage.shared.providers); 26316 }), 26317 togglebutton: renderFromBridge(createToggleButton, function (s, extras) { 26318 return renderToolbarToggleButton(s, extras.backstage.shared.providers); 26319 }), 26320 menubutton: renderFromBridge(createMenuButton, function (s, extras) { 26321 return renderMenuButton(s, 'tox-tbtn', extras.backstage, Optional.none()); 26322 }), 26323 splitbutton: renderFromBridge(createSplitButton, function (s, extras) { 26324 return renderSplitButton(s, extras.backstage.shared); 26325 }), 26326 grouptoolbarbutton: renderFromBridge(createGroupToolbarButton, function (s, extras, editor) { 26327 var _a; 26328 var buttons = editor.ui.registry.getAll().buttons; 26329 var identify = function (toolbar) { 26330 return identifyButtons(editor, { 26331 buttons: buttons, 26332 toolbar: toolbar, 26333 allowToolbarGroups: false 26334 }, extras, Optional.none()); 26335 }; 26336 var attributes = (_a = {}, _a[Attribute] = extras.backstage.shared.header.isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop, _a); 26337 switch (getToolbarMode(editor)) { 26338 case ToolbarMode.floating: 26339 return renderFloatingToolbarButton(s, extras.backstage, identify, attributes); 26340 default: 26341 throw new Error('Toolbar groups are only supported when using floating toolbar mode'); 26342 } 26343 }), 26344 styleSelectButton: function (editor, extras) { 26345 return createStyleSelect(editor, extras.backstage); 26346 }, 26347 fontsizeSelectButton: function (editor, extras) { 26348 return createFontsizeSelect(editor, extras.backstage); 26349 }, 26350 fontSelectButton: function (editor, extras) { 26351 return createFontSelect(editor, extras.backstage); 26352 }, 26353 formatButton: function (editor, extras) { 26354 return createFormatSelect(editor, extras.backstage); 26355 }, 26356 alignMenuButton: function (editor, extras) { 26357 return createAlignSelect(editor, extras.backstage); 26358 } 26359 }; 26360 var extractFrom = function (spec, extras, editor) { 26361 return get$e(types, spec.type).fold(function () { 26362 console.error('skipping button defined by', spec); 26363 return Optional.none(); 26364 }, function (render) { 26365 return Optional.some(render(spec, extras, editor)); 26366 }); 26367 }; 26368 var bespokeButtons = { 26369 styleselect: types.styleSelectButton, 26370 fontsizeselect: types.fontsizeSelectButton, 26371 fontselect: types.fontSelectButton, 26372 formatselect: types.formatButton, 26373 align: types.alignMenuButton 26374 }; 26375 var removeUnusedDefaults = function (buttons) { 26376 var filteredItemGroups = map$2(defaultToolbar, function (group) { 26377 var items = filter$2(group.items, function (subItem) { 26378 return has$2(buttons, subItem) || has$2(bespokeButtons, subItem); 26379 }); 26380 return { 26381 name: group.name, 26382 items: items 26383 }; 26384 }); 26385 return filter$2(filteredItemGroups, function (group) { 26386 return group.items.length > 0; 26387 }); 26388 }; 26389 var convertStringToolbar = function (strToolbar) { 26390 var groupsStrings = strToolbar.split('|'); 26391 return map$2(groupsStrings, function (g) { 26392 return { items: g.trim().split(' ') }; 26393 }); 26394 }; 26395 var isToolbarGroupSettingArray = function (toolbar) { 26396 return isArrayOf(toolbar, function (t) { 26397 return has$2(t, 'name') && has$2(t, 'items'); 26398 }); 26399 }; 26400 var createToolbar = function (toolbarConfig) { 26401 var toolbar = toolbarConfig.toolbar; 26402 var buttons = toolbarConfig.buttons; 26403 if (toolbar === false) { 26404 return []; 26405 } else if (toolbar === undefined || toolbar === true) { 26406 return removeUnusedDefaults(buttons); 26407 } else if (isString(toolbar)) { 26408 return convertStringToolbar(toolbar); 26409 } else if (isToolbarGroupSettingArray(toolbar)) { 26410 return toolbar; 26411 } else { 26412 console.error('Toolbar type should be string, string[], boolean or ToolbarGroup[]'); 26413 return []; 26414 } 26415 }; 26416 var lookupButton = function (editor, buttons, toolbarItem, allowToolbarGroups, extras, prefixes) { 26417 return get$e(buttons, toolbarItem.toLowerCase()).orThunk(function () { 26418 return prefixes.bind(function (ps) { 26419 return findMap(ps, function (prefix) { 26420 return get$e(buttons, prefix + toolbarItem.toLowerCase()); 26421 }); 26422 }); 26423 }).fold(function () { 26424 return get$e(bespokeButtons, toolbarItem.toLowerCase()).map(function (r) { 26425 return r(editor, extras); 26426 }).orThunk(function () { 26427 return Optional.none(); 26428 }); 26429 }, function (spec) { 26430 if (spec.type === 'grouptoolbarbutton' && !allowToolbarGroups) { 26431 console.warn('Ignoring the \'' + toolbarItem + '\' toolbar button. Group toolbar buttons are only supported when using floating toolbar mode and cannot be nested.'); 26432 return Optional.none(); 26433 } else { 26434 return extractFrom(spec, extras, editor); 26435 } 26436 }); 26437 }; 26438 var identifyButtons = function (editor, toolbarConfig, extras, prefixes) { 26439 var toolbarGroups = createToolbar(toolbarConfig); 26440 var groups = map$2(toolbarGroups, function (group) { 26441 var items = bind$3(group.items, function (toolbarItem) { 26442 return toolbarItem.trim().length === 0 ? [] : lookupButton(editor, toolbarConfig.buttons, toolbarItem, toolbarConfig.allowToolbarGroups, extras, prefixes).toArray(); 26443 }); 26444 return { 26445 title: Optional.from(editor.translate(group.name)), 26446 items: items 26447 }; 26448 }); 26449 return filter$2(groups, function (group) { 26450 return group.items.length > 0; 26451 }); 26452 }; 26453 26454 var setToolbar = function (editor, uiComponents, rawUiConfig, backstage) { 26455 var comp = uiComponents.outerContainer; 26456 var toolbarConfig = rawUiConfig.toolbar; 26457 var toolbarButtonsConfig = rawUiConfig.buttons; 26458 if (isArrayOf(toolbarConfig, isString)) { 26459 var toolbars = toolbarConfig.map(function (t) { 26460 var config = { 26461 toolbar: t, 26462 buttons: toolbarButtonsConfig, 26463 allowToolbarGroups: rawUiConfig.allowToolbarGroups 26464 }; 26465 return identifyButtons(editor, config, { backstage: backstage }, Optional.none()); 26466 }); 26467 OuterContainer.setToolbars(comp, toolbars); 26468 } else { 26469 OuterContainer.setToolbar(comp, identifyButtons(editor, rawUiConfig, { backstage: backstage }, Optional.none())); 26470 } 26471 }; 26472 26473 var detection = detect$1(); 26474 var isiOS12 = detection.os.isiOS() && detection.os.version.major <= 12; 26475 var setupEvents$1 = function (editor, uiComponents) { 26476 var dom = editor.dom; 26477 var contentWindow = editor.getWin(); 26478 var initialDocEle = editor.getDoc().documentElement; 26479 var lastWindowDimensions = Cell(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight)); 26480 var lastDocumentDimensions = Cell(SugarPosition(initialDocEle.offsetWidth, initialDocEle.offsetHeight)); 26481 var resizeWindow = function () { 26482 var outer = lastWindowDimensions.get(); 26483 if (outer.left !== contentWindow.innerWidth || outer.top !== contentWindow.innerHeight) { 26484 lastWindowDimensions.set(SugarPosition(contentWindow.innerWidth, contentWindow.innerHeight)); 26485 fireResizeContent(editor); 26486 } 26487 }; 26488 var resizeDocument = function () { 26489 var docEle = editor.getDoc().documentElement; 26490 var inner = lastDocumentDimensions.get(); 26491 if (inner.left !== docEle.offsetWidth || inner.top !== docEle.offsetHeight) { 26492 lastDocumentDimensions.set(SugarPosition(docEle.offsetWidth, docEle.offsetHeight)); 26493 fireResizeContent(editor); 26494 } 26495 }; 26496 var scroll = function (e) { 26497 return fireScrollContent(editor, e); 26498 }; 26499 dom.bind(contentWindow, 'resize', resizeWindow); 26500 dom.bind(contentWindow, 'scroll', scroll); 26501 var elementLoad = capture(SugarElement.fromDom(editor.getBody()), 'load', resizeDocument); 26502 var mothership = uiComponents.uiMothership.element; 26503 editor.on('hide', function () { 26504 set$7(mothership, 'display', 'none'); 26505 }); 26506 editor.on('show', function () { 26507 remove$6(mothership, 'display'); 26508 }); 26509 editor.on('NodeChange', resizeDocument); 26510 editor.on('remove', function () { 26511 elementLoad.unbind(); 26512 dom.unbind(contentWindow, 'resize', resizeWindow); 26513 dom.unbind(contentWindow, 'scroll', scroll); 26514 contentWindow = null; 26515 }); 26516 }; 26517 var render$1 = function (editor, uiComponents, rawUiConfig, backstage, args) { 26518 var lastToolbarWidth = Cell(0); 26519 var outerContainer = uiComponents.outerContainer; 26520 iframe(editor); 26521 var eTargetNode = SugarElement.fromDom(args.targetNode); 26522 var uiRoot = getContentContainer(getRootNode(eTargetNode)); 26523 attachSystemAfter(eTargetNode, uiComponents.mothership); 26524 attachSystem(uiRoot, uiComponents.uiMothership); 26525 editor.on('PostRender', function () { 26526 setToolbar(editor, uiComponents, rawUiConfig, backstage); 26527 lastToolbarWidth.set(editor.getWin().innerWidth); 26528 OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig)); 26529 OuterContainer.setSidebar(outerContainer, rawUiConfig.sidebar); 26530 setupEvents$1(editor, uiComponents); 26531 }); 26532 var socket = OuterContainer.getSocket(outerContainer).getOrDie('Could not find expected socket element'); 26533 if (isiOS12) { 26534 setAll(socket.element, { 26535 'overflow': 'scroll', 26536 '-webkit-overflow-scrolling': 'touch' 26537 }); 26538 var limit = first(function () { 26539 editor.fire('ScrollContent'); 26540 }, 20); 26541 var unbinder = bind(socket.element, 'scroll', limit.throttle); 26542 editor.on('remove', unbinder.unbind); 26543 } 26544 setupReadonlyModeSwitch(editor, uiComponents); 26545 editor.addCommand('ToggleSidebar', function (_ui, value) { 26546 OuterContainer.toggleSidebar(outerContainer, value); 26547 editor.fire('ToggleSidebar'); 26548 }); 26549 editor.addQueryValueHandler('ToggleSidebar', function () { 26550 return OuterContainer.whichSidebar(outerContainer); 26551 }); 26552 var toolbarMode = getToolbarMode(editor); 26553 var refreshDrawer = function () { 26554 OuterContainer.refreshToolbar(uiComponents.outerContainer); 26555 }; 26556 if (toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating) { 26557 editor.on('ResizeWindow ResizeEditor ResizeContent', function () { 26558 var width = editor.getWin().innerWidth; 26559 if (width !== lastToolbarWidth.get()) { 26560 refreshDrawer(); 26561 lastToolbarWidth.set(width); 26562 } 26563 }); 26564 } 26565 var api = { 26566 enable: function () { 26567 broadcastReadonly(uiComponents, false); 26568 }, 26569 disable: function () { 26570 broadcastReadonly(uiComponents, true); 26571 }, 26572 isDisabled: function () { 26573 return Disabling.isDisabled(outerContainer); 26574 } 26575 }; 26576 return { 26577 iframeContainer: socket.element.dom, 26578 editorContainer: outerContainer.element.dom, 26579 api: api 26580 }; 26581 }; 26582 26583 var Iframe = /*#__PURE__*/Object.freeze({ 26584 __proto__: null, 26585 render: render$1 26586 }); 26587 26588 var parseToInt = function (val) { 26589 var re = /^[0-9\.]+(|px)$/i; 26590 if (re.test('' + val)) { 26591 return Optional.some(parseInt('' + val, 10)); 26592 } 26593 return Optional.none(); 26594 }; 26595 var numToPx = function (val) { 26596 return isNumber(val) ? val + 'px' : val; 26597 }; 26598 var calcCappedSize = function (size, minSize, maxSize) { 26599 var minOverride = minSize.filter(function (min) { 26600 return size < min; 26601 }); 26602 var maxOverride = maxSize.filter(function (max) { 26603 return size > max; 26604 }); 26605 return minOverride.or(maxOverride).getOr(size); 26606 }; 26607 26608 var getHeight = function (editor) { 26609 var baseHeight = getHeightSetting(editor); 26610 var minHeight = getMinHeightSetting(editor); 26611 var maxHeight = getMaxHeightSetting(editor); 26612 return parseToInt(baseHeight).map(function (height) { 26613 return calcCappedSize(height, minHeight, maxHeight); 26614 }); 26615 }; 26616 var getHeightWithFallback = function (editor) { 26617 var height = getHeight(editor); 26618 return height.getOr(getHeightSetting(editor)); 26619 }; 26620 var getWidth = function (editor) { 26621 var baseWidth = getWidthSetting(editor); 26622 var minWidth = getMinWidthSetting(editor); 26623 var maxWidth = getMaxWidthSetting(editor); 26624 return parseToInt(baseWidth).map(function (width) { 26625 return calcCappedSize(width, minWidth, maxWidth); 26626 }); 26627 }; 26628 var getWidthWithFallback = function (editor) { 26629 var width = getWidth(editor); 26630 return width.getOr(getWidthSetting(editor)); 26631 }; 26632 26633 var InlineHeader = function (editor, targetElm, uiComponents, backstage, floatContainer) { 26634 var uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer; 26635 var DOM = global$b.DOM; 26636 var useFixedToolbarContainer = useFixedContainer(editor); 26637 var isSticky = isStickyToolbar(editor); 26638 var editorMaxWidthOpt = getMaxWidthSetting(editor).or(getWidth(editor)); 26639 var headerBackstage = backstage.shared.header; 26640 var isPositionedAtTop = headerBackstage.isPositionedAtTop; 26641 var toolbarMode = getToolbarMode(editor); 26642 var isSplitToolbar = toolbarMode === ToolbarMode.sliding || toolbarMode === ToolbarMode.floating; 26643 var visible = Cell(false); 26644 var isVisible = function () { 26645 return visible.get() && !editor.removed; 26646 }; 26647 var calcToolbarOffset = function (toolbar) { 26648 return isSplitToolbar ? toolbar.fold(constant$1(0), function (tbar) { 26649 return tbar.components().length > 1 ? get$b(tbar.components()[1].element) : 0; 26650 }) : 0; 26651 }; 26652 var calcMode = function (container) { 26653 switch (getToolbarLocation(editor)) { 26654 case ToolbarLocation.auto: 26655 var toolbar_1 = OuterContainer.getToolbar(outerContainer); 26656 var offset = calcToolbarOffset(toolbar_1); 26657 var toolbarHeight = get$b(container.element) - offset; 26658 var targetBounds = box$1(targetElm); 26659 var roomAtTop = targetBounds.y > toolbarHeight; 26660 if (roomAtTop) { 26661 return 'top'; 26662 } else { 26663 var doc = documentElement(targetElm); 26664 var docHeight = Math.max(doc.dom.scrollHeight, get$b(doc)); 26665 var roomAtBottom = targetBounds.bottom < docHeight - toolbarHeight; 26666 if (roomAtBottom) { 26667 return 'bottom'; 26668 } else { 26669 var winBounds = win(); 26670 var isRoomAtBottomViewport = winBounds.bottom < targetBounds.bottom - toolbarHeight; 26671 return isRoomAtBottomViewport ? 'bottom' : 'top'; 26672 } 26673 } 26674 case ToolbarLocation.bottom: 26675 return 'bottom'; 26676 case ToolbarLocation.top: 26677 default: 26678 return 'top'; 26679 } 26680 }; 26681 var setupMode = function (mode) { 26682 var container = floatContainer.get(); 26683 Docking.setModes(container, [mode]); 26684 headerBackstage.setDockingMode(mode); 26685 var verticalDir = isPositionedAtTop() ? AttributeValue.TopToBottom : AttributeValue.BottomToTop; 26686 set$8(container.element, Attribute, verticalDir); 26687 }; 26688 var updateChromeWidth = function () { 26689 var maxWidth = editorMaxWidthOpt.getOrThunk(function () { 26690 var bodyMargin = parseToInt(get$c(body(), 'margin-left')).getOr(0); 26691 return get$a(body()) - absolute$3(targetElm).left + bodyMargin; 26692 }); 26693 set$7(floatContainer.get().element, 'max-width', maxWidth + 'px'); 26694 }; 26695 var updateChromePosition = function () { 26696 var toolbar = OuterContainer.getToolbar(outerContainer); 26697 var offset = calcToolbarOffset(toolbar); 26698 var targetBounds = box$1(targetElm); 26699 var top = isPositionedAtTop() ? Math.max(targetBounds.y - get$b(floatContainer.get().element) + offset, 0) : targetBounds.bottom; 26700 setAll(outerContainer.element, { 26701 position: 'absolute', 26702 top: Math.round(top) + 'px', 26703 left: Math.round(targetBounds.x) + 'px' 26704 }); 26705 }; 26706 var repositionPopups$1 = function () { 26707 uiMothership.broadcastOn([repositionPopups()], {}); 26708 }; 26709 var updateChromeUi = function (resetDocking) { 26710 if (resetDocking === void 0) { 26711 resetDocking = false; 26712 } 26713 if (!isVisible()) { 26714 return; 26715 } 26716 if (!useFixedToolbarContainer) { 26717 updateChromeWidth(); 26718 } 26719 if (isSplitToolbar) { 26720 OuterContainer.refreshToolbar(outerContainer); 26721 } 26722 if (!useFixedToolbarContainer) { 26723 updateChromePosition(); 26724 } 26725 if (isSticky) { 26726 var floatContainerComp = floatContainer.get(); 26727 resetDocking ? Docking.reset(floatContainerComp) : Docking.refresh(floatContainerComp); 26728 } 26729 repositionPopups$1(); 26730 }; 26731 var updateMode = function (updateUi) { 26732 if (updateUi === void 0) { 26733 updateUi = true; 26734 } 26735 if (useFixedToolbarContainer || !isSticky || !isVisible()) { 26736 return; 26737 } 26738 var currentMode = headerBackstage.getDockingMode(); 26739 var newMode = calcMode(floatContainer.get()); 26740 if (newMode !== currentMode) { 26741 setupMode(newMode); 26742 if (updateUi) { 26743 updateChromeUi(true); 26744 } 26745 } 26746 }; 26747 var show = function () { 26748 visible.set(true); 26749 set$7(outerContainer.element, 'display', 'flex'); 26750 DOM.addClass(editor.getBody(), 'mce-edit-focus'); 26751 remove$6(uiMothership.element, 'display'); 26752 updateMode(false); 26753 updateChromeUi(); 26754 }; 26755 var hide = function () { 26756 visible.set(false); 26757 if (uiComponents.outerContainer) { 26758 set$7(outerContainer.element, 'display', 'none'); 26759 DOM.removeClass(editor.getBody(), 'mce-edit-focus'); 26760 } 26761 set$7(uiMothership.element, 'display', 'none'); 26762 }; 26763 return { 26764 isVisible: isVisible, 26765 isPositionedAtTop: isPositionedAtTop, 26766 show: show, 26767 hide: hide, 26768 update: updateChromeUi, 26769 updateMode: updateMode, 26770 repositionPopups: repositionPopups$1 26771 }; 26772 }; 26773 26774 var getTargetPosAndBounds = function (targetElm, isToolbarTop) { 26775 var bounds = box$1(targetElm); 26776 return { 26777 pos: isToolbarTop ? bounds.y : bounds.bottom, 26778 bounds: bounds 26779 }; 26780 }; 26781 var setupEvents = function (editor, targetElm, ui, toolbarPersist) { 26782 var prevPosAndBounds = Cell(getTargetPosAndBounds(targetElm, ui.isPositionedAtTop())); 26783 var resizeContent = function (e) { 26784 var _a = getTargetPosAndBounds(targetElm, ui.isPositionedAtTop()), pos = _a.pos, bounds = _a.bounds; 26785 var _b = prevPosAndBounds.get(), prevPos = _b.pos, prevBounds = _b.bounds; 26786 var hasResized = bounds.height !== prevBounds.height || bounds.width !== prevBounds.width; 26787 prevPosAndBounds.set({ 26788 pos: pos, 26789 bounds: bounds 26790 }); 26791 if (hasResized) { 26792 fireResizeContent(editor, e); 26793 } 26794 if (ui.isVisible()) { 26795 if (prevPos !== pos) { 26796 ui.update(true); 26797 } else if (hasResized) { 26798 ui.updateMode(); 26799 ui.repositionPopups(); 26800 } 26801 } 26802 }; 26803 if (!toolbarPersist) { 26804 editor.on('activate', ui.show); 26805 editor.on('deactivate', ui.hide); 26806 } 26807 editor.on('SkinLoaded ResizeWindow', function () { 26808 return ui.update(true); 26809 }); 26810 editor.on('NodeChange keydown', function (e) { 26811 global$f.requestAnimationFrame(function () { 26812 return resizeContent(e); 26813 }); 26814 }); 26815 editor.on('ScrollWindow', function () { 26816 return ui.updateMode(); 26817 }); 26818 var elementLoad = unbindable(); 26819 elementLoad.set(capture(SugarElement.fromDom(editor.getBody()), 'load', resizeContent)); 26820 editor.on('remove', function () { 26821 elementLoad.clear(); 26822 }); 26823 }; 26824 var render = function (editor, uiComponents, rawUiConfig, backstage, args) { 26825 var mothership = uiComponents.mothership, uiMothership = uiComponents.uiMothership, outerContainer = uiComponents.outerContainer; 26826 var floatContainer = Cell(null); 26827 var targetElm = SugarElement.fromDom(args.targetNode); 26828 var ui = InlineHeader(editor, targetElm, uiComponents, backstage, floatContainer); 26829 var toolbarPersist = isToolbarPersist(editor); 26830 inline(editor); 26831 var render = function () { 26832 if (floatContainer.get()) { 26833 ui.show(); 26834 return; 26835 } 26836 floatContainer.set(OuterContainer.getHeader(outerContainer).getOrDie()); 26837 var uiContainer = getUiContainer(editor); 26838 attachSystem(uiContainer, mothership); 26839 attachSystem(uiContainer, uiMothership); 26840 setToolbar(editor, uiComponents, rawUiConfig, backstage); 26841 OuterContainer.setMenubar(outerContainer, identifyMenus(editor, rawUiConfig)); 26842 ui.show(); 26843 setupEvents(editor, targetElm, ui, toolbarPersist); 26844 editor.nodeChanged(); 26845 }; 26846 editor.on('show', render); 26847 editor.on('hide', ui.hide); 26848 if (!toolbarPersist) { 26849 editor.on('focus', render); 26850 editor.on('blur', ui.hide); 26851 } 26852 editor.on('init', function () { 26853 if (editor.hasFocus() || toolbarPersist) { 26854 render(); 26855 } 26856 }); 26857 setupReadonlyModeSwitch(editor, uiComponents); 26858 var api = { 26859 show: function () { 26860 ui.show(); 26861 }, 26862 hide: function () { 26863 ui.hide(); 26864 }, 26865 enable: function () { 26866 broadcastReadonly(uiComponents, false); 26867 }, 26868 disable: function () { 26869 broadcastReadonly(uiComponents, true); 26870 }, 26871 isDisabled: function () { 26872 return Disabling.isDisabled(outerContainer); 26873 } 26874 }; 26875 return { 26876 editorContainer: outerContainer.element.dom, 26877 api: api 26878 }; 26879 }; 26880 26881 var Inline = /*#__PURE__*/Object.freeze({ 26882 __proto__: null, 26883 render: render 26884 }); 26885 26886 var showContextToolbarEvent = 'contexttoolbar-show'; 26887 var hideContextToolbarEvent = 'contexttoolbar-hide'; 26888 26889 var getFormApi = function (input) { 26890 return { 26891 hide: function () { 26892 return emit(input, sandboxClose()); 26893 }, 26894 getValue: function () { 26895 return Representing.getValue(input); 26896 } 26897 }; 26898 }; 26899 var runOnExecute = function (memInput, original) { 26900 return run$1(internalToolbarButtonExecute, function (comp, se) { 26901 var input = memInput.get(comp); 26902 var formApi = getFormApi(input); 26903 original.onAction(formApi, se.event.buttonApi); 26904 }); 26905 }; 26906 var renderContextButton = function (memInput, button, extras) { 26907 var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']); 26908 var bridged = getOrDie(createToolbarButton(__assign(__assign({}, rest), { 26909 type: 'button', 26910 onAction: noop 26911 }))); 26912 return renderToolbarButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]); 26913 }; 26914 var renderContextToggleButton = function (memInput, button, extras) { 26915 var _a = button.original; _a.primary; var rest = __rest(_a, ['primary']); 26916 var bridged = getOrDie(createToggleButton(__assign(__assign({}, rest), { 26917 type: 'togglebutton', 26918 onAction: noop 26919 }))); 26920 return renderToolbarToggleButtonWith(bridged, extras.backstage.shared.providers, [runOnExecute(memInput, button)]); 26921 }; 26922 var generateOne = function (memInput, button, providersBackstage) { 26923 var extras = { backstage: { shared: { providers: providersBackstage } } }; 26924 if (button.type === 'contextformtogglebutton') { 26925 return renderContextToggleButton(memInput, button, extras); 26926 } else { 26927 return renderContextButton(memInput, button, extras); 26928 } 26929 }; 26930 var generate = function (memInput, buttons, providersBackstage) { 26931 var mementos = map$2(buttons, function (button) { 26932 return record(generateOne(memInput, button, providersBackstage)); 26933 }); 26934 var asSpecs = function () { 26935 return map$2(mementos, function (mem) { 26936 return mem.asSpec(); 26937 }); 26938 }; 26939 var findPrimary = function (compInSystem) { 26940 return findMap(buttons, function (button, i) { 26941 if (button.primary) { 26942 return Optional.from(mementos[i]).bind(function (mem) { 26943 return mem.getOpt(compInSystem); 26944 }).filter(not(Disabling.isDisabled)); 26945 } else { 26946 return Optional.none(); 26947 } 26948 }); 26949 }; 26950 return { 26951 asSpecs: asSpecs, 26952 findPrimary: findPrimary 26953 }; 26954 }; 26955 26956 var buildInitGroups = function (ctx, providers) { 26957 var inputAttributes = ctx.label.fold(function () { 26958 return {}; 26959 }, function (label) { 26960 return { 'aria-label': label }; 26961 }); 26962 var memInput = record(Input.sketch({ 26963 inputClasses: [ 26964 'tox-toolbar-textfield', 26965 'tox-toolbar-nav-js' 26966 ], 26967 data: ctx.initValue(), 26968 inputAttributes: inputAttributes, 26969 selectOnFocus: true, 26970 inputBehaviours: derive$1([Keying.config({ 26971 mode: 'special', 26972 onEnter: function (input) { 26973 return commands.findPrimary(input).map(function (primary) { 26974 emitExecute(primary); 26975 return true; 26976 }); 26977 }, 26978 onLeft: function (comp, se) { 26979 se.cut(); 26980 return Optional.none(); 26981 }, 26982 onRight: function (comp, se) { 26983 se.cut(); 26984 return Optional.none(); 26985 } 26986 })]) 26987 })); 26988 var commands = generate(memInput, ctx.commands, providers); 26989 return [ 26990 { 26991 title: Optional.none(), 26992 items: [memInput.asSpec()] 26993 }, 26994 { 26995 title: Optional.none(), 26996 items: commands.asSpecs() 26997 } 26998 ]; 26999 }; 27000 var renderContextForm = function (toolbarType, ctx, providers) { 27001 return renderToolbar({ 27002 type: toolbarType, 27003 uid: generate$6('context-toolbar'), 27004 initGroups: buildInitGroups(ctx, providers), 27005 onEscape: Optional.none, 27006 cyclicKeying: true, 27007 providers: providers 27008 }); 27009 }; 27010 var ContextForm = { 27011 renderContextForm: renderContextForm, 27012 buildInitGroups: buildInitGroups 27013 }; 27014 27015 var isVerticalOverlap = function (a, b, threshold) { 27016 if (threshold === void 0) { 27017 threshold = 0.01; 27018 } 27019 return b.bottom - a.y >= threshold && a.bottom - b.y >= threshold; 27020 }; 27021 var getRangeRect = function (rng) { 27022 var rect = rng.getBoundingClientRect(); 27023 if (rect.height <= 0 && rect.width <= 0) { 27024 var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset).element; 27025 var elm = isText$1(leaf$1) ? parent(leaf$1) : Optional.some(leaf$1); 27026 return elm.filter(isElement$2).map(function (e) { 27027 return e.dom.getBoundingClientRect(); 27028 }).getOr(rect); 27029 } else { 27030 return rect; 27031 } 27032 }; 27033 var getSelectionBounds = function (editor) { 27034 var rng = editor.selection.getRng(); 27035 var rect = getRangeRect(rng); 27036 if (editor.inline) { 27037 var scroll_1 = get$9(); 27038 return bounds(scroll_1.left + rect.left, scroll_1.top + rect.top, rect.width, rect.height); 27039 } else { 27040 var bodyPos = absolute$2(SugarElement.fromDom(editor.getBody())); 27041 return bounds(bodyPos.x + rect.left, bodyPos.y + rect.top, rect.width, rect.height); 27042 } 27043 }; 27044 var getAnchorElementBounds = function (editor, lastElement) { 27045 return lastElement.filter(inBody).map(absolute$2).getOrThunk(function () { 27046 return getSelectionBounds(editor); 27047 }); 27048 }; 27049 var getHorizontalBounds = function (contentAreaBox, viewportBounds, margin) { 27050 var x = Math.max(contentAreaBox.x + margin, viewportBounds.x); 27051 var right = Math.min(contentAreaBox.right - margin, viewportBounds.right); 27052 return { 27053 x: x, 27054 width: right - x 27055 }; 27056 }; 27057 var getVerticalBounds = function (editor, contentAreaBox, viewportBounds, isToolbarLocationTop, toolbarType, margin) { 27058 var container = SugarElement.fromDom(editor.getContainer()); 27059 var header = descendant(container, '.tox-editor-header').getOr(container); 27060 var headerBox = box$1(header); 27061 var isToolbarBelowContentArea = headerBox.y >= contentAreaBox.bottom; 27062 var isToolbarAbove = isToolbarLocationTop && !isToolbarBelowContentArea; 27063 if (editor.inline && isToolbarAbove) { 27064 return { 27065 y: Math.max(headerBox.bottom + margin, viewportBounds.y), 27066 bottom: viewportBounds.bottom 27067 }; 27068 } 27069 if (editor.inline && !isToolbarAbove) { 27070 return { 27071 y: viewportBounds.y, 27072 bottom: Math.min(headerBox.y - margin, viewportBounds.bottom) 27073 }; 27074 } 27075 var containerBounds = toolbarType === 'line' ? box$1(container) : contentAreaBox; 27076 if (isToolbarAbove) { 27077 return { 27078 y: Math.max(headerBox.bottom + margin, viewportBounds.y), 27079 bottom: Math.min(containerBounds.bottom - margin, viewportBounds.bottom) 27080 }; 27081 } 27082 return { 27083 y: Math.max(containerBounds.y + margin, viewportBounds.y), 27084 bottom: Math.min(headerBox.y - margin, viewportBounds.bottom) 27085 }; 27086 }; 27087 var getContextToolbarBounds = function (editor, sharedBackstage, toolbarType, margin) { 27088 if (margin === void 0) { 27089 margin = 0; 27090 } 27091 var viewportBounds = getBounds$3(window); 27092 var contentAreaBox = box$1(SugarElement.fromDom(editor.getContentAreaContainer())); 27093 var toolbarOrMenubarEnabled = isMenubarEnabled(editor) || isToolbarEnabled(editor) || isMultipleToolbars(editor); 27094 var _a = getHorizontalBounds(contentAreaBox, viewportBounds, margin), x = _a.x, width = _a.width; 27095 if (editor.inline && !toolbarOrMenubarEnabled) { 27096 return bounds(x, viewportBounds.y, width, viewportBounds.height); 27097 } else { 27098 var isToolbarTop = sharedBackstage.header.isPositionedAtTop(); 27099 var _b = getVerticalBounds(editor, contentAreaBox, viewportBounds, isToolbarTop, toolbarType, margin), y = _b.y, bottom = _b.bottom; 27100 return bounds(x, y, width, bottom - y); 27101 } 27102 }; 27103 27104 var bubbleSize$1 = 12; 27105 var bubbleAlignments$1 = { 27106 valignCentre: [], 27107 alignCentre: [], 27108 alignLeft: ['tox-pop--align-left'], 27109 alignRight: ['tox-pop--align-right'], 27110 right: ['tox-pop--right'], 27111 left: ['tox-pop--left'], 27112 bottom: ['tox-pop--bottom'], 27113 top: ['tox-pop--top'], 27114 inset: ['tox-pop--inset'] 27115 }; 27116 var anchorOverrides = { 27117 maxHeightFunction: expandable$1(), 27118 maxWidthFunction: expandable() 27119 }; 27120 var isEntireElementSelected = function (editor, elem) { 27121 var rng = editor.selection.getRng(); 27122 var leaf$1 = leaf(SugarElement.fromDom(rng.startContainer), rng.startOffset); 27123 return rng.startContainer === rng.endContainer && rng.startOffset === rng.endOffset - 1 && eq(leaf$1.element, elem); 27124 }; 27125 var preservePosition = function (elem, position, f) { 27126 var currentPosition = getRaw(elem, 'position'); 27127 set$7(elem, 'position', position); 27128 var result = f(elem); 27129 currentPosition.each(function (pos) { 27130 return set$7(elem, 'position', pos); 27131 }); 27132 return result; 27133 }; 27134 var shouldUseInsetLayouts = function (position) { 27135 return position === 'node'; 27136 }; 27137 var determineInsetLayout = function (editor, contextbar, elem, data, bounds) { 27138 var selectionBounds = getSelectionBounds(editor); 27139 var isSameAnchorElement = data.lastElement().exists(function (prev) { 27140 return eq(elem, prev); 27141 }); 27142 if (isEntireElementSelected(editor, elem)) { 27143 return isSameAnchorElement ? preserve : north; 27144 } else if (isSameAnchorElement) { 27145 return preservePosition(contextbar, data.getMode(), function () { 27146 var isOverlapping = isVerticalOverlap(selectionBounds, box$1(contextbar)); 27147 return isOverlapping && !data.isReposition() ? flip$2 : preserve; 27148 }); 27149 } else { 27150 var yBounds = data.getMode() === 'fixed' ? bounds.y + get$9().top : bounds.y; 27151 var contextbarHeight = get$b(contextbar) + bubbleSize$1; 27152 return yBounds + contextbarHeight <= selectionBounds.y ? north : south; 27153 } 27154 }; 27155 var getAnchorSpec$2 = function (editor, mobile, data, position) { 27156 var smartInsetLayout = function (elem) { 27157 return function (anchor, element, bubbles, placee, bounds) { 27158 var layout = determineInsetLayout(editor, placee, elem, data, bounds); 27159 var newAnchor = __assign(__assign({}, anchor), { 27160 y: bounds.y, 27161 height: bounds.height 27162 }); 27163 return __assign(__assign({}, layout(newAnchor, element, bubbles, placee, bounds)), { alwaysFit: true }); 27164 }; 27165 }; 27166 var getInsetLayouts = function (elem) { 27167 return shouldUseInsetLayouts(position) ? [smartInsetLayout(elem)] : []; 27168 }; 27169 var desktopAnchorSpecLayouts = { 27170 onLtr: function (elem) { 27171 return [ 27172 north$2, 27173 south$2, 27174 northeast$2, 27175 southeast$2, 27176 northwest$2, 27177 southwest$2 27178 ].concat(getInsetLayouts(elem)); 27179 }, 27180 onRtl: function (elem) { 27181 return [ 27182 north$2, 27183 south$2, 27184 northwest$2, 27185 southwest$2, 27186 northeast$2, 27187 southeast$2 27188 ].concat(getInsetLayouts(elem)); 27189 } 27190 }; 27191 var mobileAnchorSpecLayouts = { 27192 onLtr: function (elem) { 27193 return [ 27194 south$2, 27195 southeast$2, 27196 southwest$2, 27197 northeast$2, 27198 northwest$2, 27199 north$2 27200 ].concat(getInsetLayouts(elem)); 27201 }, 27202 onRtl: function (elem) { 27203 return [ 27204 south$2, 27205 southwest$2, 27206 southeast$2, 27207 northwest$2, 27208 northeast$2, 27209 north$2 27210 ].concat(getInsetLayouts(elem)); 27211 } 27212 }; 27213 return mobile ? mobileAnchorSpecLayouts : desktopAnchorSpecLayouts; 27214 }; 27215 var getAnchorLayout = function (editor, position, isTouch, data) { 27216 if (position === 'line') { 27217 return { 27218 bubble: nu$5(bubbleSize$1, 0, bubbleAlignments$1), 27219 layouts: { 27220 onLtr: function () { 27221 return [east$2]; 27222 }, 27223 onRtl: function () { 27224 return [west$2]; 27225 } 27226 }, 27227 overrides: anchorOverrides 27228 }; 27229 } else { 27230 return { 27231 bubble: nu$5(0, bubbleSize$1, bubbleAlignments$1, 1 / bubbleSize$1), 27232 layouts: getAnchorSpec$2(editor, isTouch, data, position), 27233 overrides: anchorOverrides 27234 }; 27235 } 27236 }; 27237 27238 var matchTargetWith = function (elem, candidates) { 27239 var ctxs = filter$2(candidates, function (toolbarApi) { 27240 return toolbarApi.predicate(elem.dom); 27241 }); 27242 var _a = partition$3(ctxs, function (t) { 27243 return t.type === 'contexttoolbar'; 27244 }), pass = _a.pass, fail = _a.fail; 27245 return { 27246 contextToolbars: pass, 27247 contextForms: fail 27248 }; 27249 }; 27250 var filterByPositionForStartNode = function (toolbars) { 27251 if (toolbars.length <= 1) { 27252 return toolbars; 27253 } else { 27254 var doesPositionExist = function (value) { 27255 return exists(toolbars, function (t) { 27256 return t.position === value; 27257 }); 27258 }; 27259 var filterToolbarsByPosition = function (value) { 27260 return filter$2(toolbars, function (t) { 27261 return t.position === value; 27262 }); 27263 }; 27264 var hasSelectionToolbars = doesPositionExist('selection'); 27265 var hasNodeToolbars = doesPositionExist('node'); 27266 if (hasSelectionToolbars || hasNodeToolbars) { 27267 if (hasNodeToolbars && hasSelectionToolbars) { 27268 var nodeToolbars = filterToolbarsByPosition('node'); 27269 var selectionToolbars = map$2(filterToolbarsByPosition('selection'), function (t) { 27270 return __assign(__assign({}, t), { position: 'node' }); 27271 }); 27272 return nodeToolbars.concat(selectionToolbars); 27273 } else { 27274 return hasSelectionToolbars ? filterToolbarsByPosition('selection') : filterToolbarsByPosition('node'); 27275 } 27276 } else { 27277 return filterToolbarsByPosition('line'); 27278 } 27279 } 27280 }; 27281 var filterByPositionForAncestorNode = function (toolbars) { 27282 if (toolbars.length <= 1) { 27283 return toolbars; 27284 } else { 27285 var findPosition_1 = function (value) { 27286 return find$5(toolbars, function (t) { 27287 return t.position === value; 27288 }); 27289 }; 27290 var basePosition = findPosition_1('selection').orThunk(function () { 27291 return findPosition_1('node'); 27292 }).orThunk(function () { 27293 return findPosition_1('line'); 27294 }).map(function (t) { 27295 return t.position; 27296 }); 27297 return basePosition.fold(function () { 27298 return []; 27299 }, function (pos) { 27300 return filter$2(toolbars, function (t) { 27301 return t.position === pos; 27302 }); 27303 }); 27304 } 27305 }; 27306 var matchStartNode = function (elem, nodeCandidates, editorCandidates) { 27307 var nodeMatches = matchTargetWith(elem, nodeCandidates); 27308 if (nodeMatches.contextForms.length > 0) { 27309 return Optional.some({ 27310 elem: elem, 27311 toolbars: [nodeMatches.contextForms[0]] 27312 }); 27313 } else { 27314 var editorMatches = matchTargetWith(elem, editorCandidates); 27315 if (editorMatches.contextForms.length > 0) { 27316 return Optional.some({ 27317 elem: elem, 27318 toolbars: [editorMatches.contextForms[0]] 27319 }); 27320 } else if (nodeMatches.contextToolbars.length > 0 || editorMatches.contextToolbars.length > 0) { 27321 var toolbars = filterByPositionForStartNode(nodeMatches.contextToolbars.concat(editorMatches.contextToolbars)); 27322 return Optional.some({ 27323 elem: elem, 27324 toolbars: toolbars 27325 }); 27326 } else { 27327 return Optional.none(); 27328 } 27329 } 27330 }; 27331 var matchAncestor = function (isRoot, startNode, scopes) { 27332 if (isRoot(startNode)) { 27333 return Optional.none(); 27334 } else { 27335 return ancestor$2(startNode, function (ancestorElem) { 27336 if (isElement$2(ancestorElem)) { 27337 var _a = matchTargetWith(ancestorElem, scopes.inNodeScope), contextToolbars = _a.contextToolbars, contextForms = _a.contextForms; 27338 var toolbars = contextForms.length > 0 ? contextForms : filterByPositionForAncestorNode(contextToolbars); 27339 return toolbars.length > 0 ? Optional.some({ 27340 elem: ancestorElem, 27341 toolbars: toolbars 27342 }) : Optional.none(); 27343 } else { 27344 return Optional.none(); 27345 } 27346 }, isRoot); 27347 } 27348 }; 27349 var lookup$1 = function (scopes, editor) { 27350 var rootElem = SugarElement.fromDom(editor.getBody()); 27351 var isRoot = function (elem) { 27352 return eq(elem, rootElem); 27353 }; 27354 var isOutsideRoot = function (startNode) { 27355 return !isRoot(startNode) && !contains(rootElem, startNode); 27356 }; 27357 var startNode = SugarElement.fromDom(editor.selection.getNode()); 27358 if (isOutsideRoot(startNode)) { 27359 return Optional.none(); 27360 } 27361 return matchStartNode(startNode, scopes.inNodeScope, scopes.inEditorScope).orThunk(function () { 27362 return matchAncestor(isRoot, startNode, scopes); 27363 }); 27364 }; 27365 27366 var categorise = function (contextToolbars, navigate) { 27367 var forms = {}; 27368 var inNodeScope = []; 27369 var inEditorScope = []; 27370 var formNavigators = {}; 27371 var lookupTable = {}; 27372 var registerForm = function (key, toolbarSpec) { 27373 var contextForm = getOrDie(createContextForm(toolbarSpec)); 27374 forms[key] = contextForm; 27375 contextForm.launch.map(function (launch) { 27376 formNavigators['form:' + key + ''] = __assign(__assign({}, toolbarSpec.launch), { 27377 type: launch.type === 'contextformtogglebutton' ? 'togglebutton' : 'button', 27378 onAction: function () { 27379 navigate(contextForm); 27380 } 27381 }); 27382 }); 27383 if (contextForm.scope === 'editor') { 27384 inEditorScope.push(contextForm); 27385 } else { 27386 inNodeScope.push(contextForm); 27387 } 27388 lookupTable[key] = contextForm; 27389 }; 27390 var registerToolbar = function (key, toolbarSpec) { 27391 createContextToolbar(toolbarSpec).each(function (contextToolbar) { 27392 if (toolbarSpec.scope === 'editor') { 27393 inEditorScope.push(contextToolbar); 27394 } else { 27395 inNodeScope.push(contextToolbar); 27396 } 27397 lookupTable[key] = contextToolbar; 27398 }); 27399 }; 27400 var keys$1 = keys(contextToolbars); 27401 each$1(keys$1, function (key) { 27402 var toolbarApi = contextToolbars[key]; 27403 if (toolbarApi.type === 'contextform') { 27404 registerForm(key, toolbarApi); 27405 } else if (toolbarApi.type === 'contexttoolbar') { 27406 registerToolbar(key, toolbarApi); 27407 } 27408 }); 27409 return { 27410 forms: forms, 27411 inNodeScope: inNodeScope, 27412 inEditorScope: inEditorScope, 27413 lookupTable: lookupTable, 27414 formNavigators: formNavigators 27415 }; 27416 }; 27417 27418 var forwardSlideEvent = generate$6('forward-slide'); 27419 var backSlideEvent = generate$6('backward-slide'); 27420 var changeSlideEvent = generate$6('change-slide-event'); 27421 var resizingClass = 'tox-pop--resizing'; 27422 var renderContextToolbar = function (spec) { 27423 var stack = Cell([]); 27424 return InlineView.sketch({ 27425 dom: { 27426 tag: 'div', 27427 classes: ['tox-pop'] 27428 }, 27429 fireDismissalEventInstead: { event: 'doNotDismissYet' }, 27430 onShow: function (comp) { 27431 stack.set([]); 27432 InlineView.getContent(comp).each(function (c) { 27433 remove$6(c.element, 'visibility'); 27434 }); 27435 remove$2(comp.element, resizingClass); 27436 remove$6(comp.element, 'width'); 27437 }, 27438 inlineBehaviours: derive$1([ 27439 config('context-toolbar-events', [ 27440 runOnSource(transitionend(), function (comp, se) { 27441 if (se.event.raw.propertyName === 'width') { 27442 remove$2(comp.element, resizingClass); 27443 remove$6(comp.element, 'width'); 27444 } 27445 }), 27446 run$1(changeSlideEvent, function (comp, se) { 27447 var elem = comp.element; 27448 remove$6(elem, 'width'); 27449 var currentWidth = get$a(elem); 27450 InlineView.setContent(comp, se.event.contents); 27451 add$2(elem, resizingClass); 27452 var newWidth = get$a(elem); 27453 set$7(elem, 'width', currentWidth + 'px'); 27454 InlineView.getContent(comp).each(function (newContents) { 27455 se.event.focus.bind(function (f) { 27456 focus$3(f); 27457 return search(elem); 27458 }).orThunk(function () { 27459 Keying.focusIn(newContents); 27460 return active(getRootNode(elem)); 27461 }); 27462 }); 27463 global$f.setTimeout(function () { 27464 set$7(comp.element, 'width', newWidth + 'px'); 27465 }, 0); 27466 }), 27467 run$1(forwardSlideEvent, function (comp, se) { 27468 InlineView.getContent(comp).each(function (oldContents) { 27469 stack.set(stack.get().concat([{ 27470 bar: oldContents, 27471 focus: active(getRootNode(comp.element)) 27472 }])); 27473 }); 27474 emitWith(comp, changeSlideEvent, { 27475 contents: se.event.forwardContents, 27476 focus: Optional.none() 27477 }); 27478 }), 27479 run$1(backSlideEvent, function (comp, _se) { 27480 last$2(stack.get()).each(function (last) { 27481 stack.set(stack.get().slice(0, stack.get().length - 1)); 27482 emitWith(comp, changeSlideEvent, { 27483 contents: premade(last.bar), 27484 focus: last.focus 27485 }); 27486 }); 27487 }) 27488 ]), 27489 Keying.config({ 27490 mode: 'special', 27491 onEscape: function (comp) { 27492 return last$2(stack.get()).fold(function () { 27493 return spec.onEscape(); 27494 }, function (_) { 27495 emit(comp, backSlideEvent); 27496 return Optional.some(true); 27497 }); 27498 } 27499 }) 27500 ]), 27501 lazySink: function () { 27502 return Result.value(spec.sink); 27503 } 27504 }); 27505 }; 27506 27507 var transitionClass = 'tox-pop--transition'; 27508 var register$7 = function (editor, registryContextToolbars, sink, extras) { 27509 var backstage = extras.backstage; 27510 var sharedBackstage = backstage.shared; 27511 var isTouch = detect$1().deviceType.isTouch; 27512 var lastElement = value$1(); 27513 var lastTrigger = value$1(); 27514 var lastContextPosition = value$1(); 27515 var contextbar = build$1(renderContextToolbar({ 27516 sink: sink, 27517 onEscape: function () { 27518 editor.focus(); 27519 return Optional.some(true); 27520 } 27521 })); 27522 var getBounds = function () { 27523 var position = lastContextPosition.get().getOr('node'); 27524 var margin = shouldUseInsetLayouts(position) ? 1 : 0; 27525 return getContextToolbarBounds(editor, sharedBackstage, position, margin); 27526 }; 27527 var canLaunchToolbar = function () { 27528 return !editor.removed && !(isTouch() && backstage.isContextMenuOpen()); 27529 }; 27530 var isSameLaunchElement = function (elem) { 27531 return is$1(lift2(elem, lastElement.get(), eq), true); 27532 }; 27533 var shouldContextToolbarHide = function () { 27534 if (!canLaunchToolbar()) { 27535 return true; 27536 } else { 27537 var contextToolbarBounds = getBounds(); 27538 var anchorBounds = is$1(lastContextPosition.get(), 'node') ? getAnchorElementBounds(editor, lastElement.get()) : getSelectionBounds(editor); 27539 return contextToolbarBounds.height <= 0 || !isVerticalOverlap(anchorBounds, contextToolbarBounds); 27540 } 27541 }; 27542 var close = function () { 27543 lastElement.clear(); 27544 lastTrigger.clear(); 27545 lastContextPosition.clear(); 27546 InlineView.hide(contextbar); 27547 }; 27548 var hideOrRepositionIfNecessary = function () { 27549 if (InlineView.isOpen(contextbar)) { 27550 var contextBarEle = contextbar.element; 27551 remove$6(contextBarEle, 'display'); 27552 if (shouldContextToolbarHide()) { 27553 set$7(contextBarEle, 'display', 'none'); 27554 } else { 27555 lastTrigger.set(0); 27556 InlineView.reposition(contextbar); 27557 } 27558 } 27559 }; 27560 var wrapInPopDialog = function (toolbarSpec) { 27561 return { 27562 dom: { 27563 tag: 'div', 27564 classes: ['tox-pop__dialog'] 27565 }, 27566 components: [toolbarSpec], 27567 behaviours: derive$1([ 27568 Keying.config({ mode: 'acyclic' }), 27569 config('pop-dialog-wrap-events', [ 27570 runOnAttached(function (comp) { 27571 editor.shortcuts.add('ctrl+F9', 'focus statusbar', function () { 27572 return Keying.focusIn(comp); 27573 }); 27574 }), 27575 runOnDetached(function (_comp) { 27576 editor.shortcuts.remove('ctrl+F9'); 27577 }) 27578 ]) 27579 ]) 27580 }; 27581 }; 27582 var getScopes = cached(function () { 27583 return categorise(registryContextToolbars, function (toolbarApi) { 27584 var alloySpec = buildToolbar([toolbarApi]); 27585 emitWith(contextbar, forwardSlideEvent, { forwardContents: wrapInPopDialog(alloySpec) }); 27586 }); 27587 }); 27588 var buildContextToolbarGroups = function (allButtons, ctx) { 27589 return identifyButtons(editor, { 27590 buttons: allButtons, 27591 toolbar: ctx.items, 27592 allowToolbarGroups: false 27593 }, extras, Optional.some(['form:'])); 27594 }; 27595 var buildContextFormGroups = function (ctx, providers) { 27596 return ContextForm.buildInitGroups(ctx, providers); 27597 }; 27598 var buildToolbar = function (toolbars) { 27599 var buttons = editor.ui.registry.getAll().buttons; 27600 var scopes = getScopes(); 27601 var allButtons = __assign(__assign({}, buttons), scopes.formNavigators); 27602 var toolbarType = getToolbarMode(editor) === ToolbarMode.scrolling ? ToolbarMode.scrolling : ToolbarMode.default; 27603 var initGroups = flatten(map$2(toolbars, function (ctx) { 27604 return ctx.type === 'contexttoolbar' ? buildContextToolbarGroups(allButtons, ctx) : buildContextFormGroups(ctx, sharedBackstage.providers); 27605 })); 27606 return renderToolbar({ 27607 type: toolbarType, 27608 uid: generate$6('context-toolbar'), 27609 initGroups: initGroups, 27610 onEscape: Optional.none, 27611 cyclicKeying: true, 27612 providers: sharedBackstage.providers 27613 }); 27614 }; 27615 var getAnchor = function (position, element) { 27616 var anchorage = position === 'node' ? sharedBackstage.anchors.node(element) : sharedBackstage.anchors.cursor(); 27617 var anchorLayout = getAnchorLayout(editor, position, isTouch(), { 27618 lastElement: lastElement.get, 27619 isReposition: function () { 27620 return is$1(lastTrigger.get(), 0); 27621 }, 27622 getMode: function () { 27623 return Positioning.getMode(sink); 27624 } 27625 }); 27626 return deepMerge(anchorage, anchorLayout); 27627 }; 27628 var launchContext = function (toolbarApi, elem) { 27629 launchContextToolbar.cancel(); 27630 if (!canLaunchToolbar()) { 27631 return; 27632 } 27633 var toolbarSpec = buildToolbar(toolbarApi); 27634 var position = toolbarApi[0].position; 27635 var anchor = getAnchor(position, elem); 27636 lastContextPosition.set(position); 27637 lastTrigger.set(1); 27638 var contextBarEle = contextbar.element; 27639 remove$6(contextBarEle, 'display'); 27640 if (!isSameLaunchElement(elem)) { 27641 remove$2(contextBarEle, transitionClass); 27642 Positioning.reset(sink, contextbar); 27643 } 27644 InlineView.showWithinBounds(contextbar, wrapInPopDialog(toolbarSpec), { 27645 anchor: anchor, 27646 transition: { 27647 classes: [transitionClass], 27648 mode: 'placement' 27649 } 27650 }, function () { 27651 return Optional.some(getBounds()); 27652 }); 27653 elem.fold(lastElement.clear, lastElement.set); 27654 if (shouldContextToolbarHide()) { 27655 set$7(contextBarEle, 'display', 'none'); 27656 } 27657 }; 27658 var launchContextToolbar = last(function () { 27659 if (!editor.hasFocus() || editor.removed) { 27660 return; 27661 } 27662 if (has(contextbar.element, transitionClass)) { 27663 launchContextToolbar.throttle(); 27664 } else { 27665 var scopes = getScopes(); 27666 lookup$1(scopes, editor).fold(close, function (info) { 27667 launchContext(info.toolbars, Optional.some(info.elem)); 27668 }); 27669 } 27670 }, 17); 27671 editor.on('init', function () { 27672 editor.on('remove', close); 27673 editor.on('ScrollContent ScrollWindow ObjectResized ResizeEditor longpress', hideOrRepositionIfNecessary); 27674 editor.on('click keyup focus SetContent', launchContextToolbar.throttle); 27675 editor.on(hideContextToolbarEvent, close); 27676 editor.on(showContextToolbarEvent, function (e) { 27677 var scopes = getScopes(); 27678 get$e(scopes.lookupTable, e.toolbarKey).each(function (ctx) { 27679 launchContext([ctx], someIf(e.target !== editor, e.target)); 27680 InlineView.getContent(contextbar).each(Keying.focusIn); 27681 }); 27682 }); 27683 editor.on('focusout', function (_e) { 27684 global$f.setEditorTimeout(editor, function () { 27685 if (search(sink.element).isNone() && search(contextbar.element).isNone()) { 27686 close(); 27687 } 27688 }, 0); 27689 }); 27690 editor.on('SwitchMode', function () { 27691 if (editor.mode.isReadOnly()) { 27692 close(); 27693 } 27694 }); 27695 editor.on('AfterProgressState', function (event) { 27696 if (event.state) { 27697 close(); 27698 } else if (editor.hasFocus()) { 27699 launchContextToolbar.throttle(); 27700 } 27701 }); 27702 editor.on('NodeChange', function (_e) { 27703 search(contextbar.element).fold(launchContextToolbar.throttle, noop); 27704 }); 27705 }); 27706 }; 27707 27708 var register$6 = function (editor) { 27709 var alignToolbarButtons = [ 27710 { 27711 name: 'alignleft', 27712 text: 'Align left', 27713 cmd: 'JustifyLeft', 27714 icon: 'align-left' 27715 }, 27716 { 27717 name: 'aligncenter', 27718 text: 'Align center', 27719 cmd: 'JustifyCenter', 27720 icon: 'align-center' 27721 }, 27722 { 27723 name: 'alignright', 27724 text: 'Align right', 27725 cmd: 'JustifyRight', 27726 icon: 'align-right' 27727 }, 27728 { 27729 name: 'alignjustify', 27730 text: 'Justify', 27731 cmd: 'JustifyFull', 27732 icon: 'align-justify' 27733 } 27734 ]; 27735 each$1(alignToolbarButtons, function (item) { 27736 editor.ui.registry.addToggleButton(item.name, { 27737 tooltip: item.text, 27738 icon: item.icon, 27739 onAction: onActionExecCommand(editor, item.cmd), 27740 onSetup: onSetupFormatToggle(editor, item.name) 27741 }); 27742 }); 27743 editor.ui.registry.addButton('alignnone', { 27744 tooltip: 'No alignment', 27745 icon: 'align-none', 27746 onAction: onActionExecCommand(editor, 'JustifyNone') 27747 }); 27748 }; 27749 27750 var units = { 27751 unsupportedLength: [ 27752 'em', 27753 'ex', 27754 'cap', 27755 'ch', 27756 'ic', 27757 'rem', 27758 'lh', 27759 'rlh', 27760 'vw', 27761 'vh', 27762 'vi', 27763 'vb', 27764 'vmin', 27765 'vmax', 27766 'cm', 27767 'mm', 27768 'Q', 27769 'in', 27770 'pc', 27771 'pt', 27772 'px' 27773 ], 27774 fixed: [ 27775 'px', 27776 'pt' 27777 ], 27778 relative: ['%'], 27779 empty: [''] 27780 }; 27781 var pattern = function () { 27782 var decimalDigits = '[0-9]+'; 27783 var signedInteger = '[+-]?' + decimalDigits; 27784 var exponentPart = '[eE]' + signedInteger; 27785 var dot = '\\.'; 27786 var opt = function (input) { 27787 return '(?:' + input + ')?'; 27788 }; 27789 var unsignedDecimalLiteral = [ 27790 'Infinity', 27791 decimalDigits + dot + opt(decimalDigits) + opt(exponentPart), 27792 dot + decimalDigits + opt(exponentPart), 27793 decimalDigits + opt(exponentPart) 27794 ].join('|'); 27795 var float = '[+-]?(?:' + unsignedDecimalLiteral + ')'; 27796 return new RegExp('^(' + float + ')(.*)$'); 27797 }(); 27798 var isUnit = function (unit, accepted) { 27799 return exists(accepted, function (acc) { 27800 return exists(units[acc], function (check) { 27801 return unit === check; 27802 }); 27803 }); 27804 }; 27805 var parse = function (input, accepted) { 27806 var match = Optional.from(pattern.exec(input)); 27807 return match.bind(function (array) { 27808 var value = Number(array[1]); 27809 var unitRaw = array[2]; 27810 if (isUnit(unitRaw, accepted)) { 27811 return Optional.some({ 27812 value: value, 27813 unit: unitRaw 27814 }); 27815 } else { 27816 return Optional.none(); 27817 } 27818 }); 27819 }; 27820 var normalise = function (input, accepted) { 27821 return parse(input, accepted).map(function (_a) { 27822 var value = _a.value, unit = _a.unit; 27823 return value + unit; 27824 }); 27825 }; 27826 27827 var registerController = function (editor, spec) { 27828 var getMenuItems = function () { 27829 var options = spec.getOptions(editor); 27830 var initial = spec.getCurrent(editor).map(spec.hash); 27831 var current = value$1(); 27832 return map$2(options, function (value) { 27833 return { 27834 type: 'togglemenuitem', 27835 text: spec.display(value), 27836 onSetup: function (api) { 27837 var setActive = function (active) { 27838 if (active) { 27839 current.on(function (oldApi) { 27840 return oldApi.setActive(false); 27841 }); 27842 current.set(api); 27843 } 27844 api.setActive(active); 27845 }; 27846 setActive(is$1(initial, spec.hash(value))); 27847 var unbindWatcher = spec.watcher(editor, value, setActive); 27848 return function () { 27849 current.clear(); 27850 unbindWatcher(); 27851 }; 27852 }, 27853 onAction: function () { 27854 return spec.setCurrent(editor, value); 27855 } 27856 }; 27857 }); 27858 }; 27859 editor.ui.registry.addMenuButton(spec.name, { 27860 tooltip: spec.text, 27861 icon: spec.icon, 27862 fetch: function (callback) { 27863 return callback(getMenuItems()); 27864 }, 27865 onSetup: spec.onToolbarSetup 27866 }); 27867 editor.ui.registry.addNestedMenuItem(spec.name, { 27868 type: 'nestedmenuitem', 27869 text: spec.text, 27870 getSubmenuItems: getMenuItems, 27871 onSetup: spec.onMenuSetup 27872 }); 27873 }; 27874 var lineHeightSpec = { 27875 name: 'lineheight', 27876 text: 'Line height', 27877 icon: 'line-height', 27878 getOptions: getLineHeightFormats, 27879 hash: function (input) { 27880 return normalise(input, [ 27881 'fixed', 27882 'relative', 27883 'empty' 27884 ]).getOr(input); 27885 }, 27886 display: identity$1, 27887 watcher: function (editor, value, callback) { 27888 return editor.formatter.formatChanged('lineheight', callback, false, { value: value }).unbind; 27889 }, 27890 getCurrent: function (editor) { 27891 return Optional.from(editor.queryCommandValue('LineHeight')); 27892 }, 27893 setCurrent: function (editor, value) { 27894 return editor.execCommand('LineHeight', false, value); 27895 } 27896 }; 27897 var languageSpec = function (editor) { 27898 var settingsOpt = Optional.from(getContentLanguages(editor)); 27899 return settingsOpt.map(function (settings) { 27900 return { 27901 name: 'language', 27902 text: 'Language', 27903 icon: 'language', 27904 getOptions: constant$1(settings), 27905 hash: function (input) { 27906 return isUndefined(input.customCode) ? input.code : input.code + '/' + input.customCode; 27907 }, 27908 display: function (input) { 27909 return input.title; 27910 }, 27911 watcher: function (editor, value, callback) { 27912 return editor.formatter.formatChanged('lang', callback, false, { 27913 value: value.code, 27914 customValue: value.customCode 27915 }).unbind; 27916 }, 27917 getCurrent: function (editor) { 27918 var node = SugarElement.fromDom(editor.selection.getNode()); 27919 return closest$4(node, function (n) { 27920 return Optional.some(n).filter(isElement$2).bind(function (ele) { 27921 var codeOpt = getOpt(ele, 'lang'); 27922 return codeOpt.map(function (code) { 27923 var customCode = getOpt(ele, 'data-mce-lang').getOrUndefined(); 27924 return { 27925 code: code, 27926 customCode: customCode, 27927 title: '' 27928 }; 27929 }); 27930 }); 27931 }); 27932 }, 27933 setCurrent: function (editor, lang) { 27934 return editor.execCommand('Lang', false, lang); 27935 }, 27936 onToolbarSetup: function (api) { 27937 var unbinder = unbindable(); 27938 api.setActive(editor.formatter.match('lang', {}, undefined, true)); 27939 unbinder.set(editor.formatter.formatChanged('lang', api.setActive, true)); 27940 return unbinder.clear; 27941 } 27942 }; 27943 }); 27944 }; 27945 var register$5 = function (editor) { 27946 registerController(editor, lineHeightSpec); 27947 languageSpec(editor).each(function (spec) { 27948 return registerController(editor, spec); 27949 }); 27950 }; 27951 27952 var register$4 = function (editor, backstage) { 27953 alignSelectMenu(editor, backstage); 27954 fontSelectMenu(editor, backstage); 27955 styleSelectMenu(editor, backstage); 27956 formatSelectMenu(editor, backstage); 27957 fontsizeSelectMenu(editor, backstage); 27958 }; 27959 27960 var onSetupOutdentState = function (editor) { 27961 return onSetupEvent(editor, 'NodeChange', function (api) { 27962 api.setDisabled(!editor.queryCommandState('outdent')); 27963 }); 27964 }; 27965 var registerButtons$2 = function (editor) { 27966 editor.ui.registry.addButton('outdent', { 27967 tooltip: 'Decrease indent', 27968 icon: 'outdent', 27969 onSetup: onSetupOutdentState(editor), 27970 onAction: onActionExecCommand(editor, 'outdent') 27971 }); 27972 editor.ui.registry.addButton('indent', { 27973 tooltip: 'Increase indent', 27974 icon: 'indent', 27975 onAction: onActionExecCommand(editor, 'indent') 27976 }); 27977 }; 27978 var register$3 = function (editor) { 27979 registerButtons$2(editor); 27980 }; 27981 27982 var onActionToggleFormat = function (editor, fmt) { 27983 return function () { 27984 editor.execCommand('mceToggleFormat', false, fmt); 27985 }; 27986 }; 27987 var registerFormatButtons = function (editor) { 27988 global$5.each([ 27989 { 27990 name: 'bold', 27991 text: 'Bold', 27992 icon: 'bold' 27993 }, 27994 { 27995 name: 'italic', 27996 text: 'Italic', 27997 icon: 'italic' 27998 }, 27999 { 28000 name: 'underline', 28001 text: 'Underline', 28002 icon: 'underline' 28003 }, 28004 { 28005 name: 'strikethrough', 28006 text: 'Strikethrough', 28007 icon: 'strike-through' 28008 }, 28009 { 28010 name: 'subscript', 28011 text: 'Subscript', 28012 icon: 'subscript' 28013 }, 28014 { 28015 name: 'superscript', 28016 text: 'Superscript', 28017 icon: 'superscript' 28018 } 28019 ], function (btn, _idx) { 28020 editor.ui.registry.addToggleButton(btn.name, { 28021 tooltip: btn.text, 28022 icon: btn.icon, 28023 onSetup: onSetupFormatToggle(editor, btn.name), 28024 onAction: onActionToggleFormat(editor, btn.name) 28025 }); 28026 }); 28027 for (var i = 1; i <= 6; i++) { 28028 var name_1 = 'h' + i; 28029 editor.ui.registry.addToggleButton(name_1, { 28030 text: name_1.toUpperCase(), 28031 tooltip: 'Heading ' + i, 28032 onSetup: onSetupFormatToggle(editor, name_1), 28033 onAction: onActionToggleFormat(editor, name_1) 28034 }); 28035 } 28036 }; 28037 var registerCommandButtons = function (editor) { 28038 global$5.each([ 28039 { 28040 name: 'cut', 28041 text: 'Cut', 28042 action: 'Cut', 28043 icon: 'cut' 28044 }, 28045 { 28046 name: 'copy', 28047 text: 'Copy', 28048 action: 'Copy', 28049 icon: 'copy' 28050 }, 28051 { 28052 name: 'paste', 28053 text: 'Paste', 28054 action: 'Paste', 28055 icon: 'paste' 28056 }, 28057 { 28058 name: 'help', 28059 text: 'Help', 28060 action: 'mceHelp', 28061 icon: 'help' 28062 }, 28063 { 28064 name: 'selectall', 28065 text: 'Select all', 28066 action: 'SelectAll', 28067 icon: 'select-all' 28068 }, 28069 { 28070 name: 'newdocument', 28071 text: 'New document', 28072 action: 'mceNewDocument', 28073 icon: 'new-document' 28074 }, 28075 { 28076 name: 'removeformat', 28077 text: 'Clear formatting', 28078 action: 'RemoveFormat', 28079 icon: 'remove-formatting' 28080 }, 28081 { 28082 name: 'remove', 28083 text: 'Remove', 28084 action: 'Delete', 28085 icon: 'remove' 28086 } 28087 ], function (btn) { 28088 editor.ui.registry.addButton(btn.name, { 28089 tooltip: btn.text, 28090 icon: btn.icon, 28091 onAction: onActionExecCommand(editor, btn.action) 28092 }); 28093 }); 28094 }; 28095 var registerCommandToggleButtons = function (editor) { 28096 global$5.each([{ 28097 name: 'blockquote', 28098 text: 'Blockquote', 28099 action: 'mceBlockQuote', 28100 icon: 'quote' 28101 }], function (btn) { 28102 editor.ui.registry.addToggleButton(btn.name, { 28103 tooltip: btn.text, 28104 icon: btn.icon, 28105 onAction: onActionExecCommand(editor, btn.action), 28106 onSetup: onSetupFormatToggle(editor, btn.name) 28107 }); 28108 }); 28109 }; 28110 var registerButtons$1 = function (editor) { 28111 registerFormatButtons(editor); 28112 registerCommandButtons(editor); 28113 registerCommandToggleButtons(editor); 28114 }; 28115 var registerMenuItems$2 = function (editor) { 28116 global$5.each([ 28117 { 28118 name: 'bold', 28119 text: 'Bold', 28120 action: 'Bold', 28121 icon: 'bold', 28122 shortcut: 'Meta+B' 28123 }, 28124 { 28125 name: 'italic', 28126 text: 'Italic', 28127 action: 'Italic', 28128 icon: 'italic', 28129 shortcut: 'Meta+I' 28130 }, 28131 { 28132 name: 'underline', 28133 text: 'Underline', 28134 action: 'Underline', 28135 icon: 'underline', 28136 shortcut: 'Meta+U' 28137 }, 28138 { 28139 name: 'strikethrough', 28140 text: 'Strikethrough', 28141 action: 'Strikethrough', 28142 icon: 'strike-through', 28143 shortcut: '' 28144 }, 28145 { 28146 name: 'subscript', 28147 text: 'Subscript', 28148 action: 'Subscript', 28149 icon: 'subscript', 28150 shortcut: '' 28151 }, 28152 { 28153 name: 'superscript', 28154 text: 'Superscript', 28155 action: 'Superscript', 28156 icon: 'superscript', 28157 shortcut: '' 28158 }, 28159 { 28160 name: 'removeformat', 28161 text: 'Clear formatting', 28162 action: 'RemoveFormat', 28163 icon: 'remove-formatting', 28164 shortcut: '' 28165 }, 28166 { 28167 name: 'newdocument', 28168 text: 'New document', 28169 action: 'mceNewDocument', 28170 icon: 'new-document', 28171 shortcut: '' 28172 }, 28173 { 28174 name: 'cut', 28175 text: 'Cut', 28176 action: 'Cut', 28177 icon: 'cut', 28178 shortcut: 'Meta+X' 28179 }, 28180 { 28181 name: 'copy', 28182 text: 'Copy', 28183 action: 'Copy', 28184 icon: 'copy', 28185 shortcut: 'Meta+C' 28186 }, 28187 { 28188 name: 'paste', 28189 text: 'Paste', 28190 action: 'Paste', 28191 icon: 'paste', 28192 shortcut: 'Meta+V' 28193 }, 28194 { 28195 name: 'selectall', 28196 text: 'Select all', 28197 action: 'SelectAll', 28198 icon: 'select-all', 28199 shortcut: 'Meta+A' 28200 } 28201 ], function (btn) { 28202 editor.ui.registry.addMenuItem(btn.name, { 28203 text: btn.text, 28204 icon: btn.icon, 28205 shortcut: btn.shortcut, 28206 onAction: onActionExecCommand(editor, btn.action) 28207 }); 28208 }); 28209 editor.ui.registry.addMenuItem('codeformat', { 28210 text: 'Code', 28211 icon: 'sourcecode', 28212 onAction: onActionToggleFormat(editor, 'code') 28213 }); 28214 }; 28215 var register$2 = function (editor) { 28216 registerButtons$1(editor); 28217 registerMenuItems$2(editor); 28218 }; 28219 28220 var onSetupUndoRedoState = function (editor, type) { 28221 return onSetupEvent(editor, 'Undo Redo AddUndo TypingUndo ClearUndos SwitchMode', function (api) { 28222 api.setDisabled(editor.mode.isReadOnly() || !editor.undoManager[type]()); 28223 }); 28224 }; 28225 var registerMenuItems$1 = function (editor) { 28226 editor.ui.registry.addMenuItem('undo', { 28227 text: 'Undo', 28228 icon: 'undo', 28229 shortcut: 'Meta+Z', 28230 onSetup: onSetupUndoRedoState(editor, 'hasUndo'), 28231 onAction: onActionExecCommand(editor, 'undo') 28232 }); 28233 editor.ui.registry.addMenuItem('redo', { 28234 text: 'Redo', 28235 icon: 'redo', 28236 shortcut: 'Meta+Y', 28237 onSetup: onSetupUndoRedoState(editor, 'hasRedo'), 28238 onAction: onActionExecCommand(editor, 'redo') 28239 }); 28240 }; 28241 var registerButtons = function (editor) { 28242 editor.ui.registry.addButton('undo', { 28243 tooltip: 'Undo', 28244 icon: 'undo', 28245 disabled: true, 28246 onSetup: onSetupUndoRedoState(editor, 'hasUndo'), 28247 onAction: onActionExecCommand(editor, 'undo') 28248 }); 28249 editor.ui.registry.addButton('redo', { 28250 tooltip: 'Redo', 28251 icon: 'redo', 28252 disabled: true, 28253 onSetup: onSetupUndoRedoState(editor, 'hasRedo'), 28254 onAction: onActionExecCommand(editor, 'redo') 28255 }); 28256 }; 28257 var register$1 = function (editor) { 28258 registerMenuItems$1(editor); 28259 registerButtons(editor); 28260 }; 28261 28262 var onSetupVisualAidState = function (editor) { 28263 return onSetupEvent(editor, 'VisualAid', function (api) { 28264 api.setActive(editor.hasVisual); 28265 }); 28266 }; 28267 var registerMenuItems = function (editor) { 28268 editor.ui.registry.addToggleMenuItem('visualaid', { 28269 text: 'Visual aids', 28270 onSetup: onSetupVisualAidState(editor), 28271 onAction: onActionExecCommand(editor, 'mceToggleVisualAid') 28272 }); 28273 }; 28274 var registerToolbarButton = function (editor) { 28275 editor.ui.registry.addButton('visualaid', { 28276 tooltip: 'Visual aids', 28277 text: 'Visual aids', 28278 onAction: onActionExecCommand(editor, 'mceToggleVisualAid') 28279 }); 28280 }; 28281 var register = function (editor) { 28282 registerToolbarButton(editor); 28283 registerMenuItems(editor); 28284 }; 28285 28286 var setup$6 = function (editor, backstage) { 28287 register$6(editor); 28288 register$2(editor); 28289 register$4(editor, backstage); 28290 register$1(editor); 28291 register$a(editor); 28292 register(editor); 28293 register$3(editor); 28294 register$5(editor); 28295 }; 28296 28297 var nu = function (x, y) { 28298 return { 28299 type: 'makeshift', 28300 x: x, 28301 y: y 28302 }; 28303 }; 28304 var transpose = function (pos, dx, dy) { 28305 return nu(pos.x + dx, pos.y + dy); 28306 }; 28307 var isTouchEvent = function (e) { 28308 return e.type === 'longpress' || e.type.indexOf('touch') === 0; 28309 }; 28310 var fromPageXY = function (e) { 28311 if (isTouchEvent(e)) { 28312 var touch = e.touches[0]; 28313 return nu(touch.pageX, touch.pageY); 28314 } else { 28315 return nu(e.pageX, e.pageY); 28316 } 28317 }; 28318 var fromClientXY = function (e) { 28319 if (isTouchEvent(e)) { 28320 var touch = e.touches[0]; 28321 return nu(touch.clientX, touch.clientY); 28322 } else { 28323 return nu(e.clientX, e.clientY); 28324 } 28325 }; 28326 var transposeContentAreaContainer = function (element, pos) { 28327 var containerPos = global$b.DOM.getPos(element); 28328 return transpose(pos, containerPos.x, containerPos.y); 28329 }; 28330 var getPointAnchor = function (editor, e) { 28331 if (e.type === 'contextmenu' || e.type === 'longpress') { 28332 if (editor.inline) { 28333 return fromPageXY(e); 28334 } else { 28335 return transposeContentAreaContainer(editor.getContentAreaContainer(), fromClientXY(e)); 28336 } 28337 } else { 28338 return getSelectionAnchor(editor); 28339 } 28340 }; 28341 var getSelectionAnchor = function (editor) { 28342 return { 28343 type: 'selection', 28344 root: SugarElement.fromDom(editor.selection.getNode()) 28345 }; 28346 }; 28347 var getNodeAnchor = function (editor) { 28348 return { 28349 type: 'node', 28350 node: Optional.some(SugarElement.fromDom(editor.selection.getNode())), 28351 root: SugarElement.fromDom(editor.getBody()) 28352 }; 28353 }; 28354 var getAnchorSpec$1 = function (editor, e, anchorType) { 28355 switch (anchorType) { 28356 case 'node': 28357 return getNodeAnchor(editor); 28358 case 'point': 28359 return getPointAnchor(editor, e); 28360 case 'selection': 28361 return getSelectionAnchor(editor); 28362 } 28363 }; 28364 28365 var initAndShow$1 = function (editor, e, buildMenu, backstage, contextmenu, anchorType) { 28366 var items = buildMenu(); 28367 var anchorSpec = getAnchorSpec$1(editor, e, anchorType); 28368 build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, false).map(function (menuData) { 28369 e.preventDefault(); 28370 InlineView.showMenuAt(contextmenu, { anchor: anchorSpec }, { 28371 menu: { markers: markers('normal') }, 28372 data: menuData 28373 }); 28374 }); 28375 }; 28376 28377 var layouts = { 28378 onLtr: function () { 28379 return [ 28380 south$2, 28381 southeast$2, 28382 southwest$2, 28383 northeast$2, 28384 northwest$2, 28385 north$2, 28386 north, 28387 south, 28388 northeast, 28389 southeast, 28390 northwest, 28391 southwest 28392 ]; 28393 }, 28394 onRtl: function () { 28395 return [ 28396 south$2, 28397 southwest$2, 28398 southeast$2, 28399 northwest$2, 28400 northeast$2, 28401 north$2, 28402 north, 28403 south, 28404 northwest, 28405 southwest, 28406 northeast, 28407 southeast 28408 ]; 28409 } 28410 }; 28411 var bubbleSize = 12; 28412 var bubbleAlignments = { 28413 valignCentre: [], 28414 alignCentre: [], 28415 alignLeft: ['tox-pop--align-left'], 28416 alignRight: ['tox-pop--align-right'], 28417 right: ['tox-pop--right'], 28418 left: ['tox-pop--left'], 28419 bottom: ['tox-pop--bottom'], 28420 top: ['tox-pop--top'] 28421 }; 28422 var isTouchWithinSelection = function (editor, e) { 28423 var selection = editor.selection; 28424 if (selection.isCollapsed() || e.touches.length < 1) { 28425 return false; 28426 } else { 28427 var touch_1 = e.touches[0]; 28428 var rng = selection.getRng(); 28429 var rngRectOpt = getFirstRect(editor.getWin(), SimSelection.domRange(rng)); 28430 return rngRectOpt.exists(function (rngRect) { 28431 return rngRect.left <= touch_1.clientX && rngRect.right >= touch_1.clientX && rngRect.top <= touch_1.clientY && rngRect.bottom >= touch_1.clientY; 28432 }); 28433 } 28434 }; 28435 var setupiOSOverrides = function (editor) { 28436 var originalSelection = editor.selection.getRng(); 28437 var selectionReset = function () { 28438 global$f.setEditorTimeout(editor, function () { 28439 editor.selection.setRng(originalSelection); 28440 }, 10); 28441 unbindEventListeners(); 28442 }; 28443 editor.once('touchend', selectionReset); 28444 var preventMousedown = function (e) { 28445 e.preventDefault(); 28446 e.stopImmediatePropagation(); 28447 }; 28448 editor.on('mousedown', preventMousedown, true); 28449 var clearSelectionReset = function () { 28450 return unbindEventListeners(); 28451 }; 28452 editor.once('longpresscancel', clearSelectionReset); 28453 var unbindEventListeners = function () { 28454 editor.off('touchend', selectionReset); 28455 editor.off('longpresscancel', clearSelectionReset); 28456 editor.off('mousedown', preventMousedown); 28457 }; 28458 }; 28459 var getAnchorSpec = function (editor, e, anchorType) { 28460 var anchorSpec = getAnchorSpec$1(editor, e, anchorType); 28461 var bubbleYOffset = anchorType === 'point' ? bubbleSize : 0; 28462 return __assign({ 28463 bubble: nu$5(0, bubbleYOffset, bubbleAlignments), 28464 layouts: layouts, 28465 overrides: { 28466 maxWidthFunction: expandable(), 28467 maxHeightFunction: expandable$1() 28468 } 28469 }, anchorSpec); 28470 }; 28471 var show = function (editor, e, items, backstage, contextmenu, anchorType, highlightImmediately) { 28472 var anchorSpec = getAnchorSpec(editor, e, anchorType); 28473 build(items, ItemResponse$1.CLOSE_ON_EXECUTE, backstage, true).map(function (menuData) { 28474 e.preventDefault(); 28475 InlineView.showMenuWithinBounds(contextmenu, { anchor: anchorSpec }, { 28476 menu: { 28477 markers: markers('normal'), 28478 highlightImmediately: highlightImmediately 28479 }, 28480 data: menuData, 28481 type: 'horizontal' 28482 }, function () { 28483 return Optional.some(getContextToolbarBounds(editor, backstage.shared, anchorType === 'node' ? 'node' : 'selection')); 28484 }); 28485 editor.fire(hideContextToolbarEvent); 28486 }); 28487 }; 28488 var initAndShow = function (editor, e, buildMenu, backstage, contextmenu, anchorType) { 28489 var detection = detect$1(); 28490 var isiOS = detection.os.isiOS(); 28491 var isOSX = detection.os.isOSX(); 28492 var isAndroid = detection.os.isAndroid(); 28493 var isTouch = detection.deviceType.isTouch(); 28494 var shouldHighlightImmediately = function () { 28495 return !(isAndroid || isiOS || isOSX && isTouch); 28496 }; 28497 var open = function () { 28498 var items = buildMenu(); 28499 show(editor, e, items, backstage, contextmenu, anchorType, shouldHighlightImmediately()); 28500 }; 28501 if ((isOSX || isiOS) && anchorType !== 'node') { 28502 var openiOS_1 = function () { 28503 setupiOSOverrides(editor); 28504 open(); 28505 }; 28506 if (isTouchWithinSelection(editor, e)) { 28507 openiOS_1(); 28508 } else { 28509 editor.once('selectionchange', openiOS_1); 28510 editor.once('touchend', function () { 28511 return editor.off('selectionchange', openiOS_1); 28512 }); 28513 } 28514 } else { 28515 open(); 28516 } 28517 }; 28518 28519 var patchPipeConfig = function (config) { 28520 return typeof config === 'string' ? config.split(/[ ,]/) : config; 28521 }; 28522 var shouldNeverUseNative = function (editor) { 28523 return editor.getParam('contextmenu_never_use_native', false, 'boolean'); 28524 }; 28525 var getMenuItems = function (editor, name, defaultItems) { 28526 var contextMenus = editor.ui.registry.getAll().contextMenus; 28527 return Optional.from(editor.getParam(name)).map(patchPipeConfig).getOrThunk(function () { 28528 return filter$2(patchPipeConfig(defaultItems), function (item) { 28529 return has$2(contextMenus, item); 28530 }); 28531 }); 28532 }; 28533 var isContextMenuDisabled = function (editor) { 28534 return editor.getParam('contextmenu') === false; 28535 }; 28536 var getContextMenu = function (editor) { 28537 return getMenuItems(editor, 'contextmenu', 'link linkchecker image imagetools table spellchecker configurepermanentpen'); 28538 }; 28539 var getAvoidOverlapSelector = function (editor) { 28540 return editor.getParam('contextmenu_avoid_overlap', '', 'string'); 28541 }; 28542 28543 var isSeparator = function (item) { 28544 return isString(item) ? item === '|' : item.type === 'separator'; 28545 }; 28546 var separator = { type: 'separator' }; 28547 var makeContextItem = function (item) { 28548 var commonMenuItem = function (item) { 28549 return { 28550 text: item.text, 28551 icon: item.icon, 28552 disabled: item.disabled, 28553 shortcut: item.shortcut 28554 }; 28555 }; 28556 if (isString(item)) { 28557 return item; 28558 } else { 28559 switch (item.type) { 28560 case 'separator': 28561 return separator; 28562 case 'submenu': 28563 return __assign(__assign({ type: 'nestedmenuitem' }, commonMenuItem(item)), { 28564 getSubmenuItems: function () { 28565 var items = item.getSubmenuItems(); 28566 if (isString(items)) { 28567 return items; 28568 } else { 28569 return map$2(items, makeContextItem); 28570 } 28571 } 28572 }); 28573 default: 28574 return __assign(__assign({ type: 'menuitem' }, commonMenuItem(item)), { onAction: noarg(item.onAction) }); 28575 } 28576 } 28577 }; 28578 var addContextMenuGroup = function (xs, groupItems) { 28579 if (groupItems.length === 0) { 28580 return xs; 28581 } 28582 var lastMenuItem = last$2(xs).filter(function (item) { 28583 return !isSeparator(item); 28584 }); 28585 var before = lastMenuItem.fold(function () { 28586 return []; 28587 }, function (_) { 28588 return [separator]; 28589 }); 28590 return xs.concat(before).concat(groupItems).concat([separator]); 28591 }; 28592 var generateContextMenu = function (contextMenus, menuConfig, selectedElement) { 28593 var sections = foldl(menuConfig, function (acc, name) { 28594 return get$e(contextMenus, name.toLowerCase()).map(function (menu) { 28595 var items = menu.update(selectedElement); 28596 if (isString(items)) { 28597 return addContextMenuGroup(acc, items.split(' ')); 28598 } else if (items.length > 0) { 28599 var allItems = map$2(items, makeContextItem); 28600 return addContextMenuGroup(acc, allItems); 28601 } else { 28602 return acc; 28603 } 28604 }).getOrThunk(function () { 28605 return acc.concat([name]); 28606 }); 28607 }, []); 28608 if (sections.length > 0 && isSeparator(sections[sections.length - 1])) { 28609 sections.pop(); 28610 } 28611 return sections; 28612 }; 28613 var isNativeOverrideKeyEvent = function (editor, e) { 28614 return e.ctrlKey && !shouldNeverUseNative(editor); 28615 }; 28616 var isTriggeredByKeyboard = function (editor, e) { 28617 return e.type !== 'longpress' && (e.button !== 2 || e.target === editor.getBody() && e.pointerType === ''); 28618 }; 28619 var getSelectedElement = function (editor, e) { 28620 return isTriggeredByKeyboard(editor, e) ? editor.selection.getStart(true) : e.target; 28621 }; 28622 var getAnchorType = function (editor, e) { 28623 var selector = getAvoidOverlapSelector(editor); 28624 var anchorType = isTriggeredByKeyboard(editor, e) ? 'selection' : 'point'; 28625 if (isNotEmpty(selector)) { 28626 var target = getSelectedElement(editor, e); 28627 var selectorExists = closest(SugarElement.fromDom(target), selector); 28628 return selectorExists ? 'node' : anchorType; 28629 } else { 28630 return anchorType; 28631 } 28632 }; 28633 var setup$5 = function (editor, lazySink, backstage) { 28634 var detection = detect$1(); 28635 var isTouch = detection.deviceType.isTouch; 28636 var contextmenu = build$1(InlineView.sketch({ 28637 dom: { tag: 'div' }, 28638 lazySink: lazySink, 28639 onEscape: function () { 28640 return editor.focus(); 28641 }, 28642 onShow: function () { 28643 return backstage.setContextMenuState(true); 28644 }, 28645 onHide: function () { 28646 return backstage.setContextMenuState(false); 28647 }, 28648 fireDismissalEventInstead: {}, 28649 inlineBehaviours: derive$1([config('dismissContextMenu', [run$1(dismissRequested(), function (comp, _se) { 28650 Sandboxing.close(comp); 28651 editor.focus(); 28652 })])]) 28653 })); 28654 var hideContextMenu = function (_e) { 28655 return InlineView.hide(contextmenu); 28656 }; 28657 var showContextMenu = function (e) { 28658 if (shouldNeverUseNative(editor)) { 28659 e.preventDefault(); 28660 } 28661 if (isNativeOverrideKeyEvent(editor, e) || isContextMenuDisabled(editor)) { 28662 return; 28663 } 28664 var anchorType = getAnchorType(editor, e); 28665 var buildMenu = function () { 28666 var selectedElement = getSelectedElement(editor, e); 28667 var registry = editor.ui.registry.getAll(); 28668 var menuConfig = getContextMenu(editor); 28669 return generateContextMenu(registry.contextMenus, menuConfig, selectedElement); 28670 }; 28671 var initAndShow$2 = isTouch() ? initAndShow : initAndShow$1; 28672 initAndShow$2(editor, e, buildMenu, backstage, contextmenu, anchorType); 28673 }; 28674 editor.on('init', function () { 28675 var hideEvents = 'ResizeEditor ScrollContent ScrollWindow longpresscancel' + (isTouch() ? '' : ' ResizeWindow'); 28676 editor.on(hideEvents, hideContextMenu); 28677 editor.on('longpress contextmenu', showContextMenu); 28678 }); 28679 }; 28680 28681 var adt = Adt.generate([ 28682 { 28683 offset: [ 28684 'x', 28685 'y' 28686 ] 28687 }, 28688 { 28689 absolute: [ 28690 'x', 28691 'y' 28692 ] 28693 }, 28694 { 28695 fixed: [ 28696 'x', 28697 'y' 28698 ] 28699 } 28700 ]); 28701 var subtract = function (change) { 28702 return function (point) { 28703 return point.translate(-change.left, -change.top); 28704 }; 28705 }; 28706 var add = function (change) { 28707 return function (point) { 28708 return point.translate(change.left, change.top); 28709 }; 28710 }; 28711 var transform = function (changes) { 28712 return function (x, y) { 28713 return foldl(changes, function (rest, f) { 28714 return f(rest); 28715 }, SugarPosition(x, y)); 28716 }; 28717 }; 28718 var asFixed = function (coord, scroll, origin) { 28719 return coord.fold(transform([ 28720 add(origin), 28721 subtract(scroll) 28722 ]), transform([subtract(scroll)]), transform([])); 28723 }; 28724 var asAbsolute = function (coord, scroll, origin) { 28725 return coord.fold(transform([add(origin)]), transform([]), transform([add(scroll)])); 28726 }; 28727 var asOffset = function (coord, scroll, origin) { 28728 return coord.fold(transform([]), transform([subtract(origin)]), transform([ 28729 add(scroll), 28730 subtract(origin) 28731 ])); 28732 }; 28733 var withinRange = function (coord1, coord2, xRange, yRange, scroll, origin) { 28734 var a1 = asAbsolute(coord1, scroll, origin); 28735 var a2 = asAbsolute(coord2, scroll, origin); 28736 return Math.abs(a1.left - a2.left) <= xRange && Math.abs(a1.top - a2.top) <= yRange; 28737 }; 28738 var getDeltas = function (coord1, coord2, xRange, yRange, scroll, origin) { 28739 var a1 = asAbsolute(coord1, scroll, origin); 28740 var a2 = asAbsolute(coord2, scroll, origin); 28741 var left = Math.abs(a1.left - a2.left); 28742 var top = Math.abs(a1.top - a2.top); 28743 return SugarPosition(left, top); 28744 }; 28745 var toStyles = function (coord, scroll, origin) { 28746 var stylesOpt = coord.fold(function (x, y) { 28747 return { 28748 position: Optional.some('absolute'), 28749 left: Optional.some(x + 'px'), 28750 top: Optional.some(y + 'px') 28751 }; 28752 }, function (x, y) { 28753 return { 28754 position: Optional.some('absolute'), 28755 left: Optional.some(x - origin.left + 'px'), 28756 top: Optional.some(y - origin.top + 'px') 28757 }; 28758 }, function (x, y) { 28759 return { 28760 position: Optional.some('fixed'), 28761 left: Optional.some(x + 'px'), 28762 top: Optional.some(y + 'px') 28763 }; 28764 }); 28765 return __assign({ 28766 right: Optional.none(), 28767 bottom: Optional.none() 28768 }, stylesOpt); 28769 }; 28770 var translate = function (coord, deltaX, deltaY) { 28771 return coord.fold(function (x, y) { 28772 return offset(x + deltaX, y + deltaY); 28773 }, function (x, y) { 28774 return absolute(x + deltaX, y + deltaY); 28775 }, function (x, y) { 28776 return fixed(x + deltaX, y + deltaY); 28777 }); 28778 }; 28779 var absorb = function (partialCoord, originalCoord, scroll, origin) { 28780 var absorbOne = function (stencil, nu) { 28781 return function (optX, optY) { 28782 var original = stencil(originalCoord, scroll, origin); 28783 return nu(optX.getOr(original.left), optY.getOr(original.top)); 28784 }; 28785 }; 28786 return partialCoord.fold(absorbOne(asOffset, offset), absorbOne(asAbsolute, absolute), absorbOne(asFixed, fixed)); 28787 }; 28788 var offset = adt.offset; 28789 var absolute = adt.absolute; 28790 var fixed = adt.fixed; 28791 28792 var parseAttrToInt = function (element, name) { 28793 var value = get$d(element, name); 28794 return isUndefined(value) ? NaN : parseInt(value, 10); 28795 }; 28796 var get = function (component, snapsInfo) { 28797 var element = component.element; 28798 var x = parseAttrToInt(element, snapsInfo.leftAttr); 28799 var y = parseAttrToInt(element, snapsInfo.topAttr); 28800 return isNaN(x) || isNaN(y) ? Optional.none() : Optional.some(SugarPosition(x, y)); 28801 }; 28802 var set = function (component, snapsInfo, pt) { 28803 var element = component.element; 28804 set$8(element, snapsInfo.leftAttr, pt.left + 'px'); 28805 set$8(element, snapsInfo.topAttr, pt.top + 'px'); 28806 }; 28807 var clear = function (component, snapsInfo) { 28808 var element = component.element; 28809 remove$7(element, snapsInfo.leftAttr); 28810 remove$7(element, snapsInfo.topAttr); 28811 }; 28812 28813 var getCoords = function (component, snapInfo, coord, delta) { 28814 return get(component, snapInfo).fold(function () { 28815 return coord; 28816 }, function (fixed$1) { 28817 return fixed(fixed$1.left + delta.left, fixed$1.top + delta.top); 28818 }); 28819 }; 28820 var moveOrSnap = function (component, snapInfo, coord, delta, scroll, origin) { 28821 var newCoord = getCoords(component, snapInfo, coord, delta); 28822 var snap = snapInfo.mustSnap ? findClosestSnap(component, snapInfo, newCoord, scroll, origin) : findSnap(component, snapInfo, newCoord, scroll, origin); 28823 var fixedCoord = asFixed(newCoord, scroll, origin); 28824 set(component, snapInfo, fixedCoord); 28825 return snap.fold(function () { 28826 return { 28827 coord: fixed(fixedCoord.left, fixedCoord.top), 28828 extra: Optional.none() 28829 }; 28830 }, function (spanned) { 28831 return { 28832 coord: spanned.output, 28833 extra: spanned.extra 28834 }; 28835 }); 28836 }; 28837 var stopDrag = function (component, snapInfo) { 28838 clear(component, snapInfo); 28839 }; 28840 var findMatchingSnap = function (snaps, newCoord, scroll, origin) { 28841 return findMap(snaps, function (snap) { 28842 var sensor = snap.sensor; 28843 var inRange = withinRange(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin); 28844 return inRange ? Optional.some({ 28845 output: absorb(snap.output, newCoord, scroll, origin), 28846 extra: snap.extra 28847 }) : Optional.none(); 28848 }); 28849 }; 28850 var findClosestSnap = function (component, snapInfo, newCoord, scroll, origin) { 28851 var snaps = snapInfo.getSnapPoints(component); 28852 var matchSnap = findMatchingSnap(snaps, newCoord, scroll, origin); 28853 return matchSnap.orThunk(function () { 28854 var bestSnap = foldl(snaps, function (acc, snap) { 28855 var sensor = snap.sensor; 28856 var deltas = getDeltas(newCoord, sensor, snap.range.left, snap.range.top, scroll, origin); 28857 return acc.deltas.fold(function () { 28858 return { 28859 deltas: Optional.some(deltas), 28860 snap: Optional.some(snap) 28861 }; 28862 }, function (bestDeltas) { 28863 var currAvg = (deltas.left + deltas.top) / 2; 28864 var bestAvg = (bestDeltas.left + bestDeltas.top) / 2; 28865 if (currAvg <= bestAvg) { 28866 return { 28867 deltas: Optional.some(deltas), 28868 snap: Optional.some(snap) 28869 }; 28870 } else { 28871 return acc; 28872 } 28873 }); 28874 }, { 28875 deltas: Optional.none(), 28876 snap: Optional.none() 28877 }); 28878 return bestSnap.snap.map(function (snap) { 28879 return { 28880 output: absorb(snap.output, newCoord, scroll, origin), 28881 extra: snap.extra 28882 }; 28883 }); 28884 }); 28885 }; 28886 var findSnap = function (component, snapInfo, newCoord, scroll, origin) { 28887 var snaps = snapInfo.getSnapPoints(component); 28888 return findMatchingSnap(snaps, newCoord, scroll, origin); 28889 }; 28890 var snapTo$1 = function (snap, scroll, origin) { 28891 return { 28892 coord: absorb(snap.output, snap.output, scroll, origin), 28893 extra: snap.extra 28894 }; 28895 }; 28896 28897 var snapTo = function (component, dragConfig, _state, snap) { 28898 var target = dragConfig.getTarget(component.element); 28899 if (dragConfig.repositionTarget) { 28900 var doc = owner$4(component.element); 28901 var scroll_1 = get$9(doc); 28902 var origin_1 = getOrigin(target); 28903 var snapPin = snapTo$1(snap, scroll_1, origin_1); 28904 var styles = toStyles(snapPin.coord, scroll_1, origin_1); 28905 setOptions(target, styles); 28906 } 28907 }; 28908 28909 var DraggingApis = /*#__PURE__*/Object.freeze({ 28910 __proto__: null, 28911 snapTo: snapTo 28912 }); 28913 28914 var initialAttribute = 'data-initial-z-index'; 28915 var resetZIndex = function (blocker) { 28916 parent(blocker.element).filter(isElement$2).each(function (root) { 28917 getOpt(root, initialAttribute).fold(function () { 28918 return remove$6(root, 'z-index'); 28919 }, function (zIndex) { 28920 return set$7(root, 'z-index', zIndex); 28921 }); 28922 remove$7(root, initialAttribute); 28923 }); 28924 }; 28925 var changeZIndex = function (blocker) { 28926 parent(blocker.element).filter(isElement$2).each(function (root) { 28927 getRaw(root, 'z-index').each(function (zindex) { 28928 set$8(root, initialAttribute, zindex); 28929 }); 28930 set$7(root, 'z-index', get$c(blocker.element, 'z-index')); 28931 }); 28932 }; 28933 var instigate = function (anyComponent, blocker) { 28934 anyComponent.getSystem().addToGui(blocker); 28935 changeZIndex(blocker); 28936 }; 28937 var discard = function (blocker) { 28938 resetZIndex(blocker); 28939 blocker.getSystem().removeFromGui(blocker); 28940 }; 28941 var createComponent = function (component, blockerClass, blockerEvents) { 28942 return component.getSystem().build(Container.sketch({ 28943 dom: { 28944 styles: { 28945 'left': '0px', 28946 'top': '0px', 28947 'width': '100%', 28948 'height': '100%', 28949 'position': 'fixed', 28950 'z-index': '1000000000000000' 28951 }, 28952 classes: [blockerClass] 28953 }, 28954 events: blockerEvents 28955 })); 28956 }; 28957 28958 var SnapSchema = optionObjOf('snaps', [ 28959 required$1('getSnapPoints'), 28960 onHandler('onSensor'), 28961 required$1('leftAttr'), 28962 required$1('topAttr'), 28963 defaulted('lazyViewport', win), 28964 defaulted('mustSnap', false) 28965 ]); 28966 28967 var schema$6 = [ 28968 defaulted('useFixed', never), 28969 required$1('blockerClass'), 28970 defaulted('getTarget', identity$1), 28971 defaulted('onDrag', noop), 28972 defaulted('repositionTarget', true), 28973 defaulted('onDrop', noop), 28974 defaultedFunction('getBounds', win), 28975 SnapSchema 28976 ]; 28977 28978 var getCurrentCoord = function (target) { 28979 return lift3(getRaw(target, 'left'), getRaw(target, 'top'), getRaw(target, 'position'), function (left, top, position) { 28980 var nu = position === 'fixed' ? fixed : offset; 28981 return nu(parseInt(left, 10), parseInt(top, 10)); 28982 }).getOrThunk(function () { 28983 var location = absolute$3(target); 28984 return absolute(location.left, location.top); 28985 }); 28986 }; 28987 var clampCoords = function (component, coords, scroll, origin, startData) { 28988 var bounds = startData.bounds; 28989 var absoluteCoord = asAbsolute(coords, scroll, origin); 28990 var newX = clamp$1(absoluteCoord.left, bounds.x, bounds.x + bounds.width - startData.width); 28991 var newY = clamp$1(absoluteCoord.top, bounds.y, bounds.y + bounds.height - startData.height); 28992 var newCoords = absolute(newX, newY); 28993 return coords.fold(function () { 28994 var offset$1 = asOffset(newCoords, scroll, origin); 28995 return offset(offset$1.left, offset$1.top); 28996 }, constant$1(newCoords), function () { 28997 var fixed$1 = asFixed(newCoords, scroll, origin); 28998 return fixed(fixed$1.left, fixed$1.top); 28999 }); 29000 }; 29001 var calcNewCoord = function (component, optSnaps, currentCoord, scroll, origin, delta, startData) { 29002 var newCoord = optSnaps.fold(function () { 29003 var translated = translate(currentCoord, delta.left, delta.top); 29004 var fixedCoord = asFixed(translated, scroll, origin); 29005 return fixed(fixedCoord.left, fixedCoord.top); 29006 }, function (snapInfo) { 29007 var snapping = moveOrSnap(component, snapInfo, currentCoord, delta, scroll, origin); 29008 snapping.extra.each(function (extra) { 29009 snapInfo.onSensor(component, extra); 29010 }); 29011 return snapping.coord; 29012 }); 29013 return clampCoords(component, newCoord, scroll, origin, startData); 29014 }; 29015 var dragBy = function (component, dragConfig, startData, delta) { 29016 var target = dragConfig.getTarget(component.element); 29017 if (dragConfig.repositionTarget) { 29018 var doc = owner$4(component.element); 29019 var scroll_1 = get$9(doc); 29020 var origin_1 = getOrigin(target); 29021 var currentCoord = getCurrentCoord(target); 29022 var newCoord = calcNewCoord(component, dragConfig.snaps, currentCoord, scroll_1, origin_1, delta, startData); 29023 var styles = toStyles(newCoord, scroll_1, origin_1); 29024 setOptions(target, styles); 29025 } 29026 dragConfig.onDrag(component, target, delta); 29027 }; 29028 29029 var calcStartData = function (dragConfig, comp) { 29030 return { 29031 bounds: dragConfig.getBounds(), 29032 height: getOuter$2(comp.element), 29033 width: getOuter$1(comp.element) 29034 }; 29035 }; 29036 var move = function (component, dragConfig, dragState, dragMode, event) { 29037 var delta = dragState.update(dragMode, event); 29038 var dragStartData = dragState.getStartData().getOrThunk(function () { 29039 return calcStartData(dragConfig, component); 29040 }); 29041 delta.each(function (dlt) { 29042 dragBy(component, dragConfig, dragStartData, dlt); 29043 }); 29044 }; 29045 var stop = function (component, blocker, dragConfig, dragState) { 29046 blocker.each(discard); 29047 dragConfig.snaps.each(function (snapInfo) { 29048 stopDrag(component, snapInfo); 29049 }); 29050 var target = dragConfig.getTarget(component.element); 29051 dragState.reset(); 29052 dragConfig.onDrop(component, target); 29053 }; 29054 var handlers = function (events) { 29055 return function (dragConfig, dragState) { 29056 var updateStartState = function (comp) { 29057 dragState.setStartData(calcStartData(dragConfig, comp)); 29058 }; 29059 return derive$2(__spreadArray([run$1(windowScroll(), function (comp) { 29060 dragState.getStartData().each(function () { 29061 return updateStartState(comp); 29062 }); 29063 })], events(dragConfig, dragState, updateStartState), true)); 29064 }; 29065 }; 29066 29067 var init$2 = function (dragApi) { 29068 return derive$2([ 29069 run$1(mousedown(), dragApi.forceDrop), 29070 run$1(mouseup(), dragApi.drop), 29071 run$1(mousemove(), function (comp, simulatedEvent) { 29072 dragApi.move(simulatedEvent.event); 29073 }), 29074 run$1(mouseout(), dragApi.delayDrop) 29075 ]); 29076 }; 29077 29078 var getData$1 = function (event) { 29079 return Optional.from(SugarPosition(event.x, event.y)); 29080 }; 29081 var getDelta$1 = function (old, nu) { 29082 return SugarPosition(nu.left - old.left, nu.top - old.top); 29083 }; 29084 29085 var MouseData = /*#__PURE__*/Object.freeze({ 29086 __proto__: null, 29087 getData: getData$1, 29088 getDelta: getDelta$1 29089 }); 29090 29091 var events$2 = function (dragConfig, dragState, updateStartState) { 29092 return [run$1(mousedown(), function (component, simulatedEvent) { 29093 var raw = simulatedEvent.event.raw; 29094 if (raw.button !== 0) { 29095 return; 29096 } 29097 simulatedEvent.stop(); 29098 var stop$1 = function () { 29099 return stop(component, Optional.some(blocker), dragConfig, dragState); 29100 }; 29101 var delayDrop = DelayedFunction(stop$1, 200); 29102 var dragApi = { 29103 drop: stop$1, 29104 delayDrop: delayDrop.schedule, 29105 forceDrop: stop$1, 29106 move: function (event) { 29107 delayDrop.cancel(); 29108 move(component, dragConfig, dragState, MouseData, event); 29109 } 29110 }; 29111 var blocker = createComponent(component, dragConfig.blockerClass, init$2(dragApi)); 29112 var start = function () { 29113 updateStartState(component); 29114 instigate(component, blocker); 29115 }; 29116 start(); 29117 })]; 29118 }; 29119 var schema$5 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events$2) })], false); 29120 29121 var init$1 = function (dragApi) { 29122 return derive$2([ 29123 run$1(touchstart(), dragApi.forceDrop), 29124 run$1(touchend(), dragApi.drop), 29125 run$1(touchcancel(), dragApi.drop), 29126 run$1(touchmove(), function (comp, simulatedEvent) { 29127 dragApi.move(simulatedEvent.event); 29128 }) 29129 ]); 29130 }; 29131 29132 var getDataFrom = function (touches) { 29133 var touch = touches[0]; 29134 return Optional.some(SugarPosition(touch.clientX, touch.clientY)); 29135 }; 29136 var getData = function (event) { 29137 var raw = event.raw; 29138 var touches = raw.touches; 29139 return touches.length === 1 ? getDataFrom(touches) : Optional.none(); 29140 }; 29141 var getDelta = function (old, nu) { 29142 return SugarPosition(nu.left - old.left, nu.top - old.top); 29143 }; 29144 29145 var TouchData = /*#__PURE__*/Object.freeze({ 29146 __proto__: null, 29147 getData: getData, 29148 getDelta: getDelta 29149 }); 29150 29151 var events$1 = function (dragConfig, dragState, updateStartState) { 29152 var blockerSingleton = value$1(); 29153 var stopBlocking = function (component) { 29154 stop(component, blockerSingleton.get(), dragConfig, dragState); 29155 blockerSingleton.clear(); 29156 }; 29157 return [ 29158 run$1(touchstart(), function (component, simulatedEvent) { 29159 simulatedEvent.stop(); 29160 var stop = function () { 29161 return stopBlocking(component); 29162 }; 29163 var dragApi = { 29164 drop: stop, 29165 delayDrop: noop, 29166 forceDrop: stop, 29167 move: function (event) { 29168 move(component, dragConfig, dragState, TouchData, event); 29169 } 29170 }; 29171 var blocker = createComponent(component, dragConfig.blockerClass, init$1(dragApi)); 29172 blockerSingleton.set(blocker); 29173 var start = function () { 29174 updateStartState(component); 29175 instigate(component, blocker); 29176 }; 29177 start(); 29178 }), 29179 run$1(touchmove(), function (component, simulatedEvent) { 29180 simulatedEvent.stop(); 29181 move(component, dragConfig, dragState, TouchData, simulatedEvent.event); 29182 }), 29183 run$1(touchend(), function (component, simulatedEvent) { 29184 simulatedEvent.stop(); 29185 stopBlocking(component); 29186 }), 29187 run$1(touchcancel(), stopBlocking) 29188 ]; 29189 }; 29190 var schema$4 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events$1) })], false); 29191 29192 var events = function (dragConfig, dragState, updateStartState) { 29193 return __spreadArray(__spreadArray([], events$2(dragConfig, dragState, updateStartState), true), events$1(dragConfig, dragState, updateStartState), true); 29194 }; 29195 var schema$3 = __spreadArray(__spreadArray([], schema$6, true), [output$1('dragger', { handlers: handlers(events) })], false); 29196 29197 var mouse = schema$5; 29198 var touch = schema$4; 29199 var mouseOrTouch = schema$3; 29200 29201 var DraggingBranches = /*#__PURE__*/Object.freeze({ 29202 __proto__: null, 29203 mouse: mouse, 29204 touch: touch, 29205 mouseOrTouch: mouseOrTouch 29206 }); 29207 29208 var init = function () { 29209 var previous = Optional.none(); 29210 var startData = Optional.none(); 29211 var reset = function () { 29212 previous = Optional.none(); 29213 startData = Optional.none(); 29214 }; 29215 var calculateDelta = function (mode, nu) { 29216 var result = previous.map(function (old) { 29217 return mode.getDelta(old, nu); 29218 }); 29219 previous = Optional.some(nu); 29220 return result; 29221 }; 29222 var update = function (mode, dragEvent) { 29223 return mode.getData(dragEvent).bind(function (nuData) { 29224 return calculateDelta(mode, nuData); 29225 }); 29226 }; 29227 var setStartData = function (data) { 29228 startData = Optional.some(data); 29229 }; 29230 var getStartData = function () { 29231 return startData; 29232 }; 29233 var readState = constant$1({}); 29234 return nu$8({ 29235 readState: readState, 29236 reset: reset, 29237 update: update, 29238 getStartData: getStartData, 29239 setStartData: setStartData 29240 }); 29241 }; 29242 29243 var DragState = /*#__PURE__*/Object.freeze({ 29244 __proto__: null, 29245 init: init 29246 }); 29247 29248 var Dragging = createModes({ 29249 branchKey: 'mode', 29250 branches: DraggingBranches, 29251 name: 'dragging', 29252 active: { 29253 events: function (dragConfig, dragState) { 29254 var dragger = dragConfig.dragger; 29255 return dragger.handlers(dragConfig, dragState); 29256 } 29257 }, 29258 extra: { 29259 snap: function (sConfig) { 29260 return { 29261 sensor: sConfig.sensor, 29262 range: sConfig.range, 29263 output: sConfig.output, 29264 extra: Optional.from(sConfig.extra) 29265 }; 29266 } 29267 }, 29268 state: DragState, 29269 apis: DraggingApis 29270 }); 29271 29272 var snapWidth = 40; 29273 var snapOffset = snapWidth / 2; 29274 var calcSnap = function (selectorOpt, td, x, y, width, height) { 29275 return selectorOpt.fold(function () { 29276 return Dragging.snap({ 29277 sensor: absolute(x - snapOffset, y - snapOffset), 29278 range: SugarPosition(width, height), 29279 output: absolute(Optional.some(x), Optional.some(y)), 29280 extra: { td: td } 29281 }); 29282 }, function (selectorHandle) { 29283 var sensorLeft = x - snapOffset; 29284 var sensorTop = y - snapOffset; 29285 var sensorWidth = snapWidth; 29286 var sensorHeight = snapWidth; 29287 var rect = selectorHandle.element.dom.getBoundingClientRect(); 29288 return Dragging.snap({ 29289 sensor: absolute(sensorLeft, sensorTop), 29290 range: SugarPosition(sensorWidth, sensorHeight), 29291 output: absolute(Optional.some(x - rect.width / 2), Optional.some(y - rect.height / 2)), 29292 extra: { td: td } 29293 }); 29294 }); 29295 }; 29296 var getSnapsConfig = function (getSnapPoints, cell, onChange) { 29297 var isSameCell = function (cellOpt, td) { 29298 return cellOpt.exists(function (currentTd) { 29299 return eq(currentTd, td); 29300 }); 29301 }; 29302 return { 29303 getSnapPoints: getSnapPoints, 29304 leftAttr: 'data-drag-left', 29305 topAttr: 'data-drag-top', 29306 onSensor: function (component, extra) { 29307 var td = extra.td; 29308 if (!isSameCell(cell.get(), td)) { 29309 cell.set(td); 29310 onChange(td); 29311 } 29312 }, 29313 mustSnap: true 29314 }; 29315 }; 29316 var createSelector = function (snaps) { 29317 return record(Button.sketch({ 29318 dom: { 29319 tag: 'div', 29320 classes: ['tox-selector'] 29321 }, 29322 buttonBehaviours: derive$1([ 29323 Dragging.config({ 29324 mode: 'mouseOrTouch', 29325 blockerClass: 'blocker', 29326 snaps: snaps 29327 }), 29328 Unselecting.config({}) 29329 ]), 29330 eventOrder: { 29331 mousedown: [ 29332 'dragging', 29333 'alloy.base.behaviour' 29334 ], 29335 touchstart: [ 29336 'dragging', 29337 'alloy.base.behaviour' 29338 ] 29339 } 29340 })); 29341 }; 29342 var setup$4 = function (editor, sink) { 29343 var tlTds = Cell([]); 29344 var brTds = Cell([]); 29345 var isVisible = Cell(false); 29346 var startCell = value$1(); 29347 var finishCell = value$1(); 29348 var getTopLeftSnap = function (td) { 29349 var box = absolute$2(td); 29350 return calcSnap(memTopLeft.getOpt(sink), td, box.x, box.y, box.width, box.height); 29351 }; 29352 var getTopLeftSnaps = function () { 29353 return map$2(tlTds.get(), function (td) { 29354 return getTopLeftSnap(td); 29355 }); 29356 }; 29357 var getBottomRightSnap = function (td) { 29358 var box = absolute$2(td); 29359 return calcSnap(memBottomRight.getOpt(sink), td, box.right, box.bottom, box.width, box.height); 29360 }; 29361 var getBottomRightSnaps = function () { 29362 return map$2(brTds.get(), function (td) { 29363 return getBottomRightSnap(td); 29364 }); 29365 }; 29366 var topLeftSnaps = getSnapsConfig(getTopLeftSnaps, startCell, function (start) { 29367 finishCell.get().each(function (finish) { 29368 editor.fire('TableSelectorChange', { 29369 start: start, 29370 finish: finish 29371 }); 29372 }); 29373 }); 29374 var bottomRightSnaps = getSnapsConfig(getBottomRightSnaps, finishCell, function (finish) { 29375 startCell.get().each(function (start) { 29376 editor.fire('TableSelectorChange', { 29377 start: start, 29378 finish: finish 29379 }); 29380 }); 29381 }); 29382 var memTopLeft = createSelector(topLeftSnaps); 29383 var memBottomRight = createSelector(bottomRightSnaps); 29384 var topLeft = build$1(memTopLeft.asSpec()); 29385 var bottomRight = build$1(memBottomRight.asSpec()); 29386 var showOrHideHandle = function (selector, cell, isAbove, isBelow) { 29387 var cellRect = cell.dom.getBoundingClientRect(); 29388 remove$6(selector.element, 'display'); 29389 var viewportHeight = defaultView(SugarElement.fromDom(editor.getBody())).dom.innerHeight; 29390 var aboveViewport = isAbove(cellRect); 29391 var belowViewport = isBelow(cellRect, viewportHeight); 29392 if (aboveViewport || belowViewport) { 29393 set$7(selector.element, 'display', 'none'); 29394 } 29395 }; 29396 var snapTo = function (selector, cell, getSnapConfig, pos) { 29397 var snap = getSnapConfig(cell); 29398 Dragging.snapTo(selector, snap); 29399 var isAbove = function (rect) { 29400 return rect[pos] < 0; 29401 }; 29402 var isBelow = function (rect, viewportHeight) { 29403 return rect[pos] > viewportHeight; 29404 }; 29405 showOrHideHandle(selector, cell, isAbove, isBelow); 29406 }; 29407 var snapTopLeft = function (cell) { 29408 return snapTo(topLeft, cell, getTopLeftSnap, 'top'); 29409 }; 29410 var snapLastTopLeft = function () { 29411 return startCell.get().each(snapTopLeft); 29412 }; 29413 var snapBottomRight = function (cell) { 29414 return snapTo(bottomRight, cell, getBottomRightSnap, 'bottom'); 29415 }; 29416 var snapLastBottomRight = function () { 29417 return finishCell.get().each(snapBottomRight); 29418 }; 29419 if (detect$1().deviceType.isTouch()) { 29420 editor.on('TableSelectionChange', function (e) { 29421 if (!isVisible.get()) { 29422 attach(sink, topLeft); 29423 attach(sink, bottomRight); 29424 isVisible.set(true); 29425 } 29426 startCell.set(e.start); 29427 finishCell.set(e.finish); 29428 e.otherCells.each(function (otherCells) { 29429 tlTds.set(otherCells.upOrLeftCells); 29430 brTds.set(otherCells.downOrRightCells); 29431 snapTopLeft(e.start); 29432 snapBottomRight(e.finish); 29433 }); 29434 }); 29435 editor.on('ResizeEditor ResizeWindow ScrollContent', function () { 29436 snapLastTopLeft(); 29437 snapLastBottomRight(); 29438 }); 29439 editor.on('TableSelectionClear', function () { 29440 if (isVisible.get()) { 29441 detach(topLeft); 29442 detach(bottomRight); 29443 isVisible.set(false); 29444 } 29445 startCell.clear(); 29446 finishCell.clear(); 29447 }); 29448 } 29449 }; 29450 29451 var isHidden = function (elm) { 29452 if (elm.nodeType === 1) { 29453 if (elm.nodeName === 'BR' || !!elm.getAttribute('data-mce-bogus')) { 29454 return true; 29455 } 29456 if (elm.getAttribute('data-mce-type') === 'bookmark') { 29457 return true; 29458 } 29459 } 29460 return false; 29461 }; 29462 var renderElementPath = function (editor, settings, providersBackstage) { 29463 if (!settings.delimiter) { 29464 settings.delimiter = '\xBB'; 29465 } 29466 var getDataPath = function (data) { 29467 var parts = data || []; 29468 var newPathElements = map$2(parts, function (part, index) { 29469 return Button.sketch({ 29470 dom: { 29471 tag: 'div', 29472 classes: ['tox-statusbar__path-item'], 29473 attributes: { 29474 'role': 'button', 29475 'data-index': index, 29476 'tab-index': -1, 29477 'aria-level': index + 1 29478 }, 29479 innerHtml: part.name 29480 }, 29481 action: function (_btn) { 29482 editor.focus(); 29483 editor.selection.select(part.element); 29484 editor.nodeChanged(); 29485 }, 29486 buttonBehaviours: derive$1([ 29487 DisablingConfigs.button(providersBackstage.isDisabled), 29488 receivingConfig() 29489 ]) 29490 }); 29491 }); 29492 var divider = { 29493 dom: { 29494 tag: 'div', 29495 classes: ['tox-statusbar__path-divider'], 29496 attributes: { 'aria-hidden': true }, 29497 innerHtml: ' ' + settings.delimiter + ' ' 29498 } 29499 }; 29500 return foldl(newPathElements.slice(1), function (acc, element) { 29501 var newAcc = acc; 29502 newAcc.push(divider); 29503 newAcc.push(element); 29504 return newAcc; 29505 }, [newPathElements[0]]); 29506 }; 29507 var updatePath = function (parents) { 29508 var newPath = []; 29509 var i = parents.length; 29510 while (i-- > 0) { 29511 var parent_1 = parents[i]; 29512 if (parent_1.nodeType === 1 && !isHidden(parent_1)) { 29513 var args = editor.fire('ResolveName', { 29514 name: parent_1.nodeName.toLowerCase(), 29515 target: parent_1 29516 }); 29517 if (!args.isDefaultPrevented()) { 29518 newPath.push({ 29519 name: args.name, 29520 element: parent_1 29521 }); 29522 } 29523 if (args.isPropagationStopped()) { 29524 break; 29525 } 29526 } 29527 } 29528 return newPath; 29529 }; 29530 return { 29531 dom: { 29532 tag: 'div', 29533 classes: ['tox-statusbar__path'], 29534 attributes: { role: 'navigation' } 29535 }, 29536 behaviours: derive$1([ 29537 Keying.config({ 29538 mode: 'flow', 29539 selector: 'div[role=button]' 29540 }), 29541 Disabling.config({ disabled: providersBackstage.isDisabled }), 29542 receivingConfig(), 29543 Tabstopping.config({}), 29544 Replacing.config({}), 29545 config('elementPathEvents', [runOnAttached(function (comp, _e) { 29546 editor.shortcuts.add('alt+F11', 'focus statusbar elementpath', function () { 29547 return Keying.focusIn(comp); 29548 }); 29549 editor.on('NodeChange', function (e) { 29550 var newPath = updatePath(e.parents); 29551 if (newPath.length > 0) { 29552 Replacing.set(comp, getDataPath(newPath)); 29553 } else { 29554 Replacing.set(comp, []); 29555 } 29556 }); 29557 })]) 29558 ]), 29559 components: [] 29560 }; 29561 }; 29562 29563 var ResizeTypes; 29564 (function (ResizeTypes) { 29565 ResizeTypes[ResizeTypes['None'] = 0] = 'None'; 29566 ResizeTypes[ResizeTypes['Both'] = 1] = 'Both'; 29567 ResizeTypes[ResizeTypes['Vertical'] = 2] = 'Vertical'; 29568 }(ResizeTypes || (ResizeTypes = {}))); 29569 var getDimensions = function (editor, deltas, resizeType, originalHeight, originalWidth) { 29570 var dimensions = {}; 29571 dimensions.height = calcCappedSize(originalHeight + deltas.top, getMinHeightSetting(editor), getMaxHeightSetting(editor)); 29572 if (resizeType === ResizeTypes.Both) { 29573 dimensions.width = calcCappedSize(originalWidth + deltas.left, getMinWidthSetting(editor), getMaxWidthSetting(editor)); 29574 } 29575 return dimensions; 29576 }; 29577 var resize = function (editor, deltas, resizeType) { 29578 var container = SugarElement.fromDom(editor.getContainer()); 29579 var dimensions = getDimensions(editor, deltas, resizeType, get$b(container), get$a(container)); 29580 each(dimensions, function (val, dim) { 29581 return set$7(container, dim, numToPx(val)); 29582 }); 29583 fireResizeEditor(editor); 29584 }; 29585 29586 var getResizeType = function (editor) { 29587 var fallback = !editor.hasPlugin('autoresize'); 29588 var resize = editor.getParam('resize', fallback); 29589 if (resize === false) { 29590 return ResizeTypes.None; 29591 } else if (resize === 'both') { 29592 return ResizeTypes.Both; 29593 } else { 29594 return ResizeTypes.Vertical; 29595 } 29596 }; 29597 var keyboardHandler = function (editor, resizeType, x, y) { 29598 var scale = 20; 29599 var delta = SugarPosition(x * scale, y * scale); 29600 resize(editor, delta, resizeType); 29601 return Optional.some(true); 29602 }; 29603 var renderResizeHandler = function (editor, providersBackstage) { 29604 var resizeType = getResizeType(editor); 29605 if (resizeType === ResizeTypes.None) { 29606 return Optional.none(); 29607 } 29608 return Optional.some(render$3('resize-handle', { 29609 tag: 'div', 29610 classes: ['tox-statusbar__resize-handle'], 29611 attributes: { title: providersBackstage.translate('Resize') }, 29612 behaviours: [ 29613 Dragging.config({ 29614 mode: 'mouse', 29615 repositionTarget: false, 29616 onDrag: function (_comp, _target, delta) { 29617 return resize(editor, delta, resizeType); 29618 }, 29619 blockerClass: 'tox-blocker' 29620 }), 29621 Keying.config({ 29622 mode: 'special', 29623 onLeft: function () { 29624 return keyboardHandler(editor, resizeType, -1, 0); 29625 }, 29626 onRight: function () { 29627 return keyboardHandler(editor, resizeType, 1, 0); 29628 }, 29629 onUp: function () { 29630 return keyboardHandler(editor, resizeType, 0, -1); 29631 }, 29632 onDown: function () { 29633 return keyboardHandler(editor, resizeType, 0, 1); 29634 } 29635 }), 29636 Tabstopping.config({}), 29637 Focusing.config({}) 29638 ] 29639 }, providersBackstage.icons)); 29640 }; 29641 29642 var renderWordCount = function (editor, providersBackstage) { 29643 var _a; 29644 var replaceCountText = function (comp, count, mode) { 29645 return Replacing.set(comp, [text(providersBackstage.translate([ 29646 '{0} ' + mode, 29647 count[mode] 29648 ]))]); 29649 }; 29650 return Button.sketch({ 29651 dom: { 29652 tag: 'button', 29653 classes: ['tox-statusbar__wordcount'] 29654 }, 29655 components: [], 29656 buttonBehaviours: derive$1([ 29657 DisablingConfigs.button(providersBackstage.isDisabled), 29658 receivingConfig(), 29659 Tabstopping.config({}), 29660 Replacing.config({}), 29661 Representing.config({ 29662 store: { 29663 mode: 'memory', 29664 initialValue: { 29665 mode: 'words', 29666 count: { 29667 words: 0, 29668 characters: 0 29669 } 29670 } 29671 } 29672 }), 29673 config('wordcount-events', [ 29674 runOnExecute$1(function (comp) { 29675 var currentVal = Representing.getValue(comp); 29676 var newMode = currentVal.mode === 'words' ? 'characters' : 'words'; 29677 Representing.setValue(comp, { 29678 mode: newMode, 29679 count: currentVal.count 29680 }); 29681 replaceCountText(comp, currentVal.count, newMode); 29682 }), 29683 runOnAttached(function (comp) { 29684 editor.on('wordCountUpdate', function (e) { 29685 var mode = Representing.getValue(comp).mode; 29686 Representing.setValue(comp, { 29687 mode: mode, 29688 count: e.wordCount 29689 }); 29690 replaceCountText(comp, e.wordCount, mode); 29691 }); 29692 }) 29693 ]) 29694 ]), 29695 eventOrder: (_a = {}, _a[execute$5()] = [ 29696 'disabling', 29697 'alloy.base.behaviour', 29698 'wordcount-events' 29699 ], _a) 29700 }); 29701 }; 29702 29703 var renderStatusbar = function (editor, providersBackstage) { 29704 var renderBranding = function () { 29705 var label = global$e.translate([ 29706 'Powered by {0}', 29707 'Tiny' 29708 ]); 29709 var linkHtml = '<a href="https://www.tiny.cloud/?utm_campaign=editor_referral&utm_medium=poweredby&utm_source=tinymce&utm_content=v5" rel="noopener" target="_blank" tabindex="-1" aria-label="' + label + '">' + label + '</a>'; 29710 return { 29711 dom: { 29712 tag: 'span', 29713 classes: ['tox-statusbar__branding'], 29714 innerHtml: linkHtml 29715 } 29716 }; 29717 }; 29718 var getTextComponents = function () { 29719 var components = []; 29720 if (editor.getParam('elementpath', true, 'boolean')) { 29721 components.push(renderElementPath(editor, {}, providersBackstage)); 29722 } 29723 if (editor.hasPlugin('wordcount')) { 29724 components.push(renderWordCount(editor, providersBackstage)); 29725 } 29726 if (editor.getParam('branding', true, 'boolean')) { 29727 components.push(renderBranding()); 29728 } 29729 if (components.length > 0) { 29730 return [{ 29731 dom: { 29732 tag: 'div', 29733 classes: ['tox-statusbar__text-container'] 29734 }, 29735 components: components 29736 }]; 29737 } 29738 return []; 29739 }; 29740 var getComponents = function () { 29741 var components = getTextComponents(); 29742 var resizeHandler = renderResizeHandler(editor, providersBackstage); 29743 return components.concat(resizeHandler.toArray()); 29744 }; 29745 return { 29746 dom: { 29747 tag: 'div', 29748 classes: ['tox-statusbar'] 29749 }, 29750 components: getComponents() 29751 }; 29752 }; 29753 29754 var setup$3 = function (editor) { 29755 var _a; 29756 var isInline = editor.inline; 29757 var mode = isInline ? Inline : Iframe; 29758 var header = isStickyToolbar(editor) ? StickyHeader : StaticHeader; 29759 var lazyOuterContainer = Optional.none(); 29760 var platform = detect$1(); 29761 var isIE = platform.browser.isIE(); 29762 var platformClasses = isIE ? ['tox-platform-ie'] : []; 29763 var isTouch = platform.deviceType.isTouch(); 29764 var touchPlatformClass = 'tox-platform-touch'; 29765 var deviceClasses = isTouch ? [touchPlatformClass] : []; 29766 var isToolbarBottom = isToolbarLocationBottom(editor); 29767 var uiContainer = getUiContainer(editor); 29768 var dirAttributes = global$e.isRtl() ? { attributes: { dir: 'rtl' } } : {}; 29769 var verticalDirAttributes = { attributes: (_a = {}, _a[Attribute] = isToolbarBottom ? AttributeValue.BottomToTop : AttributeValue.TopToBottom, _a) }; 29770 var lazyHeader = function () { 29771 return lazyOuterContainer.bind(OuterContainer.getHeader); 29772 }; 29773 var isHeaderDocked = function () { 29774 return header.isDocked(lazyHeader); 29775 }; 29776 var resizeUiMothership = function () { 29777 set$7(uiMothership.element, 'width', document.body.clientWidth + 'px'); 29778 }; 29779 var makeSinkDefinition = function () { 29780 var isGridUiContainer = eq(body(), uiContainer) && get$c(uiContainer, 'display') === 'grid'; 29781 var sinkSpec = { 29782 dom: __assign({ 29783 tag: 'div', 29784 classes: [ 29785 'tox', 29786 'tox-silver-sink', 29787 'tox-tinymce-aux' 29788 ].concat(platformClasses).concat(deviceClasses) 29789 }, dirAttributes), 29790 behaviours: derive$1([Positioning.config({ 29791 useFixed: function () { 29792 return isHeaderDocked(); 29793 } 29794 })]) 29795 }; 29796 var reactiveWidthSpec = { 29797 dom: { styles: { width: document.body.clientWidth + 'px' } }, 29798 events: derive$2([run$1(windowResize(), resizeUiMothership)]) 29799 }; 29800 return deepMerge(sinkSpec, isGridUiContainer ? reactiveWidthSpec : {}); 29801 }; 29802 var sink = build$1(makeSinkDefinition()); 29803 var lazySink = function () { 29804 return Result.value(sink); 29805 }; 29806 var memAnchorBar = record({ 29807 dom: { 29808 tag: 'div', 29809 classes: ['tox-anchorbar'] 29810 } 29811 }); 29812 var lazyAnchorBar = function () { 29813 return lazyOuterContainer.bind(function (container) { 29814 return memAnchorBar.getOpt(container); 29815 }).getOrDie('Could not find a anchor bar element'); 29816 }; 29817 var lazyToolbar = function () { 29818 return lazyOuterContainer.bind(function (container) { 29819 return OuterContainer.getToolbar(container); 29820 }).getOrDie('Could not find more toolbar element'); 29821 }; 29822 var lazyThrobber = function () { 29823 return lazyOuterContainer.bind(function (container) { 29824 return OuterContainer.getThrobber(container); 29825 }).getOrDie('Could not find throbber element'); 29826 }; 29827 var backstage = init$7(sink, editor, lazyAnchorBar); 29828 var partMenubar = OuterContainer.parts.menubar({ 29829 dom: { 29830 tag: 'div', 29831 classes: ['tox-menubar'] 29832 }, 29833 backstage: backstage, 29834 onEscape: function () { 29835 editor.focus(); 29836 } 29837 }); 29838 var toolbarMode = getToolbarMode(editor); 29839 var partToolbar = OuterContainer.parts.toolbar(__assign({ 29840 dom: { 29841 tag: 'div', 29842 classes: ['tox-toolbar'] 29843 }, 29844 getSink: lazySink, 29845 providers: backstage.shared.providers, 29846 onEscape: function () { 29847 editor.focus(); 29848 }, 29849 type: toolbarMode, 29850 lazyToolbar: lazyToolbar, 29851 lazyHeader: function () { 29852 return lazyHeader().getOrDie('Could not find header element'); 29853 } 29854 }, verticalDirAttributes)); 29855 var partMultipleToolbar = OuterContainer.parts['multiple-toolbar']({ 29856 dom: { 29857 tag: 'div', 29858 classes: ['tox-toolbar-overlord'] 29859 }, 29860 providers: backstage.shared.providers, 29861 onEscape: function () { 29862 editor.focus(); 29863 }, 29864 type: toolbarMode 29865 }); 29866 var partSocket = OuterContainer.parts.socket({ 29867 dom: { 29868 tag: 'div', 29869 classes: ['tox-edit-area'] 29870 } 29871 }); 29872 var partSidebar = OuterContainer.parts.sidebar({ 29873 dom: { 29874 tag: 'div', 29875 classes: ['tox-sidebar'] 29876 } 29877 }); 29878 var partThrobber = OuterContainer.parts.throbber({ 29879 dom: { 29880 tag: 'div', 29881 classes: ['tox-throbber'] 29882 }, 29883 backstage: backstage 29884 }); 29885 var sb = editor.getParam('statusbar', true, 'boolean'); 29886 var statusbar = sb && !isInline ? Optional.some(renderStatusbar(editor, backstage.shared.providers)) : Optional.none(); 29887 var socketSidebarContainer = { 29888 dom: { 29889 tag: 'div', 29890 classes: ['tox-sidebar-wrap'] 29891 }, 29892 components: [ 29893 partSocket, 29894 partSidebar 29895 ] 29896 }; 29897 var hasMultipleToolbar = isMultipleToolbars(editor); 29898 var hasToolbar = isToolbarEnabled(editor); 29899 var hasMenubar = isMenubarEnabled(editor); 29900 var getPartToolbar = function () { 29901 if (hasMultipleToolbar) { 29902 return [partMultipleToolbar]; 29903 } else if (hasToolbar) { 29904 return [partToolbar]; 29905 } else { 29906 return []; 29907 } 29908 }; 29909 var partHeader = OuterContainer.parts.header({ 29910 dom: __assign({ 29911 tag: 'div', 29912 classes: ['tox-editor-header'] 29913 }, verticalDirAttributes), 29914 components: flatten([ 29915 hasMenubar ? [partMenubar] : [], 29916 getPartToolbar(), 29917 useFixedContainer(editor) ? [] : [memAnchorBar.asSpec()] 29918 ]), 29919 sticky: isStickyToolbar(editor), 29920 editor: editor, 29921 sharedBackstage: backstage.shared 29922 }); 29923 var editorComponents = flatten([ 29924 isToolbarBottom ? [] : [partHeader], 29925 isInline ? [] : [socketSidebarContainer], 29926 isToolbarBottom ? [partHeader] : [] 29927 ]); 29928 var editorContainer = { 29929 dom: { 29930 tag: 'div', 29931 classes: ['tox-editor-container'] 29932 }, 29933 components: editorComponents 29934 }; 29935 var containerComponents = flatten([ 29936 [editorContainer], 29937 isInline ? [] : statusbar.toArray(), 29938 [partThrobber] 29939 ]); 29940 var isHidden = isDistractionFree(editor); 29941 var attributes = __assign(__assign({ role: 'application' }, global$e.isRtl() ? { dir: 'rtl' } : {}), isHidden ? { 'aria-hidden': 'true' } : {}); 29942 var outerContainer = build$1(OuterContainer.sketch({ 29943 dom: { 29944 tag: 'div', 29945 classes: [ 29946 'tox', 29947 'tox-tinymce' 29948 ].concat(isInline ? ['tox-tinymce-inline'] : []).concat(isToolbarBottom ? ['tox-tinymce--toolbar-bottom'] : []).concat(deviceClasses).concat(platformClasses), 29949 styles: __assign({ visibility: 'hidden' }, isHidden ? { 29950 opacity: '0', 29951 border: '0' 29952 } : {}), 29953 attributes: attributes 29954 }, 29955 components: containerComponents, 29956 behaviours: derive$1([ 29957 receivingConfig(), 29958 Disabling.config({ disableClass: 'tox-tinymce--disabled' }), 29959 Keying.config({ 29960 mode: 'cyclic', 29961 selector: '.tox-menubar, .tox-toolbar, .tox-toolbar__primary, .tox-toolbar__overflow--open, .tox-sidebar__overflow--open, .tox-statusbar__path, .tox-statusbar__wordcount, .tox-statusbar__branding a, .tox-statusbar__resize-handle' 29962 }) 29963 ]) 29964 })); 29965 lazyOuterContainer = Optional.some(outerContainer); 29966 editor.shortcuts.add('alt+F9', 'focus menubar', function () { 29967 OuterContainer.focusMenubar(outerContainer); 29968 }); 29969 editor.shortcuts.add('alt+F10', 'focus toolbar', function () { 29970 OuterContainer.focusToolbar(outerContainer); 29971 }); 29972 editor.addCommand('ToggleToolbarDrawer', function () { 29973 OuterContainer.toggleToolbarDrawer(outerContainer); 29974 }); 29975 editor.addQueryStateHandler('ToggleToolbarDrawer', function () { 29976 return OuterContainer.isToolbarDrawerToggled(outerContainer); 29977 }); 29978 var mothership = takeover(outerContainer); 29979 var uiMothership = takeover(sink); 29980 setup$b(editor, mothership, uiMothership); 29981 var getUi = function () { 29982 var channels = { 29983 broadcastAll: uiMothership.broadcast, 29984 broadcastOn: uiMothership.broadcastOn, 29985 register: noop 29986 }; 29987 return { channels: channels }; 29988 }; 29989 var setEditorSize = function () { 29990 var parsedHeight = numToPx(getHeightWithFallback(editor)); 29991 var parsedWidth = numToPx(getWidthWithFallback(editor)); 29992 if (!editor.inline) { 29993 if (isValidValue('div', 'width', parsedWidth)) { 29994 set$7(outerContainer.element, 'width', parsedWidth); 29995 } 29996 if (isValidValue('div', 'height', parsedHeight)) { 29997 set$7(outerContainer.element, 'height', parsedHeight); 29998 } else { 29999 set$7(outerContainer.element, 'height', '200px'); 30000 } 30001 } 30002 return parsedHeight; 30003 }; 30004 var renderUI = function () { 30005 header.setup(editor, backstage.shared, lazyHeader); 30006 setup$6(editor, backstage); 30007 setup$5(editor, lazySink, backstage); 30008 setup$8(editor); 30009 setup$7(editor, lazyThrobber, backstage.shared); 30010 map$1(getToolbarGroups(editor), function (toolbarGroupButtonConfig, name) { 30011 editor.ui.registry.addGroupToolbarButton(name, toolbarGroupButtonConfig); 30012 }); 30013 var _a = editor.ui.registry.getAll(), buttons = _a.buttons, menuItems = _a.menuItems, contextToolbars = _a.contextToolbars, sidebars = _a.sidebars; 30014 var toolbarOpt = getMultipleToolbarsSetting(editor); 30015 var rawUiConfig = { 30016 menuItems: menuItems, 30017 menus: getMenus(editor), 30018 menubar: getMenubar(editor), 30019 toolbar: toolbarOpt.getOrThunk(function () { 30020 return getToolbar(editor); 30021 }), 30022 allowToolbarGroups: toolbarMode === ToolbarMode.floating, 30023 buttons: buttons, 30024 sidebar: sidebars 30025 }; 30026 register$7(editor, contextToolbars, sink, { backstage: backstage }); 30027 setup$4(editor, sink); 30028 var elm = editor.getElement(); 30029 var height = setEditorSize(); 30030 var uiComponents = { 30031 mothership: mothership, 30032 uiMothership: uiMothership, 30033 outerContainer: outerContainer 30034 }; 30035 var args = { 30036 targetNode: elm, 30037 height: height 30038 }; 30039 return mode.render(editor, uiComponents, rawUiConfig, backstage, args); 30040 }; 30041 return { 30042 mothership: mothership, 30043 uiMothership: uiMothership, 30044 backstage: backstage, 30045 renderUI: renderUI, 30046 getUi: getUi 30047 }; 30048 }; 30049 30050 var describedBy = function (describedElement, describeElement) { 30051 var describeId = Optional.from(get$d(describedElement, 'id')).fold(function () { 30052 var id = generate$6('dialog-describe'); 30053 set$8(describeElement, 'id', id); 30054 return id; 30055 }, identity$1); 30056 set$8(describedElement, 'aria-describedby', describeId); 30057 }; 30058 30059 var labelledBy = function (labelledElement, labelElement) { 30060 var labelId = getOpt(labelledElement, 'id').fold(function () { 30061 var id = generate$6('dialog-label'); 30062 set$8(labelElement, 'id', id); 30063 return id; 30064 }, identity$1); 30065 set$8(labelledElement, 'aria-labelledby', labelId); 30066 }; 30067 30068 var schema$2 = constant$1([ 30069 required$1('lazySink'), 30070 option('dragBlockClass'), 30071 defaultedFunction('getBounds', win), 30072 defaulted('useTabstopAt', always), 30073 defaulted('eventOrder', {}), 30074 field('modalBehaviours', [Keying]), 30075 onKeyboardHandler('onExecute'), 30076 onStrictKeyboardHandler('onEscape') 30077 ]); 30078 var basic = { sketch: identity$1 }; 30079 var parts$2 = constant$1([ 30080 optional({ 30081 name: 'draghandle', 30082 overrides: function (detail, spec) { 30083 return { 30084 behaviours: derive$1([Dragging.config({ 30085 mode: 'mouse', 30086 getTarget: function (handle) { 30087 return ancestor(handle, '[role="dialog"]').getOr(handle); 30088 }, 30089 blockerClass: detail.dragBlockClass.getOrDie(new Error('The drag blocker class was not specified for a dialog with a drag handle: \n' + JSON.stringify(spec, null, 2)).message), 30090 getBounds: detail.getDragBounds 30091 })]) 30092 }; 30093 } 30094 }), 30095 required({ 30096 schema: [required$1('dom')], 30097 name: 'title' 30098 }), 30099 required({ 30100 factory: basic, 30101 schema: [required$1('dom')], 30102 name: 'close' 30103 }), 30104 required({ 30105 factory: basic, 30106 schema: [required$1('dom')], 30107 name: 'body' 30108 }), 30109 optional({ 30110 factory: basic, 30111 schema: [required$1('dom')], 30112 name: 'footer' 30113 }), 30114 external$1({ 30115 factory: { 30116 sketch: function (spec, detail) { 30117 return __assign(__assign({}, spec), { 30118 dom: detail.dom, 30119 components: detail.components 30120 }); 30121 } 30122 }, 30123 schema: [ 30124 defaulted('dom', { 30125 tag: 'div', 30126 styles: { 30127 position: 'fixed', 30128 left: '0px', 30129 top: '0px', 30130 right: '0px', 30131 bottom: '0px' 30132 } 30133 }), 30134 defaulted('components', []) 30135 ], 30136 name: 'blocker' 30137 }) 30138 ]); 30139 30140 var factory$4 = function (detail, components, spec, externals) { 30141 var _a; 30142 var dialogComp = value$1(); 30143 var showDialog = function (dialog) { 30144 dialogComp.set(dialog); 30145 var sink = detail.lazySink(dialog).getOrDie(); 30146 var externalBlocker = externals.blocker(); 30147 var blocker = sink.getSystem().build(__assign(__assign({}, externalBlocker), { 30148 components: externalBlocker.components.concat([premade(dialog)]), 30149 behaviours: derive$1([ 30150 Focusing.config({}), 30151 config('dialog-blocker-events', [runOnSource(focusin(), function () { 30152 Keying.focusIn(dialog); 30153 })]) 30154 ]) 30155 })); 30156 attach(sink, blocker); 30157 Keying.focusIn(dialog); 30158 }; 30159 var hideDialog = function (dialog) { 30160 dialogComp.clear(); 30161 parent(dialog.element).each(function (blockerDom) { 30162 dialog.getSystem().getByDom(blockerDom).each(function (blocker) { 30163 detach(blocker); 30164 }); 30165 }); 30166 }; 30167 var getDialogBody = function (dialog) { 30168 return getPartOrDie(dialog, detail, 'body'); 30169 }; 30170 var getDialogFooter = function (dialog) { 30171 return getPartOrDie(dialog, detail, 'footer'); 30172 }; 30173 var setBusy = function (dialog, getBusySpec) { 30174 Blocking.block(dialog, getBusySpec); 30175 }; 30176 var setIdle = function (dialog) { 30177 Blocking.unblock(dialog); 30178 }; 30179 var modalEventsId = generate$6('modal-events'); 30180 var eventOrder = __assign(__assign({}, detail.eventOrder), (_a = {}, _a[attachedToDom()] = [modalEventsId].concat(detail.eventOrder['alloy.system.attached'] || []), _a)); 30181 return { 30182 uid: detail.uid, 30183 dom: detail.dom, 30184 components: components, 30185 apis: { 30186 show: showDialog, 30187 hide: hideDialog, 30188 getBody: getDialogBody, 30189 getFooter: getDialogFooter, 30190 setIdle: setIdle, 30191 setBusy: setBusy 30192 }, 30193 eventOrder: eventOrder, 30194 domModification: { 30195 attributes: { 30196 'role': 'dialog', 30197 'aria-modal': 'true' 30198 } 30199 }, 30200 behaviours: augment(detail.modalBehaviours, [ 30201 Replacing.config({}), 30202 Keying.config({ 30203 mode: 'cyclic', 30204 onEnter: detail.onExecute, 30205 onEscape: detail.onEscape, 30206 useTabstopAt: detail.useTabstopAt 30207 }), 30208 Blocking.config({ getRoot: dialogComp.get }), 30209 config(modalEventsId, [runOnAttached(function (c) { 30210 labelledBy(c.element, getPartOrDie(c, detail, 'title').element); 30211 describedBy(c.element, getPartOrDie(c, detail, 'body').element); 30212 })]) 30213 ]) 30214 }; 30215 }; 30216 var ModalDialog = composite({ 30217 name: 'ModalDialog', 30218 configFields: schema$2(), 30219 partFields: parts$2(), 30220 factory: factory$4, 30221 apis: { 30222 show: function (apis, dialog) { 30223 apis.show(dialog); 30224 }, 30225 hide: function (apis, dialog) { 30226 apis.hide(dialog); 30227 }, 30228 getBody: function (apis, dialog) { 30229 return apis.getBody(dialog); 30230 }, 30231 getFooter: function (apis, dialog) { 30232 return apis.getFooter(dialog); 30233 }, 30234 setBusy: function (apis, dialog, getBusySpec) { 30235 apis.setBusy(dialog, getBusySpec); 30236 }, 30237 setIdle: function (apis, dialog) { 30238 apis.setIdle(dialog); 30239 } 30240 } 30241 }); 30242 30243 var dialogToggleMenuItemSchema = objOf([ 30244 requiredString('type'), 30245 requiredString('name') 30246 ].concat(commonMenuItemFields)); 30247 var dialogToggleMenuItemDataProcessor = boolean; 30248 30249 var baseFooterButtonFields = [ 30250 field$1('name', 'name', defaultedThunk(function () { 30251 return generate$6('button-name'); 30252 }), string), 30253 optionString('icon'), 30254 defaultedStringEnum('align', 'end', [ 30255 'start', 30256 'end' 30257 ]), 30258 defaultedBoolean('primary', false), 30259 defaultedBoolean('disabled', false) 30260 ]; 30261 var dialogFooterButtonFields = __spreadArray(__spreadArray([], baseFooterButtonFields, true), [requiredString('text')], false); 30262 var normalFooterButtonFields = __spreadArray([requiredStringEnum('type', [ 30263 'submit', 30264 'cancel', 30265 'custom' 30266 ])], dialogFooterButtonFields, true); 30267 var menuFooterButtonFields = __spreadArray([ 30268 requiredStringEnum('type', ['menu']), 30269 optionString('text'), 30270 optionString('tooltip'), 30271 optionString('icon'), 30272 requiredArrayOf('items', dialogToggleMenuItemSchema) 30273 ], baseFooterButtonFields, true); 30274 var dialogFooterButtonSchema = choose$1('type', { 30275 submit: normalFooterButtonFields, 30276 cancel: normalFooterButtonFields, 30277 custom: normalFooterButtonFields, 30278 menu: menuFooterButtonFields 30279 }); 30280 30281 var alertBannerFields = [ 30282 requiredString('type'), 30283 requiredString('text'), 30284 requiredStringEnum('level', [ 30285 'info', 30286 'warn', 30287 'error', 30288 'success' 30289 ]), 30290 requiredString('icon'), 30291 defaulted('url', '') 30292 ]; 30293 var alertBannerSchema = objOf(alertBannerFields); 30294 30295 var createBarFields = function (itemsField) { 30296 return [ 30297 requiredString('type'), 30298 itemsField 30299 ]; 30300 }; 30301 30302 var buttonFields = [ 30303 requiredString('type'), 30304 requiredString('text'), 30305 defaultedBoolean('disabled', false), 30306 defaultedBoolean('primary', false), 30307 field$1('name', 'name', defaultedThunk(function () { 30308 return generate$6('button-name'); 30309 }), string), 30310 optionString('icon'), 30311 defaultedBoolean('borderless', false) 30312 ]; 30313 var buttonSchema = objOf(buttonFields); 30314 30315 var checkboxFields = [ 30316 requiredString('type'), 30317 requiredString('name'), 30318 requiredString('label'), 30319 defaultedBoolean('disabled', false) 30320 ]; 30321 var checkboxSchema = objOf(checkboxFields); 30322 var checkboxDataProcessor = boolean; 30323 30324 var formComponentFields = [ 30325 requiredString('type'), 30326 requiredString('name') 30327 ]; 30328 var formComponentWithLabelFields = formComponentFields.concat([optionString('label')]); 30329 30330 var collectionFields = formComponentWithLabelFields.concat([defaulted('columns', 'auto')]); 30331 var collectionSchema = objOf(collectionFields); 30332 var collectionDataProcessor = arrOfObj([ 30333 requiredString('value'), 30334 requiredString('text'), 30335 requiredString('icon') 30336 ]); 30337 30338 var colorInputFields = formComponentWithLabelFields; 30339 var colorInputSchema = objOf(colorInputFields); 30340 var colorInputDataProcessor = string; 30341 30342 var colorPickerFields = formComponentWithLabelFields; 30343 var colorPickerSchema = objOf(colorPickerFields); 30344 var colorPickerDataProcessor = string; 30345 30346 var customEditorFields = formComponentFields.concat([ 30347 defaultedString('tag', 'textarea'), 30348 requiredString('scriptId'), 30349 requiredString('scriptUrl'), 30350 defaultedPostMsg('settings', undefined) 30351 ]); 30352 var customEditorFieldsOld = formComponentFields.concat([ 30353 defaultedString('tag', 'textarea'), 30354 requiredFunction('init') 30355 ]); 30356 var customEditorSchema = valueOf(function (v) { 30357 return asRaw('customeditor.old', objOfOnly(customEditorFieldsOld), v).orThunk(function () { 30358 return asRaw('customeditor.new', objOfOnly(customEditorFields), v); 30359 }); 30360 }); 30361 var customEditorDataProcessor = string; 30362 30363 var dropZoneFields = formComponentWithLabelFields; 30364 var dropZoneSchema = objOf(dropZoneFields); 30365 var dropZoneDataProcessor = arrOfVal(); 30366 30367 var createGridFields = function (itemsField) { 30368 return [ 30369 requiredString('type'), 30370 requiredNumber('columns'), 30371 itemsField 30372 ]; 30373 }; 30374 30375 var htmlPanelFields = [ 30376 requiredString('type'), 30377 requiredString('html'), 30378 defaultedStringEnum('presets', 'presentation', [ 30379 'presentation', 30380 'document' 30381 ]) 30382 ]; 30383 var htmlPanelSchema = objOf(htmlPanelFields); 30384 30385 var iframeFields = formComponentWithLabelFields.concat([defaultedBoolean('sandboxed', true)]); 30386 var iframeSchema = objOf(iframeFields); 30387 var iframeDataProcessor = string; 30388 30389 var imageToolsFields = formComponentWithLabelFields.concat([requiredOf('currentState', objOf([ 30390 required$1('blob'), 30391 requiredString('url') 30392 ]))]); 30393 var imageToolsSchema = objOf(imageToolsFields); 30394 30395 var inputFields = formComponentWithLabelFields.concat([ 30396 optionString('inputMode'), 30397 optionString('placeholder'), 30398 defaultedBoolean('maximized', false), 30399 defaultedBoolean('disabled', false) 30400 ]); 30401 var inputSchema = objOf(inputFields); 30402 var inputDataProcessor = string; 30403 30404 var createLabelFields = function (itemsField) { 30405 return [ 30406 requiredString('type'), 30407 requiredString('label'), 30408 itemsField 30409 ]; 30410 }; 30411 30412 var listBoxSingleItemFields = [ 30413 requiredString('text'), 30414 requiredString('value') 30415 ]; 30416 var listBoxNestedItemFields = [ 30417 requiredString('text'), 30418 requiredArrayOf('items', thunkOf('items', function () { 30419 return listBoxItemSchema; 30420 })) 30421 ]; 30422 var listBoxItemSchema = oneOf([ 30423 objOf(listBoxSingleItemFields), 30424 objOf(listBoxNestedItemFields) 30425 ]); 30426 var listBoxFields = formComponentWithLabelFields.concat([ 30427 requiredArrayOf('items', listBoxItemSchema), 30428 defaultedBoolean('disabled', false) 30429 ]); 30430 var listBoxSchema = objOf(listBoxFields); 30431 var listBoxDataProcessor = string; 30432 30433 var selectBoxFields = formComponentWithLabelFields.concat([ 30434 requiredArrayOfObj('items', [ 30435 requiredString('text'), 30436 requiredString('value') 30437 ]), 30438 defaultedNumber('size', 1), 30439 defaultedBoolean('disabled', false) 30440 ]); 30441 var selectBoxSchema = objOf(selectBoxFields); 30442 var selectBoxDataProcessor = string; 30443 30444 var sizeInputFields = formComponentWithLabelFields.concat([ 30445 defaultedBoolean('constrain', true), 30446 defaultedBoolean('disabled', false) 30447 ]); 30448 var sizeInputSchema = objOf(sizeInputFields); 30449 var sizeInputDataProcessor = objOf([ 30450 requiredString('width'), 30451 requiredString('height') 30452 ]); 30453 30454 var tableFields = [ 30455 requiredString('type'), 30456 requiredArrayOf('header', string), 30457 requiredArrayOf('cells', arrOf(string)) 30458 ]; 30459 var tableSchema = objOf(tableFields); 30460 30461 var textAreaFields = formComponentWithLabelFields.concat([ 30462 optionString('placeholder'), 30463 defaultedBoolean('maximized', false), 30464 defaultedBoolean('disabled', false) 30465 ]); 30466 var textAreaSchema = objOf(textAreaFields); 30467 var textAreaDataProcessor = string; 30468 30469 var urlInputFields = formComponentWithLabelFields.concat([ 30470 defaultedStringEnum('filetype', 'file', [ 30471 'image', 30472 'media', 30473 'file' 30474 ]), 30475 defaulted('disabled', false) 30476 ]); 30477 var urlInputSchema = objOf(urlInputFields); 30478 var urlInputDataProcessor = objOf([ 30479 requiredString('value'), 30480 defaulted('meta', {}) 30481 ]); 30482 30483 var createItemsField = function (name) { 30484 return field$1('items', 'items', required$2(), arrOf(valueOf(function (v) { 30485 return asRaw('Checking item of ' + name, itemSchema, v).fold(function (sErr) { 30486 return Result.error(formatError(sErr)); 30487 }, function (passValue) { 30488 return Result.value(passValue); 30489 }); 30490 }))); 30491 }; 30492 var itemSchema = valueThunk(function () { 30493 return choose$2('type', { 30494 alertbanner: alertBannerSchema, 30495 bar: objOf(createBarFields(createItemsField('bar'))), 30496 button: buttonSchema, 30497 checkbox: checkboxSchema, 30498 colorinput: colorInputSchema, 30499 colorpicker: colorPickerSchema, 30500 dropzone: dropZoneSchema, 30501 grid: objOf(createGridFields(createItemsField('grid'))), 30502 iframe: iframeSchema, 30503 input: inputSchema, 30504 listbox: listBoxSchema, 30505 selectbox: selectBoxSchema, 30506 sizeinput: sizeInputSchema, 30507 textarea: textAreaSchema, 30508 urlinput: urlInputSchema, 30509 customeditor: customEditorSchema, 30510 htmlpanel: htmlPanelSchema, 30511 imagetools: imageToolsSchema, 30512 collection: collectionSchema, 30513 label: objOf(createLabelFields(createItemsField('label'))), 30514 table: tableSchema, 30515 panel: panelSchema 30516 }); 30517 }); 30518 var panelFields = [ 30519 requiredString('type'), 30520 defaulted('classes', []), 30521 requiredArrayOf('items', itemSchema) 30522 ]; 30523 var panelSchema = objOf(panelFields); 30524 30525 var tabFields = [ 30526 field$1('name', 'name', defaultedThunk(function () { 30527 return generate$6('tab-name'); 30528 }), string), 30529 requiredString('title'), 30530 requiredArrayOf('items', itemSchema) 30531 ]; 30532 var tabPanelFields = [ 30533 requiredString('type'), 30534 requiredArrayOfObj('tabs', tabFields) 30535 ]; 30536 var tabPanelSchema = objOf(tabPanelFields); 30537 30538 var dialogButtonFields = dialogFooterButtonFields; 30539 var dialogButtonSchema = dialogFooterButtonSchema; 30540 var dialogSchema = objOf([ 30541 requiredString('title'), 30542 requiredOf('body', choose$2('type', { 30543 panel: panelSchema, 30544 tabpanel: tabPanelSchema 30545 })), 30546 defaultedString('size', 'normal'), 30547 requiredArrayOf('buttons', dialogButtonSchema), 30548 defaulted('initialData', {}), 30549 defaultedFunction('onAction', noop), 30550 defaultedFunction('onChange', noop), 30551 defaultedFunction('onSubmit', noop), 30552 defaultedFunction('onClose', noop), 30553 defaultedFunction('onCancel', noop), 30554 defaulted('onTabChange', noop) 30555 ]); 30556 var createDialog = function (spec) { 30557 return asRaw('dialog', dialogSchema, spec); 30558 }; 30559 30560 var urlDialogButtonSchema = objOf(__spreadArray([requiredStringEnum('type', [ 30561 'cancel', 30562 'custom' 30563 ])], dialogButtonFields, true)); 30564 var urlDialogSchema = objOf([ 30565 requiredString('title'), 30566 requiredString('url'), 30567 optionNumber('height'), 30568 optionNumber('width'), 30569 optionArrayOf('buttons', urlDialogButtonSchema), 30570 defaultedFunction('onAction', noop), 30571 defaultedFunction('onCancel', noop), 30572 defaultedFunction('onClose', noop), 30573 defaultedFunction('onMessage', noop) 30574 ]); 30575 var createUrlDialog = function (spec) { 30576 return asRaw('dialog', urlDialogSchema, spec); 30577 }; 30578 30579 var getAllObjects = function (obj) { 30580 if (isObject(obj)) { 30581 return [obj].concat(bind$3(values(obj), getAllObjects)); 30582 } else if (isArray(obj)) { 30583 return bind$3(obj, getAllObjects); 30584 } else { 30585 return []; 30586 } 30587 }; 30588 30589 var isNamedItem = function (obj) { 30590 return isString(obj.type) && isString(obj.name); 30591 }; 30592 var dataProcessors = { 30593 checkbox: checkboxDataProcessor, 30594 colorinput: colorInputDataProcessor, 30595 colorpicker: colorPickerDataProcessor, 30596 dropzone: dropZoneDataProcessor, 30597 input: inputDataProcessor, 30598 iframe: iframeDataProcessor, 30599 sizeinput: sizeInputDataProcessor, 30600 selectbox: selectBoxDataProcessor, 30601 listbox: listBoxDataProcessor, 30602 size: sizeInputDataProcessor, 30603 textarea: textAreaDataProcessor, 30604 urlinput: urlInputDataProcessor, 30605 customeditor: customEditorDataProcessor, 30606 collection: collectionDataProcessor, 30607 togglemenuitem: dialogToggleMenuItemDataProcessor 30608 }; 30609 var getDataProcessor = function (item) { 30610 return Optional.from(dataProcessors[item.type]); 30611 }; 30612 var getNamedItems = function (structure) { 30613 return filter$2(getAllObjects(structure), isNamedItem); 30614 }; 30615 30616 var createDataValidator = function (structure) { 30617 var namedItems = getNamedItems(structure); 30618 var fields = bind$3(namedItems, function (item) { 30619 return getDataProcessor(item).fold(function () { 30620 return []; 30621 }, function (schema) { 30622 return [requiredOf(item.name, schema)]; 30623 }); 30624 }); 30625 return objOf(fields); 30626 }; 30627 30628 var extract = function (structure) { 30629 var internalDialog = getOrDie(createDialog(structure)); 30630 var dataValidator = createDataValidator(structure); 30631 var initialData = structure.initialData; 30632 return { 30633 internalDialog: internalDialog, 30634 dataValidator: dataValidator, 30635 initialData: initialData 30636 }; 30637 }; 30638 var DialogManager = { 30639 open: function (factory, structure) { 30640 var extraction = extract(structure); 30641 return factory(extraction.internalDialog, extraction.initialData, extraction.dataValidator); 30642 }, 30643 openUrl: function (factory, structure) { 30644 var internalDialog = getOrDie(createUrlDialog(structure)); 30645 return factory(internalDialog); 30646 }, 30647 redial: function (structure) { 30648 return extract(structure); 30649 } 30650 }; 30651 30652 var toValidValues = function (values) { 30653 var errors = []; 30654 var result = {}; 30655 each(values, function (value, name) { 30656 value.fold(function () { 30657 errors.push(name); 30658 }, function (v) { 30659 result[name] = v; 30660 }); 30661 }); 30662 return errors.length > 0 ? Result.error(errors) : Result.value(result); 30663 }; 30664 30665 var renderBodyPanel = function (spec, backstage) { 30666 var memForm = record(Form.sketch(function (parts) { 30667 return { 30668 dom: { 30669 tag: 'div', 30670 classes: ['tox-form'].concat(spec.classes) 30671 }, 30672 components: map$2(spec.items, function (item) { 30673 return interpretInForm(parts, item, backstage); 30674 }) 30675 }; 30676 })); 30677 return { 30678 dom: { 30679 tag: 'div', 30680 classes: ['tox-dialog__body'] 30681 }, 30682 components: [{ 30683 dom: { 30684 tag: 'div', 30685 classes: ['tox-dialog__body-content'] 30686 }, 30687 components: [memForm.asSpec()] 30688 }], 30689 behaviours: derive$1([ 30690 Keying.config({ 30691 mode: 'acyclic', 30692 useTabstopAt: not(isPseudoStop) 30693 }), 30694 ComposingConfigs.memento(memForm), 30695 RepresentingConfigs.memento(memForm, { 30696 postprocess: function (formValue) { 30697 return toValidValues(formValue).fold(function (err) { 30698 console.error(err); 30699 return {}; 30700 }, identity$1); 30701 } 30702 }) 30703 ]) 30704 }; 30705 }; 30706 30707 var factory$3 = function (detail, _spec) { 30708 return { 30709 uid: detail.uid, 30710 dom: detail.dom, 30711 components: detail.components, 30712 events: events$a(detail.action), 30713 behaviours: augment(detail.tabButtonBehaviours, [ 30714 Focusing.config({}), 30715 Keying.config({ 30716 mode: 'execution', 30717 useSpace: true, 30718 useEnter: true 30719 }), 30720 Representing.config({ 30721 store: { 30722 mode: 'memory', 30723 initialValue: detail.value 30724 } 30725 }) 30726 ]), 30727 domModification: detail.domModification 30728 }; 30729 }; 30730 var TabButton = single({ 30731 name: 'TabButton', 30732 configFields: [ 30733 defaulted('uid', undefined), 30734 required$1('value'), 30735 field$1('dom', 'dom', mergeWithThunk(function () { 30736 return { 30737 attributes: { 30738 'role': 'tab', 30739 'id': generate$6('aria'), 30740 'aria-selected': 'false' 30741 } 30742 }; 30743 }), anyValue()), 30744 option('action'), 30745 defaulted('domModification', {}), 30746 field('tabButtonBehaviours', [ 30747 Focusing, 30748 Keying, 30749 Representing 30750 ]), 30751 required$1('view') 30752 ], 30753 factory: factory$3 30754 }); 30755 30756 var schema$1 = constant$1([ 30757 required$1('tabs'), 30758 required$1('dom'), 30759 defaulted('clickToDismiss', false), 30760 field('tabbarBehaviours', [ 30761 Highlighting, 30762 Keying 30763 ]), 30764 markers$1([ 30765 'tabClass', 30766 'selectedClass' 30767 ]) 30768 ]); 30769 var tabsPart = group({ 30770 factory: TabButton, 30771 name: 'tabs', 30772 unit: 'tab', 30773 overrides: function (barDetail) { 30774 var dismissTab$1 = function (tabbar, button) { 30775 Highlighting.dehighlight(tabbar, button); 30776 emitWith(tabbar, dismissTab(), { 30777 tabbar: tabbar, 30778 button: button 30779 }); 30780 }; 30781 var changeTab$1 = function (tabbar, button) { 30782 Highlighting.highlight(tabbar, button); 30783 emitWith(tabbar, changeTab(), { 30784 tabbar: tabbar, 30785 button: button 30786 }); 30787 }; 30788 return { 30789 action: function (button) { 30790 var tabbar = button.getSystem().getByUid(barDetail.uid).getOrDie(); 30791 var activeButton = Highlighting.isHighlighted(tabbar, button); 30792 var response = function () { 30793 if (activeButton && barDetail.clickToDismiss) { 30794 return dismissTab$1; 30795 } else if (!activeButton) { 30796 return changeTab$1; 30797 } else { 30798 return noop; 30799 } 30800 }(); 30801 response(tabbar, button); 30802 }, 30803 domModification: { classes: [barDetail.markers.tabClass] } 30804 }; 30805 } 30806 }); 30807 var parts$1 = constant$1([tabsPart]); 30808 30809 var factory$2 = function (detail, components, _spec, _externals) { 30810 return { 30811 'uid': detail.uid, 30812 'dom': detail.dom, 30813 components: components, 30814 'debug.sketcher': 'Tabbar', 30815 'domModification': { attributes: { role: 'tablist' } }, 30816 'behaviours': augment(detail.tabbarBehaviours, [ 30817 Highlighting.config({ 30818 highlightClass: detail.markers.selectedClass, 30819 itemClass: detail.markers.tabClass, 30820 onHighlight: function (tabbar, tab) { 30821 set$8(tab.element, 'aria-selected', 'true'); 30822 }, 30823 onDehighlight: function (tabbar, tab) { 30824 set$8(tab.element, 'aria-selected', 'false'); 30825 } 30826 }), 30827 Keying.config({ 30828 mode: 'flow', 30829 getInitial: function (tabbar) { 30830 return Highlighting.getHighlighted(tabbar).map(function (tab) { 30831 return tab.element; 30832 }); 30833 }, 30834 selector: '.' + detail.markers.tabClass, 30835 executeOnMove: true 30836 }) 30837 ]) 30838 }; 30839 }; 30840 var Tabbar = composite({ 30841 name: 'Tabbar', 30842 configFields: schema$1(), 30843 partFields: parts$1(), 30844 factory: factory$2 30845 }); 30846 30847 var factory$1 = function (detail, _spec) { 30848 return { 30849 uid: detail.uid, 30850 dom: detail.dom, 30851 behaviours: augment(detail.tabviewBehaviours, [Replacing.config({})]), 30852 domModification: { attributes: { role: 'tabpanel' } } 30853 }; 30854 }; 30855 var Tabview = single({ 30856 name: 'Tabview', 30857 configFields: [field('tabviewBehaviours', [Replacing])], 30858 factory: factory$1 30859 }); 30860 30861 var schema = constant$1([ 30862 defaulted('selectFirst', true), 30863 onHandler('onChangeTab'), 30864 onHandler('onDismissTab'), 30865 defaulted('tabs', []), 30866 field('tabSectionBehaviours', []) 30867 ]); 30868 var barPart = required({ 30869 factory: Tabbar, 30870 schema: [ 30871 required$1('dom'), 30872 requiredObjOf('markers', [ 30873 required$1('tabClass'), 30874 required$1('selectedClass') 30875 ]) 30876 ], 30877 name: 'tabbar', 30878 defaults: function (detail) { 30879 return { tabs: detail.tabs }; 30880 } 30881 }); 30882 var viewPart = required({ 30883 factory: Tabview, 30884 name: 'tabview' 30885 }); 30886 var parts = constant$1([ 30887 barPart, 30888 viewPart 30889 ]); 30890 30891 var factory = function (detail, components, _spec, _externals) { 30892 var changeTab$1 = function (button) { 30893 var tabValue = Representing.getValue(button); 30894 getPart(button, detail, 'tabview').each(function (tabview) { 30895 var tabWithValue = find$5(detail.tabs, function (t) { 30896 return t.value === tabValue; 30897 }); 30898 tabWithValue.each(function (tabData) { 30899 var panel = tabData.view(); 30900 getOpt(button.element, 'id').each(function (id) { 30901 set$8(tabview.element, 'aria-labelledby', id); 30902 }); 30903 Replacing.set(tabview, panel); 30904 detail.onChangeTab(tabview, button, panel); 30905 }); 30906 }); 30907 }; 30908 var changeTabBy = function (section, byPred) { 30909 getPart(section, detail, 'tabbar').each(function (tabbar) { 30910 byPred(tabbar).each(emitExecute); 30911 }); 30912 }; 30913 return { 30914 uid: detail.uid, 30915 dom: detail.dom, 30916 components: components, 30917 behaviours: get$2(detail.tabSectionBehaviours), 30918 events: derive$2(flatten([ 30919 detail.selectFirst ? [runOnAttached(function (section, _simulatedEvent) { 30920 changeTabBy(section, Highlighting.getFirst); 30921 })] : [], 30922 [ 30923 run$1(changeTab(), function (section, simulatedEvent) { 30924 var button = simulatedEvent.event.button; 30925 changeTab$1(button); 30926 }), 30927 run$1(dismissTab(), function (section, simulatedEvent) { 30928 var button = simulatedEvent.event.button; 30929 detail.onDismissTab(section, button); 30930 }) 30931 ] 30932 ])), 30933 apis: { 30934 getViewItems: function (section) { 30935 return getPart(section, detail, 'tabview').map(function (tabview) { 30936 return Replacing.contents(tabview); 30937 }).getOr([]); 30938 }, 30939 showTab: function (section, tabKey) { 30940 var getTabIfNotActive = function (tabbar) { 30941 var candidates = Highlighting.getCandidates(tabbar); 30942 var optTab = find$5(candidates, function (c) { 30943 return Representing.getValue(c) === tabKey; 30944 }); 30945 return optTab.filter(function (tab) { 30946 return !Highlighting.isHighlighted(tabbar, tab); 30947 }); 30948 }; 30949 changeTabBy(section, getTabIfNotActive); 30950 } 30951 } 30952 }; 30953 }; 30954 var TabSection = composite({ 30955 name: 'TabSection', 30956 configFields: schema(), 30957 partFields: parts(), 30958 factory: factory, 30959 apis: { 30960 getViewItems: function (apis, component) { 30961 return apis.getViewItems(component); 30962 }, 30963 showTab: function (apis, component, tabKey) { 30964 apis.showTab(component, tabKey); 30965 } 30966 } 30967 }); 30968 30969 var measureHeights = function (allTabs, tabview, tabviewComp) { 30970 return map$2(allTabs, function (_tab, i) { 30971 Replacing.set(tabviewComp, allTabs[i].view()); 30972 var rect = tabview.dom.getBoundingClientRect(); 30973 Replacing.set(tabviewComp, []); 30974 return rect.height; 30975 }); 30976 }; 30977 var getMaxHeight = function (heights) { 30978 return head(sort(heights, function (a, b) { 30979 if (a > b) { 30980 return -1; 30981 } else if (a < b) { 30982 return +1; 30983 } else { 30984 return 0; 30985 } 30986 })); 30987 }; 30988 var getMaxTabviewHeight = function (dialog, tabview, tablist) { 30989 var documentElement$1 = documentElement(dialog).dom; 30990 var rootElm = ancestor(dialog, '.tox-dialog-wrap').getOr(dialog); 30991 var isFixed = get$c(rootElm, 'position') === 'fixed'; 30992 var maxHeight; 30993 if (isFixed) { 30994 maxHeight = Math.max(documentElement$1.clientHeight, window.innerHeight); 30995 } else { 30996 maxHeight = Math.max(documentElement$1.offsetHeight, documentElement$1.scrollHeight); 30997 } 30998 var tabviewHeight = get$b(tabview); 30999 var isTabListBeside = tabview.dom.offsetLeft >= tablist.dom.offsetLeft + get$a(tablist); 31000 var currentTabHeight = isTabListBeside ? Math.max(get$b(tablist), tabviewHeight) : tabviewHeight; 31001 var dialogTopMargin = parseInt(get$c(dialog, 'margin-top'), 10) || 0; 31002 var dialogBottomMargin = parseInt(get$c(dialog, 'margin-bottom'), 10) || 0; 31003 var dialogHeight = get$b(dialog) + dialogTopMargin + dialogBottomMargin; 31004 var chromeHeight = dialogHeight - currentTabHeight; 31005 return maxHeight - chromeHeight; 31006 }; 31007 var showTab = function (allTabs, comp) { 31008 head(allTabs).each(function (tab) { 31009 return TabSection.showTab(comp, tab.value); 31010 }); 31011 }; 31012 var setTabviewHeight = function (tabview, height) { 31013 set$7(tabview, 'height', height + 'px'); 31014 if (!detect$1().browser.isIE()) { 31015 set$7(tabview, 'flex-basis', height + 'px'); 31016 } else { 31017 remove$6(tabview, 'flex-basis'); 31018 } 31019 }; 31020 var updateTabviewHeight = function (dialogBody, tabview, maxTabHeight) { 31021 ancestor(dialogBody, '[role="dialog"]').each(function (dialog) { 31022 descendant(dialog, '[role="tablist"]').each(function (tablist) { 31023 maxTabHeight.get().map(function (height) { 31024 set$7(tabview, 'height', '0'); 31025 set$7(tabview, 'flex-basis', '0'); 31026 return Math.min(height, getMaxTabviewHeight(dialog, tabview, tablist)); 31027 }).each(function (height) { 31028 setTabviewHeight(tabview, height); 31029 }); 31030 }); 31031 }); 31032 }; 31033 var getTabview = function (dialog) { 31034 return descendant(dialog, '[role="tabpanel"]'); 31035 }; 31036 var setMode = function (allTabs) { 31037 var smartTabHeight = function () { 31038 var maxTabHeight = value$1(); 31039 var extraEvents = [ 31040 runOnAttached(function (comp) { 31041 var dialog = comp.element; 31042 getTabview(dialog).each(function (tabview) { 31043 set$7(tabview, 'visibility', 'hidden'); 31044 comp.getSystem().getByDom(tabview).toOptional().each(function (tabviewComp) { 31045 var heights = measureHeights(allTabs, tabview, tabviewComp); 31046 var maxTabHeightOpt = getMaxHeight(heights); 31047 maxTabHeightOpt.fold(maxTabHeight.clear, maxTabHeight.set); 31048 }); 31049 updateTabviewHeight(dialog, tabview, maxTabHeight); 31050 remove$6(tabview, 'visibility'); 31051 showTab(allTabs, comp); 31052 global$f.requestAnimationFrame(function () { 31053 updateTabviewHeight(dialog, tabview, maxTabHeight); 31054 }); 31055 }); 31056 }), 31057 run$1(windowResize(), function (comp) { 31058 var dialog = comp.element; 31059 getTabview(dialog).each(function (tabview) { 31060 updateTabviewHeight(dialog, tabview, maxTabHeight); 31061 }); 31062 }), 31063 run$1(formResizeEvent, function (comp, _se) { 31064 var dialog = comp.element; 31065 getTabview(dialog).each(function (tabview) { 31066 var oldFocus = active(getRootNode(tabview)); 31067 set$7(tabview, 'visibility', 'hidden'); 31068 var oldHeight = getRaw(tabview, 'height').map(function (h) { 31069 return parseInt(h, 10); 31070 }); 31071 remove$6(tabview, 'height'); 31072 remove$6(tabview, 'flex-basis'); 31073 var newHeight = tabview.dom.getBoundingClientRect().height; 31074 var hasGrown = oldHeight.forall(function (h) { 31075 return newHeight > h; 31076 }); 31077 if (hasGrown) { 31078 maxTabHeight.set(newHeight); 31079 updateTabviewHeight(dialog, tabview, maxTabHeight); 31080 } else { 31081 oldHeight.each(function (h) { 31082 setTabviewHeight(tabview, h); 31083 }); 31084 } 31085 remove$6(tabview, 'visibility'); 31086 oldFocus.each(focus$3); 31087 }); 31088 }) 31089 ]; 31090 var selectFirst = false; 31091 return { 31092 extraEvents: extraEvents, 31093 selectFirst: selectFirst 31094 }; 31095 }(); 31096 var naiveTabHeight = function () { 31097 var extraEvents = []; 31098 var selectFirst = true; 31099 return { 31100 extraEvents: extraEvents, 31101 selectFirst: selectFirst 31102 }; 31103 }(); 31104 return { 31105 smartTabHeight: smartTabHeight, 31106 naiveTabHeight: naiveTabHeight 31107 }; 31108 }; 31109 31110 var SendDataToSectionChannel = 'send-data-to-section'; 31111 var SendDataToViewChannel = 'send-data-to-view'; 31112 var renderTabPanel = function (spec, backstage) { 31113 var storedValue = Cell({}); 31114 var updateDataWithForm = function (form) { 31115 var formData = Representing.getValue(form); 31116 var validData = toValidValues(formData).getOr({}); 31117 var currentData = storedValue.get(); 31118 var newData = deepMerge(currentData, validData); 31119 storedValue.set(newData); 31120 }; 31121 var setDataOnForm = function (form) { 31122 var tabData = storedValue.get(); 31123 Representing.setValue(form, tabData); 31124 }; 31125 var oldTab = Cell(null); 31126 var allTabs = map$2(spec.tabs, function (tab) { 31127 return { 31128 value: tab.name, 31129 dom: { 31130 tag: 'div', 31131 classes: ['tox-dialog__body-nav-item'], 31132 innerHtml: backstage.shared.providers.translate(tab.title) 31133 }, 31134 view: function () { 31135 return [Form.sketch(function (parts) { 31136 return { 31137 dom: { 31138 tag: 'div', 31139 classes: ['tox-form'] 31140 }, 31141 components: map$2(tab.items, function (item) { 31142 return interpretInForm(parts, item, backstage); 31143 }), 31144 formBehaviours: derive$1([ 31145 Keying.config({ 31146 mode: 'acyclic', 31147 useTabstopAt: not(isPseudoStop) 31148 }), 31149 config('TabView.form.events', [ 31150 runOnAttached(setDataOnForm), 31151 runOnDetached(updateDataWithForm) 31152 ]), 31153 Receiving.config({ 31154 channels: wrapAll([ 31155 { 31156 key: SendDataToSectionChannel, 31157 value: { onReceive: updateDataWithForm } 31158 }, 31159 { 31160 key: SendDataToViewChannel, 31161 value: { onReceive: setDataOnForm } 31162 } 31163 ]) 31164 }) 31165 ]) 31166 }; 31167 })]; 31168 } 31169 }; 31170 }); 31171 var tabMode = setMode(allTabs).smartTabHeight; 31172 return TabSection.sketch({ 31173 dom: { 31174 tag: 'div', 31175 classes: ['tox-dialog__body'] 31176 }, 31177 onChangeTab: function (section, button, _viewItems) { 31178 var name = Representing.getValue(button); 31179 emitWith(section, formTabChangeEvent, { 31180 name: name, 31181 oldName: oldTab.get() 31182 }); 31183 oldTab.set(name); 31184 }, 31185 tabs: allTabs, 31186 components: [ 31187 TabSection.parts.tabbar({ 31188 dom: { 31189 tag: 'div', 31190 classes: ['tox-dialog__body-nav'] 31191 }, 31192 components: [Tabbar.parts.tabs({})], 31193 markers: { 31194 tabClass: 'tox-tab', 31195 selectedClass: 'tox-dialog__body-nav-item--active' 31196 }, 31197 tabbarBehaviours: derive$1([Tabstopping.config({})]) 31198 }), 31199 TabSection.parts.tabview({ 31200 dom: { 31201 tag: 'div', 31202 classes: ['tox-dialog__body-content'] 31203 } 31204 }) 31205 ], 31206 selectFirst: tabMode.selectFirst, 31207 tabSectionBehaviours: derive$1([ 31208 config('tabpanel', tabMode.extraEvents), 31209 Keying.config({ mode: 'acyclic' }), 31210 Composing.config({ 31211 find: function (comp) { 31212 return head(TabSection.getViewItems(comp)); 31213 } 31214 }), 31215 Representing.config({ 31216 store: { 31217 mode: 'manual', 31218 getValue: function (tsection) { 31219 tsection.getSystem().broadcastOn([SendDataToSectionChannel], {}); 31220 return storedValue.get(); 31221 }, 31222 setValue: function (tsection, value) { 31223 storedValue.set(value); 31224 tsection.getSystem().broadcastOn([SendDataToViewChannel], {}); 31225 } 31226 } 31227 }) 31228 ]) 31229 }); 31230 }; 31231 31232 var dialogChannel = generate$6('update-dialog'); 31233 var titleChannel = generate$6('update-title'); 31234 var bodyChannel = generate$6('update-body'); 31235 var footerChannel = generate$6('update-footer'); 31236 var bodySendMessageChannel = generate$6('body-send-message'); 31237 31238 var renderBody = function (spec, id, backstage, ariaAttrs) { 31239 var renderComponents = function (incoming) { 31240 switch (incoming.body.type) { 31241 case 'tabpanel': { 31242 return [renderTabPanel(incoming.body, backstage)]; 31243 } 31244 default: { 31245 return [renderBodyPanel(incoming.body, backstage)]; 31246 } 31247 } 31248 }; 31249 var updateState = function (_comp, incoming) { 31250 return Optional.some({ 31251 isTabPanel: function () { 31252 return incoming.body.type === 'tabpanel'; 31253 } 31254 }); 31255 }; 31256 var ariaAttributes = { 'aria-live': 'polite' }; 31257 return { 31258 dom: { 31259 tag: 'div', 31260 classes: ['tox-dialog__content-js'], 31261 attributes: __assign(__assign({}, id.map(function (x) { 31262 return { id: x }; 31263 }).getOr({})), ariaAttrs ? ariaAttributes : {}) 31264 }, 31265 components: [], 31266 behaviours: derive$1([ 31267 ComposingConfigs.childAt(0), 31268 Reflecting.config({ 31269 channel: bodyChannel, 31270 updateState: updateState, 31271 renderComponents: renderComponents, 31272 initialData: spec 31273 }) 31274 ]) 31275 }; 31276 }; 31277 var renderInlineBody = function (spec, contentId, backstage, ariaAttrs) { 31278 return renderBody(spec, Optional.some(contentId), backstage, ariaAttrs); 31279 }; 31280 var renderModalBody = function (spec, backstage) { 31281 var bodySpec = renderBody(spec, Optional.none(), backstage, false); 31282 return ModalDialog.parts.body(bodySpec); 31283 }; 31284 var renderIframeBody = function (spec) { 31285 var bodySpec = { 31286 dom: { 31287 tag: 'div', 31288 classes: ['tox-dialog__content-js'] 31289 }, 31290 components: [{ 31291 dom: { 31292 tag: 'div', 31293 classes: ['tox-dialog__body-iframe'] 31294 }, 31295 components: [craft({ 31296 dom: { 31297 tag: 'iframe', 31298 attributes: { src: spec.url } 31299 }, 31300 behaviours: derive$1([ 31301 Tabstopping.config({}), 31302 Focusing.config({}) 31303 ]) 31304 })] 31305 }], 31306 behaviours: derive$1([Keying.config({ 31307 mode: 'acyclic', 31308 useTabstopAt: not(isPseudoStop) 31309 })]) 31310 }; 31311 return ModalDialog.parts.body(bodySpec); 31312 }; 31313 31314 var isTouch = global$9.deviceType.isTouch(); 31315 var hiddenHeader = function (title, close) { 31316 return { 31317 dom: { 31318 tag: 'div', 31319 styles: { display: 'none' }, 31320 classes: ['tox-dialog__header'] 31321 }, 31322 components: [ 31323 title, 31324 close 31325 ] 31326 }; 31327 }; 31328 var pClose = function (onClose, providersBackstage) { 31329 return ModalDialog.parts.close(Button.sketch({ 31330 dom: { 31331 tag: 'button', 31332 classes: [ 31333 'tox-button', 31334 'tox-button--icon', 31335 'tox-button--naked' 31336 ], 31337 attributes: { 31338 'type': 'button', 31339 'aria-label': providersBackstage.translate('Close') 31340 } 31341 }, 31342 action: onClose, 31343 buttonBehaviours: derive$1([Tabstopping.config({})]) 31344 })); 31345 }; 31346 var pUntitled = function () { 31347 return ModalDialog.parts.title({ 31348 dom: { 31349 tag: 'div', 31350 classes: ['tox-dialog__title'], 31351 innerHtml: '', 31352 styles: { display: 'none' } 31353 } 31354 }); 31355 }; 31356 var pBodyMessage = function (message, providersBackstage) { 31357 return ModalDialog.parts.body({ 31358 dom: { 31359 tag: 'div', 31360 classes: ['tox-dialog__body'] 31361 }, 31362 components: [{ 31363 dom: { 31364 tag: 'div', 31365 classes: ['tox-dialog__body-content'] 31366 }, 31367 components: [{ dom: fromHtml('<p>' + providersBackstage.translate(message) + '</p>') }] 31368 }] 31369 }); 31370 }; 31371 var pFooter = function (buttons) { 31372 return ModalDialog.parts.footer({ 31373 dom: { 31374 tag: 'div', 31375 classes: ['tox-dialog__footer'] 31376 }, 31377 components: buttons 31378 }); 31379 }; 31380 var pFooterGroup = function (startButtons, endButtons) { 31381 return [ 31382 Container.sketch({ 31383 dom: { 31384 tag: 'div', 31385 classes: ['tox-dialog__footer-start'] 31386 }, 31387 components: startButtons 31388 }), 31389 Container.sketch({ 31390 dom: { 31391 tag: 'div', 31392 classes: ['tox-dialog__footer-end'] 31393 }, 31394 components: endButtons 31395 }) 31396 ]; 31397 }; 31398 var renderDialog$1 = function (spec) { 31399 var _a; 31400 var dialogClass = 'tox-dialog'; 31401 var blockerClass = dialogClass + '-wrap'; 31402 var blockerBackdropClass = blockerClass + '__backdrop'; 31403 var scrollLockClass = dialogClass + '__disable-scroll'; 31404 return ModalDialog.sketch({ 31405 lazySink: spec.lazySink, 31406 onEscape: function (comp) { 31407 spec.onEscape(comp); 31408 return Optional.some(true); 31409 }, 31410 useTabstopAt: function (elem) { 31411 return !isPseudoStop(elem); 31412 }, 31413 dom: { 31414 tag: 'div', 31415 classes: [dialogClass].concat(spec.extraClasses), 31416 styles: __assign({ position: 'relative' }, spec.extraStyles) 31417 }, 31418 components: __spreadArray([ 31419 spec.header, 31420 spec.body 31421 ], spec.footer.toArray(), true), 31422 parts: { 31423 blocker: { 31424 dom: fromHtml('<div class="' + blockerClass + '"></div>'), 31425 components: [{ 31426 dom: { 31427 tag: 'div', 31428 classes: isTouch ? [ 31429 blockerBackdropClass, 31430 blockerBackdropClass + '--opaque' 31431 ] : [blockerBackdropClass] 31432 } 31433 }] 31434 } 31435 }, 31436 dragBlockClass: blockerClass, 31437 modalBehaviours: derive$1(__spreadArray([ 31438 Focusing.config({}), 31439 config('dialog-events', spec.dialogEvents.concat([runOnSource(focusin(), function (comp, _se) { 31440 Keying.focusIn(comp); 31441 })])), 31442 config('scroll-lock', [ 31443 runOnAttached(function () { 31444 add$2(body(), scrollLockClass); 31445 }), 31446 runOnDetached(function () { 31447 remove$2(body(), scrollLockClass); 31448 }) 31449 ]) 31450 ], spec.extraBehaviours, true)), 31451 eventOrder: __assign((_a = {}, _a[execute$5()] = ['dialog-events'], _a[attachedToDom()] = [ 31452 'scroll-lock', 31453 'dialog-events', 31454 'alloy.base.behaviour' 31455 ], _a[detachedFromDom()] = [ 31456 'alloy.base.behaviour', 31457 'dialog-events', 31458 'scroll-lock' 31459 ], _a), spec.eventOrder) 31460 }); 31461 }; 31462 31463 var renderClose = function (providersBackstage) { 31464 return Button.sketch({ 31465 dom: { 31466 tag: 'button', 31467 classes: [ 31468 'tox-button', 31469 'tox-button--icon', 31470 'tox-button--naked' 31471 ], 31472 attributes: { 31473 'type': 'button', 31474 'aria-label': providersBackstage.translate('Close'), 31475 'title': providersBackstage.translate('Close') 31476 } 31477 }, 31478 components: [render$3('close', { 31479 tag: 'div', 31480 classes: ['tox-icon'] 31481 }, providersBackstage.icons)], 31482 action: function (comp) { 31483 emit(comp, formCancelEvent); 31484 } 31485 }); 31486 }; 31487 var renderTitle = function (spec, id, providersBackstage) { 31488 var renderComponents = function (data) { 31489 return [text(providersBackstage.translate(data.title))]; 31490 }; 31491 return { 31492 dom: { 31493 tag: 'div', 31494 classes: ['tox-dialog__title'], 31495 attributes: __assign({}, id.map(function (x) { 31496 return { id: x }; 31497 }).getOr({})) 31498 }, 31499 components: renderComponents(spec), 31500 behaviours: derive$1([Reflecting.config({ 31501 channel: titleChannel, 31502 renderComponents: renderComponents 31503 })]) 31504 }; 31505 }; 31506 var renderDragHandle = function () { 31507 return { dom: fromHtml('<div class="tox-dialog__draghandle"></div>') }; 31508 }; 31509 var renderInlineHeader = function (spec, titleId, providersBackstage) { 31510 return Container.sketch({ 31511 dom: fromHtml('<div class="tox-dialog__header"></div>'), 31512 components: [ 31513 renderTitle(spec, Optional.some(titleId), providersBackstage), 31514 renderDragHandle(), 31515 renderClose(providersBackstage) 31516 ], 31517 containerBehaviours: derive$1([Dragging.config({ 31518 mode: 'mouse', 31519 blockerClass: 'blocker', 31520 getTarget: function (handle) { 31521 return closest$1(handle, '[role="dialog"]').getOrDie(); 31522 }, 31523 snaps: { 31524 getSnapPoints: function () { 31525 return []; 31526 }, 31527 leftAttr: 'data-drag-left', 31528 topAttr: 'data-drag-top' 31529 } 31530 })]) 31531 }); 31532 }; 31533 var renderModalHeader = function (spec, providersBackstage) { 31534 var pTitle = ModalDialog.parts.title(renderTitle(spec, Optional.none(), providersBackstage)); 31535 var pHandle = ModalDialog.parts.draghandle(renderDragHandle()); 31536 var pClose = ModalDialog.parts.close(renderClose(providersBackstage)); 31537 var components = [pTitle].concat(spec.draggable ? [pHandle] : []).concat([pClose]); 31538 return Container.sketch({ 31539 dom: fromHtml('<div class="tox-dialog__header"></div>'), 31540 components: components 31541 }); 31542 }; 31543 31544 var getHeader = function (title, backstage) { 31545 return renderModalHeader({ 31546 title: backstage.shared.providers.translate(title), 31547 draggable: backstage.dialog.isDraggableModal() 31548 }, backstage.shared.providers); 31549 }; 31550 var getBusySpec = function (message, bs, providers) { 31551 return { 31552 dom: { 31553 tag: 'div', 31554 classes: ['tox-dialog__busy-spinner'], 31555 attributes: { 'aria-label': providers.translate(message) }, 31556 styles: { 31557 left: '0px', 31558 right: '0px', 31559 bottom: '0px', 31560 top: '0px', 31561 position: 'absolute' 31562 } 31563 }, 31564 behaviours: bs, 31565 components: [{ dom: fromHtml('<div class="tox-spinner"><div></div><div></div><div></div></div>') }] 31566 }; 31567 }; 31568 var getEventExtras = function (lazyDialog, providers, extra) { 31569 return { 31570 onClose: function () { 31571 return extra.closeWindow(); 31572 }, 31573 onBlock: function (blockEvent) { 31574 ModalDialog.setBusy(lazyDialog(), function (_comp, bs) { 31575 return getBusySpec(blockEvent.message, bs, providers); 31576 }); 31577 }, 31578 onUnblock: function () { 31579 ModalDialog.setIdle(lazyDialog()); 31580 } 31581 }; 31582 }; 31583 var renderModalDialog = function (spec, initialData, dialogEvents, backstage) { 31584 var _a; 31585 var updateState = function (_comp, incoming) { 31586 return Optional.some(incoming); 31587 }; 31588 return build$1(renderDialog$1(__assign(__assign({}, spec), { 31589 lazySink: backstage.shared.getSink, 31590 extraBehaviours: __spreadArray([ 31591 Reflecting.config({ 31592 channel: dialogChannel, 31593 updateState: updateState, 31594 initialData: initialData 31595 }), 31596 RepresentingConfigs.memory({}) 31597 ], spec.extraBehaviours, true), 31598 onEscape: function (comp) { 31599 emit(comp, formCancelEvent); 31600 }, 31601 dialogEvents: dialogEvents, 31602 eventOrder: (_a = {}, _a[receive()] = [ 31603 Reflecting.name(), 31604 Receiving.name() 31605 ], _a[attachedToDom()] = [ 31606 'scroll-lock', 31607 Reflecting.name(), 31608 'messages', 31609 'dialog-events', 31610 'alloy.base.behaviour' 31611 ], _a[detachedFromDom()] = [ 31612 'alloy.base.behaviour', 31613 'dialog-events', 31614 'messages', 31615 Reflecting.name(), 31616 'scroll-lock' 31617 ], _a) 31618 }))); 31619 }; 31620 var mapMenuButtons = function (buttons) { 31621 var mapItems = function (button) { 31622 var items = map$2(button.items, function (item) { 31623 var cell = Cell(false); 31624 return __assign(__assign({}, item), { storage: cell }); 31625 }); 31626 return __assign(__assign({}, button), { items: items }); 31627 }; 31628 return map$2(buttons, function (button) { 31629 if (button.type === 'menu') { 31630 return mapItems(button); 31631 } 31632 return button; 31633 }); 31634 }; 31635 var extractCellsToObject = function (buttons) { 31636 return foldl(buttons, function (acc, button) { 31637 if (button.type === 'menu') { 31638 var menuButton = button; 31639 return foldl(menuButton.items, function (innerAcc, item) { 31640 innerAcc[item.name] = item.storage; 31641 return innerAcc; 31642 }, acc); 31643 } 31644 return acc; 31645 }, {}); 31646 }; 31647 31648 var initCommonEvents = function (fireApiEvent, extras) { 31649 return [ 31650 runWithTarget(focusin(), onFocus), 31651 fireApiEvent(formCloseEvent, function (_api, spec) { 31652 extras.onClose(); 31653 spec.onClose(); 31654 }), 31655 fireApiEvent(formCancelEvent, function (api, spec, _event, self) { 31656 spec.onCancel(api); 31657 emit(self, formCloseEvent); 31658 }), 31659 run$1(formUnblockEvent, function (_c, _se) { 31660 return extras.onUnblock(); 31661 }), 31662 run$1(formBlockEvent, function (_c, se) { 31663 return extras.onBlock(se.event); 31664 }) 31665 ]; 31666 }; 31667 var initUrlDialog = function (getInstanceApi, extras) { 31668 var fireApiEvent = function (eventName, f) { 31669 return run$1(eventName, function (c, se) { 31670 withSpec(c, function (spec, _c) { 31671 f(getInstanceApi(), spec, se.event, c); 31672 }); 31673 }); 31674 }; 31675 var withSpec = function (c, f) { 31676 Reflecting.getState(c).get().each(function (currentDialog) { 31677 f(currentDialog, c); 31678 }); 31679 }; 31680 return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [fireApiEvent(formActionEvent, function (api, spec, event) { 31681 spec.onAction(api, { name: event.name }); 31682 })], false); 31683 }; 31684 var initDialog = function (getInstanceApi, extras, getSink) { 31685 var fireApiEvent = function (eventName, f) { 31686 return run$1(eventName, function (c, se) { 31687 withSpec(c, function (spec, _c) { 31688 f(getInstanceApi(), spec, se.event, c); 31689 }); 31690 }); 31691 }; 31692 var withSpec = function (c, f) { 31693 Reflecting.getState(c).get().each(function (currentDialogInit) { 31694 f(currentDialogInit.internalDialog, c); 31695 }); 31696 }; 31697 return __spreadArray(__spreadArray([], initCommonEvents(fireApiEvent, extras), true), [ 31698 fireApiEvent(formSubmitEvent, function (api, spec) { 31699 return spec.onSubmit(api); 31700 }), 31701 fireApiEvent(formChangeEvent, function (api, spec, event) { 31702 spec.onChange(api, { name: event.name }); 31703 }), 31704 fireApiEvent(formActionEvent, function (api, spec, event, component) { 31705 var focusIn = function () { 31706 return Keying.focusIn(component); 31707 }; 31708 var isDisabled = function (focused) { 31709 return has$1(focused, 'disabled') || getOpt(focused, 'aria-disabled').exists(function (val) { 31710 return val === 'true'; 31711 }); 31712 }; 31713 var rootNode = getRootNode(component.element); 31714 var current = active(rootNode); 31715 spec.onAction(api, { 31716 name: event.name, 31717 value: event.value 31718 }); 31719 active(rootNode).fold(focusIn, function (focused) { 31720 if (isDisabled(focused)) { 31721 focusIn(); 31722 } else if (current.exists(function (cur) { 31723 return contains(focused, cur) && isDisabled(cur); 31724 })) { 31725 focusIn(); 31726 } else { 31727 getSink().toOptional().filter(function (sink) { 31728 return !contains(sink.element, focused); 31729 }).each(focusIn); 31730 } 31731 }); 31732 }), 31733 fireApiEvent(formTabChangeEvent, function (api, spec, event) { 31734 spec.onTabChange(api, { 31735 newTabName: event.name, 31736 oldTabName: event.oldName 31737 }); 31738 }), 31739 runOnDetached(function (component) { 31740 var api = getInstanceApi(); 31741 Representing.setValue(component, api.getData()); 31742 }) 31743 ], false); 31744 }; 31745 var SilverDialogEvents = { 31746 initUrlDialog: initUrlDialog, 31747 initDialog: initDialog 31748 }; 31749 31750 var makeButton = function (button, backstage) { 31751 return renderFooterButton(button, button.type, backstage); 31752 }; 31753 var lookup = function (compInSystem, footerButtons, buttonName) { 31754 return find$5(footerButtons, function (button) { 31755 return button.name === buttonName; 31756 }).bind(function (memButton) { 31757 return memButton.memento.getOpt(compInSystem); 31758 }); 31759 }; 31760 var renderComponents = function (_data, state) { 31761 var footerButtons = state.map(function (s) { 31762 return s.footerButtons; 31763 }).getOr([]); 31764 var buttonGroups = partition$3(footerButtons, function (button) { 31765 return button.align === 'start'; 31766 }); 31767 var makeGroup = function (edge, buttons) { 31768 return Container.sketch({ 31769 dom: { 31770 tag: 'div', 31771 classes: ['tox-dialog__footer-' + edge] 31772 }, 31773 components: map$2(buttons, function (button) { 31774 return button.memento.asSpec(); 31775 }) 31776 }); 31777 }; 31778 var startButtons = makeGroup('start', buttonGroups.pass); 31779 var endButtons = makeGroup('end', buttonGroups.fail); 31780 return [ 31781 startButtons, 31782 endButtons 31783 ]; 31784 }; 31785 var renderFooter = function (initSpec, backstage) { 31786 var updateState = function (_comp, data) { 31787 var footerButtons = map$2(data.buttons, function (button) { 31788 var memButton = record(makeButton(button, backstage)); 31789 return { 31790 name: button.name, 31791 align: button.align, 31792 memento: memButton 31793 }; 31794 }); 31795 var lookupByName = function (compInSystem, buttonName) { 31796 return lookup(compInSystem, footerButtons, buttonName); 31797 }; 31798 return Optional.some({ 31799 lookupByName: lookupByName, 31800 footerButtons: footerButtons 31801 }); 31802 }; 31803 return { 31804 dom: fromHtml('<div class="tox-dialog__footer"></div>'), 31805 components: [], 31806 behaviours: derive$1([Reflecting.config({ 31807 channel: footerChannel, 31808 initialData: initSpec, 31809 updateState: updateState, 31810 renderComponents: renderComponents 31811 })]) 31812 }; 31813 }; 31814 var renderInlineFooter = function (initSpec, backstage) { 31815 return renderFooter(initSpec, backstage); 31816 }; 31817 var renderModalFooter = function (initSpec, backstage) { 31818 return ModalDialog.parts.footer(renderFooter(initSpec, backstage)); 31819 }; 31820 31821 var getCompByName = function (access, name) { 31822 var root = access.getRoot(); 31823 if (root.getSystem().isConnected()) { 31824 var form_1 = Composing.getCurrent(access.getFormWrapper()).getOr(access.getFormWrapper()); 31825 return Form.getField(form_1, name).fold(function () { 31826 var footer = access.getFooter(); 31827 var footerState = Reflecting.getState(footer); 31828 return footerState.get().bind(function (f) { 31829 return f.lookupByName(form_1, name); 31830 }); 31831 }, function (comp) { 31832 return Optional.some(comp); 31833 }); 31834 } else { 31835 return Optional.none(); 31836 } 31837 }; 31838 var validateData$1 = function (access, data) { 31839 var root = access.getRoot(); 31840 return Reflecting.getState(root).get().map(function (dialogState) { 31841 return getOrDie(asRaw('data', dialogState.dataValidator, data)); 31842 }).getOr(data); 31843 }; 31844 var getDialogApi = function (access, doRedial, menuItemStates) { 31845 var withRoot = function (f) { 31846 var root = access.getRoot(); 31847 if (root.getSystem().isConnected()) { 31848 f(root); 31849 } 31850 }; 31851 var getData = function () { 31852 var root = access.getRoot(); 31853 var valueComp = root.getSystem().isConnected() ? access.getFormWrapper() : root; 31854 var representedValues = Representing.getValue(valueComp); 31855 var menuItemCurrentState = map$1(menuItemStates, function (cell) { 31856 return cell.get(); 31857 }); 31858 return __assign(__assign({}, representedValues), menuItemCurrentState); 31859 }; 31860 var setData = function (newData) { 31861 withRoot(function (_) { 31862 var prevData = instanceApi.getData(); 31863 var mergedData = __assign(__assign({}, prevData), newData); 31864 var newInternalData = validateData$1(access, mergedData); 31865 var form = access.getFormWrapper(); 31866 Representing.setValue(form, newInternalData); 31867 each(menuItemStates, function (v, k) { 31868 if (has$2(mergedData, k)) { 31869 v.set(mergedData[k]); 31870 } 31871 }); 31872 }); 31873 }; 31874 var disable = function (name) { 31875 getCompByName(access, name).each(Disabling.disable); 31876 }; 31877 var enable = function (name) { 31878 getCompByName(access, name).each(Disabling.enable); 31879 }; 31880 var focus = function (name) { 31881 getCompByName(access, name).each(Focusing.focus); 31882 }; 31883 var block = function (message) { 31884 if (!isString(message)) { 31885 throw new Error('The dialogInstanceAPI.block function should be passed a blocking message of type string as an argument'); 31886 } 31887 withRoot(function (root) { 31888 emitWith(root, formBlockEvent, { message: message }); 31889 }); 31890 }; 31891 var unblock = function () { 31892 withRoot(function (root) { 31893 emit(root, formUnblockEvent); 31894 }); 31895 }; 31896 var showTab = function (name) { 31897 withRoot(function (_) { 31898 var body = access.getBody(); 31899 var bodyState = Reflecting.getState(body); 31900 if (bodyState.get().exists(function (b) { 31901 return b.isTabPanel(); 31902 })) { 31903 Composing.getCurrent(body).each(function (tabSection) { 31904 TabSection.showTab(tabSection, name); 31905 }); 31906 } 31907 }); 31908 }; 31909 var redial = function (d) { 31910 withRoot(function (root) { 31911 var dialogInit = doRedial(d); 31912 root.getSystem().broadcastOn([dialogChannel], dialogInit); 31913 root.getSystem().broadcastOn([titleChannel], dialogInit.internalDialog); 31914 root.getSystem().broadcastOn([bodyChannel], dialogInit.internalDialog); 31915 root.getSystem().broadcastOn([footerChannel], dialogInit.internalDialog); 31916 instanceApi.setData(dialogInit.initialData); 31917 }); 31918 }; 31919 var close = function () { 31920 withRoot(function (root) { 31921 emit(root, formCloseEvent); 31922 }); 31923 }; 31924 var instanceApi = { 31925 getData: getData, 31926 setData: setData, 31927 disable: disable, 31928 enable: enable, 31929 focus: focus, 31930 block: block, 31931 unblock: unblock, 31932 showTab: showTab, 31933 redial: redial, 31934 close: close 31935 }; 31936 return instanceApi; 31937 }; 31938 31939 var getDialogSizeClasses = function (size) { 31940 switch (size) { 31941 case 'large': 31942 return ['tox-dialog--width-lg']; 31943 case 'medium': 31944 return ['tox-dialog--width-md']; 31945 default: 31946 return []; 31947 } 31948 }; 31949 var renderDialog = function (dialogInit, extra, backstage) { 31950 var header = getHeader(dialogInit.internalDialog.title, backstage); 31951 var body = renderModalBody({ body: dialogInit.internalDialog.body }, backstage); 31952 var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons); 31953 var objOfCells = extractCellsToObject(storagedMenuButtons); 31954 var footer = renderModalFooter({ buttons: storagedMenuButtons }, backstage); 31955 var dialogEvents = SilverDialogEvents.initDialog(function () { 31956 return instanceApi; 31957 }, getEventExtras(function () { 31958 return dialog; 31959 }, backstage.shared.providers, extra), backstage.shared.getSink); 31960 var dialogSize = getDialogSizeClasses(dialogInit.internalDialog.size); 31961 var spec = { 31962 header: header, 31963 body: body, 31964 footer: Optional.some(footer), 31965 extraClasses: dialogSize, 31966 extraBehaviours: [], 31967 extraStyles: {} 31968 }; 31969 var dialog = renderModalDialog(spec, dialogInit, dialogEvents, backstage); 31970 var modalAccess = function () { 31971 var getForm = function () { 31972 var outerForm = ModalDialog.getBody(dialog); 31973 return Composing.getCurrent(outerForm).getOr(outerForm); 31974 }; 31975 return { 31976 getRoot: constant$1(dialog), 31977 getBody: function () { 31978 return ModalDialog.getBody(dialog); 31979 }, 31980 getFooter: function () { 31981 return ModalDialog.getFooter(dialog); 31982 }, 31983 getFormWrapper: getForm 31984 }; 31985 }(); 31986 var instanceApi = getDialogApi(modalAccess, extra.redial, objOfCells); 31987 return { 31988 dialog: dialog, 31989 instanceApi: instanceApi 31990 }; 31991 }; 31992 31993 var renderInlineDialog = function (dialogInit, extra, backstage, ariaAttrs) { 31994 var _a, _b; 31995 var dialogLabelId = generate$6('dialog-label'); 31996 var dialogContentId = generate$6('dialog-content'); 31997 var updateState = function (_comp, incoming) { 31998 return Optional.some(incoming); 31999 }; 32000 var memHeader = record(renderInlineHeader({ 32001 title: dialogInit.internalDialog.title, 32002 draggable: true 32003 }, dialogLabelId, backstage.shared.providers)); 32004 var memBody = record(renderInlineBody({ body: dialogInit.internalDialog.body }, dialogContentId, backstage, ariaAttrs)); 32005 var storagedMenuButtons = mapMenuButtons(dialogInit.internalDialog.buttons); 32006 var objOfCells = extractCellsToObject(storagedMenuButtons); 32007 var memFooter = record(renderInlineFooter({ buttons: storagedMenuButtons }, backstage)); 32008 var dialogEvents = SilverDialogEvents.initDialog(function () { 32009 return instanceApi; 32010 }, { 32011 onBlock: function (event) { 32012 Blocking.block(dialog, function (_comp, bs) { 32013 return getBusySpec(event.message, bs, backstage.shared.providers); 32014 }); 32015 }, 32016 onUnblock: function () { 32017 Blocking.unblock(dialog); 32018 }, 32019 onClose: function () { 32020 return extra.closeWindow(); 32021 } 32022 }, backstage.shared.getSink); 32023 var dialog = build$1({ 32024 dom: { 32025 tag: 'div', 32026 classes: [ 32027 'tox-dialog', 32028 'tox-dialog-inline' 32029 ], 32030 attributes: (_a = { role: 'dialog' }, _a['aria-labelledby'] = dialogLabelId, _a['aria-describedby'] = dialogContentId, _a) 32031 }, 32032 eventOrder: (_b = {}, _b[receive()] = [ 32033 Reflecting.name(), 32034 Receiving.name() 32035 ], _b[execute$5()] = ['execute-on-form'], _b[attachedToDom()] = [ 32036 'reflecting', 32037 'execute-on-form' 32038 ], _b), 32039 behaviours: derive$1([ 32040 Keying.config({ 32041 mode: 'cyclic', 32042 onEscape: function (c) { 32043 emit(c, formCloseEvent); 32044 return Optional.some(true); 32045 }, 32046 useTabstopAt: function (elem) { 32047 return !isPseudoStop(elem) && (name$2(elem) !== 'button' || get$d(elem, 'disabled') !== 'disabled'); 32048 } 32049 }), 32050 Reflecting.config({ 32051 channel: dialogChannel, 32052 updateState: updateState, 32053 initialData: dialogInit 32054 }), 32055 Focusing.config({}), 32056 config('execute-on-form', dialogEvents.concat([runOnSource(focusin(), function (comp, _se) { 32057 Keying.focusIn(comp); 32058 })])), 32059 Blocking.config({ 32060 getRoot: function () { 32061 return Optional.some(dialog); 32062 } 32063 }), 32064 Replacing.config({}), 32065 RepresentingConfigs.memory({}) 32066 ]), 32067 components: [ 32068 memHeader.asSpec(), 32069 memBody.asSpec(), 32070 memFooter.asSpec() 32071 ] 32072 }); 32073 var instanceApi = getDialogApi({ 32074 getRoot: constant$1(dialog), 32075 getFooter: function () { 32076 return memFooter.get(dialog); 32077 }, 32078 getBody: function () { 32079 return memBody.get(dialog); 32080 }, 32081 getFormWrapper: function () { 32082 var body = memBody.get(dialog); 32083 return Composing.getCurrent(body).getOr(body); 32084 } 32085 }, extra.redial, objOfCells); 32086 return { 32087 dialog: dialog, 32088 instanceApi: instanceApi 32089 }; 32090 }; 32091 32092 var global$1 = tinymce.util.Tools.resolve('tinymce.util.URI'); 32093 32094 var getUrlDialogApi = function (root) { 32095 var withRoot = function (f) { 32096 if (root.getSystem().isConnected()) { 32097 f(root); 32098 } 32099 }; 32100 var block = function (message) { 32101 if (!isString(message)) { 32102 throw new Error('The urlDialogInstanceAPI.block function should be passed a blocking message of type string as an argument'); 32103 } 32104 withRoot(function (root) { 32105 emitWith(root, formBlockEvent, { message: message }); 32106 }); 32107 }; 32108 var unblock = function () { 32109 withRoot(function (root) { 32110 emit(root, formUnblockEvent); 32111 }); 32112 }; 32113 var close = function () { 32114 withRoot(function (root) { 32115 emit(root, formCloseEvent); 32116 }); 32117 }; 32118 var sendMessage = function (data) { 32119 withRoot(function (root) { 32120 root.getSystem().broadcastOn([bodySendMessageChannel], data); 32121 }); 32122 }; 32123 return { 32124 block: block, 32125 unblock: unblock, 32126 close: close, 32127 sendMessage: sendMessage 32128 }; 32129 }; 32130 32131 var SUPPORTED_MESSAGE_ACTIONS = [ 32132 'insertContent', 32133 'setContent', 32134 'execCommand', 32135 'close', 32136 'block', 32137 'unblock' 32138 ]; 32139 var isSupportedMessage = function (data) { 32140 return isObject(data) && SUPPORTED_MESSAGE_ACTIONS.indexOf(data.mceAction) !== -1; 32141 }; 32142 var isCustomMessage = function (data) { 32143 return !isSupportedMessage(data) && isObject(data) && has$2(data, 'mceAction'); 32144 }; 32145 var handleMessage = function (editor, api, data) { 32146 switch (data.mceAction) { 32147 case 'insertContent': 32148 editor.insertContent(data.content); 32149 break; 32150 case 'setContent': 32151 editor.setContent(data.content); 32152 break; 32153 case 'execCommand': 32154 var ui = isBoolean(data.ui) ? data.ui : false; 32155 editor.execCommand(data.cmd, ui, data.value); 32156 break; 32157 case 'close': 32158 api.close(); 32159 break; 32160 case 'block': 32161 api.block(data.message); 32162 break; 32163 case 'unblock': 32164 api.unblock(); 32165 break; 32166 } 32167 }; 32168 var renderUrlDialog = function (internalDialog, extra, editor, backstage) { 32169 var _a; 32170 var header = getHeader(internalDialog.title, backstage); 32171 var body = renderIframeBody(internalDialog); 32172 var footer = internalDialog.buttons.bind(function (buttons) { 32173 if (buttons.length === 0) { 32174 return Optional.none(); 32175 } else { 32176 return Optional.some(renderModalFooter({ buttons: buttons }, backstage)); 32177 } 32178 }); 32179 var dialogEvents = SilverDialogEvents.initUrlDialog(function () { 32180 return instanceApi; 32181 }, getEventExtras(function () { 32182 return dialog; 32183 }, backstage.shared.providers, extra)); 32184 var styles = __assign(__assign({}, internalDialog.height.fold(function () { 32185 return {}; 32186 }, function (height) { 32187 return { 32188 'height': height + 'px', 32189 'max-height': height + 'px' 32190 }; 32191 })), internalDialog.width.fold(function () { 32192 return {}; 32193 }, function (width) { 32194 return { 32195 'width': width + 'px', 32196 'max-width': width + 'px' 32197 }; 32198 })); 32199 var classes = internalDialog.width.isNone() && internalDialog.height.isNone() ? ['tox-dialog--width-lg'] : []; 32200 var iframeUri = new global$1(internalDialog.url, { base_uri: new global$1(window.location.href) }); 32201 var iframeDomain = iframeUri.protocol + '://' + iframeUri.host + (iframeUri.port ? ':' + iframeUri.port : ''); 32202 var messageHandlerUnbinder = unbindable(); 32203 var extraBehaviours = [ 32204 config('messages', [ 32205 runOnAttached(function () { 32206 var unbind = bind(SugarElement.fromDom(window), 'message', function (e) { 32207 if (iframeUri.isSameOrigin(new global$1(e.raw.origin))) { 32208 var data = e.raw.data; 32209 if (isSupportedMessage(data)) { 32210 handleMessage(editor, instanceApi, data); 32211 } else if (isCustomMessage(data)) { 32212 internalDialog.onMessage(instanceApi, data); 32213 } 32214 } 32215 }); 32216 messageHandlerUnbinder.set(unbind); 32217 }), 32218 runOnDetached(messageHandlerUnbinder.clear) 32219 ]), 32220 Receiving.config({ 32221 channels: (_a = {}, _a[bodySendMessageChannel] = { 32222 onReceive: function (comp, data) { 32223 descendant(comp.element, 'iframe').each(function (iframeEle) { 32224 var iframeWin = iframeEle.dom.contentWindow; 32225 iframeWin.postMessage(data, iframeDomain); 32226 }); 32227 } 32228 }, _a) 32229 }) 32230 ]; 32231 var spec = { 32232 header: header, 32233 body: body, 32234 footer: footer, 32235 extraClasses: classes, 32236 extraBehaviours: extraBehaviours, 32237 extraStyles: styles 32238 }; 32239 var dialog = renderModalDialog(spec, internalDialog, dialogEvents, backstage); 32240 var instanceApi = getUrlDialogApi(dialog); 32241 return { 32242 dialog: dialog, 32243 instanceApi: instanceApi 32244 }; 32245 }; 32246 32247 var setup$2 = function (extras) { 32248 var sharedBackstage = extras.backstage.shared; 32249 var open = function (message, callback) { 32250 var closeDialog = function () { 32251 ModalDialog.hide(alertDialog); 32252 callback(); 32253 }; 32254 var memFooterClose = record(renderFooterButton({ 32255 name: 'close-alert', 32256 text: 'OK', 32257 primary: true, 32258 align: 'end', 32259 disabled: false, 32260 icon: Optional.none() 32261 }, 'cancel', extras.backstage)); 32262 var titleSpec = pUntitled(); 32263 var closeSpec = pClose(closeDialog, sharedBackstage.providers); 32264 var alertDialog = build$1(renderDialog$1({ 32265 lazySink: function () { 32266 return sharedBackstage.getSink(); 32267 }, 32268 header: hiddenHeader(titleSpec, closeSpec), 32269 body: pBodyMessage(message, sharedBackstage.providers), 32270 footer: Optional.some(pFooter(pFooterGroup([], [memFooterClose.asSpec()]))), 32271 onEscape: closeDialog, 32272 extraClasses: ['tox-alert-dialog'], 32273 extraBehaviours: [], 32274 extraStyles: {}, 32275 dialogEvents: [run$1(formCancelEvent, closeDialog)], 32276 eventOrder: {} 32277 })); 32278 ModalDialog.show(alertDialog); 32279 var footerCloseButton = memFooterClose.get(alertDialog); 32280 Focusing.focus(footerCloseButton); 32281 }; 32282 return { open: open }; 32283 }; 32284 32285 var setup$1 = function (extras) { 32286 var sharedBackstage = extras.backstage.shared; 32287 var open = function (message, callback) { 32288 var closeDialog = function (state) { 32289 ModalDialog.hide(confirmDialog); 32290 callback(state); 32291 }; 32292 var memFooterYes = record(renderFooterButton({ 32293 name: 'yes', 32294 text: 'Yes', 32295 primary: true, 32296 align: 'end', 32297 disabled: false, 32298 icon: Optional.none() 32299 }, 'submit', extras.backstage)); 32300 var footerNo = renderFooterButton({ 32301 name: 'no', 32302 text: 'No', 32303 primary: false, 32304 align: 'end', 32305 disabled: false, 32306 icon: Optional.none() 32307 }, 'cancel', extras.backstage); 32308 var titleSpec = pUntitled(); 32309 var closeSpec = pClose(function () { 32310 return closeDialog(false); 32311 }, sharedBackstage.providers); 32312 var confirmDialog = build$1(renderDialog$1({ 32313 lazySink: function () { 32314 return sharedBackstage.getSink(); 32315 }, 32316 header: hiddenHeader(titleSpec, closeSpec), 32317 body: pBodyMessage(message, sharedBackstage.providers), 32318 footer: Optional.some(pFooter(pFooterGroup([], [ 32319 footerNo, 32320 memFooterYes.asSpec() 32321 ]))), 32322 onEscape: function () { 32323 return closeDialog(false); 32324 }, 32325 extraClasses: ['tox-confirm-dialog'], 32326 extraBehaviours: [], 32327 extraStyles: {}, 32328 dialogEvents: [ 32329 run$1(formCancelEvent, function () { 32330 return closeDialog(false); 32331 }), 32332 run$1(formSubmitEvent, function () { 32333 return closeDialog(true); 32334 }) 32335 ], 32336 eventOrder: {} 32337 })); 32338 ModalDialog.show(confirmDialog); 32339 var footerYesButton = memFooterYes.get(confirmDialog); 32340 Focusing.focus(footerYesButton); 32341 }; 32342 return { open: open }; 32343 }; 32344 32345 var validateData = function (data, validator) { 32346 return getOrDie(asRaw('data', validator, data)); 32347 }; 32348 var isAlertOrConfirmDialog = function (target) { 32349 return closest(target, '.tox-alert-dialog') || closest(target, '.tox-confirm-dialog'); 32350 }; 32351 var inlineAdditionalBehaviours = function (editor, isStickyToolbar, isToolbarLocationTop) { 32352 if (isStickyToolbar && isToolbarLocationTop) { 32353 return []; 32354 } else { 32355 return [Docking.config({ 32356 contextual: { 32357 lazyContext: function () { 32358 return Optional.some(box$1(SugarElement.fromDom(editor.getContentAreaContainer()))); 32359 }, 32360 fadeInClass: 'tox-dialog-dock-fadein', 32361 fadeOutClass: 'tox-dialog-dock-fadeout', 32362 transitionClass: 'tox-dialog-dock-transition' 32363 }, 32364 modes: ['top'] 32365 })]; 32366 } 32367 }; 32368 var setup = function (extras) { 32369 var backstage = extras.backstage; 32370 var editor = extras.editor; 32371 var isStickyToolbar$1 = isStickyToolbar(editor); 32372 var alertDialog = setup$2(extras); 32373 var confirmDialog = setup$1(extras); 32374 var open = function (config, params, closeWindow) { 32375 if (params !== undefined && params.inline === 'toolbar') { 32376 return openInlineDialog(config, backstage.shared.anchors.inlineDialog(), closeWindow, params.ariaAttrs); 32377 } else if (params !== undefined && params.inline === 'cursor') { 32378 return openInlineDialog(config, backstage.shared.anchors.cursor(), closeWindow, params.ariaAttrs); 32379 } else { 32380 return openModalDialog(config, closeWindow); 32381 } 32382 }; 32383 var openUrl = function (config, closeWindow) { 32384 return openModalUrlDialog(config, closeWindow); 32385 }; 32386 var openModalUrlDialog = function (config, closeWindow) { 32387 var factory = function (contents) { 32388 var dialog = renderUrlDialog(contents, { 32389 closeWindow: function () { 32390 ModalDialog.hide(dialog.dialog); 32391 closeWindow(dialog.instanceApi); 32392 } 32393 }, editor, backstage); 32394 ModalDialog.show(dialog.dialog); 32395 return dialog.instanceApi; 32396 }; 32397 return DialogManager.openUrl(factory, config); 32398 }; 32399 var openModalDialog = function (config, closeWindow) { 32400 var factory = function (contents, internalInitialData, dataValidator) { 32401 var initialData = internalInitialData; 32402 var dialogInit = { 32403 dataValidator: dataValidator, 32404 initialData: initialData, 32405 internalDialog: contents 32406 }; 32407 var dialog = renderDialog(dialogInit, { 32408 redial: DialogManager.redial, 32409 closeWindow: function () { 32410 ModalDialog.hide(dialog.dialog); 32411 closeWindow(dialog.instanceApi); 32412 } 32413 }, backstage); 32414 ModalDialog.show(dialog.dialog); 32415 dialog.instanceApi.setData(initialData); 32416 return dialog.instanceApi; 32417 }; 32418 return DialogManager.open(factory, config); 32419 }; 32420 var openInlineDialog = function (config$1, anchor, closeWindow, ariaAttrs) { 32421 var factory = function (contents, internalInitialData, dataValidator) { 32422 var initialData = validateData(internalInitialData, dataValidator); 32423 var inlineDialog = value$1(); 32424 var isToolbarLocationTop = backstage.shared.header.isPositionedAtTop(); 32425 var dialogInit = { 32426 dataValidator: dataValidator, 32427 initialData: initialData, 32428 internalDialog: contents 32429 }; 32430 var refreshDocking = function () { 32431 return inlineDialog.on(function (dialog) { 32432 InlineView.reposition(dialog); 32433 Docking.refresh(dialog); 32434 }); 32435 }; 32436 var dialogUi = renderInlineDialog(dialogInit, { 32437 redial: DialogManager.redial, 32438 closeWindow: function () { 32439 inlineDialog.on(InlineView.hide); 32440 editor.off('ResizeEditor', refreshDocking); 32441 inlineDialog.clear(); 32442 closeWindow(dialogUi.instanceApi); 32443 } 32444 }, backstage, ariaAttrs); 32445 var inlineDialogComp = build$1(InlineView.sketch(__assign(__assign({ 32446 lazySink: backstage.shared.getSink, 32447 dom: { 32448 tag: 'div', 32449 classes: [] 32450 }, 32451 fireDismissalEventInstead: {} 32452 }, isToolbarLocationTop ? {} : { fireRepositionEventInstead: {} }), { 32453 inlineBehaviours: derive$1(__spreadArray([config('window-manager-inline-events', [run$1(dismissRequested(), function (_comp, _se) { 32454 emit(dialogUi.dialog, formCancelEvent); 32455 })])], inlineAdditionalBehaviours(editor, isStickyToolbar$1, isToolbarLocationTop), true)), 32456 isExtraPart: function (_comp, target) { 32457 return isAlertOrConfirmDialog(target); 32458 } 32459 }))); 32460 inlineDialog.set(inlineDialogComp); 32461 InlineView.showWithin(inlineDialogComp, premade(dialogUi.dialog), { anchor: anchor }, Optional.some(body())); 32462 if (!isStickyToolbar$1 || !isToolbarLocationTop) { 32463 Docking.refresh(inlineDialogComp); 32464 editor.on('ResizeEditor', refreshDocking); 32465 } 32466 dialogUi.instanceApi.setData(initialData); 32467 Keying.focusIn(dialogUi.dialog); 32468 return dialogUi.instanceApi; 32469 }; 32470 return DialogManager.open(factory, config$1); 32471 }; 32472 var confirm = function (message, callback) { 32473 confirmDialog.open(message, function (state) { 32474 callback(state); 32475 }); 32476 }; 32477 var alert = function (message, callback) { 32478 alertDialog.open(message, function () { 32479 callback(); 32480 }); 32481 }; 32482 var close = function (instanceApi) { 32483 instanceApi.close(); 32484 }; 32485 return { 32486 open: open, 32487 openUrl: openUrl, 32488 alert: alert, 32489 close: close, 32490 confirm: confirm 32491 }; 32492 }; 32493 32494 function Theme () { 32495 global$g.add('silver', function (editor) { 32496 var _a = setup$3(editor), uiMothership = _a.uiMothership, backstage = _a.backstage, renderUI = _a.renderUI, getUi = _a.getUi; 32497 Autocompleter.register(editor, backstage.shared); 32498 var windowMgr = setup({ 32499 editor: editor, 32500 backstage: backstage 32501 }); 32502 return { 32503 renderUI: renderUI, 32504 getWindowManagerImpl: constant$1(windowMgr), 32505 getNotificationManagerImpl: function () { 32506 return NotificationManagerImpl(editor, { backstage: backstage }, uiMothership); 32507 }, 32508 ui: getUi() 32509 }; 32510 }); 32511 } 32512 32513 Theme(); 32514 32515 }());
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 |