Completed
Branch master (2f299a)
by Ron
09:20
created

public/js/tinymce/themes/mobile/theme.js   F

Complexity

Total Complexity 2857
Complexity/F 1.25

Size

Lines of Code 12634
Function Count 2290

Duplication

Duplicated Lines 469
Ratio 3.71 %

Importance

Changes 0
Metric Value
eloc 9203
nc 0
dl 469
loc 12634
c 0
b 0
f 0
cc 0
rs 0.8
wmc 2857
mnd 5
bc 2586
fnc 2290
bpm 1.1292
cpm 1.2475
noi 27

1010 Functions

Rating   Name   Duplication   Size   Complexity  
A theme.js ➔ fasttrack 0 6 2
A theme.js ➔ diagnose 0 4 1
A theme.js ➔ register$2 0 36 1
A theme.js ➔ shrink 0 5 2
A theme.js ➔ hasShrunk 0 3 1
A theme.js ➔ siblings 0 8 1
A theme.js ➔ getAttrs$1 0 11 1
A theme.js ➔ stubborn 0 27 1
A theme.js ➔ configureMenu 0 8 1
A theme.js ➔ foldl 0 6 1
A theme.js ➔ relativeToNative 0 6 1
A theme.js ➔ accountableKeyboardHeight 0 7 4
A theme.js ➔ onHover 0 8 4
A theme.js ➔ onlyOne 0 15 3
A theme.js ➔ substitute 0 14 1
A theme.js ➔ map 0 8 1
A theme.js ➔ Dimension(ꞌwidthꞌ) 0 3 1
A theme.js ➔ tryNext 0 4 1
A theme.js ➔ exhibit$2 0 11 1
A theme.js ➔ getBody 0 6 3
A theme.js ➔ type 0 3 1
A theme.js ➔ hasNative 0 3 1
A theme.js ➔ unsuppMessage 0 3 1
A theme.js ➔ isDangerous 0 7 1
A theme.js ➔ defaultUidsSchema 0 5 1
A theme.js ➔ onUnload$1 0 3 1
A theme.js ➔ toEvents 0 3 1
A theme.js ➔ locateInElement 0 10 2
A theme.js ➔ isType$1 0 5 1
A theme.js ➔ unsupportedFields 0 5 1
A theme.js ➔ classifyScrolling 0 3 1
A theme.js ➔ transpose 0 8 1
A theme.js ➔ unknown$1 0 6 1
A theme.js ➔ dataUriToBlob 0 7 1
A theme.js ➔ getEnd 0 7 2
A theme.js ➔ builder 0 32 2
A theme.js ➔ descendants$1 0 3 1
A theme.js ➔ get3dContext 0 11 2
A theme.js ➔ readOpt$1 0 3 1
A theme.js ➔ cycleDown$1 0 3 1
A theme.js ➔ getEventSource 0 14 5
A theme.js ➔ query 0 4 1
A theme.js ➔ runOnSourceName 0 14 1
A theme.js ➔ fromPoint 0 4 1
A theme.js ➔ getAttrs 0 10 2
A theme.js ➔ toModification 0 5 1
A theme.js ➔ read$1 0 4 3
A theme.js ➔ scan 0 7 2
A theme.js ➔ parse 0 3 1
A composite$1.apis.resetToMin 0 3 1
A theme.js ➔ difference 0 5 1
A theme.js ➔ arrOf 0 19 1
A theme.js ➔ defaulted 0 3 1
A theme.js ➔ toggleGrow 0 4 2
A theme.js ➔ substituteAll 0 5 1
A theme.js ➔ each 0 8 2
A theme.js ➔ field$2 0 45 1
A theme.js ➔ doDefaultExecute 0 4 1
B theme.js ➔ takeover$1 0 45 1
B theme.js ➔ init$3 0 63 1
A theme.js ➔ has$1 0 4 3
A theme.js ➔ toMatrix 0 5 1
A theme.js ➔ write 0 5 1
A theme.js ➔ tryPrev 0 4 1
A theme.js ➔ useH 0 6 1
A theme.js ➔ locate$1 0 11 1
A theme.js ➔ timid 0 20 1
A theme.js ➔ doSetNativeRange 0 6 1
A theme.js ➔ derive 0 3 1
A theme.js ➔ get$2 0 3 1
A theme.js ➔ orientation 0 3 1
A theme.js ➔ exactly 0 3 1
A theme.js ➔ subPlaceholder 0 12 2
A theme.js ➔ tupleMap 0 8 1
B theme.js ➔ findValueOfX 0 13 6
A theme.js ➔ onStrictKeyboardHandler 0 3 1
A theme.js ➔ dataUriToBlobSync$1 0 3 1
A theme.js ➔ hasFocus 0 4 1
A theme.js ➔ trace 0 8 1
A theme.js ➔ collapsedRect 0 10 1
A theme.js ➔ noLink 0 10 1
A theme.js ➔ detect 0 6 2
A theme.js ➔ create$5 0 31 1
A theme.js ➔ getStart 0 3 1
A theme.js ➔ getFirstRect$1 0 4 1
A theme.js ➔ mergeErrors 0 3 1
A theme.js ➔ moveRight$2 0 3 1
A theme.js ➔ deregister 0 3 1
A theme.js ➔ flatten 0 9 3
A theme.js ➔ setToLedge 0 3 1
A theme.js ➔ detectBrowser 0 9 1
A theme.js ➔ markAsHorizontal 0 3 1
A theme.js ➔ narrow 0 9 1
A theme.js ➔ getBodyFromFrame 0 3 1
A theme.js ➔ par$1 0 3 1
A theme.js ➔ slowIndexOf 0 8 3
A theme.js ➔ isTextNodeWithCursorPosition 0 5 1
A theme.js ➔ progressTo 0 12 1
A theme.js ➔ triggerUntilStopped 0 4 1
A theme.js ➔ dehighlight 0 7 2
A theme.js ➔ groupByEvents 0 4 1
A theme.js ➔ detect$1 0 6 1
A theme.js ➔ imageToBlob 0 7 2
A theme.js ➔ TAB 0 3 1
A theme.js ➔ siblings$2 0 5 1
B theme.js ➔ makeSlider 0 49 1
A theme.js ➔ api$2 0 28 1
A theme.js ➔ setToRedge 0 3 1
A theme.js ➔ nu$1 0 14 1
A theme.js ➔ parents 0 15 5
A theme.js ➔ exhibit 0 3 1
A theme.js ➔ defaultedThunk 0 3 1
A theme.js ➔ onStrictHandler 0 3 1
A theme.js ➔ filter 0 10 3
A theme.js ➔ cycleLeft$1 0 3 1
A theme.js ➔ execute$1 0 3 1
A theme.js ➔ preserve$1 0 5 1
A theme.js ➔ events$5 0 11 2
A theme.js ➔ findCurrent$1 0 5 1
A theme.js ➔ markAsBehaviourApi 0 13 1
A theme.js ➔ state$1 0 3 1
A theme.js ➔ hasKey 0 3 1
A theme.js ➔ cata 0 3 1
A theme.js ➔ DelayedFunction 0 23 1
A theme.js ➔ init 0 3 1
A theme.js ➔ onLoad 0 4 2
A theme.js ➔ extract$1 0 4 2
A theme.js ➔ dispatchWith 0 4 1
A theme.js ➔ register$1 0 49 1
A theme.js ➔ chooseChannels 0 5 2
A theme.js ➔ id 3 3 1
A theme.js ➔ cat 0 10 2
A theme.js ➔ documentPositionPreceding 0 3 1
A theme.js ➔ blobToCanvas 0 10 1
A theme.js ➔ chooseFrom 0 8 1
A theme.js ➔ locate$2 0 8 1
A theme.js ➔ Blob 0 4 1
A theme.js ➔ ancestor 0 13 5
A theme.js ➔ findDelta 0 5 2
A theme.js ➔ assemble 0 18 1
A theme.js ➔ one 0 4 3
A theme.js ➔ append$2 0 3 1
A rawIndexOf.constructor 0 10 2
A theme.js ➔ remove$3 0 3 1
A theme.js ➔ execute$2 0 5 1
A theme.js ➔ applySize 0 6 2
A theme.js ➔ doSetRange 0 4 1
A theme.js ➔ owner$2 0 3 1
A theme.js ➔ insert 0 4 1
A theme.js ➔ fromTag 0 5 1
A theme.js ➔ on 0 4 1
A theme.js ➔ rawSet 0 8 4
A theme.js ➔ set$5 0 3 1
A theme.js ➔ asRawOrDie 0 3 1
A theme.js ➔ extract 0 8 1
A theme.js ➔ first$3 0 3 1
A theme.js ➔ moveScrollAndTop 0 15 1
A theme.js ➔ blobToDataUri 0 9 1
A theme.js ➔ setLegacyRtlRange 0 4 1
A theme.js ➔ events$1 0 8 2
A theme.js ➔ strictOf 0 3 1
A theme.js ➔ makeApi 0 10 1
A theme.js ➔ requestAnimationFrame 0 4 1
A theme.js ➔ locateVisible 0 4 1
A theme.js ➔ cycleUp 0 3 1
A theme.js ➔ not 0 9 1
A theme.js ➔ combine$2 0 4 1
A theme.js ➔ identifyFromArray 0 5 1
A theme.js ➔ schemas 0 7 1
A theme.js ➔ use 0 9 1
A theme.js ➔ set$1 0 9 1
A theme.js ➔ doCreate 0 50 1
A theme.js ➔ getCurrent 0 3 1
A theme.js ➔ input$1 0 13 1
A theme.js ➔ asStruct 0 3 1
A theme.js ➔ getValue$2 0 3 1
A theme.js ➔ custom 0 5 1
A NoState.init 0 7 1
A theme.js ➔ unknown$2 0 6 1
A theme.js ➔ owner 0 3 1
A theme.js ➔ getState 0 4 2
B theme.js ➔ create$8 0 101 1
A theme.js ➔ dom$1 0 4 1
A theme.js ➔ wrapApi 0 20 1
A theme.js ➔ defaultedObjOf 0 3 1
A theme.js ➔ register 0 3 1
A theme.js ➔ sketch$2 0 16 1
A theme.js ➔ isDisabled 0 3 2
A theme.js ➔ onKeyboardHandler 0 3 1
A theme.js ➔ remove$4 0 8 2
A theme.js ➔ fallbackAccess 0 6 1
A theme.js ➔ mergeValues 0 3 1
A theme.js ➔ get$6 0 3 1
A theme.js ➔ events$2 0 23 2
A theme.js ➔ find$2 0 9 3
A theme.js ➔ DOWN 0 3 1
A theme.js ➔ isRecursive 0 3 1
A theme.js ➔ bypassSelector 0 3 1
A theme.js ➔ highlightFirst 0 5 1
A createModes$1.active.events 0 4 1
A theme.js ➔ edgePart 0 17 1
A theme.js ➔ exhibit$1 0 7 2
A theme.js ➔ getBounds$2 0 4 2
A required.overrides 0 9 1
A theme.js ➔ makeItem 0 29 3
A theme.js ➔ get$7 0 3 1
A theme.js ➔ makeSocket 0 7 1
A theme.js ➔ onPresenceHandler 0 12 1
A theme.js ➔ doTriggerHandler 0 27 1
A theme.js ➔ none 0 3 1
A theme.js ➔ init$1 0 3 1
A theme.js ➔ noop$$1 2 2 1
A theme.js ➔ fromText 0 5 1
A theme.js ➔ isSource 0 3 1
A theme.js ➔ get$4 0 7 4
A theme.js ➔ prune 0 15 1
A theme.js ➔ updatePressed 0 6 2
B theme.js ➔ value$1 0 53 1
A theme.js ➔ closest$2 0 3 1
A theme.js ➔ receive$1 0 6 1
A theme.js ➔ onChange 0 35 1
A theme.js ➔ generate$2 0 16 1
A theme.js ➔ canScrollVertically 0 6 1
A theme.js ➔ execute$4 0 5 1
A theme.js ➔ makeRange 0 7 1
A theme.js ➔ compose 0 9 1
B theme.js ➔ create$2 0 88 1
A theme.js ➔ moveHorizontal 0 6 1
A theme.js ➔ cutter 0 5 1
A theme.js ➔ bind$2 0 3 1
A theme.js ➔ from 0 3 3
A theme.js ➔ wasSimple 0 5 1
A theme.js ➔ events$4 0 3 1
A theme.js ➔ cycleRight 0 3 1
A theme.js ➔ preserve$2 0 18 1
A theme.js ➔ findMap 0 9 3
A theme.js ➔ optionObjOfOnly 0 3 1
A theme.js ➔ contains$1 0 3 1
A theme.js ➔ readOr 0 5 1
A theme.js ➔ RIGHT 0 3 1
A theme.js ➔ nextSibling 0 4 1
A theme.js ➔ fuse$1 0 13 2
A theme.js ➔ readOptFrom$1 0 3 1
A theme.js ➔ blobToDataUri$1 0 3 1
A theme.js ➔ clear 0 4 1
A theme.js ➔ cycleUp$1 0 3 1
A createModes$1.apis.setGridSize 0 7 2
A theme.js ➔ getRules$5 0 27 1
A theme.js ➔ doGetExact 0 5 2
A theme.js ➔ SPACE 0 3 1
A theme.js ➔ showEdit 0 3 1
A theme.js ➔ updateTop 0 4 1
A theme.js ➔ optionAccess 0 3 1
A theme.js ➔ moveRight$1 0 3 1
A theme.js ➔ map$1 0 9 2
A theme.js ➔ getByIndex 0 6 1
A theme.js ➔ createCollapsedNode 0 6 1
A theme.js ➔ highlightLast 0 5 1
A theme.js ➔ ariaDisable 0 3 1
A theme.js ➔ eq 3 3 1
A theme.js ➔ ariaIsDisabled 0 3 1
B theme.js ➔ monitorEvent 0 64 1
A theme.js ➔ exhibit$4 0 3 2
A theme.js ➔ NodeValue 0 29 3
A theme.js ➔ getDimensionProperty 0 3 1
A theme.js ➔ forToolbar 0 7 1
A composite$1.apis.setGroups 0 3 1
A theme.js ➔ ESCAPE 0 3 1
A theme.js ➔ cycleVertical$1 0 6 1
A theme.js ➔ EventRegistry 0 47 1
A theme.js ➔ disable 0 7 2
A theme.js ➔ pure$2 0 5 1
A theme.js ➔ clobberStyles 0 25 2
A theme.js ➔ sketch$5 0 33 1
A theme.js ➔ regularContains 0 4 2
A theme.js ➔ setStart 0 9 1
A theme.js ➔ east 0 4 1
A theme.js ➔ takeoverDropup 0 15 1
A theme.js ➔ isSupported 0 3 1
A theme.js ➔ descendantRtl 0 15 1
A theme.js ➔ moveUp 0 3 1
A theme.js ➔ merge$1 0 13 1
A theme.js ➔ UP 0 3 1
A theme.js ➔ isSkinDisabled 0 3 1
A theme.js ➔ getTouch 0 7 3
A theme.js ➔ markAsExtraApi 0 13 1
A theme.js ➔ sort$1 0 3 1
A theme.js ➔ foldr 0 6 1
A theme.js ➔ getLastWindowSize 0 3 1
A theme.js ➔ nu$9 0 47 1
A theme.js ➔ optionDefaultedAccess 0 6 1
A theme.js ➔ getOrDie 0 6 3
A theme.js ➔ isControl 0 4 1
A theme.js ➔ detachChildren 0 6 1
A theme.js ➔ substitutePlaces 0 12 1
A theme.js ➔ focusIn$2 0 9 1
A theme.js ➔ strictObjOf 0 3 1
A theme.js ➔ build$1 0 8 1
A theme.js ➔ choose$2 0 8 1
A theme.js ➔ consolidateObj 0 4 2
A theme.js ➔ checkContains 0 5 1
A theme.js ➔ renderDef 0 4 1
A theme.js ➔ contents 0 3 1
A theme.js ➔ set$7 0 9 1
A theme.js ➔ fromDom 0 5 3
A theme.js ➔ exhibit$3 0 8 1
A theme.js ➔ nativeDisable 0 3 1
A theme.js ➔ getRules$2 0 10 3
A theme.js ➔ executeEvent 0 5 1
A group.defaults 0 4 1
B theme.js ➔ FakeSelection 0 47 1
A theme.js ➔ getFirst 0 5 1
A theme.js ➔ clear$1 0 4 1
A theme.js ➔ Cell 0 17 1
A theme.js ➔ setValue 0 3 1
A theme.js ➔ inside 0 3 1
A theme.js ➔ jumpTo 0 7 3
A theme.js ➔ adjust 0 9 3
A theme.js ➔ getGreenzone 0 6 1
A theme.js ➔ increaseBy 0 11 4
A theme.js ➔ getTransitionOf 0 10 1
A theme.js ➔ sketch$a 0 24 1
A theme.js ➔ tieredData 0 7 1
A theme.js ➔ slowIndex 0 3 1
A theme.js ➔ isTransitioning 0 3 1
A theme.js ➔ doMove$2 0 17 1
A theme.js ➔ names 0 3 1
A theme.js ➔ strict$1 0 3 1
A theme.js ➔ focus$2 0 3 1
A theme.js ➔ get$5 0 3 1
A theme.js ➔ first$2 0 3 1
A theme.js ➔ classifyFixed 0 4 1
A theme.js ➔ Dimension(ꞌheightꞌ) 0 4 2
A theme.js ➔ onUnload 0 3 1
A theme.js ➔ runWithTarget 0 8 1
A create$1.extra.setValueFrom 0 4 1
A theme.js ➔ sketch$3 0 44 1
A theme.js ➔ moveDown$1 0 3 1
A theme.js ➔ uncurried 0 6 1
A theme.js ➔ curryArgs 0 3 1
A theme.js ➔ fastIndex 0 3 1
A theme.js ➔ checkDupes 0 9 1
A theme.js ➔ defaulted$1 0 3 1
A theme.js ➔ blur$$1 0 3 1
A theme.js ➔ field$1 0 5 1
A theme.js ➔ combine 0 4 1
A theme.js ➔ sortKeys 0 27 1
A theme.js ➔ onLoad$4 0 7 1
A theme.js ➔ state$1(ꞌwinꞌ) 0 3 1
A theme.js ➔ getSelectionFromFrame 0 4 1
A theme.js ➔ getPremade 0 3 1
A theme.js ➔ isFocused 0 3 1
A theme.js ➔ state$1(ꞌmouseIsDownꞌ) 0 3 1
A theme.js ➔ invalidTypeMessage 0 3 1
A theme.js ➔ moveLeft$1 0 3 1
A theme.js ➔ broadcast 0 9 1
A theme.js ➔ has$2 0 3 1
A theme.js ➔ markers 0 3 1
A theme.js ➔ getBoundsFrom 0 6 1
A theme.js ➔ focusIn 0 5 1
B theme.js ➔ is 15 15 6
A theme.js ➔ tag 0 25 1
A theme.js ➔ cycleLeft 0 3 1
A theme.js ➔ parent 0 4 1
A createModes$1.apis.focusIn 0 3 1
A theme.js ➔ defaultToEmpty 0 3 3
A theme.js ➔ ??? 0 3 1
A theme.js ➔ getBehaviours 0 3 1
A theme.js ➔ siblings$1 0 3 1
A theme.js ➔ descendant$2 0 3 1
A theme.js ➔ combine$1 0 33 1
A theme.js ➔ resize 0 5 1
A theme.js ➔ events$6 0 8 1
A theme.js ➔ toDefinition 0 16 1
A theme.js ➔ closest 0 6 1
A theme.js ➔ dispatchEvent 0 3 1
A theme.js ➔ wrap$2 0 3 1
A theme.js ➔ onLoad$3 0 5 1
A theme.js ➔ emit 0 3 1
A theme.js ➔ config 0 13 1
A theme.js ➔ binder 0 5 1
A theme.js ➔ ui 0 16 1
A theme.js ➔ stopper 0 5 1
A theme.js ➔ cleanClass 0 6 3
A theme.js ➔ get$1 0 4 2
A theme.js ➔ fuse 0 22 1
A theme.js ➔ moveUp$1 0 3 1
A theme.js ➔ search$1 0 4 2
A theme.js ➔ buildFromSpec 0 6 1
A theme.js ➔ findIndex 0 9 3
A theme.js ➔ swap 0 4 1
A theme.js ➔ toggle$2 0 4 1
A theme.js ➔ setAll$1 0 6 1
A theme.js ➔ error 0 44 1
B theme.js ➔ makeMenu 0 58 2
A theme.js ➔ attachSystem 0 7 1
A theme.js ➔ asStructOrDie 0 3 1
A theme.js ➔ runActionExtra 0 10 1
A theme.js ➔ sketch$4 0 13 1
B theme.js ➔ monitor 0 60 1
A theme.js ➔ identity 0 3 1
A theme.js ➔ softKeyboardLimits 0 3 1
A theme.js ➔ cycleHorizontal$1 0 6 1
A theme.js ➔ isSketchSpec 0 3 1
A theme.js ➔ hasGrown 0 3 1
B theme.js ➔ setup 0 94 1
A theme.js ➔ attach 0 3 1
A theme.js ➔ hasKey$1 0 3 1
A theme.js ➔ forToolbarStateAction 0 4 1
A theme.js ➔ buildSubcomponents 0 4 1
A theme.js ➔ forbid 0 5 1
A theme.js ➔ firstMatch 0 8 3
A theme.js ➔ missingStrict 0 5 1
A theme.js ➔ resolve$1 0 3 1
A theme.js ➔ highlightAt 0 7 1
A theme.js ➔ getRawOrComputed 0 13 2
A theme.js ➔ nu$2 0 15 1
A theme.js ➔ onDirection 0 5 1
A theme.js ➔ set 0 3 1
A theme.js ➔ active 0 4 2
A theme.js ➔ isHighlighted 0 3 1
A theme.js ➔ findCurrent 0 5 1
A theme.js ➔ generateOne 0 9 1
A theme.js ➔ doImmediateShrink 0 9 1
A theme.js ➔ singleData 0 7 1
A theme.js ➔ resume$1 0 10 1
A theme.js ➔ cycleBy 0 8 3
A theme.js ➔ objOfOnly 0 20 1
A theme.js ➔ init$2 0 6 1
A theme.js ➔ collapseItem$1 0 6 1
A theme.js ➔ doStartShrink 0 9 1
A theme.js ➔ documentPositionContainedBy 0 3 1
A theme.js ➔ isFarEnough 0 5 1
A theme.js ➔ locateOffset 0 15 1
B theme.js ➔ complete 0 9 6
A theme.js ➔ getDimension 0 3 1
A theme.js ➔ focusIn$4 0 5 1
A theme.js ➔ partition$1 0 15 1
A theme.js ➔ toRect$2 0 10 1
A theme.js ➔ getActualWidth 0 5 3
B theme.js ➔ ScrollingToolbar 0 73 1
A theme.js ➔ pure 0 3 1
A theme.js ➔ create$1 0 4 1
A theme.js ➔ findFixtures 0 4 1
A theme.js ➔ getAnimationRoot 0 7 1
A theme.js ➔ onLoad$2 0 5 1
A theme.js ➔ focusIn$3 0 5 1
A theme.js ➔ read 0 7 2
A theme.js ➔ detach 0 9 1
A theme.js ➔ get$3 0 3 1
A theme.js ➔ generate$3 0 3 1
A theme.js ➔ factory$1 0 14 1
A theme.js ➔ getDelta 0 10 1
A theme.js ➔ init$4 0 17 1
A theme.js ➔ searchInChildren 0 8 1
A theme.js ➔ highlight 0 8 2
A theme.js ➔ make$2 0 40 1
A theme.js ➔ output$1 0 3 1
A theme.js ➔ eachr 0 6 2
A theme.js ➔ set$6 0 5 2
A theme.js ➔ noop 0 6 2
A theme.js ➔ setGrown 0 5 1
A theme.js ➔ fromLink 0 13 2
A theme.js ➔ getOrDerive 0 11 1
A theme.js ➔ capture 0 3 1
A theme.js ➔ setOf 0 25 1
A theme.js ➔ moveRight$4 0 4 1
A theme.js ➔ takeoverViewport 0 21 1
A theme.js ➔ reflow 0 3 1
A theme.js ➔ detectOs 0 9 1
A browsers.search 0 4 1
A theme.js ➔ apply 0 3 1
A theme.js ➔ remove$7 0 7 1
A theme.js ➔ factory 0 27 1
A theme.js ➔ getOuter 0 6 1
A theme.js ➔ getEventX 0 6 1
A theme.js ➔ applyInfo 0 18 1
A theme.js ➔ curried 0 6 1
A theme.js ➔ getRectsFromRange 0 12 2
A theme.js ➔ capture$1 0 3 1
A theme.js ➔ doDiagnose 0 15 2
B theme.js ➔ getRules 0 10 6
A theme.js ➔ blobToImage$1 0 3 1
A theme.js ➔ inBody 0 4 2
A theme.js ➔ createModes$1 0 4 1
A theme.js ➔ cycleVertical 0 12 1
B theme.js ➔ sketch$9 0 53 1
A theme.js ➔ emitExecute 0 3 1
A theme.js ➔ nu 0 6 1
A theme.js ➔ caretPositionFromPoint 0 10 1
A theme.js ➔ toOmega 0 3 1
A theme.js ➔ wrapAll 0 7 1
A theme.js ➔ onLoad$5 0 5 2
A theme.js ➔ isShrinking 0 4 1
A theme.js ➔ strictAccess 0 5 1
A theme.js ➔ unknown 0 3 1
A theme.js ➔ FileReader 0 4 1
A theme.js ➔ rule 0 6 1
A theme.js ➔ ENTER 0 3 1
A theme.js ➔ descendant 0 13 1
A theme.js ➔ children 0 4 1
A theme.js ➔ ancestor$2 0 5 1
A theme.js ➔ loadEvent 0 5 1
A theme.js ➔ strictFunction 0 3 1
A theme.js ➔ calculate 0 4 2
A theme.js ➔ horizontal 0 8 1
A theme.js ➔ getFrame 0 3 1
A theme.js ➔ getLastHeight 0 3 1
A theme.js ➔ getWinFromFrame 0 3 1
A theme.js ➔ uriToBlob$1 0 3 1
A theme.js ➔ ancestors$1 0 5 1
A theme.js ➔ execute$5 0 5 1
A theme.js ➔ create$3 0 3 1
A theme.js ➔ isBrowser 0 5 1
A theme.js ➔ getExact 0 5 1
A theme.js ➔ option 0 3 1
A theme.js ➔ toAlpha 0 3 1
A theme.js ➔ nu$8 0 41 1
A theme.js ➔ disableTransitions 0 7 1
A theme.js ➔ fireShiftTab 0 3 2
A theme.js ➔ grow 0 5 2
A theme.js ➔ produce$1 0 27 1
A theme.js ➔ handle 0 16 1
A theme.js ➔ substitutes 0 3 1
A theme.js ➔ mergeWith 0 3 1
B theme.js ➔ build$2 0 52 1
A theme.js ➔ setValue$1 0 6 1
B theme.js ➔ sketch$7 0 168 1
A theme.js ➔ nul 3 3 1
A theme.js ➔ getSize 0 12 1
A theme.js ➔ onFocus 0 3 1
A theme.js ➔ refreshInput 0 9 1
A theme.js ➔ exhibit$5 0 10 2
A theme.js ➔ isVisible 0 4 1
A theme.js ➔ west 0 4 1
A theme.js ➔ endsWith 0 3 1
A theme.js ➔ convert 0 6 1
A theme.js ➔ withGrid 0 8 1
A composite$1.apis.resetToMax 0 3 1
A theme.js ➔ child 0 4 1
A theme.js ➔ changeEvent 0 3 1
A theme.js ➔ remove$5 0 7 3
A theme.js ➔ constant 0 5 1
A theme.js ➔ all$3 0 3 1
A theme.js ➔ choose$1 0 3 1
B theme.js ➔ promise 161 161 1
A theme.js ➔ cyclePrev 0 5 1
A theme.js ➔ prepend 0 8 1
A theme.js ➔ cycleRight$1 0 3 1
A theme.js ➔ apply$1 0 5 1
A theme.js ➔ fireChange 0 3 1
A theme.js ➔ getUid 0 3 1
A theme.js ➔ forall 0 9 3
A theme.js ➔ getOption 0 3 1
A theme.js ➔ oneReplace 0 26 1
A theme.js ➔ doStartGrow 0 9 1
A theme.js ➔ missingBranch 0 5 1
A theme.js ➔ moveLeft$4 0 4 1
A theme.js ➔ getValue$4 0 3 1
A theme.js ➔ renderToDom 0 13 1
A theme.js ➔ canvasToBlob 0 12 2
A theme.js ➔ exclude 0 9 1
A theme.js ➔ enable 0 7 2
A me.fold 3 3 1
B theme.js ➔ initEvents 0 56 2
A theme.js ➔ getTop 0 4 1
A theme.js ➔ internalRemove 0 4 2
A theme.js ➔ pure$1 0 5 1
A theme.js ➔ dispatch 0 3 1
A theme.js ➔ missingKey 0 5 1
A theme.js ➔ getDocFromFrame 0 3 1
A theme.js ➔ setFinish 0 9 1
A theme.js ➔ get$d 0 3 1
A theme.js ➔ blobToBase64 0 5 1
A theme.js ➔ checkRange 0 8 3
A oses.search 0 3 1
A theme.js ➔ deep 0 4 2
A theme.js ➔ dataset 0 14 1
A theme.js ➔ openLink 0 11 1
A theme.js ➔ get$8 0 4 1
A theme.js ➔ blobToArrayBuffer 0 9 1
A theme.js ➔ getNewRoute 0 6 1
A theme.js ➔ getTextToApply 0 5 1
A theme.js ➔ readOptFrom 0 3 1
A theme.js ➔ revokeImageUrl 0 3 1
A theme.js ➔ get$c 0 4 1
A theme.js ➔ getCollapseDirection 0 3 2
B theme.js ➔ path 6 6 6
A theme.js ➔ createModes 0 5 1
A theme.js ➔ anyUriToBlob 26 26 1
A theme.js ➔ sketch$8 0 12 1
A theme.js ➔ getFromItem 0 7 2
A theme.js ➔ reqMessage 0 3 1
B theme.js ➔ searchForPoint 0 19 7
A theme.js ➔ remove 0 5 2
A theme.js ➔ init$5 0 16 1
A theme.js ➔ builder$1 0 7 1
A theme.js ➔ updateAriaState 0 5 1
A theme.js ➔ findIndex$2 0 5 1
A theme.js ➔ detect$4 0 9 1
A theme.js ➔ getLast 0 7 2
A theme.js ➔ imageToBlob$1 0 3 1
A theme.js ➔ dispatchFocus 0 3 1
A theme.js ➔ concat 0 6 1
A theme.js ➔ setToX 0 4 1
A theme.js ➔ element 0 3 1
A theme.js ➔ getBehaviours$1 0 9 1
A theme.js ➔ ieContains 0 3 1
A theme.js ➔ inRect 0 3 1
A theme.js ➔ defaultedOf 0 3 1
A theme.js ➔ wrap$1 0 5 1
A theme.js ➔ fireDetaching 0 5 1
A theme.js ➔ mapToArray 0 7 1
A theme.js ➔ getOrListen 0 7 1
A theme.js ➔ isHidden 0 3 1
A theme.js ➔ snapValueOfX 0 15 1
A theme.js ➔ locateInEmpty 0 5 1
A theme.js ➔ bindFocus 0 7 2
A theme.js ➔ get$9 0 3 1
A theme.js ➔ make 0 33 1
A theme.js ➔ getYFixedProperty 0 3 1
A theme.js ➔ getDomDefinition 0 6 1
B theme.js ➔ getActiveApi 0 61 1
B theme.js ➔ setup$2 0 83 2
A theme.js ➔ fromHtml$2 0 12 2
A theme.js ➔ trim 0 3 1
B theme.js ➔ typeOf 0 10 6
A theme.js ➔ isOn 0 3 1
A theme.js ➔ read$2 0 4 2
A theme.js ➔ nativeEnable 0 3 1
A theme.js ➔ set$2 0 4 1
A theme.js ➔ can 0 6 1
A theme.js ➔ fireSkinLoaded 0 13 1
A theme.js ➔ value$3 0 21 1
A theme.js ➔ Immutable 0 20 2
A theme.js ➔ getHtml 0 4 1
A theme.js ➔ getHeight 0 3 1
A theme.js ➔ remove$1 0 3 1
A theme.js ➔ subs 0 29 1
A theme.js ➔ getHighlighted 0 5 1
A composite$1.apis.refresh 0 3 1
A theme.js ➔ r 0 10 1
A theme.js ➔ takeoverToolbar 0 15 1
A theme.js ➔ add$3 0 5 1
A theme.js ➔ searchFromPoint 0 8 1
B theme.js ➔ takeover 0 144 1
A theme.js ➔ getData 0 3 1
A theme.js ➔ dom 0 12 1
A theme.js ➔ manual 0 5 1
A theme.js ➔ identify 0 4 3
A theme.js ➔ redirectToUid 0 7 1
A theme.js ➔ get$a 0 3 1
A theme.js ➔ resume 0 15 2
A theme.js ➔ restoreStyles 0 12 1
A theme.js ➔ format 0 11 1
A theme.js ➔ validateStrArr 0 8 2
A theme.js ➔ deriveViewportHeight 0 6 1
A theme.js ➔ doTriggerOnUntilStopped 0 9 1
A theme.js ➔ nu$3 0 6 1
A theme.js ➔ fromHtml$1 0 6 1
A theme.js ➔ combineGroups 0 15 1
A theme.js ➔ BACKSPACE 0 3 1
A theme.js ➔ updateFixed 0 5 1
A theme.js ➔ canScrollHorizontally 0 6 1
A theme.js ➔ stringify 0 3 1
A theme.js ➔ revokeBehaviour 0 6 1
A theme.js ➔ setExact 0 4 1
A theme.js ➔ makeItems$1 0 7 1
A theme.js ➔ valueOf 0 5 1
A me.toArray 3 3 1
A theme.js ➔ getScrollTop 0 3 1
A theme.js ➔ nu$7 0 4 1
A theme.js ➔ cExtract 0 6 1
A theme.js ➔ caretRangeFromPoint 0 3 1
A theme.js ➔ getPrevious 0 3 1
A theme.js ➔ enhanceGroups 0 3 1
A theme.js ➔ getRectangles 0 4 3
A theme.js ➔ beforeSpecial 0 12 4
A theme.js ➔ base$1 0 10 2
A theme.js ➔ markAsSketchApi 0 13 1
A theme.js ➔ updateChecked 0 3 1
A theme.js ➔ dataUriToBlobSync 23 23 4
A theme.js ➔ missingOrderError 0 5 1
A theme.js ➔ closest$3 0 6 1
A theme.js ➔ mkEvent 0 11 1
A theme.js ➔ createBistate 0 12 1
A theme.js ➔ itemMarkers 0 3 1
A theme.js ➔ single$2 0 16 1
A theme.js ➔ moveVertical 0 6 1
A theme.js ➔ triggerHandler 0 4 1
A theme.js ➔ narrow$1 0 3 1
A theme.js ➔ forToolbarCommand 0 5 1
A theme.js ➔ cycleNext 0 5 1
D mobile.constructor 469 12632 9
B theme.js ➔ IosRealm 0 54 1
A theme.js ➔ fromExternal 0 15 1
A theme.js ➔ capValue 0 3 1
A theme.js ➔ consolidateArr 0 4 2
A theme.js ➔ preprocessExact 0 5 1
A theme.js ➔ createTristate 0 43 1
A theme.js ➔ fireChange$1 0 6 1
A theme.js ➔ isShift 0 4 1
A theme.js ➔ triggerOnUntilStopped 0 4 1
A theme.js ➔ updatePositions 0 7 1
A theme.js ➔ last$3 25 25 1
A theme.js ➔ supports 0 3 1
B theme.js ➔ sketch$1 0 115 3
A theme.js ➔ setValue$2 0 4 1
A theme.js ➔ single$1 0 5 1
A theme.js ➔ state$1(ꞌbodyꞌ) 0 3 1
A theme.js ➔ derive$4 0 11 1
A theme.js ➔ fireAttaching 0 5 1
A theme.js ➔ name$1 0 6 1
A theme.js ➔ bindBlur 0 7 2
A theme.js ➔ BackgroundActivity 0 18 1
A theme.js ➔ get$e 0 5 1
A theme.js ➔ cleanParameters 0 5 1
A theme.js ➔ bind 0 4 1
A group.overrides 0 7 1
A theme.js ➔ setShrunk 0 6 1
A theme.js ➔ hasScroll 0 3 2
A theme.js ➔ find$1 0 12 2
A theme.js ➔ byInnerKey 0 10 1
A theme.js ➔ classify 0 5 2
A theme.js ➔ button 0 9 1
A theme.js ➔ sizeToIndex 0 5 1
A theme.js ➔ forAndroid 0 4 2
A theme.js ➔ external$1 0 32 1
A theme.js ➔ cExtractOne 0 38 1
A theme.js ➔ updateSelected 0 3 1
A theme.js ➔ hidden 0 14 1
A theme.js ➔ json 0 3 1
A theme.js ➔ append 0 3 1
A theme.js ➔ findRoute 0 5 1
A theme.js ➔ getCurried 0 3 1
A theme.js ➔ text 0 4 1
A theme.js ➔ run 0 6 1
A theme.js ➔ onHandler 0 3 1
A theme.js ➔ getClasses 0 3 1
A theme.js ➔ factory$2 0 18 1
A group.factory.sketch 0 4 1
A theme.js ➔ attachWith 0 8 2
A theme.js ➔ ClosestOrAncestor 0 3 4
A theme.js ➔ clone$2 0 7 1
A theme.js ➔ OuterContainer 0 10 1
A theme.js ➔ premade 0 3 1
A theme.js ➔ moveDown 0 3 1
A theme.js ➔ move$1 0 22 3
A theme.js ➔ factory$4 0 28 2
A theme.js ➔ factory$3 0 9 1
A theme.js ➔ toRect$1 0 10 1
A theme.js ➔ search 0 5 1
A theme.js ➔ extractBlob 0 5 1
A theme.js ➔ supplant 0 10 1
A theme.js ➔ state$1(ꞌvalueꞌ) 0 3 1
A theme.js ➔ remove$6 0 5 1
A theme.js ➔ defaultView 0 5 1
A theme.js ➔ getCurrentRoute 0 7 2
B theme.js ➔ AndroidRealm 0 50 1
A theme.js ➔ sketch$6 0 24 1
A theme.js ➔ hasVerticalScroll 0 3 1
A theme.js ➔ setRangeFromRelative 0 21 1
A theme.js ➔ scrollIntoView 0 9 4
A theme.js ➔ and 0 7 1
A theme.js ➔ convert$1 0 14 1
A theme.js ➔ behaviourTuple 0 6 1
A theme.js ➔ add$1 0 3 1
A theme.js ➔ getRaw 0 7 1
A theme.js ➔ ancestors 0 3 1
A theme.js ➔ exactToNative 0 6 1
A theme.js ➔ emitWith 0 3 1
B theme.js ➔ generate 0 65 3
A theme.js ➔ Theme 0 2 1
A theme.js ➔ getAllParts 0 6 1
A theme.js ➔ handleExact 0 7 2
A theme.js ➔ getToggleBehaviours 0 13 1
A theme.js ➔ formatError 0 3 1
A theme.js ➔ optionObjOf 0 3 1
A theme.js ➔ exclude$1 0 3 1
A theme.js ➔ consolidate 0 3 1
A theme.js ➔ fireTab 0 3 2
B global$1.add(ꞌmobileꞌ) 0 190 1
A theme.js ➔ hideEdit 0 3 1
A theme.js ➔ setLastHeight 0 3 1
A theme.js ➔ makeSlider$1 0 8 1
A theme.js ➔ events$9 0 20 1
A theme.js ➔ get2dContext 0 3 1
A theme.js ➔ events$a 0 13 1
A theme.js ➔ cached 15 15 1
A theme.js ➔ dom$2 0 16 1
A theme.js ➔ blobToImage 24 24 1
A theme.js ➔ duplicate 0 5 1
A theme.js ➔ configureGrid 0 11 1
A theme.js ➔ measureTargetSize 0 6 1
A theme.js ➔ updateExpanded 0 3 1
A theme.js ➔ asRaw 0 3 1
A theme.js ➔ isNotEmpty 0 3 1
A theme.js ➔ generateFrom 0 28 1
A theme.js ➔ setup$1 0 25 1
A theme.js ➔ isOmega 0 3 1
A theme.js ➔ create$7 0 32 1
A theme.js ➔ locate 0 8 1
A theme.js ➔ dehighlightAll 0 9 1
A theme.js ➔ reduceBy 0 11 4
A theme.js ➔ produce 0 27 1
A theme.js ➔ getValue$3 0 3 1
A theme.js ➔ any 0 11 1
A theme.js ➔ composite$1 0 18 1
A theme.js ➔ after$3 0 5 1
A theme.js ➔ nu$4 0 10 4
A theme.js ➔ redirectToPart 0 4 1
A theme.js ➔ immediateShrink 0 5 2
A theme.js ➔ locateIn 0 6 1
A theme.js ➔ getApis$5 0 3 1
A theme.js ➔ each$1 0 6 2
A theme.js ➔ prepend$2 0 3 1
A theme.js ➔ getUnsafeProperty 0 3 2
A theme.js ➔ fromSource 0 19 1
A single$2.apis.collapseMenu 0 3 1
B NONE.constructor 53 53 2
A theme.js ➔ moveOnlyTop 0 15 1
A theme.js ➔ add$2 0 6 2
A theme.js ➔ contains 0 3 1
A theme.js ➔ all 0 4 3
A theme.js ➔ cap 0 7 3
A theme.js ➔ readOpt 0 5 1
A theme.js ➔ getEvents$6 0 4 1
A theme.js ➔ first$4 25 25 1
A theme.js ➔ fromHtml 0 10 3
A theme.js ➔ getTrace 0 13 2
A theme.js ➔ output$1(ꞌgetDimensionꞌ) 0 3 1
A theme.js ➔ blur$1 0 5 2
A theme.js ➔ useV 0 5 1
A theme.js ➔ formatObj 0 3 3
A theme.js ➔ off 0 4 1
A theme.js ➔ getWidth 0 3 1
A theme.js ➔ exclusive 0 7 1
A theme.js ➔ resolve 0 4 1
B theme.js ➔ some 62 62 1
A theme.js ➔ setXFromEvent 0 6 1
A theme.js ➔ clone$1 0 3 1
A theme.js ➔ handleTab 0 3 2
A theme.js ➔ focusIn$1 0 5 1
A theme.js ➔ highlights 0 16 1
A theme.js ➔ supplyUid 0 3 1
A theme.js ➔ Uint8Array 0 4 1
A theme.js ➔ updateFixture 0 7 1
A theme.js ➔ nativeIsDisabled 0 3 1
A theme.js ➔ after 0 11 1
A theme.js ➔ spec 0 4 1
A theme.js ➔ refresh 0 11 2
A theme.js ➔ doMove 0 7 1
A theme.js ➔ before 0 6 1
A theme.js ➔ memory 0 22 1
A theme.js ➔ set$4 0 3 1
A theme.js ➔ wrapAll$1 0 3 1
A theme.js ➔ reverse 0 5 1
A theme.js ➔ focus$3 0 6 2
A theme.js ➔ toRect 0 10 1
A theme.js ➔ generate$5 0 16 1
A theme.js ➔ matchColor 0 4 3
A theme.js ➔ Dimension 0 37 1
A theme.js ➔ execute$3 0 5 1
A theme.js ➔ base 0 6 1
A theme.js ➔ blobToBase64$1 0 3 1
B theme.js ➔ Registry 0 51 1
A theme.js ➔ createRoutes 0 9 1
A theme.js ➔ updatePadding 0 5 1
A theme.js ➔ shallow 0 3 1
A theme.js ➔ getPart 0 4 1
A theme.js ➔ runOnName 0 5 1
A theme.js ➔ isType 0 5 1
A theme.js ➔ getOrDie$1 0 5 1
A theme.js ➔ derive$2 0 3 1
A theme.js ➔ getValue 0 3 1
A theme.js ➔ snapshot$1 0 3 1
A theme.js ➔ internalSet 0 8 3
A theme.js ➔ makeEditSwitch 0 10 1
A theme.js ➔ getTransition 0 6 1
A theme.js ➔ writeOnly 0 3 1
A theme.js ➔ uriToBlob 0 9 3
B theme.js ➔ builder$2 0 72 2
A theme.js ➔ generate$4 0 4 1
A theme.js ➔ cycleDown 0 3 1
A theme.js ➔ inSet 0 6 1
A theme.js ➔ generate$1 0 7 1
A theme.js ➔ flatgrid 0 25 1
A theme.js ➔ record 0 17 3
A theme.js ➔ objOf 0 29 1
A theme.js ➔ exists 0 3 1
A theme.js ➔ doEscape 0 3 1
A theme.js ➔ composite 0 9 1
A theme.js ➔ getInfo 0 7 1
A theme.js ➔ create 0 5 1
A theme.js ➔ optionOf 0 3 1
A theme.js ➔ baseWith 0 21 2
A theme.js ➔ disableTransition 0 7 1
A theme.js ➔ events$7 0 8 1
A theme.js ➔ isOS 0 5 1
A theme.js ➔ highlightBy 0 10 1
A theme.js ➔ getSetKeys 0 6 1
A theme.js ➔ getFirstRect 0 5 4
A theme.js ➔ onUnload$2 0 3 1
A theme.js ➔ searchTextNodes 0 8 1
A theme.js ➔ getFromExpandingItem 0 11 1
A theme.js ➔ DeviceType 20 20 1
A theme.js ➔ objSafeMerge 0 14 1
A theme.js ➔ doDetach 0 5 1
A theme.js ➔ abort 0 6 1
A theme.js ➔ choose 0 21 1
B theme.js ➔ setup$3 0 81 1
A theme.js ➔ curry 14 14 2
A theme.js ➔ all$1 0 11 1
A theme.js ➔ monitor$1 0 25 1
A theme.js ➔ doGenerateOne 0 7 1
A theme.js ➔ last$2 0 3 1
A theme.js ➔ defToStr 0 4 1
A theme.js ➔ getDirection 0 3 2
A theme.js ➔ clashingOptArrays 0 15 1
A theme.js ➔ compareDocumentPosition 0 3 1
A theme.js ➔ node 0 4 1
A theme.js ➔ getRanges 0 30 1
A theme.js ➔ LEFT 0 3 1
A theme.js ➔ getChildren 0 12 3
A theme.js ➔ getValue$1 0 9 1
A theme.js ➔ bounce 0 12 1
A theme.js ➔ moveLeft$2 0 3 1
A theme.js ➔ broadcastHandler 0 6 1
A theme.js ➔ remove$2 0 10 2
A theme.js ➔ locateNode 0 4 2
A theme.js ➔ firstChild 0 3 1
A theme.js ➔ getNext 0 3 1
A theme.js ➔ undef 3 3 1
A theme.js ➔ tieredMenuMarkers 0 3 1
A theme.js ➔ focusBehaviours 0 9 2
A theme.js ➔ canvasToDataURL 0 6 1
A theme.js ➔ ariaEnable 0 3 1
A theme.js ➔ unlinkIfRequired 0 6 1
A theme.js ➔ fromRange 0 3 1
A theme.js ➔ readOr$1 0 3 1
A theme.js ➔ value$2 0 18 1
A theme.js ➔ asNamedPart 0 3 1
B theme.js ➔ findDevice 0 58 1
A theme.js ➔ toggle 0 7 2
A me.getOrDie 3 3 1
A theme.js ➔ onLoad$1 0 3 1
A theme.js ➔ empty 0 6 1
A theme.js ➔ derive$3 0 6 1
A theme.js ➔ setAll 0 6 1
B theme.js ➔ toInfo 0 47 1
A theme.js ➔ makeItems 0 3 1
A theme.js ➔ bind$1 0 3 1
A theme.js ➔ name 0 4 1
A theme.js ➔ asLtrRange 0 17 1
A theme.js ➔ atob 0 4 1
A theme.js ➔ setValue$3 0 4 1
A theme.js ➔ indexToSize 0 3 1
A theme.js ➔ asStructOrDie$1 0 4 1
A theme.js ➔ doMove$1 0 7 1
A theme.js ➔ isGrowing 0 4 1
B theme.js ➔ build 0 65 1
A theme.js ➔ add 0 6 1
A theme.js ➔ readOnlyOnInit 0 3 1
A theme.js ➔ expand 0 14 1
A theme.js ➔ events$3 0 6 1
A theme.js ➔ getPartName 0 3 1
B theme.js ➔ make$3 0 189 2
A theme.js ➔ components 0 3 1
A theme.js ➔ isCursorPosition 0 4 1
A theme.js ➔ NoContextApi 0 23 1
A theme.js ➔ toggle$1 0 3 2
A theme.js ➔ MixedBag 0 29 2
A theme.js ➔ updateMode 0 6 3
A theme.js ➔ typedValue 0 6 1
A theme.js ➔ call$$1 3 3 1
A theme.js ➔ defaultUids 0 9 1
A theme.js ➔ ensure 0 3 1
A theme.js ➔ autocompleteHack 0 7 1
A theme.js ➔ behaviours 0 18 1
A theme.js ➔ cycleHorizontal 0 11 1
A theme.js ➔ safeParse 0 4 2
A theme.js ➔ detect$2 0 12 1
A theme.js ➔ baseMerge 0 18 1
A theme.js ➔ formatErrors 0 11 2
A theme.js ➔ getPartOrDie 0 3 1
A theme.js ➔ isAlpha 0 3 1
A theme.js ➔ par 0 22 1
A theme.js ➔ getYFixedData 0 3 1
A theme.js ➔ getEvents$5 0 3 1
A theme.js ➔ updateScrollingFixed 0 7 1
A theme.js ➔ defToRaw 0 20 1
A theme.js ➔ nameToHandlers 0 7 1
A theme.js ➔ defaultExecute 0 3 3
A theme.js ➔ shallow$1 0 3 1
A theme.js ➔ typical 0 36 1
A theme.js ➔ events 0 13 1
A theme.js ➔ addImage 0 11 1
A theme.js ➔ unsafe 0 3 1
A theme.js ➔ factory$5 0 12 1
B theme.js ➔ initEvents$1 0 113 1
A theme.js ➔ moveWindowScroll 0 9 1
A theme.js ➔ unbind 0 3 1
A theme.js ➔ moveOnlyScroll 0 23 1
A theme.js ➔ hasHorizontalScroll 0 3 1
A theme.js ➔ readRange 0 9 2
A theme.js ➔ toCell 0 11 1
A theme.js ➔ generateFrom$1 0 3 1
A theme.js ➔ die 0 5 1
A theme.js ➔ forToolbarStateCommand 0 6 1
A theme.js ➔ append$1 0 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like public/js/tinymce/themes/mobile/theme.js often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
(function () {
2
var mobile = (function () {
3
    'use strict';
4
5
    var noop = function () {
6
      var args = [];
7
      for (var _i = 0; _i < arguments.length; _i++) {
8
        args[_i] = arguments[_i];
9
      }
10
    };
11
    var compose = function (fa, fb) {
12
      return function () {
13
        var args = [];
14
        for (var _i = 0; _i < arguments.length; _i++) {
15
          args[_i] = arguments[_i];
16
        }
17
        return fa(fb.apply(null, args));
18
      };
19
    };
20
    var constant = function (value) {
21
      return function () {
22
        return value;
23
      };
24
    };
25
    var identity = function (x) {
26
      return x;
27
    };
28 View Code Duplication
    function curry(fn) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
29
      var initialArgs = [];
30
      for (var _i = 1; _i < arguments.length; _i++) {
31
        initialArgs[_i - 1] = arguments[_i];
32
      }
33
      return function () {
34
        var restArgs = [];
35
        for (var _i = 0; _i < arguments.length; _i++) {
36
          restArgs[_i] = arguments[_i];
37
        }
38
        var all = initialArgs.concat(restArgs);
39
        return fn.apply(null, all);
40
      };
41
    }
42
    var not = function (f) {
43
      return function () {
44
        var args = [];
45
        for (var _i = 0; _i < arguments.length; _i++) {
46
          args[_i] = arguments[_i];
47
        }
48
        return !f.apply(null, args);
49
      };
50
    };
51
    var die = function (msg) {
52
      return function () {
53
        throw new Error(msg);
54
      };
55
    };
56
    var apply = function (f) {
57
      return f();
58
    };
59
    var never = constant(false);
60
    var always = constant(true);
61
62
    var typeOf = function (x) {
63
      if (x === null)
64
        return 'null';
65
      var t = typeof x;
66
      if (t === 'object' && Array.prototype.isPrototypeOf(x))
67
        return 'array';
68
      if (t === 'object' && String.prototype.isPrototypeOf(x))
69
        return 'string';
70
      return t;
71
    };
72
    var isType = function (type) {
73
      return function (value) {
74
        return typeOf(value) === type;
75
      };
76
    };
77
    var isString = isType('string');
78
    var isObject = isType('object');
79
    var isArray = isType('array');
80
    var isBoolean = isType('boolean');
81
    var isFunction = isType('function');
82
    var isNumber = isType('number');
83
84
    var hasOwnProperty = Object.prototype.hasOwnProperty;
85
    var shallow = function (old, nu) {
86
      return nu;
87
    };
88
    var deep = function (old, nu) {
89
      var bothObjects = isObject(old) && isObject(nu);
90
      return bothObjects ? deepMerge(old, nu) : nu;
91
    };
92
    var baseMerge = function (merger) {
93
      return function () {
94
        var objects = new Array(arguments.length);
95
        for (var i = 0; i < objects.length; i++)
96
          objects[i] = arguments[i];
97
        if (objects.length === 0)
98
          throw new Error('Can\'t merge zero objects');
99
        var ret = {};
100
        for (var j = 0; j < objects.length; j++) {
101
          var curObject = objects[j];
102
          for (var key in curObject)
103
            if (hasOwnProperty.call(curObject, key)) {
104
              ret[key] = merger(ret[key], curObject[key]);
105
            }
106
        }
107
        return ret;
108
      };
109
    };
110
    var deepMerge = baseMerge(deep);
111
    var merge = baseMerge(shallow);
112
113
    var never$1 = never;
114
    var always$1 = always;
115
    var none = function () {
116
      return NONE;
117
    };
118 View Code Duplication
    var NONE = function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
119
      var eq = function (o) {
120
        return o.isNone();
121
      };
122
      var call$$1 = function (thunk) {
123
        return thunk();
124
      };
125
      var id = function (n) {
126
        return n;
127
      };
128
      var noop$$1 = function () {
129
      };
130
      var nul = function () {
131
        return null;
132
      };
133
      var undef = function () {
134
        return undefined;
135
      };
136
      var me = {
137
        fold: function (n, s) {
138
          return n();
139
        },
140
        is: never$1,
141
        isSome: never$1,
142
        isNone: always$1,
143
        getOr: id,
144
        getOrThunk: call$$1,
145
        getOrDie: function (msg) {
146
          throw new Error(msg || 'error: getOrDie called on none.');
147
        },
148
        getOrNull: nul,
149
        getOrUndefined: undef,
150
        or: id,
151
        orThunk: call$$1,
152
        map: none,
153
        ap: none,
154
        each: noop$$1,
155
        bind: none,
156
        flatten: none,
157
        exists: never$1,
158
        forall: always$1,
159
        filter: none,
160
        equals: eq,
161
        equals_: eq,
162
        toArray: function () {
163
          return [];
164
        },
165
        toString: constant('none()')
166
      };
167
      if (Object.freeze)
168
        Object.freeze(me);
169
      return me;
170
    }();
171 View Code Duplication
    var some = function (a) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
172
      var constant_a = function () {
173
        return a;
174
      };
175
      var self = function () {
176
        return me;
177
      };
178
      var map = function (f) {
179
        return some(f(a));
180
      };
181
      var bind = function (f) {
182
        return f(a);
183
      };
184
      var me = {
185
        fold: function (n, s) {
186
          return s(a);
187
        },
188
        is: function (v) {
189
          return a === v;
190
        },
191
        isSome: always$1,
192
        isNone: never$1,
193
        getOr: constant_a,
194
        getOrThunk: constant_a,
195
        getOrDie: constant_a,
196
        getOrNull: constant_a,
197
        getOrUndefined: constant_a,
198
        or: self,
199
        orThunk: self,
200
        map: map,
201
        ap: function (optfab) {
202
          return optfab.fold(none, function (fab) {
203
            return some(fab(a));
204
          });
205
        },
206
        each: function (f) {
207
          f(a);
208
        },
209
        bind: bind,
210
        flatten: constant_a,
211
        exists: bind,
212
        forall: bind,
213
        filter: function (f) {
214
          return f(a) ? me : NONE;
215
        },
216
        equals: function (o) {
217
          return o.is(a);
218
        },
219
        equals_: function (o, elementEq) {
220
          return o.fold(never$1, function (b) {
221
            return elementEq(a, b);
222
          });
223
        },
224
        toArray: function () {
225
          return [a];
226
        },
227
        toString: function () {
228
          return 'some(' + a + ')';
229
        }
230
      };
231
      return me;
232
    };
233
    var from = function (value) {
234
      return value === null || value === undefined ? NONE : some(value);
235
    };
236
    var Option = {
237
      some: some,
238
      none: none,
239
      from: from
240
    };
241
242
    var keys = Object.keys;
243
    var each = function (obj, f) {
244
      var props = keys(obj);
245
      for (var k = 0, len = props.length; k < len; k++) {
246
        var i = props[k];
247
        var x = obj[i];
248
        f(x, i, obj);
249
      }
250
    };
251
    var map = function (obj, f) {
252
      return tupleMap(obj, function (x, i, obj) {
253
        return {
254
          k: i,
255
          v: f(x, i, obj)
256
        };
257
      });
258
    };
259
    var tupleMap = function (obj, f) {
260
      var r = {};
261
      each(obj, function (x, i) {
262
        var tuple = f(x, i, obj);
263
        r[tuple.k] = tuple.v;
264
      });
265
      return r;
266
    };
267
    var mapToArray = function (obj, f) {
268
      var r = [];
269
      each(obj, function (value, name) {
270
        r.push(f(value, name));
271
      });
272
      return r;
273
    };
274
275
    var touchstart = constant('touchstart');
276
    var touchmove = constant('touchmove');
277
    var touchend = constant('touchend');
278
    var mousedown = constant('mousedown');
279
    var mousemove = constant('mousemove');
280
    var mouseup = constant('mouseup');
281
    var mouseover = constant('mouseover');
282
    var keydown = constant('keydown');
283
    var input = constant('input');
284
    var change = constant('change');
285
    var click = constant('click');
286
    var transitionend = constant('transitionend');
287
    var selectstart = constant('selectstart');
288
289 View Code Duplication
    var cached = function (f) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
290
      var called = false;
291
      var r;
292
      return function () {
293
        var args = [];
294
        for (var _i = 0; _i < arguments.length; _i++) {
295
          args[_i] = arguments[_i];
296
        }
297
        if (!called) {
298
          called = true;
299
          r = f.apply(null, args);
300
        }
301
        return r;
302
      };
303
    };
304
305
    var firstMatch = function (regexes, s) {
306
      for (var i = 0; i < regexes.length; i++) {
307
        var x = regexes[i];
308
        if (x.test(s))
309
          return x;
310
      }
311
      return undefined;
312
    };
313
    var find$1 = function (regexes, agent) {
314
      var r = firstMatch(regexes, agent);
315
      if (!r)
316
        return {
317
          major: 0,
318
          minor: 0
319
        };
320
      var group = function (i) {
321
        return Number(agent.replace(r, '$' + i));
322
      };
323
      return nu(group(1), group(2));
324
    };
325
    var detect = function (versionRegexes, agent) {
326
      var cleanedAgent = String(agent).toLowerCase();
327
      if (versionRegexes.length === 0)
328
        return unknown();
329
      return find$1(versionRegexes, cleanedAgent);
330
    };
331
    var unknown = function () {
332
      return nu(0, 0);
333
    };
334
    var nu = function (major, minor) {
335
      return {
336
        major: major,
337
        minor: minor
338
      };
339
    };
340
    var Version = {
341
      nu: nu,
342
      detect: detect,
343
      unknown: unknown
344
    };
345
346
    var edge = 'Edge';
347
    var chrome = 'Chrome';
348
    var ie = 'IE';
349
    var opera = 'Opera';
350
    var firefox = 'Firefox';
351
    var safari = 'Safari';
352
    var isBrowser = function (name, current) {
353
      return function () {
354
        return current === name;
355
      };
356
    };
357
    var unknown$1 = function () {
358
      return nu$1({
359
        current: undefined,
360
        version: Version.unknown()
361
      });
362
    };
363
    var nu$1 = function (info) {
364
      var current = info.current;
365
      var version = info.version;
366
      return {
367
        current: current,
368
        version: version,
369
        isEdge: isBrowser(edge, current),
370
        isChrome: isBrowser(chrome, current),
371
        isIE: isBrowser(ie, current),
372
        isOpera: isBrowser(opera, current),
373
        isFirefox: isBrowser(firefox, current),
374
        isSafari: isBrowser(safari, current)
375
      };
376
    };
377
    var Browser = {
378
      unknown: unknown$1,
379
      nu: nu$1,
380
      edge: constant(edge),
381
      chrome: constant(chrome),
382
      ie: constant(ie),
383
      opera: constant(opera),
384
      firefox: constant(firefox),
385
      safari: constant(safari)
386
    };
387
388
    var windows = 'Windows';
389
    var ios = 'iOS';
390
    var android = 'Android';
391
    var linux = 'Linux';
392
    var osx = 'OSX';
393
    var solaris = 'Solaris';
394
    var freebsd = 'FreeBSD';
395
    var isOS = function (name, current) {
396
      return function () {
397
        return current === name;
398
      };
399
    };
400
    var unknown$2 = function () {
401
      return nu$2({
402
        current: undefined,
403
        version: Version.unknown()
404
      });
405
    };
406
    var nu$2 = function (info) {
407
      var current = info.current;
408
      var version = info.version;
409
      return {
410
        current: current,
411
        version: version,
412
        isWindows: isOS(windows, current),
413
        isiOS: isOS(ios, current),
414
        isAndroid: isOS(android, current),
415
        isOSX: isOS(osx, current),
416
        isLinux: isOS(linux, current),
417
        isSolaris: isOS(solaris, current),
418
        isFreeBSD: isOS(freebsd, current)
419
      };
420
    };
421
    var OperatingSystem = {
422
      unknown: unknown$2,
423
      nu: nu$2,
424
      windows: constant(windows),
425
      ios: constant(ios),
426
      android: constant(android),
427
      linux: constant(linux),
428
      osx: constant(osx),
429
      solaris: constant(solaris),
430
      freebsd: constant(freebsd)
431
    };
432
433 View Code Duplication
    var DeviceType = function (os, browser, userAgent) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
434
      var isiPad = os.isiOS() && /ipad/i.test(userAgent) === true;
435
      var isiPhone = os.isiOS() && !isiPad;
436
      var isAndroid3 = os.isAndroid() && os.version.major === 3;
437
      var isAndroid4 = os.isAndroid() && os.version.major === 4;
438
      var isTablet = isiPad || isAndroid3 || isAndroid4 && /mobile/i.test(userAgent) === true;
439
      var isTouch = os.isiOS() || os.isAndroid();
440
      var isPhone = isTouch && !isTablet;
441
      var iOSwebview = browser.isSafari() && os.isiOS() && /safari/i.test(userAgent) === false;
442
      return {
443
        isiPad: constant(isiPad),
444
        isiPhone: constant(isiPhone),
445
        isTablet: constant(isTablet),
446
        isPhone: constant(isPhone),
447
        isTouch: constant(isTouch),
448
        isAndroid: os.isAndroid,
449
        isiOS: os.isiOS,
450
        isWebView: constant(iOSwebview)
451
      };
452
    };
453
454
    var rawIndexOf = function () {
455
      var pIndexOf = Array.prototype.indexOf;
456
      var fastIndex = function (xs, x) {
457
        return pIndexOf.call(xs, x);
458
      };
459
      var slowIndex = function (xs, x) {
460
        return slowIndexOf(xs, x);
461
      };
462
      return pIndexOf === undefined ? slowIndex : fastIndex;
463
    }();
464
    var contains = function (xs, x) {
465
      return rawIndexOf(xs, x) > -1;
466
    };
467
    var exists = function (xs, pred) {
468
      return findIndex(xs, pred).isSome();
469
    };
470
    var map$1 = function (xs, f) {
471
      var len = xs.length;
472
      var r = new Array(len);
473
      for (var i = 0; i < len; i++) {
474
        var x = xs[i];
475
        r[i] = f(x, i, xs);
476
      }
477
      return r;
478
    };
479
    var each$1 = function (xs, f) {
480
      for (var i = 0, len = xs.length; i < len; i++) {
481
        var x = xs[i];
482
        f(x, i, xs);
483
      }
484
    };
485
    var eachr = function (xs, f) {
486
      for (var i = xs.length - 1; i >= 0; i--) {
487
        var x = xs[i];
488
        f(x, i, xs);
489
      }
490
    };
491
    var filter = function (xs, pred) {
492
      var r = [];
493
      for (var i = 0, len = xs.length; i < len; i++) {
494
        var x = xs[i];
495
        if (pred(x, i, xs)) {
496
          r.push(x);
497
        }
498
      }
499
      return r;
500
    };
501
    var foldr = function (xs, f, acc) {
502
      eachr(xs, function (x) {
503
        acc = f(acc, x);
504
      });
505
      return acc;
506
    };
507
    var foldl = function (xs, f, acc) {
508
      each$1(xs, function (x) {
509
        acc = f(acc, x);
510
      });
511
      return acc;
512
    };
513
    var find$2 = function (xs, pred) {
514
      for (var i = 0, len = xs.length; i < len; i++) {
515
        var x = xs[i];
516
        if (pred(x, i, xs)) {
517
          return Option.some(x);
518
        }
519
      }
520
      return Option.none();
521
    };
522
    var findIndex = function (xs, pred) {
523
      for (var i = 0, len = xs.length; i < len; i++) {
524
        var x = xs[i];
525
        if (pred(x, i, xs)) {
526
          return Option.some(i);
527
        }
528
      }
529
      return Option.none();
530
    };
531
    var slowIndexOf = function (xs, x) {
532
      for (var i = 0, len = xs.length; i < len; ++i) {
533
        if (xs[i] === x) {
534
          return i;
535
        }
536
      }
537
      return -1;
538
    };
539
    var push = Array.prototype.push;
540
    var flatten = function (xs) {
541
      var r = [];
542
      for (var i = 0, len = xs.length; i < len; ++i) {
543
        if (!Array.prototype.isPrototypeOf(xs[i]))
544
          throw new Error('Arr.flatten item ' + i + ' was not an array, input: ' + xs);
545
        push.apply(r, xs[i]);
546
      }
547
      return r;
548
    };
549
    var bind = function (xs, f) {
550
      var output = map$1(xs, f);
551
      return flatten(output);
552
    };
553
    var forall = function (xs, pred) {
554
      for (var i = 0, len = xs.length; i < len; ++i) {
555
        var x = xs[i];
556
        if (pred(x, i, xs) !== true) {
557
          return false;
558
        }
559
      }
560
      return true;
561
    };
562
    var slice = Array.prototype.slice;
563
    var reverse = function (xs) {
564
      var r = slice.call(xs, 0);
565
      r.reverse();
566
      return r;
567
    };
568
    var difference = function (a1, a2) {
569
      return filter(a1, function (x) {
570
        return !contains(a2, x);
571
      });
572
    };
573
    var pure = function (x) {
574
      return [x];
575
    };
576
    var from$1 = isFunction(Array.from) ? Array.from : function (x) {
577
      return slice.call(x);
578
    };
579
580
    var detect$1 = function (candidates, userAgent) {
581
      var agent = String(userAgent).toLowerCase();
582
      return find$2(candidates, function (candidate) {
583
        return candidate.search(agent);
584
      });
585
    };
586
    var detectBrowser = function (browsers, userAgent) {
587
      return detect$1(browsers, userAgent).map(function (browser) {
588
        var version = Version.detect(browser.versionRegexes, userAgent);
589
        return {
590
          current: browser.name,
591
          version: version
592
        };
593
      });
594
    };
595
    var detectOs = function (oses, userAgent) {
596
      return detect$1(oses, userAgent).map(function (os) {
597
        var version = Version.detect(os.versionRegexes, userAgent);
598
        return {
599
          current: os.name,
600
          version: version
601
        };
602
      });
603
    };
604
    var UaString = {
605
      detectBrowser: detectBrowser,
606
      detectOs: detectOs
607
    };
608
609
    var checkRange = function (str, substr, start) {
610
      if (substr === '')
611
        return true;
612
      if (str.length < substr.length)
613
        return false;
614
      var x = str.substr(start, start + substr.length);
615
      return x === substr;
616
    };
617
    var supplant = function (str, obj) {
618
      var isStringOrNumber = function (a) {
619
        var t = typeof a;
620
        return t === 'string' || t === 'number';
621
      };
622
      return str.replace(/\$\{([^{}]*)\}/g, function (fullMatch, key) {
623
        var value = obj[key];
624
        return isStringOrNumber(value) ? value.toString() : fullMatch;
625
      });
626
    };
627
    var contains$1 = function (str, substr) {
628
      return str.indexOf(substr) !== -1;
629
    };
630
    var endsWith = function (str, suffix) {
631
      return checkRange(str, suffix, str.length - suffix.length);
632
    };
633
    var trim = function (str) {
634
      return str.replace(/^\s+|\s+$/g, '');
635
    };
636
637
    var normalVersionRegex = /.*?version\/\ ?([0-9]+)\.([0-9]+).*/;
638
    var checkContains = function (target) {
639
      return function (uastring) {
640
        return contains$1(uastring, target);
641
      };
642
    };
643
    var browsers = [
644
      {
645
        name: 'Edge',
646
        versionRegexes: [/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],
647
        search: function (uastring) {
648
          var monstrosity = contains$1(uastring, 'edge/') && contains$1(uastring, 'chrome') && contains$1(uastring, 'safari') && contains$1(uastring, 'applewebkit');
649
          return monstrosity;
650
        }
651
      },
652
      {
653
        name: 'Chrome',
654
        versionRegexes: [
655
          /.*?chrome\/([0-9]+)\.([0-9]+).*/,
656
          normalVersionRegex
657
        ],
658
        search: function (uastring) {
659
          return contains$1(uastring, 'chrome') && !contains$1(uastring, 'chromeframe');
660
        }
661
      },
662
      {
663
        name: 'IE',
664
        versionRegexes: [
665
          /.*?msie\ ?([0-9]+)\.([0-9]+).*/,
666
          /.*?rv:([0-9]+)\.([0-9]+).*/
667
        ],
668
        search: function (uastring) {
669
          return contains$1(uastring, 'msie') || contains$1(uastring, 'trident');
670
        }
671
      },
672
      {
673
        name: 'Opera',
674
        versionRegexes: [
675
          normalVersionRegex,
676
          /.*?opera\/([0-9]+)\.([0-9]+).*/
677
        ],
678
        search: checkContains('opera')
679
      },
680
      {
681
        name: 'Firefox',
682
        versionRegexes: [/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],
683
        search: checkContains('firefox')
684
      },
685
      {
686
        name: 'Safari',
687
        versionRegexes: [
688
          normalVersionRegex,
689
          /.*?cpu os ([0-9]+)_([0-9]+).*/
690
        ],
691
        search: function (uastring) {
692
          return (contains$1(uastring, 'safari') || contains$1(uastring, 'mobile/')) && contains$1(uastring, 'applewebkit');
693
        }
694
      }
695
    ];
696
    var oses = [
697
      {
698
        name: 'Windows',
699
        search: checkContains('win'),
700
        versionRegexes: [/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]
701
      },
702
      {
703
        name: 'iOS',
704
        search: function (uastring) {
705
          return contains$1(uastring, 'iphone') || contains$1(uastring, 'ipad');
706
        },
707
        versionRegexes: [
708
          /.*?version\/\ ?([0-9]+)\.([0-9]+).*/,
709
          /.*cpu os ([0-9]+)_([0-9]+).*/,
710
          /.*cpu iphone os ([0-9]+)_([0-9]+).*/
711
        ]
712
      },
713
      {
714
        name: 'Android',
715
        search: checkContains('android'),
716
        versionRegexes: [/.*?android\ ?([0-9]+)\.([0-9]+).*/]
717
      },
718
      {
719
        name: 'OSX',
720
        search: checkContains('os x'),
721
        versionRegexes: [/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]
722
      },
723
      {
724
        name: 'Linux',
725
        search: checkContains('linux'),
726
        versionRegexes: []
727
      },
728
      {
729
        name: 'Solaris',
730
        search: checkContains('sunos'),
731
        versionRegexes: []
732
      },
733
      {
734
        name: 'FreeBSD',
735
        search: checkContains('freebsd'),
736
        versionRegexes: []
737
      }
738
    ];
739
    var PlatformInfo = {
740
      browsers: constant(browsers),
741
      oses: constant(oses)
742
    };
743
744
    var detect$2 = function (userAgent) {
745
      var browsers = PlatformInfo.browsers();
746
      var oses = PlatformInfo.oses();
747
      var browser = UaString.detectBrowser(browsers, userAgent).fold(Browser.unknown, Browser.nu);
748
      var os = UaString.detectOs(oses, userAgent).fold(OperatingSystem.unknown, OperatingSystem.nu);
749
      var deviceType = DeviceType(os, browser, userAgent);
750
      return {
751
        browser: browser,
752
        os: os,
753
        deviceType: deviceType
754
      };
755
    };
756
    var PlatformDetection = { detect: detect$2 };
757
758
    var detect$3 = cached(function () {
759
      var userAgent = navigator.userAgent;
760
      return PlatformDetection.detect(userAgent);
761
    });
762
    var PlatformDetection$1 = { detect: detect$3 };
763
764
    var alloy = { tap: constant('alloy.tap') };
765
    var focus$1 = constant('alloy.focus');
766
    var postBlur = constant('alloy.blur.post');
767
    var receive = constant('alloy.receive');
768
    var execute = constant('alloy.execute');
769
    var focusItem = constant('alloy.focus.item');
770
    var tap = alloy.tap;
771
    var tapOrClick = PlatformDetection$1.detect().deviceType.isTouch() ? alloy.tap : click;
772
    var longpress = constant('alloy.longpress');
773
    var systemInit = constant('alloy.system.init');
774
    var windowScroll = constant('alloy.system.scroll');
775
    var attachedToDom = constant('alloy.system.attached');
776
    var detachedFromDom = constant('alloy.system.detached');
777
778
    var emit = function (component, event) {
779
      dispatchWith(component, component.element(), event, {});
780
    };
781
    var emitWith = function (component, event, properties) {
782
      dispatchWith(component, component.element(), event, properties);
783
    };
784
    var emitExecute = function (component) {
785
      emit(component, execute());
786
    };
787
    var dispatch = function (component, target, event) {
788
      dispatchWith(component, target, event, {});
789
    };
790
    var dispatchWith = function (component, target, event, properties) {
791
      var data = deepMerge({ target: target }, properties);
792
      component.getSystem().triggerEvent(event, target, map(data, constant));
793
    };
794
    var dispatchEvent = function (component, target, event, simulatedEvent) {
795
      component.getSystem().triggerEvent(event, target, simulatedEvent.event());
796
    };
797
    var dispatchFocus = function (component, target) {
798
      component.getSystem().triggerFocus(target, component.element());
799
    };
800
801
    var fromHtml = function (html, scope) {
802
      var doc = scope || document;
803
      var div = doc.createElement('div');
804
      div.innerHTML = html;
805
      if (!div.hasChildNodes() || div.childNodes.length > 1) {
806
        console.error('HTML does not have a single root node', html);
807
        throw 'HTML must have a single root node';
808
      }
809
      return fromDom(div.childNodes[0]);
810
    };
811
    var fromTag = function (tag, scope) {
812
      var doc = scope || document;
813
      var node = doc.createElement(tag);
814
      return fromDom(node);
815
    };
816
    var fromText = function (text, scope) {
817
      var doc = scope || document;
818
      var node = doc.createTextNode(text);
819
      return fromDom(node);
820
    };
821
    var fromDom = function (node) {
822
      if (node === null || node === undefined)
823
        throw new Error('Node cannot be null or undefined');
824
      return { dom: constant(node) };
825
    };
826
    var fromPoint = function (docElm, x, y) {
827
      var doc = docElm.dom();
828
      return Option.from(doc.elementFromPoint(x, y)).map(fromDom);
829
    };
830
    var Element$$1 = {
831
      fromHtml: fromHtml,
832
      fromTag: fromTag,
833
      fromText: fromText,
834
      fromDom: fromDom,
835
      fromPoint: fromPoint
836
    };
837
838
    var ATTRIBUTE = Node.ATTRIBUTE_NODE;
839
    var CDATA_SECTION = Node.CDATA_SECTION_NODE;
840
    var COMMENT = Node.COMMENT_NODE;
841
    var DOCUMENT = Node.DOCUMENT_NODE;
842
    var DOCUMENT_TYPE = Node.DOCUMENT_TYPE_NODE;
843
    var DOCUMENT_FRAGMENT = Node.DOCUMENT_FRAGMENT_NODE;
844
    var ELEMENT = Node.ELEMENT_NODE;
845
    var TEXT = Node.TEXT_NODE;
846
    var PROCESSING_INSTRUCTION = Node.PROCESSING_INSTRUCTION_NODE;
847
    var ENTITY_REFERENCE = Node.ENTITY_REFERENCE_NODE;
848
    var ENTITY = Node.ENTITY_NODE;
849
    var NOTATION = Node.NOTATION_NODE;
850
851
    var name = function (element) {
852
      var r = element.dom().nodeName;
853
      return r.toLowerCase();
854
    };
855
    var type = function (element) {
856
      return element.dom().nodeType;
857
    };
858
    var isType$1 = function (t) {
859
      return function (element) {
860
        return type(element) === t;
861
      };
862
    };
863
    var isElement = isType$1(ELEMENT);
864
    var isText = isType$1(TEXT);
865
866
    var inBody = function (element) {
867
      var dom = isText(element) ? element.dom().parentNode : element.dom();
868
      return dom !== undefined && dom !== null && dom.ownerDocument.body.contains(dom);
869
    };
870
    var body = cached(function () {
871
      return getBody(Element$$1.fromDom(document));
872
    });
873
    var getBody = function (doc) {
874
      var body = doc.dom().body;
875
      if (body === null || body === undefined)
876
        throw 'Body is not available yet';
877
      return Element$$1.fromDom(body);
878
    };
879
880
    var Immutable = function () {
881
      var fields = [];
882
      for (var _i = 0; _i < arguments.length; _i++) {
883
        fields[_i] = arguments[_i];
884
      }
885
      return function () {
886
        var values = [];
887
        for (var _i = 0; _i < arguments.length; _i++) {
888
          values[_i] = arguments[_i];
889
        }
890
        if (fields.length !== values.length) {
891
          throw new Error('Wrong number of arguments to struct. Expected "[' + fields.length + ']", got ' + values.length + ' arguments');
892
        }
893
        var struct = {};
894
        each$1(fields, function (name, i) {
895
          struct[name] = constant(values[i]);
896
        });
897
        return struct;
898
      };
899
    };
900
901
    var sort$1 = function (arr) {
902
      return arr.slice(0).sort();
903
    };
904
    var reqMessage = function (required, keys) {
905
      throw new Error('All required keys (' + sort$1(required).join(', ') + ') were not specified. Specified keys were: ' + sort$1(keys).join(', ') + '.');
906
    };
907
    var unsuppMessage = function (unsupported) {
908
      throw new Error('Unsupported keys for object: ' + sort$1(unsupported).join(', '));
909
    };
910
    var validateStrArr = function (label, array) {
911
      if (!isArray(array))
912
        throw new Error('The ' + label + ' fields must be an array. Was: ' + array + '.');
913
      each$1(array, function (a) {
914
        if (!isString(a))
915
          throw new Error('The value ' + a + ' in the ' + label + ' fields was not a string.');
916
      });
917
    };
918
    var invalidTypeMessage = function (incorrect, type) {
919
      throw new Error('All values need to be of type: ' + type + '. Keys (' + sort$1(incorrect).join(', ') + ') were not.');
920
    };
921
    var checkDupes = function (everything) {
922
      var sorted = sort$1(everything);
923
      var dupe = find$2(sorted, function (s, i) {
924
        return i < sorted.length - 1 && s === sorted[i + 1];
925
      });
926
      dupe.each(function (d) {
927
        throw new Error('The field: ' + d + ' occurs more than once in the combined fields: [' + sorted.join(', ') + '].');
928
      });
929
    };
930
931
    var MixedBag = function (required, optional) {
932
      var everything = required.concat(optional);
933
      if (everything.length === 0)
934
        throw new Error('You must specify at least one required or optional field.');
935
      validateStrArr('required', required);
936
      validateStrArr('optional', optional);
937
      checkDupes(everything);
938
      return function (obj) {
939
        var keys$$1 = keys(obj);
940
        var allReqd = forall(required, function (req) {
941
          return contains(keys$$1, req);
942
        });
943
        if (!allReqd)
944
          reqMessage(required, keys$$1);
945
        var unsupported = filter(keys$$1, function (key) {
946
          return !contains(everything, key);
947
        });
948
        if (unsupported.length > 0)
949
          unsuppMessage(unsupported);
950
        var r = {};
951
        each$1(required, function (req) {
952
          r[req] = constant(obj[req]);
953
        });
954
        each$1(optional, function (opt) {
955
          r[opt] = constant(Object.prototype.hasOwnProperty.call(obj, opt) ? Option.some(obj[opt]) : Option.none());
956
        });
957
        return r;
958
      };
959
    };
960
961
    var Global = typeof window !== 'undefined' ? window : Function('return this;')();
962
963 View Code Duplication
    var path = function (parts, scope) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
964
      var o = scope !== undefined && scope !== null ? scope : Global;
965
      for (var i = 0; i < parts.length && o !== undefined && o !== null; ++i)
966
        o = o[parts[i]];
967
      return o;
968
    };
969
    var resolve = function (p, scope) {
970
      var parts = p.split('.');
971
      return path(parts, scope);
972
    };
973
974
    var unsafe = function (name, scope) {
975
      return resolve(name, scope);
976
    };
977
    var getOrDie = function (name, scope) {
978
      var actual = unsafe(name, scope);
979
      if (actual === undefined || actual === null)
980
        throw name + ' not available on this browser';
981
      return actual;
982
    };
983
    var Global$1 = { getOrDie: getOrDie };
984
985
    var node = function () {
986
      var f = Global$1.getOrDie('Node');
987
      return f;
988
    };
989
    var compareDocumentPosition = function (a, b, match) {
990
      return (a.compareDocumentPosition(b) & match) !== 0;
991
    };
992
    var documentPositionPreceding = function (a, b) {
993
      return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_PRECEDING);
994
    };
995
    var documentPositionContainedBy = function (a, b) {
996
      return compareDocumentPosition(a, b, node().DOCUMENT_POSITION_CONTAINED_BY);
997
    };
998
    var Node$1 = {
999
      documentPositionPreceding: documentPositionPreceding,
1000
      documentPositionContainedBy: documentPositionContainedBy
1001
    };
1002
1003
    var ELEMENT$1 = ELEMENT;
1004
    var DOCUMENT$1 = DOCUMENT;
1005 View Code Duplication
    var is = function (element, selector) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1006
      var elem = element.dom();
1007
      if (elem.nodeType !== ELEMENT$1)
1008
        return false;
1009
      else if (elem.matches !== undefined)
1010
        return elem.matches(selector);
1011
      else if (elem.msMatchesSelector !== undefined)
1012
        return elem.msMatchesSelector(selector);
1013
      else if (elem.webkitMatchesSelector !== undefined)
1014
        return elem.webkitMatchesSelector(selector);
1015
      else if (elem.mozMatchesSelector !== undefined)
1016
        return elem.mozMatchesSelector(selector);
1017
      else
1018
        throw new Error('Browser lacks native selectors');
1019
    };
1020
    var bypassSelector = function (dom) {
1021
      return dom.nodeType !== ELEMENT$1 && dom.nodeType !== DOCUMENT$1 || dom.childElementCount === 0;
1022
    };
1023
    var all = function (selector, scope) {
1024
      var base = scope === undefined ? document : scope.dom();
1025
      return bypassSelector(base) ? [] : map$1(base.querySelectorAll(selector), Element$$1.fromDom);
1026
    };
1027
    var one = function (selector, scope) {
1028
      var base = scope === undefined ? document : scope.dom();
1029
      return bypassSelector(base) ? Option.none() : Option.from(base.querySelector(selector)).map(Element$$1.fromDom);
1030
    };
1031
1032
    var eq = function (e1, e2) {
1033
      return e1.dom() === e2.dom();
1034
    };
1035
    var regularContains = function (e1, e2) {
1036
      var d1 = e1.dom(), d2 = e2.dom();
1037
      return d1 === d2 ? false : d1.contains(d2);
1038
    };
1039
    var ieContains = function (e1, e2) {
1040
      return Node$1.documentPositionContainedBy(e1.dom(), e2.dom());
1041
    };
1042
    var browser = PlatformDetection$1.detect().browser;
1043
    var contains$2 = browser.isIE() ? ieContains : regularContains;
1044
1045
    var owner = function (element) {
1046
      return Element$$1.fromDom(element.dom().ownerDocument);
1047
    };
1048
    var defaultView = function (element) {
1049
      var el = element.dom();
1050
      var defaultView = el.ownerDocument.defaultView;
1051
      return Element$$1.fromDom(defaultView);
1052
    };
1053
    var parent = function (element) {
1054
      var dom = element.dom();
1055
      return Option.from(dom.parentNode).map(Element$$1.fromDom);
1056
    };
1057
    var parents = function (element, isRoot) {
1058
      var stop = isFunction(isRoot) ? isRoot : constant(false);
1059
      var dom = element.dom();
1060
      var ret = [];
1061
      while (dom.parentNode !== null && dom.parentNode !== undefined) {
1062
        var rawParent = dom.parentNode;
1063
        var parent = Element$$1.fromDom(rawParent);
1064
        ret.push(parent);
1065
        if (stop(parent) === true)
1066
          break;
1067
        else
1068
          dom = rawParent;
1069
      }
1070
      return ret;
1071
    };
1072
    var siblings = function (element) {
1073
      var filterSelf = function (elements) {
1074
        return filter(elements, function (x) {
1075
          return !eq(element, x);
1076
        });
1077
      };
1078
      return parent(element).map(children).map(filterSelf).getOr([]);
1079
    };
1080
    var nextSibling = function (element) {
1081
      var dom = element.dom();
1082
      return Option.from(dom.nextSibling).map(Element$$1.fromDom);
1083
    };
1084
    var children = function (element) {
1085
      var dom = element.dom();
1086
      return map$1(dom.childNodes, Element$$1.fromDom);
1087
    };
1088
    var child = function (element, index) {
1089
      var children = element.dom().childNodes;
1090
      return Option.from(children[index]).map(Element$$1.fromDom);
1091
    };
1092
    var firstChild = function (element) {
1093
      return child(element, 0);
1094
    };
1095
    var spot = Immutable('element', 'offset');
1096
1097
    var before = function (marker, element) {
1098
      var parent$$1 = parent(marker);
1099
      parent$$1.each(function (v) {
1100
        v.dom().insertBefore(element.dom(), marker.dom());
1101
      });
1102
    };
1103
    var after = function (marker, element) {
1104
      var sibling = nextSibling(marker);
1105
      sibling.fold(function () {
1106
        var parent$$1 = parent(marker);
1107
        parent$$1.each(function (v) {
1108
          append(v, element);
1109
        });
1110
      }, function (v) {
1111
        before(v, element);
1112
      });
1113
    };
1114
    var prepend = function (parent$$1, element) {
1115
      var firstChild$$1 = firstChild(parent$$1);
1116
      firstChild$$1.fold(function () {
1117
        append(parent$$1, element);
1118
      }, function (v) {
1119
        parent$$1.dom().insertBefore(element.dom(), v.dom());
1120
      });
1121
    };
1122
    var append = function (parent$$1, element) {
1123
      parent$$1.dom().appendChild(element.dom());
1124
    };
1125
1126
    var append$1 = function (parent, elements) {
1127
      each$1(elements, function (x) {
1128
        append(parent, x);
1129
      });
1130
    };
1131
1132
    var empty = function (element) {
1133
      element.dom().textContent = '';
1134
      each$1(children(element), function (rogue) {
1135
        remove(rogue);
1136
      });
1137
    };
1138
    var remove = function (element) {
1139
      var dom = element.dom();
1140
      if (dom.parentNode !== null)
1141
        dom.parentNode.removeChild(dom);
1142
    };
1143
1144
    var fireDetaching = function (component) {
1145
      emit(component, detachedFromDom());
1146
      var children$$1 = component.components();
1147
      each$1(children$$1, fireDetaching);
1148
    };
1149
    var fireAttaching = function (component) {
1150
      var children$$1 = component.components();
1151
      each$1(children$$1, fireAttaching);
1152
      emit(component, attachedToDom());
1153
    };
1154
    var attach = function (parent$$1, child$$1) {
1155
      attachWith(parent$$1, child$$1, append);
1156
    };
1157
    var attachWith = function (parent$$1, child$$1, insertion) {
1158
      parent$$1.getSystem().addToWorld(child$$1);
1159
      insertion(parent$$1.element(), child$$1.element());
1160
      if (inBody(parent$$1.element())) {
1161
        fireAttaching(child$$1);
1162
      }
1163
      parent$$1.syncComponents();
1164
    };
1165
    var doDetach = function (component) {
1166
      fireDetaching(component);
1167
      remove(component.element());
1168
      component.getSystem().removeFromWorld(component);
1169
    };
1170
    var detach = function (component) {
1171
      var parent$$1 = parent(component.element()).bind(function (p) {
1172
        return component.getSystem().getByDom(p).fold(Option.none, Option.some);
1173
      });
1174
      doDetach(component);
1175
      parent$$1.each(function (p) {
1176
        p.syncComponents();
1177
      });
1178
    };
1179
    var detachChildren = function (component) {
1180
      var subs = component.components();
1181
      each$1(subs, doDetach);
1182
      empty(component.element());
1183
      component.syncComponents();
1184
    };
1185
    var attachSystem = function (element, guiSystem) {
1186
      append(element, guiSystem.element());
1187
      var children$$1 = children(guiSystem.element());
1188
      each$1(children$$1, function (child$$1) {
1189
        guiSystem.getByDom(child$$1).each(fireAttaching);
1190
      });
1191
    };
1192
1193
    var value$1 = function (o) {
1194
      var is = function (v) {
1195
        return o === v;
1196
      };
1197
      var or = function (opt) {
1198
        return value$1(o);
1199
      };
1200
      var orThunk = function (f) {
1201
        return value$1(o);
1202
      };
1203
      var map = function (f) {
1204
        return value$1(f(o));
1205
      };
1206
      var mapError = function (f) {
1207
        return value$1(o);
1208
      };
1209
      var each = function (f) {
1210
        f(o);
1211
      };
1212
      var bind = function (f) {
1213
        return f(o);
1214
      };
1215
      var fold = function (_, onValue) {
1216
        return onValue(o);
1217
      };
1218
      var exists = function (f) {
1219
        return f(o);
1220
      };
1221
      var forall = function (f) {
1222
        return f(o);
1223
      };
1224
      var toOption = function () {
1225
        return Option.some(o);
1226
      };
1227
      return {
1228
        is: is,
1229
        isValue: always,
1230
        isError: never,
1231
        getOr: constant(o),
1232
        getOrThunk: constant(o),
1233
        getOrDie: constant(o),
1234
        or: or,
1235
        orThunk: orThunk,
1236
        fold: fold,
1237
        map: map,
1238
        mapError: mapError,
1239
        each: each,
1240
        bind: bind,
1241
        exists: exists,
1242
        forall: forall,
1243
        toOption: toOption
1244
      };
1245
    };
1246
    var error = function (message) {
1247
      var getOrThunk = function (f) {
1248
        return f();
1249
      };
1250
      var getOrDie = function () {
1251
        return die(String(message))();
1252
      };
1253
      var or = function (opt) {
1254
        return opt;
1255
      };
1256
      var orThunk = function (f) {
1257
        return f();
1258
      };
1259
      var map = function (f) {
1260
        return error(message);
1261
      };
1262
      var mapError = function (f) {
1263
        return error(f(message));
1264
      };
1265
      var bind = function (f) {
1266
        return error(message);
1267
      };
1268
      var fold = function (onError, _) {
1269
        return onError(message);
1270
      };
1271
      return {
1272
        is: never,
1273
        isValue: never,
1274
        isError: always,
1275
        getOr: identity,
1276
        getOrThunk: getOrThunk,
1277
        getOrDie: getOrDie,
1278
        or: or,
1279
        orThunk: orThunk,
1280
        fold: fold,
1281
        map: map,
1282
        mapError: mapError,
1283
        each: noop,
1284
        bind: bind,
1285
        exists: never,
1286
        forall: always,
1287
        toOption: Option.none
1288
      };
1289
    };
1290
    var Result = {
1291
      value: value$1,
1292
      error: error
1293
    };
1294
1295
    var generate = function (cases) {
1296
      if (!isArray(cases)) {
1297
        throw new Error('cases must be an array');
1298
      }
1299
      if (cases.length === 0) {
1300
        throw new Error('there must be at least one case');
1301
      }
1302
      var constructors = [];
1303
      var adt = {};
1304
      each$1(cases, function (acase, count) {
1305
        var keys$$1 = keys(acase);
1306
        if (keys$$1.length !== 1) {
1307
          throw new Error('one and only one name per case');
1308
        }
1309
        var key = keys$$1[0];
1310
        var value = acase[key];
1311
        if (adt[key] !== undefined) {
1312
          throw new Error('duplicate key detected:' + key);
1313
        } else if (key === 'cata') {
1314
          throw new Error('cannot have a case named cata (sorry)');
1315
        } else if (!isArray(value)) {
1316
          throw new Error('case arguments must be an array');
1317
        }
1318
        constructors.push(key);
1319
        adt[key] = function () {
1320
          var argLength = arguments.length;
1321
          if (argLength !== value.length) {
1322
            throw new Error('Wrong number of arguments to case ' + key + '. Expected ' + value.length + ' (' + value + '), got ' + argLength);
1323
          }
1324
          var args = new Array(argLength);
1325
          for (var i = 0; i < args.length; i++)
1326
            args[i] = arguments[i];
1327
          var match = function (branches) {
1328
            var branchKeys = keys(branches);
1329
            if (constructors.length !== branchKeys.length) {
1330
              throw new Error('Wrong number of arguments to match. Expected: ' + constructors.join(',') + '\nActual: ' + branchKeys.join(','));
1331
            }
1332
            var allReqd = forall(constructors, function (reqKey) {
1333
              return contains(branchKeys, reqKey);
1334
            });
1335
            if (!allReqd)
1336
              throw new Error('Not all branches were specified when using match. Specified: ' + branchKeys.join(', ') + '\nRequired: ' + constructors.join(', '));
1337
            return branches[key].apply(null, args);
1338
          };
1339
          return {
1340
            fold: function () {
1341
              if (arguments.length !== cases.length) {
1342
                throw new Error('Wrong number of arguments to fold. Expected ' + cases.length + ', got ' + arguments.length);
1343
              }
1344
              var target = arguments[count];
1345
              return target.apply(null, args);
1346
            },
1347
            match: match,
1348
            log: function (label) {
1349
              console.log(label, {
1350
                constructors: constructors,
1351
                constructor: key,
1352
                params: args
1353
              });
1354
            }
1355
          };
1356
        };
1357
      });
1358
      return adt;
1359
    };
1360
    var Adt = { generate: generate };
1361
1362
    var adt = Adt.generate([
1363
      { strict: [] },
1364
      { defaultedThunk: ['fallbackThunk'] },
1365
      { asOption: [] },
1366
      { asDefaultedOptionThunk: ['fallbackThunk'] },
1367
      { mergeWithThunk: ['baseThunk'] }
1368
    ]);
1369
    var defaulted = function (fallback) {
1370
      return adt.defaultedThunk(constant(fallback));
1371
    };
1372
    var mergeWith = function (base) {
1373
      return adt.mergeWithThunk(constant(base));
1374
    };
1375
    var strict = adt.strict;
1376
    var asOption = adt.asOption;
1377
    var defaultedThunk = adt.defaultedThunk;
1378
    var asDefaultedOptionThunk = adt.asDefaultedOptionThunk;
1379
    var mergeWithThunk = adt.mergeWithThunk;
1380
1381
    var comparison = Adt.generate([
1382
      {
1383
        bothErrors: [
1384
          'error1',
1385
          'error2'
1386
        ]
1387
      },
1388
      {
1389
        firstError: [
1390
          'error1',
1391
          'value2'
1392
        ]
1393
      },
1394
      {
1395
        secondError: [
1396
          'value1',
1397
          'error2'
1398
        ]
1399
      },
1400
      {
1401
        bothValues: [
1402
          'value1',
1403
          'value2'
1404
        ]
1405
      }
1406
    ]);
1407
    var partition$1 = function (results) {
1408
      var errors = [];
1409
      var values = [];
1410
      each$1(results, function (result) {
1411
        result.fold(function (err) {
1412
          errors.push(err);
1413
        }, function (value) {
1414
          values.push(value);
1415
        });
1416
      });
1417
      return {
1418
        errors: errors,
1419
        values: values
1420
      };
1421
    };
1422
1423
    var mergeValues = function (values, base) {
1424
      return Result.value(deepMerge.apply(undefined, [base].concat(values)));
1425
    };
1426
    var mergeErrors = function (errors) {
1427
      return compose(Result.error, flatten)(errors);
1428
    };
1429
    var consolidateObj = function (objects, base) {
1430
      var partitions = partition$1(objects);
1431
      return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : mergeValues(partitions.values, base);
1432
    };
1433
    var consolidateArr = function (objects) {
1434
      var partitions = partition$1(objects);
1435
      return partitions.errors.length > 0 ? mergeErrors(partitions.errors) : Result.value(partitions.values);
1436
    };
1437
    var ResultCombine = {
1438
      consolidateObj: consolidateObj,
1439
      consolidateArr: consolidateArr
1440
    };
1441
1442
    var narrow = function (obj, fields) {
1443
      var r = {};
1444
      each$1(fields, function (field) {
1445
        if (obj[field] !== undefined && obj.hasOwnProperty(field)) {
1446
          r[field] = obj[field];
1447
        }
1448
      });
1449
      return r;
1450
    };
1451
    var exclude = function (obj, fields) {
1452
      var r = {};
1453
      each(obj, function (v, k) {
1454
        if (!contains(fields, k)) {
1455
          r[k] = v;
1456
        }
1457
      });
1458
      return r;
1459
    };
1460
1461
    var readOpt = function (key) {
1462
      return function (obj) {
1463
        return obj.hasOwnProperty(key) ? Option.from(obj[key]) : Option.none();
1464
      };
1465
    };
1466
    var readOr = function (key, fallback) {
1467
      return function (obj) {
1468
        return readOpt(key)(obj).getOr(fallback);
1469
      };
1470
    };
1471
    var readOptFrom = function (obj, key) {
1472
      return readOpt(key)(obj);
1473
    };
1474
    var hasKey = function (obj, key) {
1475
      return obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null;
1476
    };
1477
1478
    var wrap$1 = function (key, value) {
1479
      var r = {};
1480
      r[key] = value;
1481
      return r;
1482
    };
1483
    var wrapAll = function (keyvalues) {
1484
      var r = {};
1485
      each$1(keyvalues, function (kv) {
1486
        r[kv.key] = kv.value;
1487
      });
1488
      return r;
1489
    };
1490
1491
    var narrow$1 = function (obj, fields) {
1492
      return narrow(obj, fields);
1493
    };
1494
    var exclude$1 = function (obj, fields) {
1495
      return exclude(obj, fields);
1496
    };
1497
    var readOpt$1 = function (key) {
1498
      return readOpt(key);
1499
    };
1500
    var readOr$1 = function (key, fallback) {
1501
      return readOr(key, fallback);
1502
    };
1503
    var readOptFrom$1 = function (obj, key) {
1504
      return readOptFrom(obj, key);
1505
    };
1506
    var wrap$2 = function (key, value) {
1507
      return wrap$1(key, value);
1508
    };
1509
    var wrapAll$1 = function (keyvalues) {
1510
      return wrapAll(keyvalues);
1511
    };
1512
    var consolidate = function (objs, base) {
1513
      return ResultCombine.consolidateObj(objs, base);
1514
    };
1515
    var hasKey$1 = function (obj, key) {
1516
      return hasKey(obj, key);
1517
    };
1518
1519
    var typeAdt = Adt.generate([
1520
      {
1521
        setOf: [
1522
          'validator',
1523
          'valueType'
1524
        ]
1525
      },
1526
      { arrOf: ['valueType'] },
1527
      { objOf: ['fields'] },
1528
      { itemOf: ['validator'] },
1529
      {
1530
        choiceOf: [
1531
          'key',
1532
          'branches'
1533
        ]
1534
      },
1535
      { thunk: ['description'] },
1536
      {
1537
        func: [
1538
          'args',
1539
          'outputSchema'
1540
        ]
1541
      }
1542
    ]);
1543
    var fieldAdt = Adt.generate([
1544
      {
1545
        field: [
1546
          'name',
1547
          'presence',
1548
          'type'
1549
        ]
1550
      },
1551
      { state: ['name'] }
1552
    ]);
1553
1554
    var json = function () {
1555
      return Global$1.getOrDie('JSON');
1556
    };
1557
    var parse = function (text) {
1558
      return json().parse(text);
1559
    };
1560
    var stringify = function (obj, replacer, space) {
1561
      return json().stringify(obj, replacer, space);
1562
    };
1563
    var Json = {
1564
      parse: parse,
1565
      stringify: stringify
1566
    };
1567
1568
    var formatObj = function (input) {
1569
      return isObject(input) && keys(input).length > 100 ? ' removed due to size' : Json.stringify(input, null, 2);
1570
    };
1571
    var formatErrors = function (errors) {
1572
      var es = errors.length > 10 ? errors.slice(0, 10).concat([{
1573
          path: [],
1574
          getErrorInfo: function () {
1575
            return '... (only showing first ten failures)';
1576
          }
1577
        }]) : errors;
1578
      return map$1(es, function (e) {
1579
        return 'Failed path: (' + e.path.join(' > ') + ')\n' + e.getErrorInfo();
1580
      });
1581
    };
1582
1583
    var nu$3 = function (path, getErrorInfo) {
1584
      return Result.error([{
1585
          path: path,
1586
          getErrorInfo: getErrorInfo
1587
        }]);
1588
    };
1589
    var missingStrict = function (path, key, obj) {
1590
      return nu$3(path, function () {
1591
        return 'Could not find valid *strict* value for "' + key + '" in ' + formatObj(obj);
1592
      });
1593
    };
1594
    var missingKey = function (path, key) {
1595
      return nu$3(path, function () {
1596
        return 'Choice schema did not contain choice key: "' + key + '"';
1597
      });
1598
    };
1599
    var missingBranch = function (path, branches, branch) {
1600
      return nu$3(path, function () {
1601
        return 'The chosen schema: "' + branch + '" did not exist in branches: ' + formatObj(branches);
1602
      });
1603
    };
1604
    var unsupportedFields = function (path, unsupported) {
1605
      return nu$3(path, function () {
1606
        return 'There are unsupported fields: [' + unsupported.join(', ') + '] specified';
1607
      });
1608
    };
1609
    var custom = function (path, err) {
1610
      return nu$3(path, function () {
1611
        return err;
1612
      });
1613
    };
1614
1615
    var adt$1 = Adt.generate([
1616
      {
1617
        field: [
1618
          'key',
1619
          'okey',
1620
          'presence',
1621
          'prop'
1622
        ]
1623
      },
1624
      {
1625
        state: [
1626
          'okey',
1627
          'instantiator'
1628
        ]
1629
      }
1630
    ]);
1631
    var strictAccess = function (path, obj, key) {
1632
      return readOptFrom(obj, key).fold(function () {
1633
        return missingStrict(path, key, obj);
1634
      }, Result.value);
1635
    };
1636
    var fallbackAccess = function (obj, key, fallbackThunk) {
1637
      var v = readOptFrom(obj, key).fold(function () {
1638
        return fallbackThunk(obj);
1639
      }, identity);
1640
      return Result.value(v);
1641
    };
1642
    var optionAccess = function (obj, key) {
1643
      return Result.value(readOptFrom(obj, key));
1644
    };
1645
    var optionDefaultedAccess = function (obj, key, fallback) {
1646
      var opt = readOptFrom(obj, key).map(function (val) {
1647
        return val === true ? fallback(obj) : val;
1648
      });
1649
      return Result.value(opt);
1650
    };
1651
    var cExtractOne = function (path, obj, field, strength) {
1652
      return field.fold(function (key, okey, presence, prop) {
1653
        var bundle = function (av) {
1654
          return prop.extract(path.concat([key]), strength, av).map(function (res) {
1655
            return wrap$1(okey, strength(res));
1656
          });
1657
        };
1658
        var bundleAsOption = function (optValue) {
1659
          return optValue.fold(function () {
1660
            var outcome = wrap$1(okey, strength(Option.none()));
1661
            return Result.value(outcome);
1662
          }, function (ov) {
1663
            return prop.extract(path.concat([key]), strength, ov).map(function (res) {
1664
              return wrap$1(okey, strength(Option.some(res)));
1665
            });
1666
          });
1667
        };
1668
        return function () {
1669
          return presence.fold(function () {
1670
            return strictAccess(path, obj, key).bind(bundle);
1671
          }, function (fallbackThunk) {
1672
            return fallbackAccess(obj, key, fallbackThunk).bind(bundle);
1673
          }, function () {
1674
            return optionAccess(obj, key).bind(bundleAsOption);
1675
          }, function (fallbackThunk) {
1676
            return optionDefaultedAccess(obj, key, fallbackThunk).bind(bundleAsOption);
1677
          }, function (baseThunk) {
1678
            var base = baseThunk(obj);
1679
            return fallbackAccess(obj, key, constant({})).map(function (v) {
1680
              return deepMerge(base, v);
1681
            }).bind(bundle);
1682
          });
1683
        }();
1684
      }, function (okey, instantiator) {
1685
        var state = instantiator(obj);
1686
        return Result.value(wrap$1(okey, strength(state)));
1687
      });
1688
    };
1689
    var cExtract = function (path, obj, fields, strength) {
1690
      var results = map$1(fields, function (field) {
1691
        return cExtractOne(path, obj, field, strength);
1692
      });
1693
      return ResultCombine.consolidateObj(results, {});
1694
    };
1695
    var value$2 = function (validator) {
1696
      var extract = function (path, strength, val) {
1697
        return validator(val, strength).fold(function (err) {
1698
          return custom(path, err);
1699
        }, Result.value);
1700
      };
1701
      var toString$$1 = function () {
1702
        return 'val';
1703
      };
1704
      var toDsl = function () {
1705
        return typeAdt.itemOf(validator);
1706
      };
1707
      return {
1708
        extract: extract,
1709
        toString: toString$$1,
1710
        toDsl: toDsl
1711
      };
1712
    };
1713
    var getSetKeys = function (obj) {
1714
      var keys$$1 = keys(obj);
1715
      return filter(keys$$1, function (k) {
1716
        return hasKey$1(obj, k);
1717
      });
1718
    };
1719
    var objOfOnly = function (fields) {
1720
      var delegate = objOf(fields);
1721
      var fieldNames = foldr(fields, function (acc, f) {
1722
        return f.fold(function (key) {
1723
          return deepMerge(acc, wrap$2(key, true));
1724
        }, constant(acc));
1725
      }, {});
1726
      var extract = function (path, strength, o) {
1727
        var keys$$1 = isBoolean(o) ? [] : getSetKeys(o);
1728
        var extra = filter(keys$$1, function (k) {
1729
          return !hasKey$1(fieldNames, k);
1730
        });
1731
        return extra.length === 0 ? delegate.extract(path, strength, o) : unsupportedFields(path, extra);
1732
      };
1733
      return {
1734
        extract: extract,
1735
        toString: delegate.toString,
1736
        toDsl: delegate.toDsl
1737
      };
1738
    };
1739
    var objOf = function (fields) {
1740
      var extract = function (path, strength, o) {
1741
        return cExtract(path, o, fields, strength);
1742
      };
1743
      var toString$$1 = function () {
1744
        var fieldStrings = map$1(fields, function (field) {
1745
          return field.fold(function (key, okey, presence, prop) {
1746
            return key + ' -> ' + prop.toString();
1747
          }, function (okey, instantiator) {
1748
            return 'state(' + okey + ')';
1749
          });
1750
        });
1751
        return 'obj{\n' + fieldStrings.join('\n') + '}';
1752
      };
1753
      var toDsl = function () {
1754
        return typeAdt.objOf(map$1(fields, function (f) {
1755
          return f.fold(function (key, okey, presence, prop) {
1756
            return fieldAdt.field(key, presence, prop);
1757
          }, function (okey, instantiator) {
1758
            return fieldAdt.state(okey);
1759
          });
1760
        }));
1761
      };
1762
      return {
1763
        extract: extract,
1764
        toString: toString$$1,
1765
        toDsl: toDsl
1766
      };
1767
    };
1768
    var arrOf = function (prop) {
1769
      var extract = function (path, strength, array) {
1770
        var results = map$1(array, function (a, i) {
1771
          return prop.extract(path.concat(['[' + i + ']']), strength, a);
1772
        });
1773
        return ResultCombine.consolidateArr(results);
1774
      };
1775
      var toString$$1 = function () {
1776
        return 'array(' + prop.toString() + ')';
1777
      };
1778
      var toDsl = function () {
1779
        return typeAdt.arrOf(prop);
1780
      };
1781
      return {
1782
        extract: extract,
1783
        toString: toString$$1,
1784
        toDsl: toDsl
1785
      };
1786
    };
1787
    var setOf = function (validator, prop) {
1788
      var validateKeys = function (path, keys$$1) {
1789
        return arrOf(value$2(validator)).extract(path, identity, keys$$1);
1790
      };
1791
      var extract = function (path, strength, o) {
1792
        var keys$$1 = keys(o);
1793
        return validateKeys(path, keys$$1).bind(function (validKeys) {
1794
          var schema = map$1(validKeys, function (vk) {
1795
            return adt$1.field(vk, vk, strict(), prop);
1796
          });
1797
          return objOf(schema).extract(path, strength, o);
1798
        });
1799
      };
1800
      var toString$$1 = function () {
1801
        return 'setOf(' + prop.toString() + ')';
1802
      };
1803
      var toDsl = function () {
1804
        return typeAdt.setOf(validator, prop);
1805
      };
1806
      return {
1807
        extract: extract,
1808
        toString: toString$$1,
1809
        toDsl: toDsl
1810
      };
1811
    };
1812
    var anyValue = constant(value$2(Result.value));
1813
    var state = adt$1.state;
1814
    var field = adt$1.field;
1815
1816
    var chooseFrom = function (path, strength, input, branches, ch) {
1817
      var fields = readOptFrom$1(branches, ch);
1818
      return fields.fold(function () {
1819
        return missingBranch(path, branches, ch);
1820
      }, function (fs) {
1821
        return objOf(fs).extract(path.concat(['branch: ' + ch]), strength, input);
1822
      });
1823
    };
1824
    var choose = function (key, branches) {
1825
      var extract = function (path, strength, input) {
1826
        var choice = readOptFrom$1(input, key);
1827
        return choice.fold(function () {
1828
          return missingKey(path, key);
1829
        }, function (chosen) {
1830
          return chooseFrom(path, strength, input, branches, chosen);
1831
        });
1832
      };
1833
      var toString$$1 = function () {
1834
        return 'chooseOn(' + key + '). Possible values: ' + keys(branches);
1835
      };
1836
      var toDsl = function () {
1837
        return typeAdt.choiceOf(key, branches);
1838
      };
1839
      return {
1840
        extract: extract,
1841
        toString: toString$$1,
1842
        toDsl: toDsl
1843
      };
1844
    };
1845
1846
    var _anyValue = value$2(Result.value);
1847
    var valueOf = function (validator) {
1848
      return value$2(function (v) {
1849
        return validator(v);
1850
      });
1851
    };
1852
    var extract = function (label, prop, strength, obj) {
1853
      return prop.extract([label], strength, obj).fold(function (errs) {
1854
        return Result.error({
1855
          input: obj,
1856
          errors: errs
1857
        });
1858
      }, Result.value);
1859
    };
1860
    var asStruct = function (label, prop, obj) {
1861
      return extract(label, prop, constant, obj);
1862
    };
1863
    var asRaw = function (label, prop, obj) {
1864
      return extract(label, prop, identity, obj);
1865
    };
1866
    var getOrDie$1 = function (extraction) {
1867
      return extraction.fold(function (errInfo) {
1868
        throw new Error(formatError(errInfo));
1869
      }, identity);
1870
    };
1871
    var asRawOrDie = function (label, prop, obj) {
1872
      return getOrDie$1(asRaw(label, prop, obj));
1873
    };
1874
    var asStructOrDie = function (label, prop, obj) {
1875
      return getOrDie$1(asStruct(label, prop, obj));
1876
    };
1877
    var formatError = function (errInfo) {
1878
      return 'Errors: \n' + formatErrors(errInfo.errors) + '\n\nInput object: ' + formatObj(errInfo.input);
1879
    };
1880
    var choose$1 = function (key, branches) {
1881
      return choose(key, branches);
1882
    };
1883
    var anyValue$1 = constant(_anyValue);
1884
    var typedValue = function (validator, expectedType) {
1885
      return value$2(function (a) {
1886
        var actualType = typeof a;
1887
        return validator(a) ? Result.value(a) : Result.error('Expected type: ' + expectedType + ' but got: ' + actualType);
1888
      });
1889
    };
1890
    var functionProcessor = typedValue(isFunction, 'function');
1891
1892
    var strict$1 = function (key) {
1893
      return field(key, key, strict(), anyValue());
1894
    };
1895
    var strictOf = function (key, schema) {
1896
      return field(key, key, strict(), schema);
1897
    };
1898
    var strictFunction = function (key) {
1899
      return strictOf(key, functionProcessor);
1900
    };
1901
    var forbid = function (key, message) {
1902
      return field(key, key, asOption(), value$2(function (v) {
1903
        return Result.error('The field: ' + key + ' is forbidden. ' + message);
1904
      }));
1905
    };
1906
    var strictObjOf = function (key, objSchema) {
1907
      return field(key, key, strict(), objOf(objSchema));
1908
    };
1909
    var option = function (key) {
1910
      return field(key, key, asOption(), anyValue());
1911
    };
1912
    var optionOf = function (key, schema) {
1913
      return field(key, key, asOption(), schema);
1914
    };
1915
    var optionObjOf = function (key, objSchema) {
1916
      return field(key, key, asOption(), objOf(objSchema));
1917
    };
1918
    var optionObjOfOnly = function (key, objSchema) {
1919
      return field(key, key, asOption(), objOfOnly(objSchema));
1920
    };
1921
    var defaulted$1 = function (key, fallback) {
1922
      return field(key, key, defaulted(fallback), anyValue());
1923
    };
1924
    var defaultedOf = function (key, fallback, schema) {
1925
      return field(key, key, defaulted(fallback), schema);
1926
    };
1927
    var defaultedObjOf = function (key, fallback, objSchema) {
1928
      return field(key, key, defaulted(fallback), objOf(objSchema));
1929
    };
1930
    var state$1 = function (okey, instantiator) {
1931
      return state(okey, instantiator);
1932
    };
1933
1934
    var isSource = function (component, simulatedEvent) {
1935
      return eq(component.element(), simulatedEvent.event().target());
1936
    };
1937
1938
    var nu$4 = function (parts) {
1939
      if (!hasKey$1(parts, 'can') && !hasKey$1(parts, 'abort') && !hasKey$1(parts, 'run')) {
1940
        throw new Error('EventHandler defined by: ' + Json.stringify(parts, null, 2) + ' does not have can, abort, or run!');
1941
      }
1942
      return asRawOrDie('Extracting event.handler', objOfOnly([
1943
        defaulted$1('can', constant(true)),
1944
        defaulted$1('abort', constant(false)),
1945
        defaulted$1('run', noop)
1946
      ]), parts);
1947
    };
1948
    var all$1 = function (handlers, f) {
1949
      return function () {
1950
        var args = [];
1951
        for (var _i = 0; _i < arguments.length; _i++) {
1952
          args[_i] = arguments[_i];
1953
        }
1954
        return foldl(handlers, function (acc, handler) {
1955
          return acc && f(handler).apply(undefined, args);
1956
        }, true);
1957
      };
1958
    };
1959
    var any = function (handlers, f) {
1960
      return function () {
1961
        var args = [];
1962
        for (var _i = 0; _i < arguments.length; _i++) {
1963
          args[_i] = arguments[_i];
1964
        }
1965
        return foldl(handlers, function (acc, handler) {
1966
          return acc || f(handler).apply(undefined, args);
1967
        }, false);
1968
      };
1969
    };
1970
    var read = function (handler) {
1971
      return isFunction(handler) ? {
1972
        can: constant(true),
1973
        abort: constant(false),
1974
        run: handler
1975
      } : handler;
1976
    };
1977
    var fuse = function (handlers) {
1978
      var can = all$1(handlers, function (handler) {
1979
        return handler.can;
1980
      });
1981
      var abort = any(handlers, function (handler) {
1982
        return handler.abort;
1983
      });
1984
      var run = function () {
1985
        var args = [];
1986
        for (var _i = 0; _i < arguments.length; _i++) {
1987
          args[_i] = arguments[_i];
1988
        }
1989
        each$1(handlers, function (handler) {
1990
          handler.run.apply(undefined, args);
1991
        });
1992
      };
1993
      return nu$4({
1994
        can: can,
1995
        abort: abort,
1996
        run: run
1997
      });
1998
    };
1999
2000
    var derive = function (configs) {
2001
      return wrapAll$1(configs);
2002
    };
2003
    var abort = function (name, predicate) {
2004
      return {
2005
        key: name,
2006
        value: nu$4({ abort: predicate })
2007
      };
2008
    };
2009
    var can = function (name, predicate) {
2010
      return {
2011
        key: name,
2012
        value: nu$4({ can: predicate })
2013
      };
2014
    };
2015
    var run = function (name, handler) {
2016
      return {
2017
        key: name,
2018
        value: nu$4({ run: handler })
2019
      };
2020
    };
2021
    var runActionExtra = function (name, action, extra) {
2022
      return {
2023
        key: name,
2024
        value: nu$4({
2025
          run: function (component) {
2026
            action.apply(undefined, [component].concat(extra));
2027
          }
2028
        })
2029
      };
2030
    };
2031
    var runOnName = function (name) {
2032
      return function (handler) {
2033
        return run(name, handler);
2034
      };
2035
    };
2036
    var runOnSourceName = function (name) {
2037
      return function (handler) {
2038
        return {
2039
          key: name,
2040
          value: nu$4({
2041
            run: function (component, simulatedEvent) {
2042
              if (isSource(component, simulatedEvent)) {
2043
                handler(component, simulatedEvent);
2044
              }
2045
            }
2046
          })
2047
        };
2048
      };
2049
    };
2050
    var redirectToUid = function (name, uid) {
2051
      return run(name, function (component, simulatedEvent) {
2052
        component.getSystem().getByUid(uid).each(function (redirectee) {
2053
          dispatchEvent(redirectee, redirectee.element(), name, simulatedEvent);
2054
        });
2055
      });
2056
    };
2057
    var redirectToPart = function (name, detail, partName) {
2058
      var uid = detail.partUids()[partName];
2059
      return redirectToUid(name, uid);
2060
    };
2061
    var runWithTarget = function (name, f) {
2062
      return run(name, function (component, simulatedEvent) {
2063
        var ev = simulatedEvent.event();
2064
        component.getSystem().getByDom(ev.target()).each(function (target) {
2065
          f(component, target, simulatedEvent);
2066
        });
2067
      });
2068
    };
2069
    var cutter = function (name) {
2070
      return run(name, function (component, simulatedEvent) {
2071
        simulatedEvent.cut();
2072
      });
2073
    };
2074
    var stopper = function (name) {
2075
      return run(name, function (component, simulatedEvent) {
2076
        simulatedEvent.stop();
2077
      });
2078
    };
2079
    var runOnAttached = runOnSourceName(attachedToDom());
2080
    var runOnDetached = runOnSourceName(detachedFromDom());
2081
    var runOnInit = runOnSourceName(systemInit());
2082
    var runOnExecute = runOnName(execute());
2083
2084
    var markAsBehaviourApi = function (f, apiName, apiFunction) {
2085
      var delegate = apiFunction.toString();
2086
      var endIndex = delegate.indexOf(')') + 1;
2087
      var openBracketIndex = delegate.indexOf('(');
2088
      var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
2089
      f.toFunctionAnnotation = function () {
2090
        return {
2091
          name: apiName,
2092
          parameters: cleanParameters(parameters.slice(0, 1).concat(parameters.slice(3)))
2093
        };
2094
      };
2095
      return f;
2096
    };
2097
    var cleanParameters = function (parameters) {
2098
      return map$1(parameters, function (p) {
2099
        return endsWith(p, '/*') ? p.substring(0, p.length - '/*'.length) : p;
2100
      });
2101
    };
2102
    var markAsExtraApi = function (f, extraName) {
2103
      var delegate = f.toString();
2104
      var endIndex = delegate.indexOf(')') + 1;
2105
      var openBracketIndex = delegate.indexOf('(');
2106
      var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
2107
      f.toFunctionAnnotation = function () {
2108
        return {
2109
          name: extraName,
2110
          parameters: cleanParameters(parameters)
2111
        };
2112
      };
2113
      return f;
2114
    };
2115
    var markAsSketchApi = function (f, apiFunction) {
2116
      var delegate = apiFunction.toString();
2117
      var endIndex = delegate.indexOf(')') + 1;
2118
      var openBracketIndex = delegate.indexOf('(');
2119
      var parameters = delegate.substring(openBracketIndex + 1, endIndex - 1).split(/,\s*/);
2120
      f.toFunctionAnnotation = function () {
2121
        return {
2122
          name: 'OVERRIDE',
2123
          parameters: cleanParameters(parameters.slice(1))
2124
        };
2125
      };
2126
      return f;
2127
    };
2128
2129
    var nu$5 = MixedBag(['tag'], [
2130
      'classes',
2131
      'attributes',
2132
      'styles',
2133
      'value',
2134
      'innerHtml',
2135
      'domChildren',
2136
      'defChildren'
2137
    ]);
2138
    var defToStr = function (defn) {
2139
      var raw = defToRaw(defn);
2140
      return Json.stringify(raw, null, 2);
2141
    };
2142
    var defToRaw = function (defn) {
2143
      return {
2144
        tag: defn.tag(),
2145
        classes: defn.classes().getOr([]),
2146
        attributes: defn.attributes().getOr({}),
2147
        styles: defn.styles().getOr({}),
2148
        value: defn.value().getOr('<none>'),
2149
        innerHtml: defn.innerHtml().getOr('<none>'),
2150
        defChildren: defn.defChildren().fold(function () {
2151
          return '<none>';
2152
        }, function (d) {
2153
          return Json.stringify(d, null, 2);
2154
        }),
2155
        domChildren: defn.domChildren().fold(function () {
2156
          return '<none>';
2157
        }, function (children) {
2158
          return children.length === 0 ? '0 children, but still specified' : String(children.length);
2159
        })
2160
      };
2161
    };
2162
2163
    var fields = [
2164
      'classes',
2165
      'attributes',
2166
      'styles',
2167
      'value',
2168
      'innerHtml',
2169
      'defChildren',
2170
      'domChildren'
2171
    ];
2172
    var nu$6 = MixedBag([], fields);
2173
    var clashingOptArrays = function (key, oArr1, oArr2) {
2174
      return oArr1.fold(function () {
2175
        return oArr2.fold(function () {
2176
          return {};
2177
        }, function (arr2) {
2178
          return wrap$2(key, arr2);
2179
        });
2180
      }, function (arr1) {
2181
        return oArr2.fold(function () {
2182
          return wrap$2(key, arr1);
2183
        }, function (arr2) {
2184
          return wrap$2(key, arr2);
2185
        });
2186
      });
2187
    };
2188
    var merge$1 = function (defnA, mod) {
2189
      var raw = deepMerge({
2190
        tag: defnA.tag(),
2191
        classes: mod.classes().getOr([]).concat(defnA.classes().getOr([])),
2192
        attributes: merge(defnA.attributes().getOr({}), mod.attributes().getOr({})),
2193
        styles: merge(defnA.styles().getOr({}), mod.styles().getOr({}))
2194
      }, mod.innerHtml().or(defnA.innerHtml()).map(function (innerHtml) {
2195
        return wrap$2('innerHtml', innerHtml);
2196
      }).getOr({}), clashingOptArrays('domChildren', mod.domChildren(), defnA.domChildren()), clashingOptArrays('defChildren', mod.defChildren(), defnA.defChildren()), mod.value().or(defnA.value()).map(function (value) {
2197
        return wrap$2('value', value);
2198
      }).getOr({}));
2199
      return nu$5(raw);
2200
    };
2201
2202
    var executeEvent = function (bConfig, bState, executor) {
2203
      return runOnExecute(function (component) {
2204
        executor(component, bConfig, bState);
2205
      });
2206
    };
2207
    var loadEvent = function (bConfig, bState, f) {
2208
      return runOnInit(function (component, simulatedEvent) {
2209
        f(component, bConfig, bState);
2210
      });
2211
    };
2212
    var create = function (schema, name, active, apis, extra, state) {
2213
      var configSchema = objOfOnly(schema);
2214
      var schemaSchema = optionObjOf(name, [optionObjOfOnly('config', schema)]);
2215
      return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
2216
    };
2217
    var createModes = function (modes, name, active, apis, extra, state) {
2218
      var configSchema = modes;
2219
      var schemaSchema = optionObjOf(name, [optionOf('config', modes)]);
2220
      return doCreate(configSchema, schemaSchema, name, active, apis, extra, state);
2221
    };
2222
    var wrapApi = function (bName, apiFunction, apiName) {
2223
      var f = function (component) {
2224
        var rest = [];
2225
        for (var _i = 1; _i < arguments.length; _i++) {
2226
          rest[_i - 1] = arguments[_i];
2227
        }
2228
        var args = [component].concat(rest);
2229
        return component.config({ name: constant(bName) }).fold(function () {
2230
          throw new Error('We could not find any behaviour configuration for: ' + bName + '. Using API: ' + apiName);
2231
        }, function (info) {
2232
          var rest = Array.prototype.slice.call(args, 1);
2233
          return apiFunction.apply(undefined, [
2234
            component,
2235
            info.config,
2236
            info.state
2237
          ].concat(rest));
2238
        });
2239
      };
2240
      return markAsBehaviourApi(f, apiName, apiFunction);
2241
    };
2242
    var revokeBehaviour = function (name) {
2243
      return {
2244
        key: name,
2245
        value: undefined
2246
      };
2247
    };
2248
    var doCreate = function (configSchema, schemaSchema, name, active, apis, extra, state) {
2249
      var getConfig = function (info) {
2250
        return hasKey$1(info, name) ? info[name]() : Option.none();
2251
      };
2252
      var wrappedApis = map(apis, function (apiF, apiName) {
2253
        return wrapApi(name, apiF, apiName);
2254
      });
2255
      var wrappedExtra = map(extra, function (extraF, extraName) {
2256
        return markAsExtraApi(extraF, extraName);
2257
      });
2258
      var me = deepMerge(wrappedExtra, wrappedApis, {
2259
        revoke: curry(revokeBehaviour, name),
2260
        config: function (spec) {
2261
          var prepared = asStructOrDie(name + '-config', configSchema, spec);
2262
          return {
2263
            key: name,
2264
            value: {
2265
              config: prepared,
2266
              me: me,
2267
              configAsRaw: cached(function () {
2268
                return asRawOrDie(name + '-config', configSchema, spec);
2269
              }),
2270
              initialConfig: spec,
2271
              state: state
2272
            }
2273
          };
2274
        },
2275
        schema: function () {
2276
          return schemaSchema;
2277
        },
2278
        exhibit: function (info, base) {
2279
          return getConfig(info).bind(function (behaviourInfo) {
2280
            return readOptFrom$1(active, 'exhibit').map(function (exhibitor) {
2281
              return exhibitor(base, behaviourInfo.config, behaviourInfo.state);
2282
            });
2283
          }).getOr(nu$6({}));
2284
        },
2285
        name: function () {
2286
          return name;
2287
        },
2288
        handlers: function (info) {
2289
          return getConfig(info).bind(function (behaviourInfo) {
2290
            return readOptFrom$1(active, 'events').map(function (events) {
2291
              return events(behaviourInfo.config, behaviourInfo.state);
2292
            });
2293
          }).getOr({});
2294
        }
2295
      });
2296
      return me;
2297
    };
2298
2299
    var base = function (handleUnsupported, required) {
2300
      return baseWith(handleUnsupported, required, {
2301
        validate: isFunction,
2302
        label: 'function'
2303
      });
2304
    };
2305
    var baseWith = function (handleUnsupported, required, pred) {
2306
      if (required.length === 0)
2307
        throw new Error('You must specify at least one required field.');
2308
      validateStrArr('required', required);
2309
      checkDupes(required);
2310
      return function (obj) {
2311
        var keys$$1 = keys(obj);
2312
        var allReqd = forall(required, function (req) {
2313
          return contains(keys$$1, req);
2314
        });
2315
        if (!allReqd)
2316
          reqMessage(required, keys$$1);
2317
        handleUnsupported(required, keys$$1);
2318
        var invalidKeys = filter(required, function (key) {
2319
          return !pred.validate(obj[key], key);
2320
        });
2321
        if (invalidKeys.length > 0)
2322
          invalidTypeMessage(invalidKeys, pred.label);
2323
        return obj;
2324
      };
2325
    };
2326
    var handleExact = function (required, keys$$1) {
2327
      var unsupported = filter(keys$$1, function (key) {
2328
        return !contains(required, key);
2329
      });
2330
      if (unsupported.length > 0)
2331
        unsuppMessage(unsupported);
2332
    };
2333
    var allowExtra = noop;
2334
    var exactly = function (required) {
2335
      return base(handleExact, required);
2336
    };
2337
    var ensure = function (required) {
2338
      return base(allowExtra, required);
2339
    };
2340
2341
    var NoState = {
2342
      init: function () {
2343
        return nu$7({
2344
          readState: function () {
2345
            return 'No State required';
2346
          }
2347
        });
2348
      }
2349
    };
2350
    var nu$7 = function (spec) {
2351
      ensure(['readState'])(spec);
2352
      return spec;
2353
    };
2354
2355
    var derive$2 = function (capabilities) {
2356
      return wrapAll$1(capabilities);
2357
    };
2358
    var simpleSchema = objOfOnly([
2359
      strict$1('fields'),
2360
      strict$1('name'),
2361
      defaulted$1('active', {}),
2362
      defaulted$1('apis', {}),
2363
      defaulted$1('state', NoState),
2364
      defaulted$1('extra', {})
2365
    ]);
2366
    var create$1 = function (data) {
2367
      var value = asRawOrDie('Creating behaviour: ' + data.name, simpleSchema, data);
2368
      return create(value.fields, value.name, value.active, value.apis, value.extra, value.state);
2369
    };
2370
    var modeSchema = objOfOnly([
2371
      strict$1('branchKey'),
2372
      strict$1('branches'),
2373
      strict$1('name'),
2374
      defaulted$1('active', {}),
2375
      defaulted$1('apis', {}),
2376
      defaulted$1('state', NoState),
2377
      defaulted$1('extra', {})
2378
    ]);
2379
    var createModes$1 = function (data) {
2380
      var value = asRawOrDie('Creating behaviour: ' + data.name, modeSchema, data);
2381
      return createModes(choose$1(value.branchKey, value.branches), value.name, value.active, value.apis, value.extra, value.state);
2382
    };
2383
    var revoke = constant(undefined);
2384
2385
    var rawSet = function (dom, key, value$$1) {
2386
      if (isString(value$$1) || isBoolean(value$$1) || isNumber(value$$1)) {
2387
        dom.setAttribute(key, value$$1 + '');
2388
      } else {
2389
        console.error('Invalid call to Attr.set. Key ', key, ':: Value ', value$$1, ':: Element ', dom);
2390
        throw new Error('Attribute value was not simple');
2391
      }
2392
    };
2393
    var set = function (element, key, value$$1) {
2394
      rawSet(element.dom(), key, value$$1);
2395
    };
2396
    var setAll = function (element, attrs) {
2397
      var dom = element.dom();
2398
      each(attrs, function (v, k) {
2399
        rawSet(dom, k, v);
2400
      });
2401
    };
2402
    var get$1 = function (element, key) {
2403
      var v = element.dom().getAttribute(key);
2404
      return v === null ? undefined : v;
2405
    };
2406
    var has$1 = function (element, key) {
2407
      var dom = element.dom();
2408
      return dom && dom.hasAttribute ? dom.hasAttribute(key) : false;
2409
    };
2410
    var remove$1 = function (element, key) {
2411
      element.dom().removeAttribute(key);
2412
    };
2413
2414
    var read$1 = function (element, attr) {
2415
      var value = get$1(element, attr);
2416
      return value === undefined || value === '' ? [] : value.split(' ');
2417
    };
2418
    var add = function (element, attr, id) {
2419
      var old = read$1(element, attr);
2420
      var nu = old.concat([id]);
2421
      set(element, attr, nu.join(' '));
2422
      return true;
2423
    };
2424
    var remove$2 = function (element, attr, id) {
2425
      var nu = filter(read$1(element, attr), function (v) {
2426
        return v !== id;
2427
      });
2428
      if (nu.length > 0)
2429
        set(element, attr, nu.join(' '));
2430
      else
2431
        remove$1(element, attr);
2432
      return false;
2433
    };
2434
2435
    var supports = function (element) {
2436
      return element.dom().classList !== undefined;
2437
    };
2438
    var get$2 = function (element) {
2439
      return read$1(element, 'class');
2440
    };
2441
    var add$1 = function (element, clazz) {
2442
      return add(element, 'class', clazz);
2443
    };
2444
    var remove$3 = function (element, clazz) {
2445
      return remove$2(element, 'class', clazz);
2446
    };
2447
    var toggle = function (element, clazz) {
2448
      if (contains(get$2(element), clazz)) {
2449
        return remove$3(element, clazz);
2450
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
2451
        return add$1(element, clazz);
2452
      }
2453
    };
2454
2455
    var add$2 = function (element, clazz) {
2456
      if (supports(element))
2457
        element.dom().classList.add(clazz);
2458
      else
2459
        add$1(element, clazz);
2460
    };
2461
    var cleanClass = function (element) {
2462
      var classList = supports(element) ? element.dom().classList : get$2(element);
2463
      if (classList.length === 0) {
2464
        remove$1(element, 'class');
2465
      }
2466
    };
2467
    var remove$4 = function (element, clazz) {
2468
      if (supports(element)) {
2469
        var classList = element.dom().classList;
2470
        classList.remove(clazz);
2471
      } else
2472
        remove$3(element, clazz);
2473
      cleanClass(element);
2474
    };
2475
    var toggle$1 = function (element, clazz) {
2476
      return supports(element) ? element.dom().classList.toggle(clazz) : toggle(element, clazz);
2477
    };
2478
    var has$2 = function (element, clazz) {
2479
      return supports(element) && element.dom().classList.contains(clazz);
2480
    };
2481
2482
    var swap = function (element, addCls, removeCls) {
2483
      remove$4(element, removeCls);
2484
      add$2(element, addCls);
2485
    };
2486
    var toAlpha = function (component, swapConfig, swapState) {
2487
      swap(component.element(), swapConfig.alpha(), swapConfig.omega());
2488
    };
2489
    var toOmega = function (component, swapConfig, swapState) {
2490
      swap(component.element(), swapConfig.omega(), swapConfig.alpha());
2491
    };
2492
    var clear = function (component, swapConfig, swapState) {
2493
      remove$4(component.element(), swapConfig.alpha());
2494
      remove$4(component.element(), swapConfig.omega());
2495
    };
2496
    var isAlpha = function (component, swapConfig, swapState) {
2497
      return has$2(component.element(), swapConfig.alpha());
2498
    };
2499
    var isOmega = function (component, swapConfig, swapState) {
2500
      return has$2(component.element(), swapConfig.omega());
2501
    };
2502
2503
    var SwapApis = /*#__PURE__*/Object.freeze({
2504
        toAlpha: toAlpha,
2505
        toOmega: toOmega,
2506
        isAlpha: isAlpha,
2507
        isOmega: isOmega,
2508
        clear: clear
2509
    });
2510
2511
    var SwapSchema = [
2512
      strict$1('alpha'),
2513
      strict$1('omega')
2514
    ];
2515
2516
    var Swapping = create$1({
2517
      fields: SwapSchema,
2518
      name: 'swapping',
2519
      apis: SwapApis
2520
    });
2521
2522
    var Cell = function (initial) {
2523
      var value = initial;
2524
      var get = function () {
2525
        return value;
2526
      };
2527
      var set = function (v) {
2528
        value = v;
2529
      };
2530
      var clone = function () {
2531
        return Cell(get());
2532
      };
2533
      return {
2534
        get: get,
2535
        set: set,
2536
        clone: clone
2537
      };
2538
    };
2539
2540
    function ClosestOrAncestor (is, ancestor, scope, a, isRoot) {
2541
      return is(scope, a) ? Option.some(scope) : isFunction(isRoot) && isRoot(scope) ? Option.none() : ancestor(scope, a, isRoot);
2542
    }
2543
2544
    var ancestor = function (scope, predicate, isRoot) {
2545
      var element = scope.dom();
2546
      var stop = isFunction(isRoot) ? isRoot : constant(false);
2547
      while (element.parentNode) {
2548
        element = element.parentNode;
2549
        var el = Element$$1.fromDom(element);
2550
        if (predicate(el))
2551
          return Option.some(el);
2552
        else if (stop(el))
2553
          break;
2554
      }
2555
      return Option.none();
2556
    };
2557
    var closest = function (scope, predicate, isRoot) {
2558
      var is = function (scope) {
2559
        return predicate(scope);
2560
      };
2561
      return ClosestOrAncestor(is, ancestor, scope, predicate, isRoot);
2562
    };
2563
    var descendant = function (scope, predicate) {
2564
      var descend = function (node) {
2565
        for (var i = 0; i < node.childNodes.length; i++) {
2566
          if (predicate(Element$$1.fromDom(node.childNodes[i])))
2567
            return Option.some(Element$$1.fromDom(node.childNodes[i]));
2568
          var res = descend(node.childNodes[i]);
2569
          if (res.isSome())
2570
            return res;
2571
        }
2572
        return Option.none();
2573
      };
2574
      return descend(scope.dom());
2575
    };
2576
2577
    var focus$2 = function (element) {
2578
      element.dom().focus();
2579
    };
2580
    var blur$$1 = function (element) {
2581
      element.dom().blur();
2582
    };
2583
    var hasFocus = function (element) {
2584
      var doc = owner(element).dom();
2585
      return element.dom() === doc.activeElement;
2586
    };
2587
    var active = function (_doc) {
2588
      var doc = _doc !== undefined ? _doc.dom() : document;
2589
      return Option.from(doc.activeElement).map(Element$$1.fromDom);
2590
    };
2591
    var search = function (element) {
2592
      return active(owner(element)).filter(function (e) {
2593
        return element.dom().contains(e.dom());
2594
      });
2595
    };
2596
2597
    var global = tinymce.util.Tools.resolve('tinymce.dom.DOMUtils');
2598
2599
    var global$1 = tinymce.util.Tools.resolve('tinymce.ThemeManager');
2600
2601
    var openLink = function (target) {
2602
      var link = document.createElement('a');
2603
      link.target = '_blank';
2604
      link.href = target.href;
2605
      link.rel = 'noreferrer noopener';
2606
      var nuEvt = document.createEvent('MouseEvents');
2607
      nuEvt.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
2608
      document.body.appendChild(link);
2609
      link.dispatchEvent(nuEvt);
2610
      document.body.removeChild(link);
2611
    };
2612
    var TinyCodeDupe = { openLink: openLink };
2613
2614
    var isSkinDisabled = function (editor) {
2615
      return editor.settings.skin === false;
2616
    };
2617
    var readOnlyOnInit = function (editor) {
2618
      return false;
2619
    };
2620
2621
    var formatChanged = 'formatChanged';
2622
    var orientationChanged = 'orientationChanged';
2623
    var dropupDismissed = 'dropupDismissed';
2624
    var TinyChannels = {
2625
      formatChanged: constant(formatChanged),
2626
      orientationChanged: constant(orientationChanged),
2627
      dropupDismissed: constant(dropupDismissed)
2628
    };
2629
2630
    var fromHtml$1 = function (html, scope) {
2631
      var doc = scope || document;
2632
      var div = doc.createElement('div');
2633
      div.innerHTML = html;
2634
      return children(Element$$1.fromDom(div));
2635
    };
2636
2637
    var get$3 = function (element) {
2638
      return element.dom().innerHTML;
2639
    };
2640
    var set$1 = function (element, content) {
2641
      var owner$$1 = owner(element);
2642
      var docDom = owner$$1.dom();
2643
      var fragment = Element$$1.fromDom(docDom.createDocumentFragment());
2644
      var contentElements = fromHtml$1(content, docDom);
2645
      append$1(fragment, contentElements);
2646
      empty(element);
2647
      append(element, fragment);
2648
    };
2649
    var getOuter = function (element) {
2650
      var container = Element$$1.fromTag('div');
2651
      var clone = Element$$1.fromDom(element.dom().cloneNode(true));
2652
      append(container, clone);
2653
      return get$3(container);
2654
    };
2655
2656
    var clone$1 = function (original, deep) {
2657
      return Element$$1.fromDom(original.dom().cloneNode(deep));
2658
    };
2659
    var shallow$1 = function (original) {
2660
      return clone$1(original, false);
2661
    };
2662
2663
    var getHtml = function (element) {
2664
      var clone = shallow$1(element);
2665
      return getOuter(clone);
2666
    };
2667
2668
    var element = function (elem) {
2669
      return getHtml(elem);
2670
    };
2671
2672
    var chooseChannels = function (channels, message) {
2673
      return message.universal() ? channels : filter(channels, function (ch) {
2674
        return contains(message.channels(), ch);
2675
      });
2676
    };
2677
    var events = function (receiveConfig) {
2678
      return derive([run(receive(), function (component, message) {
2679
          var channelMap = receiveConfig.channels();
2680
          var channels = keys(channelMap);
2681
          var targetChannels = chooseChannels(channels, message);
2682
          each$1(targetChannels, function (ch) {
2683
            var channelInfo = channelMap[ch]();
2684
            var channelSchema = channelInfo.schema();
2685
            var data = asStructOrDie('channel[' + ch + '] data\nReceiver: ' + element(component.element()), channelSchema, message.data());
2686
            channelInfo.onReceive()(component, data);
2687
          });
2688
        })]);
2689
    };
2690
2691
    var ActiveReceiving = /*#__PURE__*/Object.freeze({
2692
        events: events
2693
    });
2694
2695
    var cat = function (arr) {
2696
      var r = [];
2697
      var push = function (x) {
2698
        r.push(x);
2699
      };
2700
      for (var i = 0; i < arr.length; i++) {
2701
        arr[i].each(push);
2702
      }
2703
      return r;
2704
    };
2705
    var findMap = function (arr, f) {
2706
      for (var i = 0; i < arr.length; i++) {
2707
        var r = f(arr[i], i);
2708
        if (r.isSome()) {
2709
          return r;
2710
        }
2711
      }
2712
      return Option.none();
2713
    };
2714
2715
    var unknown$3 = 'unknown';
2716
    var eventsMonitored = [];
2717
    var path$1 = [
2718
      'alloy/data/Fields',
2719
      'alloy/debugging/Debugging'
2720
    ];
2721
    var getTrace = function () {
2722
      var err = new Error();
2723
      if (err.stack !== undefined) {
2724
        var lines = err.stack.split('\n');
2725
        return find$2(lines, function (line) {
2726
          return line.indexOf('alloy') > 0 && !exists(path$1, function (p) {
2727
            return line.indexOf(p) > -1;
2728
          });
2729
        }).getOr(unknown$3);
2730
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
2731
        return unknown$3;
2732
      }
2733
    };
2734
    var ignoreEvent = {
2735
      logEventCut: noop,
2736
      logEventStopped: noop,
2737
      logNoParent: noop,
2738
      logEventNoHandlers: noop,
2739
      logEventResponse: noop,
2740
      write: noop
2741
    };
2742
    var monitorEvent = function (eventName, initialTarget, f) {
2743
      var logger = eventsMonitored === '*' || contains(eventsMonitored, eventName) ? function () {
2744
        var sequence = [];
2745
        return {
2746
          logEventCut: function (name$$1, target, purpose) {
2747
            sequence.push({
2748
              outcome: 'cut',
2749
              target: target,
2750
              purpose: purpose
2751
            });
2752
          },
2753
          logEventStopped: function (name$$1, target, purpose) {
2754
            sequence.push({
2755
              outcome: 'stopped',
2756
              target: target,
2757
              purpose: purpose
2758
            });
2759
          },
2760
          logNoParent: function (name$$1, target, purpose) {
2761
            sequence.push({
2762
              outcome: 'no-parent',
2763
              target: target,
2764
              purpose: purpose
2765
            });
2766
          },
2767
          logEventNoHandlers: function (name$$1, target) {
2768
            sequence.push({
2769
              outcome: 'no-handlers-left',
2770
              target: target
2771
            });
2772
          },
2773
          logEventResponse: function (name$$1, target, purpose) {
2774
            sequence.push({
2775
              outcome: 'response',
2776
              purpose: purpose,
2777
              target: target
2778
            });
2779
          },
2780
          write: function () {
2781
            if (contains([
2782
                'mousemove',
2783
                'mouseover',
2784
                'mouseout',
2785
                systemInit()
2786
              ], eventName)) {
2787
              return;
2788
            }
2789
            console.log(eventName, {
2790
              event: eventName,
2791
              target: initialTarget.dom(),
2792
              sequence: map$1(sequence, function (s) {
2793
                if (!contains([
2794
                    'cut',
2795
                    'stopped',
2796
                    'response'
2797
                  ], s.outcome)) {
2798
                  return s.outcome;
2799
                } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
2800
                  return '{' + s.purpose + '} ' + s.outcome + ' at (' + element(s.target) + ')';
2801
                }
2802
              })
2803
            });
2804
          }
2805
        };
2806
      }() : ignoreEvent;
2807
      var output = f(logger);
2808
      logger.write();
2809
      return output;
2810
    };
2811
2812
    var menuFields = constant([
2813
      strict$1('menu'),
2814
      strict$1('selectedMenu')
2815
    ]);
2816
    var itemFields = constant([
2817
      strict$1('item'),
2818
      strict$1('selectedItem')
2819
    ]);
2820
    var schema = constant(objOfOnly(itemFields().concat(menuFields())));
2821
    var itemSchema = constant(objOfOnly(itemFields()));
2822
2823
    var _initSize = strictObjOf('initSize', [
2824
      strict$1('numColumns'),
2825
      strict$1('numRows')
2826
    ]);
2827
    var itemMarkers = function () {
2828
      return strictOf('markers', itemSchema());
2829
    };
2830
    var tieredMenuMarkers = function () {
2831
      return strictObjOf('markers', [strict$1('backgroundMenu')].concat(menuFields()).concat(itemFields()));
2832
    };
2833
    var markers = function (required) {
2834
      return strictObjOf('markers', map$1(required, strict$1));
2835
    };
2836
    var onPresenceHandler = function (label, fieldName, presence) {
2837
      var trace = getTrace();
2838
      return field(fieldName, fieldName, presence, valueOf(function (f) {
2839
        return Result.value(function () {
2840
          var args = [];
2841
          for (var _i = 0; _i < arguments.length; _i++) {
2842
            args[_i] = arguments[_i];
2843
          }
2844
          return f.apply(undefined, args);
2845
        });
2846
      }));
2847
    };
2848
    var onHandler = function (fieldName) {
2849
      return onPresenceHandler('onHandler', fieldName, defaulted(noop));
2850
    };
2851
    var onKeyboardHandler = function (fieldName) {
2852
      return onPresenceHandler('onKeyboardHandler', fieldName, defaulted(Option.none));
2853
    };
2854
    var onStrictHandler = function (fieldName) {
2855
      return onPresenceHandler('onHandler', fieldName, strict());
2856
    };
2857
    var onStrictKeyboardHandler = function (fieldName) {
2858
      return onPresenceHandler('onKeyboardHandler', fieldName, strict());
2859
    };
2860
    var output$1 = function (name, value) {
2861
      return state$1(name, constant(value));
2862
    };
2863
    var snapshot$1 = function (name) {
2864
      return state$1(name, identity);
2865
    };
2866
    var initSize = constant(_initSize);
2867
2868
    var ReceivingSchema = [strictOf('channels', setOf(Result.value, objOfOnly([
2869
        onStrictHandler('onReceive'),
2870
        defaulted$1('schema', anyValue$1())
2871
      ])))];
2872
2873
    var Receiving = create$1({
2874
      fields: ReceivingSchema,
2875
      name: 'receiving',
2876
      active: ActiveReceiving
2877
    });
2878
2879
    var updateAriaState = function (component, toggleConfig) {
2880
      var pressed = isOn(component, toggleConfig);
2881
      var ariaInfo = toggleConfig.aria();
2882
      ariaInfo.update()(component, ariaInfo, pressed);
2883
    };
2884
    var toggle$2 = function (component, toggleConfig, toggleState) {
2885
      toggle$1(component.element(), toggleConfig.toggleClass());
2886
      updateAriaState(component, toggleConfig);
2887
    };
2888
    var on = function (component, toggleConfig, toggleState) {
2889
      add$2(component.element(), toggleConfig.toggleClass());
2890
      updateAriaState(component, toggleConfig);
2891
    };
2892
    var off = function (component, toggleConfig, toggleState) {
2893
      remove$4(component.element(), toggleConfig.toggleClass());
2894
      updateAriaState(component, toggleConfig);
2895
    };
2896
    var isOn = function (component, toggleConfig) {
2897
      return has$2(component.element(), toggleConfig.toggleClass());
2898
    };
2899
    var onLoad = function (component, toggleConfig, toggleState) {
2900
      var api = toggleConfig.selected() ? on : off;
2901
      api(component, toggleConfig, toggleState);
2902
    };
2903
2904
    var ToggleApis = /*#__PURE__*/Object.freeze({
2905
        onLoad: onLoad,
2906
        toggle: toggle$2,
2907
        isOn: isOn,
2908
        on: on,
2909
        off: off
2910
    });
2911
2912
    var exhibit = function (base, toggleConfig, toggleState) {
2913
      return nu$6({});
2914
    };
2915
    var events$1 = function (toggleConfig, toggleState) {
2916
      var execute = executeEvent(toggleConfig, toggleState, toggle$2);
2917
      var load = loadEvent(toggleConfig, toggleState, onLoad);
2918
      return derive(flatten([
2919
        toggleConfig.toggleOnExecute() ? [execute] : [],
2920
        [load]
2921
      ]));
2922
    };
2923
2924
    var ActiveToggle = /*#__PURE__*/Object.freeze({
2925
        exhibit: exhibit,
2926
        events: events$1
2927
    });
2928
2929
    var updatePressed = function (component, ariaInfo, status) {
2930
      set(component.element(), 'aria-pressed', status);
2931
      if (ariaInfo.syncWithExpanded()) {
2932
        updateExpanded(component, ariaInfo, status);
2933
      }
2934
    };
2935
    var updateSelected = function (component, ariaInfo, status) {
2936
      set(component.element(), 'aria-selected', status);
2937
    };
2938
    var updateChecked = function (component, ariaInfo, status) {
2939
      set(component.element(), 'aria-checked', status);
2940
    };
2941
    var updateExpanded = function (component, ariaInfo, status) {
2942
      set(component.element(), 'aria-expanded', status);
2943
    };
2944
2945
    var ToggleSchema = [
2946
      defaulted$1('selected', false),
2947
      strict$1('toggleClass'),
2948
      defaulted$1('toggleOnExecute', true),
2949
      defaultedOf('aria', { mode: 'none' }, choose$1('mode', {
2950
        pressed: [
2951
          defaulted$1('syncWithExpanded', false),
2952
          output$1('update', updatePressed)
2953
        ],
2954
        checked: [output$1('update', updateChecked)],
2955
        expanded: [output$1('update', updateExpanded)],
2956
        selected: [output$1('update', updateSelected)],
2957
        none: [output$1('update', noop)]
2958
      }))
2959
    ];
2960
2961
    var Toggling = create$1({
2962
      fields: ToggleSchema,
2963
      name: 'toggling',
2964
      active: ActiveToggle,
2965
      apis: ToggleApis
2966
    });
2967
2968
    var format = function (command, update) {
2969
      return Receiving.config({
2970
        channels: wrap$2(TinyChannels.formatChanged(), {
2971
          onReceive: function (button, data) {
2972
            if (data.command === command) {
2973
              update(button, data.state);
2974
            }
2975
          }
2976
        })
2977
      });
2978
    };
2979
    var orientation = function (onReceive) {
2980
      return Receiving.config({ channels: wrap$2(TinyChannels.orientationChanged(), { onReceive: onReceive }) });
2981
    };
2982
    var receive$1 = function (channel, onReceive) {
2983
      return {
2984
        key: channel,
2985
        value: { onReceive: onReceive }
2986
      };
2987
    };
2988
    var Receivers = {
2989
      format: format,
2990
      orientation: orientation,
2991
      receive: receive$1
2992
    };
2993
2994
    var prefix = 'tinymce-mobile';
2995
    var resolve$1 = function (p) {
2996
      return prefix + '-' + p;
2997
    };
2998
    var Styles = {
2999
      resolve: resolve$1,
3000
      prefix: constant(prefix)
3001
    };
3002
3003
    var events$2 = function (optAction) {
3004
      var executeHandler = function (action) {
3005
        return run(execute(), function (component, simulatedEvent) {
3006
          action(component);
3007
          simulatedEvent.stop();
3008
        });
3009
      };
3010
      var onClick = function (component, simulatedEvent) {
3011
        simulatedEvent.stop();
3012
        emitExecute(component);
3013
      };
3014
      var onMousedown = function (component, simulatedEvent) {
3015
        simulatedEvent.cut();
3016
      };
3017
      var pointerEvents = PlatformDetection$1.detect().deviceType.isTouch() ? [run(tap(), onClick)] : [
3018
        run(click(), onClick),
3019
        run(mousedown(), onMousedown)
3020
      ];
3021
      return derive(flatten([
3022
        optAction.map(executeHandler).toArray(),
3023
        pointerEvents
3024
      ]));
3025
    };
3026
3027
    var focus$3 = function (component, focusConfig) {
3028
      if (!focusConfig.ignore()) {
3029
        focus$2(component.element());
3030
        focusConfig.onFocus()(component);
3031
      }
3032
    };
3033
    var blur$1 = function (component, focusConfig) {
3034
      if (!focusConfig.ignore()) {
3035
        blur$$1(component.element());
3036
      }
3037
    };
3038
    var isFocused = function (component) {
3039
      return hasFocus(component.element());
3040
    };
3041
3042
    var FocusApis = /*#__PURE__*/Object.freeze({
3043
        focus: focus$3,
3044
        blur: blur$1,
3045
        isFocused: isFocused
3046
    });
3047
3048
    var exhibit$1 = function (base, focusConfig) {
3049
      if (focusConfig.ignore()) {
3050
        return nu$6({});
3051
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
3052
        return nu$6({ attributes: { tabindex: '-1' } });
3053
      }
3054
    };
3055
    var events$3 = function (focusConfig) {
3056
      return derive([run(focus$1(), function (component, simulatedEvent) {
3057
          focus$3(component, focusConfig);
3058
          simulatedEvent.stop();
3059
        })]);
3060
    };
3061
3062
    var ActiveFocus = /*#__PURE__*/Object.freeze({
3063
        exhibit: exhibit$1,
3064
        events: events$3
3065
    });
3066
3067
    var FocusSchema = [
3068
      onHandler('onFocus'),
3069
      defaulted$1('ignore', false)
3070
    ];
3071
3072
    var Focusing = create$1({
3073
      fields: FocusSchema,
3074
      name: 'focusing',
3075
      active: ActiveFocus,
3076
      apis: FocusApis
3077
    });
3078
3079
    var isSupported = function (dom) {
3080
      return dom.style !== undefined;
3081
    };
3082
3083
    var internalSet = function (dom, property, value$$1) {
3084
      if (!isString(value$$1)) {
3085
        console.error('Invalid call to CSS.set. Property ', property, ':: Value ', value$$1, ':: Element ', dom);
3086
        throw new Error('CSS value must be a string: ' + value$$1);
3087
      }
3088
      if (isSupported(dom))
3089
        dom.style.setProperty(property, value$$1);
3090
    };
3091
    var internalRemove = function (dom, property) {
3092
      if (isSupported(dom))
3093
        dom.style.removeProperty(property);
3094
    };
3095
    var set$2 = function (element, property, value$$1) {
3096
      var dom = element.dom();
3097
      internalSet(dom, property, value$$1);
3098
    };
3099
    var setAll$1 = function (element, css) {
3100
      var dom = element.dom();
3101
      each(css, function (v, k) {
3102
        internalSet(dom, k, v);
3103
      });
3104
    };
3105
    var get$4 = function (element, property) {
3106
      var dom = element.dom();
3107
      var styles = window.getComputedStyle(dom);
3108
      var r = styles.getPropertyValue(property);
3109
      var v = r === '' && !inBody(element) ? getUnsafeProperty(dom, property) : r;
3110
      return v === null ? undefined : v;
3111
    };
3112
    var getUnsafeProperty = function (dom, property) {
3113
      return isSupported(dom) ? dom.style.getPropertyValue(property) : '';
3114
    };
3115
    var getRaw = function (element, property) {
3116
      var dom = element.dom();
3117
      var raw = getUnsafeProperty(dom, property);
3118
      return Option.from(raw).filter(function (r) {
3119
        return r.length > 0;
3120
      });
3121
    };
3122
    var remove$5 = function (element, property) {
3123
      var dom = element.dom();
3124
      internalRemove(dom, property);
3125
      if (has$1(element, 'style') && trim(get$1(element, 'style')) === '') {
3126
        remove$1(element, 'style');
3127
      }
3128
    };
3129
    var reflow = function (e) {
3130
      return e.dom().offsetWidth;
3131
    };
3132
3133
    function Dimension (name, getOffset) {
3134
      var set = function (element, h) {
3135
        if (!isNumber(h) && !h.match(/^[0-9]+$/))
3136
          throw name + '.set accepts only positive integer values. Value was ' + h;
3137
        var dom = element.dom();
3138
        if (isSupported(dom))
3139
          dom.style[name] = h + 'px';
3140
      };
3141
      var get = function (element) {
3142
        var r = getOffset(element);
3143
        if (r <= 0 || r === null) {
3144
          var css = get$4(element, name);
3145
          return parseFloat(css) || 0;
3146
        }
3147
        return r;
3148
      };
3149
      var getOuter = get;
3150
      var aggregate = function (element, properties) {
3151
        return foldl(properties, function (acc, property) {
3152
          var val = get$4(element, property);
3153
          var value = val === undefined ? 0 : parseInt(val, 10);
3154
          return isNaN(value) ? acc : acc + value;
3155
        }, 0);
3156
      };
3157
      var max = function (element, value, properties) {
3158
        var cumulativeInclusions = aggregate(element, properties);
3159
        var absoluteMax = value > cumulativeInclusions ? value - cumulativeInclusions : 0;
3160
        return absoluteMax;
3161
      };
3162
      return {
3163
        set: set,
3164
        get: get,
3165
        getOuter: getOuter,
3166
        aggregate: aggregate,
3167
        max: max
3168
      };
3169
    }
3170
3171
    var api = Dimension('height', function (element) {
3172
      var dom = element.dom();
3173
      return inBody(element) ? dom.getBoundingClientRect().height : dom.offsetHeight;
3174
    });
3175
    var get$5 = function (element) {
3176
      return api.get(element);
3177
    };
3178
3179
    var ancestors = function (scope, predicate, isRoot) {
3180
      return filter(parents(scope, isRoot), predicate);
3181
    };
3182
    var siblings$1 = function (scope, predicate) {
3183
      return filter(siblings(scope), predicate);
3184
    };
3185
3186
    var all$3 = function (selector) {
3187
      return all(selector);
3188
    };
3189
    var ancestors$1 = function (scope, selector, isRoot) {
3190
      return ancestors(scope, function (e) {
3191
        return is(e, selector);
3192
      }, isRoot);
3193
    };
3194
    var siblings$2 = function (scope, selector) {
3195
      return siblings$1(scope, function (e) {
3196
        return is(e, selector);
3197
      });
3198
    };
3199
    var descendants$1 = function (scope, selector) {
3200
      return all(selector, scope);
3201
    };
3202
3203
    var first$2 = function (selector) {
3204
      return one(selector);
3205
    };
3206
    var ancestor$2 = function (scope, selector, isRoot) {
3207
      return ancestor(scope, function (e) {
3208
        return is(e, selector);
3209
      }, isRoot);
3210
    };
3211
    var descendant$2 = function (scope, selector) {
3212
      return one(selector, scope);
3213
    };
3214
    var closest$2 = function (scope, selector, isRoot) {
3215
      return ClosestOrAncestor(is, ancestor$2, scope, selector, isRoot);
3216
    };
3217
3218
    var BACKSPACE = function () {
3219
      return [8];
3220
    };
3221
    var TAB = function () {
3222
      return [9];
3223
    };
3224
    var ENTER = function () {
3225
      return [13];
3226
    };
3227
    var ESCAPE = function () {
3228
      return [27];
3229
    };
3230
    var SPACE = function () {
3231
      return [32];
3232
    };
3233
    var LEFT = function () {
3234
      return [37];
3235
    };
3236
    var UP = function () {
3237
      return [38];
3238
    };
3239
    var RIGHT = function () {
3240
      return [39];
3241
    };
3242
    var DOWN = function () {
3243
      return [40];
3244
    };
3245
3246
    var cyclePrev = function (values, index, predicate) {
3247
      var before = reverse(values.slice(0, index));
3248
      var after = reverse(values.slice(index + 1));
3249
      return find$2(before.concat(after), predicate);
3250
    };
3251
    var tryPrev = function (values, index, predicate) {
3252
      var before = reverse(values.slice(0, index));
3253
      return find$2(before, predicate);
3254
    };
3255
    var cycleNext = function (values, index, predicate) {
3256
      var before = values.slice(0, index);
3257
      var after = values.slice(index + 1);
3258
      return find$2(after.concat(before), predicate);
3259
    };
3260
    var tryNext = function (values, index, predicate) {
3261
      var after = values.slice(index + 1);
3262
      return find$2(after, predicate);
3263
    };
3264
3265
    var inSet = function (keys) {
3266
      return function (event) {
3267
        var raw = event.raw();
3268
        return contains(keys, raw.which);
3269
      };
3270
    };
3271
    var and = function (preds) {
3272
      return function (event) {
3273
        return forall(preds, function (pred) {
3274
          return pred(event);
3275
        });
3276
      };
3277
    };
3278
    var isShift = function (event) {
3279
      var raw = event.raw();
3280
      return raw.shiftKey === true;
3281
    };
3282
    var isControl = function (event) {
3283
      var raw = event.raw();
3284
      return raw.ctrlKey === true;
3285
    };
3286
    var isNotShift = not(isShift);
3287
3288
    var rule = function (matches, action) {
3289
      return {
3290
        matches: matches,
3291
        classification: action
3292
      };
3293
    };
3294
    var choose$2 = function (transitions, event) {
3295
      var transition = find$2(transitions, function (t) {
3296
        return t.matches(event);
3297
      });
3298
      return transition.map(function (t) {
3299
        return t.classification;
3300
      });
3301
    };
3302
3303
    var cycleBy = function (value, delta, min, max) {
3304
      var r = value + delta;
3305
      if (r > max) {
3306
        return min;
3307
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
3308
        return r < min ? max : r;
3309
      }
3310
    };
3311
    var cap = function (value, min, max) {
3312
      if (value <= min) {
3313
        return min;
3314
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
3315
        return value >= max ? max : value;
3316
      }
3317
    };
3318
3319
    var dehighlightAll = function (component, hConfig, hState) {
3320
      var highlighted = descendants$1(component.element(), '.' + hConfig.highlightClass());
3321
      each$1(highlighted, function (h) {
3322
        remove$4(h, hConfig.highlightClass());
3323
        component.getSystem().getByDom(h).each(function (target) {
3324
          hConfig.onDehighlight()(component, target);
3325
        });
3326
      });
3327
    };
3328
    var dehighlight = function (component, hConfig, hState, target) {
3329
      var wasHighlighted = isHighlighted(component, hConfig, hState, target);
3330
      remove$4(target.element(), hConfig.highlightClass());
3331
      if (wasHighlighted) {
3332
        hConfig.onDehighlight()(component, target);
3333
      }
3334
    };
3335
    var highlight = function (component, hConfig, hState, target) {
3336
      var wasHighlighted = isHighlighted(component, hConfig, hState, target);
3337
      dehighlightAll(component, hConfig, hState);
3338
      add$2(target.element(), hConfig.highlightClass());
3339
      if (!wasHighlighted) {
3340
        hConfig.onHighlight()(component, target);
3341
      }
3342
    };
3343
    var highlightFirst = function (component, hConfig, hState) {
3344
      getFirst(component, hConfig, hState).each(function (firstComp) {
3345
        highlight(component, hConfig, hState, firstComp);
3346
      });
3347
    };
3348
    var highlightLast = function (component, hConfig, hState) {
3349
      getLast(component, hConfig, hState).each(function (lastComp) {
3350
        highlight(component, hConfig, hState, lastComp);
3351
      });
3352
    };
3353
    var highlightAt = function (component, hConfig, hState, index) {
3354
      getByIndex(component, hConfig, hState, index).fold(function (err) {
3355
        throw new Error(err);
3356
      }, function (firstComp) {
3357
        highlight(component, hConfig, hState, firstComp);
3358
      });
3359
    };
3360
    var highlightBy = function (component, hConfig, hState, predicate) {
3361
      var items = descendants$1(component.element(), '.' + hConfig.itemClass());
3362
      var itemComps = cat(map$1(items, function (i) {
3363
        return component.getSystem().getByDom(i).toOption();
3364
      }));
3365
      var targetComp = find$2(itemComps, predicate);
3366
      targetComp.each(function (c) {
3367
        highlight(component, hConfig, hState, c);
3368
      });
3369
    };
3370
    var isHighlighted = function (component, hConfig, hState, queryTarget) {
3371
      return has$2(queryTarget.element(), hConfig.highlightClass());
3372
    };
3373
    var getHighlighted = function (component, hConfig, hState) {
3374
      return descendant$2(component.element(), '.' + hConfig.highlightClass()).bind(function (e) {
3375
        return component.getSystem().getByDom(e).toOption();
3376
      });
3377
    };
3378
    var getByIndex = function (component, hConfig, hState, index) {
3379
      var items = descendants$1(component.element(), '.' + hConfig.itemClass());
3380
      return Option.from(items[index]).fold(function () {
3381
        return Result.error('No element found with index ' + index);
3382
      }, component.getSystem().getByDom);
3383
    };
3384
    var getFirst = function (component, hConfig, hState) {
3385
      return descendant$2(component.element(), '.' + hConfig.itemClass()).bind(function (e) {
3386
        return component.getSystem().getByDom(e).toOption();
3387
      });
3388
    };
3389
    var getLast = function (component, hConfig, hState) {
3390
      var items = descendants$1(component.element(), '.' + hConfig.itemClass());
3391
      var last$$1 = items.length > 0 ? Option.some(items[items.length - 1]) : Option.none();
3392
      return last$$1.bind(function (c) {
3393
        return component.getSystem().getByDom(c).toOption();
3394
      });
3395
    };
3396
    var getDelta = function (component, hConfig, hState, delta) {
3397
      var items = descendants$1(component.element(), '.' + hConfig.itemClass());
3398
      var current = findIndex(items, function (item) {
3399
        return has$2(item, hConfig.highlightClass());
3400
      });
3401
      return current.bind(function (selected) {
3402
        var dest = cycleBy(selected, delta, 0, items.length - 1);
3403
        return component.getSystem().getByDom(items[dest]).toOption();
3404
      });
3405
    };
3406
    var getPrevious = function (component, hConfig, hState) {
3407
      return getDelta(component, hConfig, hState, -1);
3408
    };
3409
    var getNext = function (component, hConfig, hState) {
3410
      return getDelta(component, hConfig, hState, +1);
3411
    };
3412
3413
    var HighlightApis = /*#__PURE__*/Object.freeze({
3414
        dehighlightAll: dehighlightAll,
3415
        dehighlight: dehighlight,
3416
        highlight: highlight,
3417
        highlightFirst: highlightFirst,
3418
        highlightLast: highlightLast,
3419
        highlightAt: highlightAt,
3420
        highlightBy: highlightBy,
3421
        isHighlighted: isHighlighted,
3422
        getHighlighted: getHighlighted,
3423
        getFirst: getFirst,
3424
        getLast: getLast,
3425
        getPrevious: getPrevious,
3426
        getNext: getNext
3427
    });
3428
3429
    var HighlightSchema = [
3430
      strict$1('highlightClass'),
3431
      strict$1('itemClass'),
3432
      onHandler('onHighlight'),
3433
      onHandler('onDehighlight')
3434
    ];
3435
3436
    var Highlighting = create$1({
3437
      fields: HighlightSchema,
3438
      name: 'highlighting',
3439
      apis: HighlightApis
3440
    });
3441
3442
    var dom = function () {
3443
      var get = function (component) {
3444
        return search(component.element());
3445
      };
3446
      var set = function (component, focusee) {
3447
        component.getSystem().triggerFocus(focusee, component.element());
3448
      };
3449
      return {
3450
        get: get,
3451
        set: set
3452
      };
3453
    };
3454
    var highlights = function () {
3455
      var get = function (component) {
3456
        return Highlighting.getHighlighted(component).map(function (item) {
3457
          return item.element();
3458
        });
3459
      };
3460
      var set = function (component, element) {
3461
        component.getSystem().getByDom(element).fold(noop, function (item) {
3462
          Highlighting.highlight(component, item);
3463
        });
3464
      };
3465
      return {
3466
        get: get,
3467
        set: set
3468
      };
3469
    };
3470
3471
    var typical = function (infoSchema, stateInit, getRules, getEvents, getApis, optFocusIn) {
3472
      var schema = function () {
3473
        return infoSchema.concat([
3474
          defaulted$1('focusManager', dom()),
3475
          output$1('handler', me),
3476
          output$1('state', stateInit)
3477
        ]);
3478
      };
3479
      var processKey = function (component, simulatedEvent, keyingConfig, keyingState) {
3480
        var rules = getRules(component, simulatedEvent, keyingConfig, keyingState);
3481
        return choose$2(rules, simulatedEvent.event()).bind(function (rule$$1) {
3482
          return rule$$1(component, simulatedEvent, keyingConfig, keyingState);
3483
        });
3484
      };
3485
      var toEvents = function (keyingConfig, keyingState) {
3486
        var otherEvents = getEvents(keyingConfig, keyingState);
3487
        var keyEvents = derive(optFocusIn.map(function (focusIn) {
3488
          return run(focus$1(), function (component, simulatedEvent) {
3489
            focusIn(component, keyingConfig, keyingState, simulatedEvent);
3490
            simulatedEvent.stop();
3491
          });
3492
        }).toArray().concat([run(keydown(), function (component, simulatedEvent) {
3493
            processKey(component, simulatedEvent, keyingConfig, keyingState).each(function (_) {
3494
              simulatedEvent.stop();
3495
            });
3496
          })]));
3497
        return deepMerge(otherEvents, keyEvents);
3498
      };
3499
      var me = {
3500
        schema: schema,
3501
        processKey: processKey,
3502
        toEvents: toEvents,
3503
        toApis: getApis
3504
      };
3505
      return me;
3506
    };
3507
3508
    var create$2 = function (cyclicField) {
3509
      var schema = [
3510
        option('onEscape'),
3511
        option('onEnter'),
3512
        defaulted$1('selector', '[data-alloy-tabstop="true"]'),
3513
        defaulted$1('firstTabstop', 0),
3514
        defaulted$1('useTabstopAt', constant(true)),
3515
        option('visibilitySelector')
3516
      ].concat([cyclicField]);
3517
      var isVisible = function (tabbingConfig, element) {
3518
        var target = tabbingConfig.visibilitySelector().bind(function (sel) {
3519
          return closest$2(element, sel);
3520
        }).getOr(element);
3521
        return get$5(target) > 0;
3522
      };
3523
      var findInitial = function (component, tabbingConfig) {
3524
        var tabstops = descendants$1(component.element(), tabbingConfig.selector());
3525
        var visibles = filter(tabstops, function (elem) {
3526
          return isVisible(tabbingConfig, elem);
3527
        });
3528
        return Option.from(visibles[tabbingConfig.firstTabstop()]);
3529
      };
3530
      var findCurrent = function (component, tabbingConfig) {
3531
        return tabbingConfig.focusManager().get(component).bind(function (elem) {
3532
          return closest$2(elem, tabbingConfig.selector());
3533
        });
3534
      };
3535
      var isTabstop = function (tabbingConfig, element) {
3536
        return isVisible(tabbingConfig, element) && tabbingConfig.useTabstopAt()(element);
3537
      };
3538
      var focusIn = function (component, tabbingConfig) {
3539
        findInitial(component, tabbingConfig).each(function (target) {
3540
          tabbingConfig.focusManager().set(component, target);
3541
        });
3542
      };
3543
      var goFromTabstop = function (component, tabstops, stopIndex, tabbingConfig, cycle) {
3544
        return cycle(tabstops, stopIndex, function (elem) {
3545
          return isTabstop(tabbingConfig, elem);
3546
        }).fold(function () {
3547
          return tabbingConfig.cyclic() ? Option.some(true) : Option.none();
3548
        }, function (target) {
3549
          tabbingConfig.focusManager().set(component, target);
3550
          return Option.some(true);
3551
        });
3552
      };
3553
      var go = function (component, simulatedEvent, tabbingConfig, cycle) {
3554
        var tabstops = descendants$1(component.element(), tabbingConfig.selector());
3555
        return findCurrent(component, tabbingConfig).bind(function (tabstop) {
3556
          var optStopIndex = findIndex(tabstops, curry(eq, tabstop));
3557
          return optStopIndex.bind(function (stopIndex) {
3558
            return goFromTabstop(component, tabstops, stopIndex, tabbingConfig, cycle);
3559
          });
3560
        });
3561
      };
3562
      var goBackwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
3563
        var navigate = tabbingConfig.cyclic() ? cyclePrev : tryPrev;
3564
        return go(component, simulatedEvent, tabbingConfig, navigate);
3565
      };
3566
      var goForwards = function (component, simulatedEvent, tabbingConfig, tabbingState) {
3567
        var navigate = tabbingConfig.cyclic() ? cycleNext : tryNext;
3568
        return go(component, simulatedEvent, tabbingConfig, navigate);
3569
      };
3570
      var execute = function (component, simulatedEvent, tabbingConfig, tabbingState) {
3571
        return tabbingConfig.onEnter().bind(function (f) {
3572
          return f(component, simulatedEvent);
3573
        });
3574
      };
3575
      var exit = function (component, simulatedEvent, tabbingConfig, tabbingState) {
3576
        return tabbingConfig.onEscape().bind(function (f) {
3577
          return f(component, simulatedEvent);
3578
        });
3579
      };
3580
      var getRules = constant([
3581
        rule(and([
3582
          isShift,
3583
          inSet(TAB())
3584
        ]), goBackwards),
3585
        rule(inSet(TAB()), goForwards),
3586
        rule(inSet(ESCAPE()), exit),
3587
        rule(and([
3588
          isNotShift,
3589
          inSet(ENTER())
3590
        ]), execute)
3591
      ]);
3592
      var getEvents = constant({});
3593
      var getApis = constant({});
3594
      return typical(schema, NoState.init, getRules, getEvents, getApis, Option.some(focusIn));
3595
    };
3596
3597
    var AcyclicType = create$2(state$1('cyclic', constant(false)));
3598
3599
    var CyclicType = create$2(state$1('cyclic', constant(true)));
3600
3601
    var inside = function (target) {
3602
      return name(target) === 'input' && get$1(target, 'type') !== 'radio' || name(target) === 'textarea';
3603
    };
3604
3605
    var doDefaultExecute = function (component, simulatedEvent, focused) {
3606
      dispatch(component, focused, execute());
3607
      return Option.some(true);
3608
    };
3609
    var defaultExecute = function (component, simulatedEvent, focused) {
3610
      return inside(focused) && inSet(SPACE())(simulatedEvent.event()) ? Option.none() : doDefaultExecute(component, simulatedEvent, focused);
3611
    };
3612
3613
    var schema$1 = [
3614
      defaulted$1('execute', defaultExecute),
3615
      defaulted$1('useSpace', false),
3616
      defaulted$1('useEnter', true),
3617
      defaulted$1('useControlEnter', false),
3618
      defaulted$1('useDown', false)
3619
    ];
3620
    var execute$1 = function (component, simulatedEvent, executeConfig) {
3621
      return executeConfig.execute()(component, simulatedEvent, component.element());
3622
    };
3623
    var getRules = function (component, simulatedEvent, executeConfig, executeState) {
3624
      var spaceExec = executeConfig.useSpace() && !inside(component.element()) ? SPACE() : [];
3625
      var enterExec = executeConfig.useEnter() ? ENTER() : [];
3626
      var downExec = executeConfig.useDown() ? DOWN() : [];
3627
      var execKeys = spaceExec.concat(enterExec).concat(downExec);
3628
      return [rule(inSet(execKeys), execute$1)].concat(executeConfig.useControlEnter() ? [rule(and([
3629
          isControl,
3630
          inSet(ENTER())
3631
        ]), execute$1)] : []);
3632
    };
3633
    var getEvents = constant({});
3634
    var getApis = constant({});
3635
    var ExecutionType = typical(schema$1, NoState.init, getRules, getEvents, getApis, Option.none());
3636
3637
    var flatgrid = function (spec) {
3638
      var dimensions = Cell(Option.none());
3639
      var setGridSize = function (numRows, numColumns) {
3640
        dimensions.set(Option.some({
3641
          numRows: constant(numRows),
3642
          numColumns: constant(numColumns)
3643
        }));
3644
      };
3645
      var getNumRows = function () {
3646
        return dimensions.get().map(function (d) {
3647
          return d.numRows();
3648
        });
3649
      };
3650
      var getNumColumns = function () {
3651
        return dimensions.get().map(function (d) {
3652
          return d.numColumns();
3653
        });
3654
      };
3655
      return nu$7({
3656
        readState: constant({}),
3657
        setGridSize: setGridSize,
3658
        getNumRows: getNumRows,
3659
        getNumColumns: getNumColumns
3660
      });
3661
    };
3662
    var init = function (spec) {
3663
      return spec.state()(spec);
3664
    };
3665
3666
    var KeyingState = /*#__PURE__*/Object.freeze({
3667
        flatgrid: flatgrid,
3668
        init: init
3669
    });
3670
3671
    var onDirection = function (isLtr, isRtl) {
3672
      return function (element) {
3673
        return getDirection(element) === 'rtl' ? isRtl : isLtr;
3674
      };
3675
    };
3676
    var getDirection = function (element) {
3677
      return get$4(element, 'direction') === 'rtl' ? 'rtl' : 'ltr';
3678
    };
3679
3680
    var useH = function (movement) {
3681
      return function (component, simulatedEvent, config, state) {
3682
        var move = movement(component.element());
3683
        return use(move, component, simulatedEvent, config, state);
3684
      };
3685
    };
3686
    var west = function (moveLeft, moveRight) {
3687
      var movement = onDirection(moveLeft, moveRight);
3688
      return useH(movement);
3689
    };
3690
    var east = function (moveLeft, moveRight) {
3691
      var movement = onDirection(moveRight, moveLeft);
3692
      return useH(movement);
3693
    };
3694
    var useV = function (move) {
3695
      return function (component, simulatedEvent, config, state) {
3696
        return use(move, component, simulatedEvent, config, state);
3697
      };
3698
    };
3699
    var use = function (move, component, simulatedEvent, config, state) {
3700
      var outcome = config.focusManager().get(component).bind(function (focused) {
3701
        return move(component.element(), focused, config, state);
3702
      });
3703
      return outcome.map(function (newFocus) {
3704
        config.focusManager().set(component, newFocus);
3705
        return true;
3706
      });
3707
    };
3708
    var north = useV;
3709
    var south = useV;
3710
    var move = useV;
3711
3712
    var isHidden = function (dom) {
3713
      return dom.offsetWidth <= 0 && dom.offsetHeight <= 0;
3714
    };
3715
    var isVisible = function (element) {
3716
      var dom = element.dom();
3717
      return !isHidden(dom);
3718
    };
3719
3720
    var indexInfo = MixedBag([
3721
      'index',
3722
      'candidates'
3723
    ], []);
3724
    var locate = function (candidates, predicate) {
3725
      return findIndex(candidates, predicate).map(function (index) {
3726
        return indexInfo({
3727
          index: index,
3728
          candidates: candidates
3729
        });
3730
      });
3731
    };
3732
3733
    var locateVisible = function (container, current, selector) {
3734
      var filter$$1 = isVisible;
3735
      return locateIn(container, current, selector, filter$$1);
3736
    };
3737
    var locateIn = function (container, current, selector, filter$$1) {
3738
      var predicate = curry(eq, current);
3739
      var candidates = descendants$1(container, selector);
3740
      var visible = filter(candidates, isVisible);
3741
      return locate(visible, predicate);
3742
    };
3743
    var findIndex$2 = function (elements, target) {
3744
      return findIndex(elements, function (elem) {
3745
        return eq(target, elem);
3746
      });
3747
    };
3748
3749
    var withGrid = function (values, index, numCols, f) {
3750
      var oldRow = Math.floor(index / numCols);
3751
      var oldColumn = index % numCols;
3752
      return f(oldRow, oldColumn).bind(function (address) {
3753
        var newIndex = address.row() * numCols + address.column();
3754
        return newIndex >= 0 && newIndex < values.length ? Option.some(values[newIndex]) : Option.none();
3755
      });
3756
    };
3757
    var cycleHorizontal = function (values, index, numRows, numCols, delta) {
3758
      return withGrid(values, index, numCols, function (oldRow, oldColumn) {
3759
        var onLastRow = oldRow === numRows - 1;
3760
        var colsInRow = onLastRow ? values.length - oldRow * numCols : numCols;
3761
        var newColumn = cycleBy(oldColumn, delta, 0, colsInRow - 1);
3762
        return Option.some({
3763
          row: constant(oldRow),
3764
          column: constant(newColumn)
3765
        });
3766
      });
3767
    };
3768
    var cycleVertical = function (values, index, numRows, numCols, delta) {
3769
      return withGrid(values, index, numCols, function (oldRow, oldColumn) {
3770
        var newRow = cycleBy(oldRow, delta, 0, numRows - 1);
3771
        var onLastRow = newRow === numRows - 1;
3772
        var colsInRow = onLastRow ? values.length - newRow * numCols : numCols;
3773
        var newCol = cap(oldColumn, 0, colsInRow - 1);
3774
        return Option.some({
3775
          row: constant(newRow),
3776
          column: constant(newCol)
3777
        });
3778
      });
3779
    };
3780
    var cycleRight = function (values, index, numRows, numCols) {
3781
      return cycleHorizontal(values, index, numRows, numCols, +1);
3782
    };
3783
    var cycleLeft = function (values, index, numRows, numCols) {
3784
      return cycleHorizontal(values, index, numRows, numCols, -1);
3785
    };
3786
    var cycleUp = function (values, index, numRows, numCols) {
3787
      return cycleVertical(values, index, numRows, numCols, -1);
3788
    };
3789
    var cycleDown = function (values, index, numRows, numCols) {
3790
      return cycleVertical(values, index, numRows, numCols, +1);
3791
    };
3792
3793
    var schema$2 = [
3794
      strict$1('selector'),
3795
      defaulted$1('execute', defaultExecute),
3796
      onKeyboardHandler('onEscape'),
3797
      defaulted$1('captureTab', false),
3798
      initSize()
3799
    ];
3800
    var focusIn = function (component, gridConfig, gridState) {
3801
      descendant$2(component.element(), gridConfig.selector()).each(function (first) {
3802
        gridConfig.focusManager().set(component, first);
3803
      });
3804
    };
3805
    var findCurrent = function (component, gridConfig) {
3806
      return gridConfig.focusManager().get(component).bind(function (elem) {
3807
        return closest$2(elem, gridConfig.selector());
3808
      });
3809
    };
3810
    var execute$2 = function (component, simulatedEvent, gridConfig, gridState) {
3811
      return findCurrent(component, gridConfig).bind(function (focused) {
3812
        return gridConfig.execute()(component, simulatedEvent, focused);
3813
      });
3814
    };
3815
    var doMove = function (cycle) {
3816
      return function (element, focused, gridConfig, gridState) {
3817
        return locateVisible(element, focused, gridConfig.selector()).bind(function (identified) {
3818
          return cycle(identified.candidates(), identified.index(), gridState.getNumRows().getOr(gridConfig.initSize().numRows()), gridState.getNumColumns().getOr(gridConfig.initSize().numColumns()));
3819
        });
3820
      };
3821
    };
3822
    var handleTab = function (component, simulatedEvent, gridConfig, gridState) {
3823
      return gridConfig.captureTab() ? Option.some(true) : Option.none();
3824
    };
3825
    var doEscape = function (component, simulatedEvent, gridConfig, gridState) {
3826
      return gridConfig.onEscape()(component, simulatedEvent);
3827
    };
3828
    var moveLeft = doMove(cycleLeft);
3829
    var moveRight = doMove(cycleRight);
3830
    var moveNorth = doMove(cycleUp);
3831
    var moveSouth = doMove(cycleDown);
3832
    var getRules$1 = constant([
3833
      rule(inSet(LEFT()), west(moveLeft, moveRight)),
3834
      rule(inSet(RIGHT()), east(moveLeft, moveRight)),
3835
      rule(inSet(UP()), north(moveNorth)),
3836
      rule(inSet(DOWN()), south(moveSouth)),
3837
      rule(and([
3838
        isShift,
3839
        inSet(TAB())
3840
      ]), handleTab),
3841
      rule(and([
3842
        isNotShift,
3843
        inSet(TAB())
3844
      ]), handleTab),
3845
      rule(inSet(ESCAPE()), doEscape),
3846
      rule(inSet(SPACE().concat(ENTER())), execute$2)
3847
    ]);
3848
    var getEvents$1 = constant({});
3849
    var getApis$1 = {};
3850
    var FlatgridType = typical(schema$2, flatgrid, getRules$1, getEvents$1, getApis$1, Option.some(focusIn));
3851
3852
    var horizontal = function (container, selector, current, delta) {
3853
      return locateVisible(container, current, selector).bind(function (identified) {
3854
        var index = identified.index();
3855
        var candidates = identified.candidates();
3856
        var newIndex = cycleBy(index, delta, 0, candidates.length - 1);
3857
        return Option.from(candidates[newIndex]);
3858
      });
3859
    };
3860
3861
    var schema$3 = [
3862
      strict$1('selector'),
3863
      defaulted$1('getInitial', Option.none),
3864
      defaulted$1('execute', defaultExecute),
3865
      defaulted$1('executeOnMove', false),
3866
      defaulted$1('allowVertical', true)
3867
    ];
3868
    var findCurrent$1 = function (component, flowConfig) {
3869
      return flowConfig.focusManager().get(component).bind(function (elem) {
3870
        return closest$2(elem, flowConfig.selector());
3871
      });
3872
    };
3873
    var execute$3 = function (component, simulatedEvent, flowConfig) {
3874
      return findCurrent$1(component, flowConfig).bind(function (focused) {
3875
        return flowConfig.execute()(component, simulatedEvent, focused);
3876
      });
3877
    };
3878
    var focusIn$1 = function (component, flowConfig) {
3879
      flowConfig.getInitial()(component).or(descendant$2(component.element(), flowConfig.selector())).each(function (first) {
3880
        flowConfig.focusManager().set(component, first);
3881
      });
3882
    };
3883
    var moveLeft$1 = function (element, focused, info) {
3884
      return horizontal(element, info.selector(), focused, -1);
3885
    };
3886
    var moveRight$1 = function (element, focused, info) {
3887
      return horizontal(element, info.selector(), focused, +1);
3888
    };
3889
    var doMove$1 = function (movement) {
3890
      return function (component, simulatedEvent, flowConfig) {
3891
        return movement(component, simulatedEvent, flowConfig).bind(function () {
3892
          return flowConfig.executeOnMove() ? execute$3(component, simulatedEvent, flowConfig) : Option.some(true);
3893
        });
3894
      };
3895
    };
3896
    var getRules$2 = function (_component, _se, flowConfig, _flowState) {
3897
      var westMovers = LEFT().concat(flowConfig.allowVertical() ? UP() : []);
3898
      var eastMovers = RIGHT().concat(flowConfig.allowVertical() ? DOWN() : []);
3899
      return [
3900
        rule(inSet(westMovers), doMove$1(west(moveLeft$1, moveRight$1))),
3901
        rule(inSet(eastMovers), doMove$1(east(moveLeft$1, moveRight$1))),
3902
        rule(inSet(ENTER()), execute$3),
3903
        rule(inSet(SPACE()), execute$3)
3904
      ];
3905
    };
3906
    var getEvents$2 = constant({});
3907
    var getApis$2 = constant({});
3908
    var FlowType = typical(schema$3, NoState.init, getRules$2, getEvents$2, getApis$2, Option.some(focusIn$1));
3909
3910
    var outcome = MixedBag([
3911
      'rowIndex',
3912
      'columnIndex',
3913
      'cell'
3914
    ], []);
3915
    var toCell = function (matrix, rowIndex, columnIndex) {
3916
      return Option.from(matrix[rowIndex]).bind(function (row) {
3917
        return Option.from(row[columnIndex]).map(function (cell) {
3918
          return outcome({
3919
            rowIndex: rowIndex,
3920
            columnIndex: columnIndex,
3921
            cell: cell
3922
          });
3923
        });
3924
      });
3925
    };
3926
    var cycleHorizontal$1 = function (matrix, rowIndex, startCol, deltaCol) {
3927
      var row = matrix[rowIndex];
3928
      var colsInRow = row.length;
3929
      var newColIndex = cycleBy(startCol, deltaCol, 0, colsInRow - 1);
3930
      return toCell(matrix, rowIndex, newColIndex);
3931
    };
3932
    var cycleVertical$1 = function (matrix, colIndex, startRow, deltaRow) {
3933
      var nextRowIndex = cycleBy(startRow, deltaRow, 0, matrix.length - 1);
3934
      var colsInNextRow = matrix[nextRowIndex].length;
3935
      var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
3936
      return toCell(matrix, nextRowIndex, nextColIndex);
3937
    };
3938
    var moveHorizontal = function (matrix, rowIndex, startCol, deltaCol) {
3939
      var row = matrix[rowIndex];
3940
      var colsInRow = row.length;
3941
      var newColIndex = cap(startCol + deltaCol, 0, colsInRow - 1);
3942
      return toCell(matrix, rowIndex, newColIndex);
3943
    };
3944
    var moveVertical = function (matrix, colIndex, startRow, deltaRow) {
3945
      var nextRowIndex = cap(startRow + deltaRow, 0, matrix.length - 1);
3946
      var colsInNextRow = matrix[nextRowIndex].length;
3947
      var nextColIndex = cap(colIndex, 0, colsInNextRow - 1);
3948
      return toCell(matrix, nextRowIndex, nextColIndex);
3949
    };
3950
    var cycleRight$1 = function (matrix, startRow, startCol) {
3951
      return cycleHorizontal$1(matrix, startRow, startCol, +1);
3952
    };
3953
    var cycleLeft$1 = function (matrix, startRow, startCol) {
3954
      return cycleHorizontal$1(matrix, startRow, startCol, -1);
3955
    };
3956
    var cycleUp$1 = function (matrix, startRow, startCol) {
3957
      return cycleVertical$1(matrix, startCol, startRow, -1);
3958
    };
3959
    var cycleDown$1 = function (matrix, startRow, startCol) {
3960
      return cycleVertical$1(matrix, startCol, startRow, +1);
3961
    };
3962
    var moveLeft$2 = function (matrix, startRow, startCol) {
3963
      return moveHorizontal(matrix, startRow, startCol, -1);
3964
    };
3965
    var moveRight$2 = function (matrix, startRow, startCol) {
3966
      return moveHorizontal(matrix, startRow, startCol, +1);
3967
    };
3968
    var moveUp = function (matrix, startRow, startCol) {
3969
      return moveVertical(matrix, startCol, startRow, -1);
3970
    };
3971
    var moveDown = function (matrix, startRow, startCol) {
3972
      return moveVertical(matrix, startCol, startRow, +1);
3973
    };
3974
3975
    var schema$4 = [
3976
      strictObjOf('selectors', [
3977
        strict$1('row'),
3978
        strict$1('cell')
3979
      ]),
3980
      defaulted$1('cycles', true),
3981
      defaulted$1('previousSelector', Option.none),
3982
      defaulted$1('execute', defaultExecute)
3983
    ];
3984
    var focusIn$2 = function (component, matrixConfig) {
3985
      var focused = matrixConfig.previousSelector()(component).orThunk(function () {
3986
        var selectors = matrixConfig.selectors();
3987
        return descendant$2(component.element(), selectors.cell());
3988
      });
3989
      focused.each(function (cell) {
3990
        matrixConfig.focusManager().set(component, cell);
3991
      });
3992
    };
3993
    var execute$4 = function (component, simulatedEvent, matrixConfig) {
3994
      return search(component.element()).bind(function (focused) {
3995
        return matrixConfig.execute()(component, simulatedEvent, focused);
3996
      });
3997
    };
3998
    var toMatrix = function (rows, matrixConfig) {
3999
      return map$1(rows, function (row) {
4000
        return descendants$1(row, matrixConfig.selectors().cell());
4001
      });
4002
    };
4003
    var doMove$2 = function (ifCycle, ifMove) {
4004
      return function (element, focused, matrixConfig) {
4005
        var move$$1 = matrixConfig.cycles() ? ifCycle : ifMove;
4006
        return closest$2(focused, matrixConfig.selectors().row()).bind(function (inRow) {
4007
          var cellsInRow = descendants$1(inRow, matrixConfig.selectors().cell());
4008
          return findIndex$2(cellsInRow, focused).bind(function (colIndex) {
4009
            var allRows = descendants$1(element, matrixConfig.selectors().row());
4010
            return findIndex$2(allRows, inRow).bind(function (rowIndex) {
4011
              var matrix = toMatrix(allRows, matrixConfig);
4012
              return move$$1(matrix, rowIndex, colIndex).map(function (next) {
4013
                return next.cell();
4014
              });
4015
            });
4016
          });
4017
        });
4018
      };
4019
    };
4020
    var moveLeft$3 = doMove$2(cycleLeft$1, moveLeft$2);
4021
    var moveRight$3 = doMove$2(cycleRight$1, moveRight$2);
4022
    var moveNorth$1 = doMove$2(cycleUp$1, moveUp);
4023
    var moveSouth$1 = doMove$2(cycleDown$1, moveDown);
4024
    var getRules$3 = constant([
4025
      rule(inSet(LEFT()), west(moveLeft$3, moveRight$3)),
4026
      rule(inSet(RIGHT()), east(moveLeft$3, moveRight$3)),
4027
      rule(inSet(UP()), north(moveNorth$1)),
4028
      rule(inSet(DOWN()), south(moveSouth$1)),
4029
      rule(inSet(SPACE().concat(ENTER())), execute$4)
4030
    ]);
4031
    var getEvents$3 = constant({});
4032
    var getApis$3 = constant({});
4033
    var MatrixType = typical(schema$4, NoState.init, getRules$3, getEvents$3, getApis$3, Option.some(focusIn$2));
4034
4035
    var schema$5 = [
4036
      strict$1('selector'),
4037
      defaulted$1('execute', defaultExecute),
4038
      defaulted$1('moveOnTab', false)
4039
    ];
4040
    var execute$5 = function (component, simulatedEvent, menuConfig) {
4041
      return menuConfig.focusManager().get(component).bind(function (focused) {
4042
        return menuConfig.execute()(component, simulatedEvent, focused);
4043
      });
4044
    };
4045
    var focusIn$3 = function (component, menuConfig) {
4046
      descendant$2(component.element(), menuConfig.selector()).each(function (first) {
4047
        menuConfig.focusManager().set(component, first);
4048
      });
4049
    };
4050
    var moveUp$1 = function (element, focused, info) {
4051
      return horizontal(element, info.selector(), focused, -1);
4052
    };
4053
    var moveDown$1 = function (element, focused, info) {
4054
      return horizontal(element, info.selector(), focused, +1);
4055
    };
4056
    var fireShiftTab = function (component, simulatedEvent, menuConfig) {
4057
      return menuConfig.moveOnTab() ? move(moveUp$1)(component, simulatedEvent, menuConfig) : Option.none();
4058
    };
4059
    var fireTab = function (component, simulatedEvent, menuConfig) {
4060
      return menuConfig.moveOnTab() ? move(moveDown$1)(component, simulatedEvent, menuConfig) : Option.none();
4061
    };
4062
    var getRules$4 = constant([
4063
      rule(inSet(UP()), move(moveUp$1)),
4064
      rule(inSet(DOWN()), move(moveDown$1)),
4065
      rule(and([
4066
        isShift,
4067
        inSet(TAB())
4068
      ]), fireShiftTab),
4069
      rule(and([
4070
        isNotShift,
4071
        inSet(TAB())
4072
      ]), fireTab),
4073
      rule(inSet(ENTER()), execute$5),
4074
      rule(inSet(SPACE()), execute$5)
4075
    ]);
4076
    var getEvents$4 = constant({});
4077
    var getApis$4 = constant({});
4078
    var MenuType = typical(schema$5, NoState.init, getRules$4, getEvents$4, getApis$4, Option.some(focusIn$3));
4079
4080
    var schema$6 = [
4081
      onKeyboardHandler('onSpace'),
4082
      onKeyboardHandler('onEnter'),
4083
      onKeyboardHandler('onShiftEnter'),
4084
      onKeyboardHandler('onLeft'),
4085
      onKeyboardHandler('onRight'),
4086
      onKeyboardHandler('onTab'),
4087
      onKeyboardHandler('onShiftTab'),
4088
      onKeyboardHandler('onUp'),
4089
      onKeyboardHandler('onDown'),
4090
      onKeyboardHandler('onEscape'),
4091
      option('focusIn')
4092
    ];
4093
    var getRules$5 = function (component, simulatedEvent, specialInfo) {
4094
      return [
4095
        rule(inSet(SPACE()), specialInfo.onSpace()),
4096
        rule(and([
4097
          isNotShift,
4098
          inSet(ENTER())
4099
        ]), specialInfo.onEnter()),
4100
        rule(and([
4101
          isShift,
4102
          inSet(ENTER())
4103
        ]), specialInfo.onShiftEnter()),
4104
        rule(and([
4105
          isShift,
4106
          inSet(TAB())
4107
        ]), specialInfo.onShiftTab()),
4108
        rule(and([
4109
          isNotShift,
4110
          inSet(TAB())
4111
        ]), specialInfo.onTab()),
4112
        rule(inSet(UP()), specialInfo.onUp()),
4113
        rule(inSet(DOWN()), specialInfo.onDown()),
4114
        rule(inSet(LEFT()), specialInfo.onLeft()),
4115
        rule(inSet(RIGHT()), specialInfo.onRight()),
4116
        rule(inSet(SPACE()), specialInfo.onSpace()),
4117
        rule(inSet(ESCAPE()), specialInfo.onEscape())
4118
      ];
4119
    };
4120
    var focusIn$4 = function (component, specialInfo) {
4121
      return specialInfo.focusIn().bind(function (f) {
4122
        return f(component, specialInfo);
4123
      });
4124
    };
4125
    var getEvents$5 = function () {
4126
      return {};
4127
    };
4128
    var getApis$5 = function () {
4129
      return {};
4130
    };
4131
    var SpecialType = typical(schema$6, NoState.init, getRules$5, getEvents$5, getApis$5, Option.some(focusIn$4));
4132
4133
    var acyclic = AcyclicType.schema();
4134
    var cyclic = CyclicType.schema();
4135
    var flow = FlowType.schema();
4136
    var flatgrid$1 = FlatgridType.schema();
4137
    var matrix = MatrixType.schema();
4138
    var execution = ExecutionType.schema();
4139
    var menu = MenuType.schema();
4140
    var special = SpecialType.schema();
4141
4142
    var KeyboardBranches = /*#__PURE__*/Object.freeze({
4143
        acyclic: acyclic,
4144
        cyclic: cyclic,
4145
        flow: flow,
4146
        flatgrid: flatgrid$1,
4147
        matrix: matrix,
4148
        execution: execution,
4149
        menu: menu,
4150
        special: special
4151
    });
4152
4153
    var Keying = createModes$1({
4154
      branchKey: 'mode',
4155
      branches: KeyboardBranches,
4156
      name: 'keying',
4157
      active: {
4158
        events: function (keyingConfig, keyingState) {
4159
          var handler = keyingConfig.handler();
4160
          return handler.toEvents(keyingConfig, keyingState);
4161
        }
4162
      },
4163
      apis: {
4164
        focusIn: function (component) {
4165
          component.getSystem().triggerFocus(component.element(), component.element());
4166
        },
4167
        setGridSize: function (component, keyConfig, keyState, numRows, numColumns) {
4168
          if (!hasKey$1(keyState, 'setGridSize')) {
4169
            console.error('Layout does not support setGridSize');
4170
          } else {
4171
            keyState.setGridSize(numRows, numColumns);
4172
          }
4173
        }
4174
      },
4175
      state: KeyingState
4176
    });
4177
4178
    var field$1 = function (name, forbidden) {
4179
      return defaultedObjOf(name, {}, map$1(forbidden, function (f) {
4180
        return forbid(f.name(), 'Cannot configure ' + f.name() + ' for ' + name);
4181
      }).concat([state$1('dump', identity)]));
4182
    };
4183
    var get$6 = function (data) {
4184
      return data.dump();
4185
    };
4186
4187
    var _placeholder = 'placeholder';
4188
    var adt$2 = Adt.generate([
4189
      {
4190
        single: [
4191
          'required',
4192
          'valueThunk'
4193
        ]
4194
      },
4195
      {
4196
        multiple: [
4197
          'required',
4198
          'valueThunks'
4199
        ]
4200
      }
4201
    ]);
4202
    var subPlaceholder = function (owner, detail, compSpec, placeholders) {
4203
      if (owner.exists(function (o) {
4204
          return o !== compSpec.owner;
4205
        })) {
4206
        return adt$2.single(true, constant(compSpec));
4207
      }
4208
      return readOptFrom$1(placeholders, compSpec.name).fold(function () {
4209
        throw new Error('Unknown placeholder component: ' + compSpec.name + '\nKnown: [' + keys(placeholders) + ']\nNamespace: ' + owner.getOr('none') + '\nSpec: ' + Json.stringify(compSpec, null, 2));
4210
      }, function (newSpec) {
4211
        return newSpec.replace();
4212
      });
4213
    };
4214
    var scan = function (owner, detail, compSpec, placeholders) {
4215
      if (compSpec.uiType === _placeholder) {
4216
        return subPlaceholder(owner, detail, compSpec, placeholders);
4217
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
4218
        return adt$2.single(false, constant(compSpec));
4219
      }
4220
    };
4221
    var substitute = function (owner, detail, compSpec, placeholders) {
4222
      var base = scan(owner, detail, compSpec, placeholders);
4223
      return base.fold(function (req, valueThunk) {
4224
        var value = valueThunk(detail, compSpec.config, compSpec.validated);
4225
        var childSpecs = readOptFrom$1(value, 'components').getOr([]);
4226
        var substituted = bind(childSpecs, function (c) {
4227
          return substitute(owner, detail, c, placeholders);
4228
        });
4229
        return [deepMerge(value, { components: substituted })];
4230
      }, function (req, valuesThunk) {
4231
        var values$$1 = valuesThunk(detail, compSpec.config, compSpec.validated);
4232
        return values$$1;
4233
      });
4234
    };
4235
    var substituteAll = function (owner, detail, components, placeholders) {
4236
      return bind(components, function (c) {
4237
        return substitute(owner, detail, c, placeholders);
4238
      });
4239
    };
4240
    var oneReplace = function (label, replacements) {
4241
      var called = false;
4242
      var used = function () {
4243
        return called;
4244
      };
4245
      var replace = function () {
4246
        if (called === true) {
4247
          throw new Error('Trying to use the same placeholder more than once: ' + label);
4248
        }
4249
        called = true;
4250
        return replacements;
4251
      };
4252
      var required = function () {
4253
        return replacements.fold(function (req, _) {
4254
          return req;
4255
        }, function (req, _) {
4256
          return req;
4257
        });
4258
      };
4259
      return {
4260
        name: constant(label),
4261
        required: required,
4262
        used: used,
4263
        replace: replace
4264
      };
4265
    };
4266
    var substitutePlaces = function (owner, detail, components, placeholders) {
4267
      var ps = map(placeholders, function (ph, name) {
4268
        return oneReplace(name, ph);
4269
      });
4270
      var outcome = substituteAll(owner, detail, components, ps);
4271
      each(ps, function (p) {
4272
        if (p.used() === false && p.required()) {
4273
          throw new Error('Placeholder: ' + p.name() + ' was not found in components list\nNamespace: ' + owner.getOr('none') + '\nComponents: ' + Json.stringify(detail.components(), null, 2));
4274
        }
4275
      });
4276
      return outcome;
4277
    };
4278
    var single = adt$2.single;
4279
    var multiple = adt$2.multiple;
4280
    var placeholder = constant(_placeholder);
4281
4282
    var unique = 0;
4283
    var generate$1 = function (prefix) {
4284
      var date = new Date();
4285
      var time = date.getTime();
4286
      var random = Math.floor(Math.random() * 1000000000);
4287
      unique++;
4288
      return prefix + '_' + random + unique + String(time);
4289
    };
4290
4291
    var adt$3 = Adt.generate([
4292
      { required: ['data'] },
4293
      { external: ['data'] },
4294
      { optional: ['data'] },
4295
      { group: ['data'] }
4296
    ]);
4297
    var fFactory = defaulted$1('factory', { sketch: identity });
4298
    var fSchema = defaulted$1('schema', []);
4299
    var fName = strict$1('name');
4300
    var fPname = field('pname', 'pname', defaultedThunk(function (typeSpec) {
4301
      return '<alloy.' + generate$1(typeSpec.name) + '>';
4302
    }), anyValue$1());
4303
    var fDefaults = defaulted$1('defaults', constant({}));
4304
    var fOverrides = defaulted$1('overrides', constant({}));
4305
    var requiredSpec = objOf([
4306
      fFactory,
4307
      fSchema,
4308
      fName,
4309
      fPname,
4310
      fDefaults,
4311
      fOverrides
4312
    ]);
4313
    var externalSpec = objOf([
4314
      fFactory,
4315
      fSchema,
4316
      fName,
4317
      fDefaults,
4318
      fOverrides
4319
    ]);
4320
    var optionalSpec = objOf([
4321
      fFactory,
4322
      fSchema,
4323
      fName,
4324
      fPname,
4325
      fDefaults,
4326
      fOverrides
4327
    ]);
4328
    var groupSpec = objOf([
4329
      fFactory,
4330
      fSchema,
4331
      fName,
4332
      strict$1('unit'),
4333
      fPname,
4334
      fDefaults,
4335
      fOverrides
4336
    ]);
4337
    var asNamedPart = function (part) {
4338
      return part.fold(Option.some, Option.none, Option.some, Option.some);
4339
    };
4340
    var name$1 = function (part) {
4341
      var get = function (data) {
4342
        return data.name();
4343
      };
4344
      return part.fold(get, get, get, get);
4345
    };
4346
    var convert = function (adtConstructor, partSchema) {
4347
      return function (spec) {
4348
        var data = asStructOrDie('Converting part type', partSchema, spec);
4349
        return adtConstructor(data);
4350
      };
4351
    };
4352
    var required = convert(adt$3.required, requiredSpec);
4353
    var external = convert(adt$3.external, externalSpec);
4354
    var optional = convert(adt$3.optional, optionalSpec);
4355
    var group = convert(adt$3.group, groupSpec);
4356
    var original = constant('entirety');
4357
4358
    var combine = function (detail, data, partSpec, partValidated) {
4359
      var spec = partSpec;
4360
      return deepMerge(data.defaults()(detail, partSpec, partValidated), partSpec, { uid: detail.partUids()[data.name()] }, data.overrides()(detail, partSpec, partValidated), { 'debug.sketcher': wrap$2('part-' + data.name(), spec) });
4361
    };
4362
    var subs = function (owner, detail, parts) {
4363
      var internals = {};
4364
      var externals = {};
4365
      each$1(parts, function (part) {
4366
        part.fold(function (data) {
4367
          internals[data.pname()] = single(true, function (detail, partSpec, partValidated) {
4368
            return data.factory().sketch(combine(detail, data, partSpec, partValidated));
4369
          });
4370
        }, function (data) {
4371
          var partSpec = detail.parts()[data.name()]();
4372
          externals[data.name()] = constant(combine(detail, data, partSpec[original()]()));
4373
        }, function (data) {
4374
          internals[data.pname()] = single(false, function (detail, partSpec, partValidated) {
4375
            return data.factory().sketch(combine(detail, data, partSpec, partValidated));
4376
          });
4377
        }, function (data) {
4378
          internals[data.pname()] = multiple(true, function (detail, _partSpec, _partValidated) {
4379
            var units = detail[data.name()]();
4380
            return map$1(units, function (u) {
4381
              return data.factory().sketch(deepMerge(data.defaults()(detail, u), u, data.overrides()(detail, u)));
4382
            });
4383
          });
4384
        });
4385
      });
4386
      return {
4387
        internals: constant(internals),
4388
        externals: constant(externals)
4389
      };
4390
    };
4391
4392
    var generate$2 = function (owner, parts) {
4393
      var r = {};
4394
      each$1(parts, function (part) {
4395
        asNamedPart(part).each(function (np) {
4396
          var g = doGenerateOne(owner, np.pname());
4397
          r[np.name()] = function (config) {
4398
            var validated = asRawOrDie('Part: ' + np.name() + ' in ' + owner, objOf(np.schema()), config);
4399
            return deepMerge(g, {
4400
              config: config,
4401
              validated: validated
4402
            });
4403
          };
4404
        });
4405
      });
4406
      return r;
4407
    };
4408
    var doGenerateOne = function (owner, pname) {
4409
      return {
4410
        uiType: placeholder(),
4411
        owner: owner,
4412
        name: pname
4413
      };
4414
    };
4415
    var generateOne = function (owner, pname, config) {
4416
      return {
4417
        uiType: placeholder(),
4418
        owner: owner,
4419
        name: pname,
4420
        config: config,
4421
        validated: {}
4422
      };
4423
    };
4424
    var schemas = function (parts) {
4425
      return bind(parts, function (part) {
4426
        return part.fold(Option.none, Option.some, Option.none, Option.none).map(function (data) {
4427
          return strictObjOf(data.name(), data.schema().concat([snapshot$1(original())]));
4428
        }).toArray();
4429
      });
4430
    };
4431
    var names = function (parts) {
4432
      return map$1(parts, name$1);
4433
    };
4434
    var substitutes = function (owner, detail, parts) {
4435
      return subs(owner, detail, parts);
4436
    };
4437
    var components = function (owner, detail, internals) {
4438
      return substitutePlaces(Option.some(owner), detail, detail.components(), internals);
4439
    };
4440
    var getPart = function (component, detail, partKey) {
4441
      var uid = detail.partUids()[partKey];
4442
      return component.getSystem().getByUid(uid).toOption();
4443
    };
4444
    var getPartOrDie = function (component, detail, partKey) {
4445
      return getPart(component, detail, partKey).getOrDie('Could not find part: ' + partKey);
4446
    };
4447
    var getAllParts = function (component, detail) {
4448
      var system = component.getSystem();
4449
      return map(detail.partUids(), function (pUid, k) {
4450
        return constant(system.getByUid(pUid));
4451
      });
4452
    };
4453
    var defaultUids = function (baseUid, partTypes) {
4454
      var partNames = names(partTypes);
4455
      return wrapAll$1(map$1(partNames, function (pn) {
4456
        return {
4457
          key: pn,
4458
          value: baseUid + '-' + pn
4459
        };
4460
      }));
4461
    };
4462
    var defaultUidsSchema = function (partTypes) {
4463
      return field('partUids', 'partUids', mergeWithThunk(function (spec) {
4464
        return defaultUids(spec.uid, partTypes);
4465
      }), anyValue$1());
4466
    };
4467
4468
    var premadeTag = generate$1('alloy-premade');
4469
    var _apiConfig = generate$1('api');
4470
    var premade = function (comp) {
4471
      return wrap$2(premadeTag, comp);
4472
    };
4473
    var getPremade = function (spec) {
4474
      return readOptFrom$1(spec, premadeTag);
4475
    };
4476
    var makeApi = function (f) {
4477
      return markAsSketchApi(function (component) {
4478
        var rest = [];
4479
        for (var _i = 1; _i < arguments.length; _i++) {
4480
          rest[_i - 1] = arguments[_i];
4481
        }
4482
        var spi = component.config(_apiConfig);
4483
        return f.apply(undefined, [spi].concat([component].concat(rest)));
4484
      }, f);
4485
    };
4486
    var apiConfig = constant(_apiConfig);
4487
4488
    var prefix$1 = constant('alloy-id-');
4489
    var idAttr = constant('data-alloy-id');
4490
4491
    var prefix$2 = prefix$1();
4492
    var idAttr$1 = idAttr();
4493
    var write = function (label, elem) {
4494
      var id = generate$1(prefix$2 + label);
4495
      set(elem, idAttr$1, id);
4496
      return id;
4497
    };
4498
    var writeOnly = function (elem, uid) {
4499
      set(elem, idAttr$1, uid);
4500
    };
4501
    var read$2 = function (elem) {
4502
      var id = isElement(elem) ? get$1(elem, idAttr$1) : null;
4503
      return Option.from(id);
4504
    };
4505
    var generate$3 = function (prefix) {
4506
      return generate$1(prefix);
4507
    };
4508
4509
    var base$1 = function (label, partSchemas, partUidsSchemas, spec) {
4510
      var ps = partSchemas.length > 0 ? [strictObjOf('parts', partSchemas)] : [];
4511
      return ps.concat([
4512
        strict$1('uid'),
4513
        defaulted$1('dom', {}),
4514
        defaulted$1('components', []),
4515
        snapshot$1('originalSpec'),
4516
        defaulted$1('debug.sketcher', {})
4517
      ]).concat(partUidsSchemas);
4518
    };
4519
    var asStructOrDie$1 = function (label, schema, spec, partSchemas, partUidsSchemas) {
4520
      var baseS = base$1(label, partSchemas, partUidsSchemas, spec);
4521
      return asStructOrDie(label + ' [SpecSchema]', objOfOnly(baseS.concat(schema)), spec);
4522
    };
4523
4524
    var single$1 = function (owner, schema, factory, spec) {
4525
      var specWithUid = supplyUid(spec);
4526
      var detail = asStructOrDie$1(owner, schema, specWithUid, [], []);
4527
      return deepMerge(factory(detail, specWithUid), { 'debug.sketcher': wrap$2(owner, spec) });
4528
    };
4529
    var composite = function (owner, schema, partTypes, factory, spec) {
4530
      var specWithUid = supplyUid(spec);
4531
      var partSchemas = schemas(partTypes);
4532
      var partUidsSchema = defaultUidsSchema(partTypes);
4533
      var detail = asStructOrDie$1(owner, schema, specWithUid, partSchemas, [partUidsSchema]);
4534
      var subs = substitutes(owner, detail, partTypes);
4535
      var components$$1 = components(owner, detail, subs.internals());
4536
      return deepMerge(factory(detail, components$$1, specWithUid, subs.externals()), { 'debug.sketcher': wrap$2(owner, spec) });
4537
    };
4538
    var supplyUid = function (spec) {
4539
      return deepMerge({ uid: generate$3('uid') }, spec);
4540
    };
4541
4542
    function isSketchSpec(spec) {
4543
      return spec.uid !== undefined;
4544
    }
4545
    var singleSchema = objOfOnly([
4546
      strict$1('name'),
4547
      strict$1('factory'),
4548
      strict$1('configFields'),
4549
      defaulted$1('apis', {}),
4550
      defaulted$1('extraApis', {})
4551
    ]);
4552
    var compositeSchema = objOfOnly([
4553
      strict$1('name'),
4554
      strict$1('factory'),
4555
      strict$1('configFields'),
4556
      strict$1('partFields'),
4557
      defaulted$1('apis', {}),
4558
      defaulted$1('extraApis', {})
4559
    ]);
4560
    var single$2 = function (rawConfig) {
4561
      var config = asRawOrDie('Sketcher for ' + rawConfig.name, singleSchema, rawConfig);
4562
      var sketch = function (spec) {
4563
        return single$1(config.name, config.configFields, config.factory, spec);
4564
      };
4565
      var apis = map(config.apis, makeApi);
4566
      var extraApis = map(config.extraApis, function (f, k) {
4567
        return markAsExtraApi(f, k);
4568
      });
4569
      return deepMerge({
4570
        name: constant(config.name),
4571
        partFields: constant([]),
4572
        configFields: constant(config.configFields),
4573
        sketch: sketch
4574
      }, apis, extraApis);
4575
    };
4576
    var composite$1 = function (rawConfig) {
4577
      var config = asRawOrDie('Sketcher for ' + rawConfig.name, compositeSchema, rawConfig);
4578
      var sketch = function (spec) {
4579
        return composite(config.name, config.configFields, config.partFields, config.factory, spec);
4580
      };
4581
      var parts = generate$2(config.name, config.partFields);
4582
      var apis = map(config.apis, makeApi);
4583
      var extraApis = map(config.extraApis, function (f, k) {
4584
        return markAsExtraApi(f, k);
4585
      });
4586
      return deepMerge({
4587
        name: constant(config.name),
4588
        partFields: constant(config.partFields),
4589
        configFields: constant(config.configFields),
4590
        sketch: sketch,
4591
        parts: constant(parts)
4592
      }, apis, extraApis);
4593
    };
4594
4595
    var factory = function (detail) {
4596
      var events = events$2(detail.action());
4597
      var optType = readOptFrom$1(detail.dom(), 'attributes').bind(readOpt$1('type'));
4598
      var optTag = readOptFrom$1(detail.dom(), 'tag');
4599
      return {
4600
        uid: detail.uid(),
4601
        dom: detail.dom(),
4602
        components: detail.components(),
4603
        events: events,
4604
        behaviours: deepMerge(derive$2([
4605
          Focusing.config({}),
4606
          Keying.config({
4607
            mode: 'execution',
4608
            useSpace: true,
4609
            useEnter: true
4610
          })
4611
        ]), get$6(detail.buttonBehaviours())),
4612
        domModification: {
4613
          attributes: deepMerge(optType.fold(function () {
4614
            return optTag.is('button') ? { type: 'button' } : {};
4615
          }, function (t) {
4616
            return {};
4617
          }), { role: detail.role().getOr('button') })
4618
        },
4619
        eventOrder: detail.eventOrder()
4620
      };
4621
    };
4622
    var Button = single$2({
4623
      name: 'Button',
4624
      factory: factory,
4625
      configFields: [
4626
        defaulted$1('uid', undefined),
4627
        strict$1('dom'),
4628
        defaulted$1('components', []),
4629
        field$1('buttonBehaviours', [
4630
          Focusing,
4631
          Keying
4632
        ]),
4633
        option('action'),
4634
        option('role'),
4635
        defaulted$1('eventOrder', {})
4636
      ]
4637
    });
4638
4639
    var exhibit$2 = function (base, unselectConfig) {
4640
      return nu$6({
4641
        styles: {
4642
          '-webkit-user-select': 'none',
4643
          'user-select': 'none',
4644
          '-ms-user-select': 'none',
4645
          '-moz-user-select': '-moz-none'
4646
        },
4647
        attributes: { unselectable: 'on' }
4648
      });
4649
    };
4650
    var events$4 = function (unselectConfig) {
4651
      return derive([abort(selectstart(), constant(true))]);
4652
    };
4653
4654
    var ActiveUnselecting = /*#__PURE__*/Object.freeze({
4655
        events: events$4,
4656
        exhibit: exhibit$2
4657
    });
4658
4659
    var Unselecting = create$1({
4660
      fields: [],
4661
      name: 'unselecting',
4662
      active: ActiveUnselecting
4663
    });
4664
4665
    var getAttrs = function (elem) {
4666
      var attributes = elem.dom().attributes !== undefined ? elem.dom().attributes : [];
4667
      return foldl(attributes, function (b, attr) {
4668
        if (attr.name === 'class') {
4669
          return b;
4670
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
4671
          return deepMerge(b, wrap$2(attr.name, attr.value));
4672
        }
4673
      }, {});
4674
    };
4675
    var getClasses = function (elem) {
4676
      return Array.prototype.slice.call(elem.dom().classList, 0);
4677
    };
4678
    var fromHtml$2 = function (html) {
4679
      var elem = Element$$1.fromHtml(html);
4680
      var children$$1 = children(elem);
4681
      var attrs = getAttrs(elem);
4682
      var classes = getClasses(elem);
4683
      var contents = children$$1.length === 0 ? {} : { innerHtml: get$3(elem) };
4684
      return deepMerge({
4685
        tag: name(elem),
4686
        classes: classes,
4687
        attributes: attrs
4688
      }, contents);
4689
    };
4690
4691
    var dom$1 = function (rawHtml) {
4692
      var html = supplant(rawHtml, { prefix: Styles.prefix() });
4693
      return fromHtml$2(html);
4694
    };
4695
    var spec = function (rawHtml) {
4696
      var sDom = dom$1(rawHtml);
4697
      return { dom: sDom };
4698
    };
4699
4700
    var forToolbarCommand = function (editor, command) {
4701
      return forToolbar(command, function () {
4702
        editor.execCommand(command);
4703
      }, {});
4704
    };
4705
    var getToggleBehaviours = function (command) {
4706
      return derive$2([
4707
        Toggling.config({
4708
          toggleClass: Styles.resolve('toolbar-button-selected'),
4709
          toggleOnExecute: false,
4710
          aria: { mode: 'pressed' }
4711
        }),
4712
        Receivers.format(command, function (button, status) {
4713
          var toggle = status ? Toggling.on : Toggling.off;
4714
          toggle(button);
4715
        })
4716
      ]);
4717
    };
4718
    var forToolbarStateCommand = function (editor, command) {
4719
      var extraBehaviours = getToggleBehaviours(command);
4720
      return forToolbar(command, function () {
4721
        editor.execCommand(command);
4722
      }, extraBehaviours);
4723
    };
4724
    var forToolbarStateAction = function (editor, clazz, command, action) {
4725
      var extraBehaviours = getToggleBehaviours(command);
4726
      return forToolbar(clazz, action, extraBehaviours);
4727
    };
4728
    var forToolbar = function (clazz, action, extraBehaviours) {
4729
      return Button.sketch({
4730
        dom: dom$1('<span class="${prefix}-toolbar-button ${prefix}-icon-' + clazz + ' ${prefix}-icon"></span>'),
4731
        action: action,
4732
        buttonBehaviours: deepMerge(derive$2([Unselecting.config({})]), extraBehaviours)
4733
      });
4734
    };
4735
    var Buttons = {
4736
      forToolbar: forToolbar,
4737
      forToolbarCommand: forToolbarCommand,
4738
      forToolbarStateAction: forToolbarStateAction,
4739
      forToolbarStateCommand: forToolbarStateCommand
4740
    };
4741
4742
    var r = function (left, top) {
4743
      var translate = function (x, y) {
4744
        return r(left + x, top + y);
4745
      };
4746
      return {
4747
        left: constant(left),
4748
        top: constant(top),
4749
        translate: translate
4750
      };
4751
    };
4752
    var Position = r;
4753
4754
    var reduceBy = function (value, min, max, step) {
4755
      if (value < min) {
4756
        return value;
4757
      } else if (value > max) {
4758
        return max;
4759
      } else if (value === min) {
4760
        return min - 1;
4761
      } else {
4762
        return Math.max(min, value - step);
4763
      }
4764
    };
4765
    var increaseBy = function (value, min, max, step) {
4766
      if (value > max) {
4767
        return value;
4768
      } else if (value < min) {
4769
        return min;
4770
      } else if (value === max) {
4771
        return max + 1;
4772
      } else {
4773
        return Math.min(max, value + step);
4774
      }
4775
    };
4776
    var capValue = function (value, min, max) {
4777
      return Math.max(min, Math.min(max, value));
4778
    };
4779
    var snapValueOfX = function (bounds, value, min, max, step, snapStart) {
4780
      return snapStart.fold(function () {
4781
        var initValue = value - min;
4782
        var extraValue = Math.round(initValue / step) * step;
4783
        return capValue(min + extraValue, min - 1, max + 1);
4784
      }, function (start) {
4785
        var remainder = (value - start) % step;
4786
        var adjustment = Math.round(remainder / step);
4787
        var rawSteps = Math.floor((value - start) / step);
4788
        var maxSteps = Math.floor((max - start) / step);
4789
        var numSteps = Math.min(maxSteps, rawSteps + adjustment);
4790
        var r = start + numSteps * step;
4791
        return Math.max(start, r);
4792
      });
4793
    };
4794
    var findValueOfX = function (bounds, min, max, xValue, step, snapToGrid, snapStart) {
4795
      var range = max - min;
4796
      if (xValue < bounds.left) {
4797
        return min - 1;
4798
      } else if (xValue > bounds.right) {
4799
        return max + 1;
4800
      } else {
4801
        var xOffset = Math.min(bounds.right, Math.max(xValue, bounds.left)) - bounds.left;
4802
        var newValue = capValue(xOffset / bounds.width * range + min, min - 1, max + 1);
4803
        var roundedValue = Math.round(newValue);
4804
        return snapToGrid && newValue >= min && newValue <= max ? snapValueOfX(bounds, newValue, min, max, step, snapStart) : roundedValue;
4805
      }
4806
    };
4807
4808
    var _changeEvent = 'slider.change.value';
4809
    var isTouch = PlatformDetection$1.detect().deviceType.isTouch();
4810
    var getEventSource = function (simulatedEvent) {
4811
      var evt = simulatedEvent.event().raw();
4812
      if (isTouch) {
4813
        var touchEvent = evt;
4814
        return touchEvent.touches !== undefined && touchEvent.touches.length === 1 ? Option.some(touchEvent.touches[0]).map(function (t) {
4815
          return Position(t.clientX, t.clientY);
4816
        }) : Option.none();
4817
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
4818
        var mouseEvent = evt;
4819
        return mouseEvent.clientX !== undefined ? Option.some(mouseEvent).map(function (me) {
4820
          return Position(me.clientX, me.clientY);
4821
        }) : Option.none();
4822
      }
4823
    };
4824
    var getEventX = function (simulatedEvent) {
4825
      var spot = getEventSource(simulatedEvent);
4826
      return spot.map(function (s) {
4827
        return s.left();
4828
      });
4829
    };
4830
    var fireChange = function (component, value) {
4831
      emitWith(component, _changeEvent, { value: value });
4832
    };
4833
    var setToRedge = function (redge, detail) {
4834
      fireChange(redge, detail.max() + 1);
4835
    };
4836
    var setToLedge = function (ledge, detail) {
4837
      fireChange(ledge, detail.min() - 1);
4838
    };
4839
    var setToX = function (spectrum, spectrumBounds, detail, xValue) {
4840
      var value = findValueOfX(spectrumBounds, detail.min(), detail.max(), xValue, detail.stepSize(), detail.snapToGrid(), detail.snapStart());
4841
      fireChange(spectrum, value);
4842
    };
4843
    var setXFromEvent = function (spectrum, detail, spectrumBounds, simulatedEvent) {
4844
      return getEventX(simulatedEvent).map(function (xValue) {
4845
        setToX(spectrum, spectrumBounds, detail, xValue);
4846
        return xValue;
4847
      });
4848
    };
4849
    var moveLeft$4 = function (spectrum, detail) {
4850
      var newValue = reduceBy(detail.value().get(), detail.min(), detail.max(), detail.stepSize());
4851
      fireChange(spectrum, newValue);
4852
    };
4853
    var moveRight$4 = function (spectrum, detail) {
4854
      var newValue = increaseBy(detail.value().get(), detail.min(), detail.max(), detail.stepSize());
4855
      fireChange(spectrum, newValue);
4856
    };
4857
    var changeEvent = function () {
4858
      return _changeEvent;
4859
    };
4860
4861
    var platform = PlatformDetection$1.detect();
4862
    var isTouch$1 = platform.deviceType.isTouch();
4863
    var edgePart = function (name, action) {
4864
      return optional({
4865
        name: '' + name + '-edge',
4866
        overrides: function (detail) {
4867
          var touchEvents = derive([runActionExtra(touchstart(), action, [detail])]);
4868
          var mouseEvents = derive([
4869
            runActionExtra(mousedown(), action, [detail]),
4870
            runActionExtra(mousemove(), function (l, det) {
4871
              if (det.mouseIsDown().get()) {
4872
                action(l, det);
4873
              }
4874
            }, [detail])
4875
          ]);
4876
          return { events: isTouch$1 ? touchEvents : mouseEvents };
4877
        }
4878
      });
4879
    };
4880
    var ledgePart = edgePart('left', setToLedge);
4881
    var redgePart = edgePart('right', setToRedge);
4882
    var thumbPart = required({
4883
      name: 'thumb',
4884
      defaults: constant({ dom: { styles: { position: 'absolute' } } }),
4885
      overrides: function (detail) {
4886
        return {
4887
          events: derive([
4888
            redirectToPart(touchstart(), detail, 'spectrum'),
4889
            redirectToPart(touchmove(), detail, 'spectrum'),
4890
            redirectToPart(touchend(), detail, 'spectrum')
4891
          ])
4892
        };
4893
      }
4894
    });
4895
    var spectrumPart = required({
4896
      schema: [state$1('mouseIsDown', function () {
4897
          return Cell(false);
4898
        })],
4899
      name: 'spectrum',
4900
      overrides: function (detail) {
4901
        var moveToX = function (spectrum, simulatedEvent) {
4902
          var domElem = spectrum.element().dom();
4903
          var spectrumBounds = domElem.getBoundingClientRect();
4904
          setXFromEvent(spectrum, detail, spectrumBounds, simulatedEvent);
4905
        };
4906
        var touchEvents = derive([
4907
          run(touchstart(), moveToX),
4908
          run(touchmove(), moveToX)
4909
        ]);
4910
        var mouseEvents = derive([
4911
          run(mousedown(), moveToX),
4912
          run(mousemove(), function (spectrum, se) {
4913
            if (detail.mouseIsDown().get()) {
4914
              moveToX(spectrum, se);
4915
            }
4916
          })
4917
        ]);
4918
        return {
4919
          behaviours: derive$2(isTouch$1 ? [] : [
4920
            Keying.config({
4921
              mode: 'special',
4922
              onLeft: function (spectrum) {
4923
                moveLeft$4(spectrum, detail);
4924
                return Option.some(true);
4925
              },
4926
              onRight: function (spectrum) {
4927
                moveRight$4(spectrum, detail);
4928
                return Option.some(true);
4929
              }
4930
            }),
4931
            Focusing.config({})
4932
          ]),
4933
          events: isTouch$1 ? touchEvents : mouseEvents
4934
        };
4935
      }
4936
    });
4937
    var SliderParts = [
4938
      ledgePart,
4939
      redgePart,
4940
      thumbPart,
4941
      spectrumPart
4942
    ];
4943
4944
    var onLoad$1 = function (component, repConfig, repState) {
4945
      repConfig.store().manager().onLoad(component, repConfig, repState);
4946
    };
4947
    var onUnload = function (component, repConfig, repState) {
4948
      repConfig.store().manager().onUnload(component, repConfig, repState);
4949
    };
4950
    var setValue = function (component, repConfig, repState, data) {
4951
      repConfig.store().manager().setValue(component, repConfig, repState, data);
4952
    };
4953
    var getValue = function (component, repConfig, repState) {
4954
      return repConfig.store().manager().getValue(component, repConfig, repState);
4955
    };
4956
4957
    var RepresentApis = /*#__PURE__*/Object.freeze({
4958
        onLoad: onLoad$1,
4959
        onUnload: onUnload,
4960
        setValue: setValue,
4961
        getValue: getValue
4962
    });
4963
4964
    var events$5 = function (repConfig, repState) {
4965
      var es = repConfig.resetOnDom() ? [
4966
        runOnAttached(function (comp, se) {
4967
          onLoad$1(comp, repConfig, repState);
4968
        }),
4969
        runOnDetached(function (comp, se) {
4970
          onUnload(comp, repConfig, repState);
4971
        })
4972
      ] : [loadEvent(repConfig, repState, onLoad$1)];
4973
      return derive(es);
4974
    };
4975
4976
    var ActiveRepresenting = /*#__PURE__*/Object.freeze({
4977
        events: events$5
4978
    });
4979
4980
    var memory = function () {
4981
      var data = Cell(null);
4982
      var readState = function () {
4983
        return {
4984
          mode: 'memory',
4985
          value: data.get()
4986
        };
4987
      };
4988
      var isNotSet = function () {
4989
        return data.get() === null;
4990
      };
4991
      var clear = function () {
4992
        data.set(null);
4993
      };
4994
      return nu$7({
4995
        set: data.set,
4996
        get: data.get,
4997
        isNotSet: isNotSet,
4998
        clear: clear,
4999
        readState: readState
5000
      });
5001
    };
5002
    var manual = function () {
5003
      var readState = function () {
5004
      };
5005
      return nu$7({ readState: readState });
5006
    };
5007
    var dataset = function () {
5008
      var data = Cell({});
5009
      var readState = function () {
5010
        return {
5011
          mode: 'dataset',
5012
          dataset: data.get()
5013
        };
5014
      };
5015
      return nu$7({
5016
        readState: readState,
5017
        set: data.set,
5018
        get: data.get
5019
      });
5020
    };
5021
    var init$1 = function (spec) {
5022
      return spec.store().manager().state(spec);
5023
    };
5024
5025
    var RepresentState = /*#__PURE__*/Object.freeze({
5026
        memory: memory,
5027
        dataset: dataset,
5028
        manual: manual,
5029
        init: init$1
5030
    });
5031
5032
    var setValue$1 = function (component, repConfig, repState, data) {
5033
      var dataKey = repConfig.store().getDataKey();
5034
      repState.set({});
5035
      repConfig.store().setData()(component, data);
5036
      repConfig.onSetValue()(component, data);
5037
    };
5038
    var getValue$1 = function (component, repConfig, repState) {
5039
      var key = repConfig.store().getDataKey()(component);
5040
      var dataset$$1 = repState.get();
5041
      return readOptFrom$1(dataset$$1, key).fold(function () {
5042
        return repConfig.store().getFallbackEntry()(key);
5043
      }, function (data) {
5044
        return data;
5045
      });
5046
    };
5047
    var onLoad$2 = function (component, repConfig, repState) {
5048
      repConfig.store().initialValue().each(function (data) {
5049
        setValue$1(component, repConfig, repState, data);
5050
      });
5051
    };
5052
    var onUnload$1 = function (component, repConfig, repState) {
5053
      repState.set({});
5054
    };
5055
    var DatasetStore = [
5056
      option('initialValue'),
5057
      strict$1('getFallbackEntry'),
5058
      strict$1('getDataKey'),
5059
      strict$1('setData'),
5060
      output$1('manager', {
5061
        setValue: setValue$1,
5062
        getValue: getValue$1,
5063
        onLoad: onLoad$2,
5064
        onUnload: onUnload$1,
5065
        state: dataset
5066
      })
5067
    ];
5068
5069
    var getValue$2 = function (component, repConfig, repState) {
5070
      return repConfig.store().getValue()(component);
5071
    };
5072
    var setValue$2 = function (component, repConfig, repState, data) {
5073
      repConfig.store().setValue()(component, data);
5074
      repConfig.onSetValue()(component, data);
5075
    };
5076
    var onLoad$3 = function (component, repConfig, repState) {
5077
      repConfig.store().initialValue().each(function (data) {
5078
        repConfig.store().setValue()(component, data);
5079
      });
5080
    };
5081
    var ManualStore = [
5082
      strict$1('getValue'),
5083
      defaulted$1('setValue', noop),
5084
      option('initialValue'),
5085
      output$1('manager', {
5086
        setValue: setValue$2,
5087
        getValue: getValue$2,
5088
        onLoad: onLoad$3,
5089
        onUnload: noop,
5090
        state: NoState.init
5091
      })
5092
    ];
5093
5094
    var setValue$3 = function (component, repConfig, repState, data) {
5095
      repState.set(data);
5096
      repConfig.onSetValue()(component, data);
5097
    };
5098
    var getValue$3 = function (component, repConfig, repState) {
5099
      return repState.get();
5100
    };
5101
    var onLoad$4 = function (component, repConfig, repState) {
5102
      repConfig.store().initialValue().each(function (initVal) {
5103
        if (repState.isNotSet()) {
5104
          repState.set(initVal);
5105
        }
5106
      });
5107
    };
5108
    var onUnload$2 = function (component, repConfig, repState) {
5109
      repState.clear();
5110
    };
5111
    var MemoryStore = [
5112
      option('initialValue'),
5113
      output$1('manager', {
5114
        setValue: setValue$3,
5115
        getValue: getValue$3,
5116
        onLoad: onLoad$4,
5117
        onUnload: onUnload$2,
5118
        state: memory
5119
      })
5120
    ];
5121
5122
    var RepresentSchema = [
5123
      defaultedOf('store', { mode: 'memory' }, choose$1('mode', {
5124
        memory: MemoryStore,
5125
        manual: ManualStore,
5126
        dataset: DatasetStore
5127
      })),
5128
      onHandler('onSetValue'),
5129
      defaulted$1('resetOnDom', false)
5130
    ];
5131
5132
    var Representing = create$1({
5133
      fields: RepresentSchema,
5134
      name: 'representing',
5135
      active: ActiveRepresenting,
5136
      apis: RepresentApis,
5137
      extra: {
5138
        setValueFrom: function (component, source) {
5139
          var value = Representing.getValue(source);
5140
          Representing.setValue(component, value);
5141
        }
5142
      },
5143
      state: RepresentState
5144
    });
5145
5146
    var isTouch$2 = PlatformDetection$1.detect().deviceType.isTouch();
5147
    var SliderSchema = [
5148
      strict$1('min'),
5149
      strict$1('max'),
5150
      defaulted$1('stepSize', 1),
5151
      defaulted$1('onChange', noop),
5152
      defaulted$1('onInit', noop),
5153
      defaulted$1('onDragStart', noop),
5154
      defaulted$1('onDragEnd', noop),
5155
      defaulted$1('snapToGrid', false),
5156
      option('snapStart'),
5157
      strict$1('getInitialValue'),
5158
      field$1('sliderBehaviours', [
5159
        Keying,
5160
        Representing
5161
      ]),
5162
      state$1('value', function (spec) {
5163
        return Cell(spec.min);
5164
      })
5165
    ].concat(!isTouch$2 ? [state$1('mouseIsDown', function () {
5166
        return Cell(false);
5167
      })] : []);
5168
5169
    var api$1 = Dimension('width', function (element) {
5170
      return element.dom().offsetWidth;
5171
    });
5172
    var set$4 = function (element, h) {
5173
      api$1.set(element, h);
5174
    };
5175
    var get$7 = function (element) {
5176
      return api$1.get(element);
5177
    };
5178
5179
    var isTouch$3 = PlatformDetection$1.detect().deviceType.isTouch();
5180
    var sketch$1 = function (detail, components$$1, spec, externals) {
5181
      var range$$1 = detail.max() - detail.min();
5182
      var getXCentre = function (component) {
5183
        var rect = component.element().dom().getBoundingClientRect();
5184
        return (rect.left + rect.right) / 2;
5185
      };
5186
      var getThumb = function (component) {
5187
        return getPartOrDie(component, detail, 'thumb');
5188
      };
5189
      var getXOffset = function (slider, spectrumBounds, detail) {
5190
        var v = detail.value().get();
5191
        if (v < detail.min()) {
5192
          return getPart(slider, detail, 'left-edge').fold(function () {
5193
            return 0;
5194
          }, function (ledge) {
5195
            return getXCentre(ledge) - spectrumBounds.left;
5196
          });
5197
        } else if (v > detail.max()) {
5198
          return getPart(slider, detail, 'right-edge').fold(function () {
5199
            return spectrumBounds.width;
5200
          }, function (redge) {
5201
            return getXCentre(redge) - spectrumBounds.left;
5202
          });
5203
        } else {
5204
          return (detail.value().get() - detail.min()) / range$$1 * spectrumBounds.width;
5205
        }
5206
      };
5207
      var getXPos = function (slider) {
5208
        var spectrum = getPartOrDie(slider, detail, 'spectrum');
5209
        var spectrumBounds = spectrum.element().dom().getBoundingClientRect();
5210
        var sliderBounds = slider.element().dom().getBoundingClientRect();
5211
        var xOffset = getXOffset(slider, spectrumBounds, detail);
5212
        return spectrumBounds.left - sliderBounds.left + xOffset;
5213
      };
5214
      var refresh = function (component) {
5215
        var pos = getXPos(component);
5216
        var thumb = getThumb(component);
5217
        var thumbRadius = get$7(thumb.element()) / 2;
5218
        set$2(thumb.element(), 'left', pos - thumbRadius + 'px');
5219
      };
5220
      var changeValue = function (component, newValue) {
5221
        var oldValue = detail.value().get();
5222
        var thumb = getThumb(component);
5223
        if (oldValue !== newValue || getRaw(thumb.element(), 'left').isNone()) {
5224
          detail.value().set(newValue);
5225
          refresh(component);
5226
          detail.onChange()(component, thumb, newValue);
5227
          return Option.some(true);
5228
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
5229
          return Option.none();
5230
        }
5231
      };
5232
      var resetToMin = function (slider) {
5233
        changeValue(slider, detail.min());
5234
      };
5235
      var resetToMax = function (slider) {
5236
        changeValue(slider, detail.max());
5237
      };
5238
      var uiEventsArr = isTouch$3 ? [
5239
        run(touchstart(), function (slider, simulatedEvent) {
5240
          detail.onDragStart()(slider, getThumb(slider));
5241
        }),
5242
        run(touchend(), function (slider, simulatedEvent) {
5243
          detail.onDragEnd()(slider, getThumb(slider));
5244
        })
5245
      ] : [
5246
        run(mousedown(), function (slider, simulatedEvent) {
5247
          simulatedEvent.stop();
5248
          detail.onDragStart()(slider, getThumb(slider));
5249
          detail.mouseIsDown().set(true);
5250
        }),
5251
        run(mouseup(), function (slider, simulatedEvent) {
5252
          detail.onDragEnd()(slider, getThumb(slider));
5253
          detail.mouseIsDown().set(false);
5254
        })
5255
      ];
5256
      return {
5257
        uid: detail.uid(),
5258
        dom: detail.dom(),
5259
        components: components$$1,
5260
        behaviours: deepMerge(derive$2(flatten([
5261
          !isTouch$3 ? [Keying.config({
5262
              mode: 'special',
5263
              focusIn: function (slider) {
5264
                return getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(constant(true));
5265
              }
5266
            })] : [],
5267
          [Representing.config({
5268
              store: {
5269
                mode: 'manual',
5270
                getValue: function (_) {
5271
                  return detail.value().get();
5272
                }
5273
              }
5274
            })]
5275
        ])), get$6(detail.sliderBehaviours())),
5276
        events: derive([
5277
          run(changeEvent(), function (slider, simulatedEvent) {
5278
            changeValue(slider, simulatedEvent.event().value());
5279
          }),
5280
          runOnAttached(function (slider, simulatedEvent) {
5281
            detail.value().set(detail.getInitialValue()());
5282
            var thumb = getThumb(slider);
5283
            refresh(slider);
5284
            detail.onInit()(slider, thumb, detail.value().get());
5285
          })
5286
        ].concat(uiEventsArr)),
5287
        apis: {
5288
          resetToMin: resetToMin,
5289
          resetToMax: resetToMax,
5290
          refresh: refresh
5291
        },
5292
        domModification: { styles: { position: 'relative' } }
5293
      };
5294
    };
5295
5296
    var Slider = composite$1({
5297
      name: 'Slider',
5298
      configFields: SliderSchema,
5299
      partFields: SliderParts,
5300
      factory: sketch$1,
5301
      apis: {
5302
        resetToMin: function (apis, slider) {
5303
          apis.resetToMin(slider);
5304
        },
5305
        resetToMax: function (apis, slider) {
5306
          apis.resetToMax(slider);
5307
        },
5308
        refresh: function (apis, slider) {
5309
          apis.refresh(slider);
5310
        }
5311
      }
5312
    });
5313
5314
    var button = function (realm, clazz, makeItems) {
5315
      return Buttons.forToolbar(clazz, function () {
5316
        var items = makeItems();
5317
        realm.setContextToolbar([{
5318
            label: clazz + ' group',
5319
            items: items
5320
          }]);
5321
      }, {});
5322
    };
5323
5324
    var BLACK = -1;
5325
    var makeSlider = function (spec$$1) {
5326
      var getColor = function (hue) {
5327
        if (hue < 0) {
5328
          return 'black';
5329
        } else if (hue > 360) {
5330
          return 'white';
5331
        } else {
5332
          return 'hsl(' + hue + ', 100%, 50%)';
5333
        }
5334
      };
5335
      var onInit = function (slider, thumb, value) {
5336
        var color = getColor(value);
5337
        set$2(thumb.element(), 'background-color', color);
5338
      };
5339
      var onChange = function (slider, thumb, value) {
5340
        var color = getColor(value);
5341
        set$2(thumb.element(), 'background-color', color);
5342
        spec$$1.onChange(slider, thumb, color);
5343
      };
5344
      return Slider.sketch({
5345
        dom: dom$1('<div class="${prefix}-slider ${prefix}-hue-slider-container"></div>'),
5346
        components: [
5347
          Slider.parts()['left-edge'](spec('<div class="${prefix}-hue-slider-black"></div>')),
5348
          Slider.parts().spectrum({
5349
            dom: dom$1('<div class="${prefix}-slider-gradient-container"></div>'),
5350
            components: [spec('<div class="${prefix}-slider-gradient"></div>')],
5351
            behaviours: derive$2([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
5352
          }),
5353
          Slider.parts()['right-edge'](spec('<div class="${prefix}-hue-slider-white"></div>')),
5354
          Slider.parts().thumb({
5355
            dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
5356
            behaviours: derive$2([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
5357
          })
5358
        ],
5359
        onChange: onChange,
5360
        onDragStart: function (slider, thumb) {
5361
          Toggling.on(thumb);
5362
        },
5363
        onDragEnd: function (slider, thumb) {
5364
          Toggling.off(thumb);
5365
        },
5366
        onInit: onInit,
5367
        stepSize: 10,
5368
        min: 0,
5369
        max: 360,
5370
        getInitialValue: spec$$1.getInitialValue,
5371
        sliderBehaviours: derive$2([Receivers.orientation(Slider.refresh)])
5372
      });
5373
    };
5374
    var makeItems = function (spec$$1) {
5375
      return [makeSlider(spec$$1)];
5376
    };
5377
    var sketch$2 = function (realm, editor) {
5378
      var spec$$1 = {
5379
        onChange: function (slider, thumb, color) {
5380
          editor.undoManager.transact(function () {
5381
            editor.formatter.apply('forecolor', { value: color });
5382
            editor.nodeChanged();
5383
          });
5384
        },
5385
        getInitialValue: function () {
5386
          return BLACK;
5387
        }
5388
      };
5389
      return button(realm, 'color', function () {
5390
        return makeItems(spec$$1);
5391
      });
5392
    };
5393
    var ColorSlider = {
5394
      makeItems: makeItems,
5395
      sketch: sketch$2
5396
    };
5397
5398
    var schema$7 = objOfOnly([
5399
      strict$1('getInitialValue'),
5400
      strict$1('onChange'),
5401
      strict$1('category'),
5402
      strict$1('sizes')
5403
    ]);
5404
    var sketch$3 = function (rawSpec) {
5405
      var spec$$1 = asRawOrDie('SizeSlider', schema$7, rawSpec);
5406
      var isValidValue = function (valueIndex) {
5407
        return valueIndex >= 0 && valueIndex < spec$$1.sizes.length;
5408
      };
5409
      var onChange = function (slider, thumb, valueIndex) {
5410
        if (isValidValue(valueIndex)) {
5411
          spec$$1.onChange(valueIndex);
5412
        }
5413
      };
5414
      return Slider.sketch({
5415
        dom: {
5416
          tag: 'div',
5417
          classes: [
5418
            Styles.resolve('slider-' + spec$$1.category + '-size-container'),
5419
            Styles.resolve('slider'),
5420
            Styles.resolve('slider-size-container')
5421
          ]
5422
        },
5423
        onChange: onChange,
5424
        onDragStart: function (slider, thumb) {
5425
          Toggling.on(thumb);
5426
        },
5427
        onDragEnd: function (slider, thumb) {
5428
          Toggling.off(thumb);
5429
        },
5430
        min: 0,
5431
        max: spec$$1.sizes.length - 1,
5432
        stepSize: 1,
5433
        getInitialValue: spec$$1.getInitialValue,
5434
        snapToGrid: true,
5435
        sliderBehaviours: derive$2([Receivers.orientation(Slider.refresh)]),
5436
        components: [
5437
          Slider.parts().spectrum({
5438
            dom: dom$1('<div class="${prefix}-slider-size-container"></div>'),
5439
            components: [spec('<div class="${prefix}-slider-size-line"></div>')]
5440
          }),
5441
          Slider.parts().thumb({
5442
            dom: dom$1('<div class="${prefix}-slider-thumb"></div>'),
5443
            behaviours: derive$2([Toggling.config({ toggleClass: Styles.resolve('thumb-active') })])
5444
          })
5445
        ]
5446
      });
5447
    };
5448
    var SizeSlider = { sketch: sketch$3 };
5449
5450
    var candidates = [
5451
      '9px',
5452
      '10px',
5453
      '11px',
5454
      '12px',
5455
      '14px',
5456
      '16px',
5457
      '18px',
5458
      '20px',
5459
      '24px',
5460
      '32px',
5461
      '36px'
5462
    ];
5463
    var defaultSize = 'medium';
5464
    var defaultIndex = 2;
5465
    var indexToSize = function (index) {
5466
      return Option.from(candidates[index]);
5467
    };
5468
    var sizeToIndex = function (size) {
5469
      return findIndex(candidates, function (v) {
5470
        return v === size;
5471
      });
5472
    };
5473
    var getRawOrComputed = function (isRoot, rawStart) {
5474
      var optStart = isElement(rawStart) ? Option.some(rawStart) : parent(rawStart);
5475
      return optStart.map(function (start) {
5476
        var inline = closest(start, function (elem) {
5477
          return getRaw(elem, 'font-size').isSome();
5478
        }, isRoot).bind(function (elem) {
5479
          return getRaw(elem, 'font-size');
5480
        });
5481
        return inline.getOrThunk(function () {
5482
          return get$4(start, 'font-size');
5483
        });
5484
      }).getOr('');
5485
    };
5486
    var getSize = function (editor) {
5487
      var node = editor.selection.getStart();
5488
      var elem = Element$$1.fromDom(node);
5489
      var root = Element$$1.fromDom(editor.getBody());
5490
      var isRoot = function (e) {
5491
        return eq(root, e);
5492
      };
5493
      var elemSize = getRawOrComputed(isRoot, elem);
5494
      return find$2(candidates, function (size) {
5495
        return elemSize === size;
5496
      }).getOr(defaultSize);
5497
    };
5498
    var applySize = function (editor, value$$1) {
5499
      var currentValue = getSize(editor);
5500
      if (currentValue !== value$$1) {
5501
        editor.execCommand('fontSize', false, value$$1);
5502
      }
5503
    };
5504
    var get$8 = function (editor) {
5505
      var size = getSize(editor);
5506
      return sizeToIndex(size).getOr(defaultIndex);
5507
    };
5508
    var apply$1 = function (editor, index) {
5509
      indexToSize(index).each(function (size) {
5510
        applySize(editor, size);
5511
      });
5512
    };
5513
    var FontSizes = {
5514
      candidates: constant(candidates),
5515
      get: get$8,
5516
      apply: apply$1
5517
    };
5518
5519
    var sizes = FontSizes.candidates();
5520
    var makeSlider$1 = function (spec$$1) {
5521
      return SizeSlider.sketch({
5522
        onChange: spec$$1.onChange,
5523
        sizes: sizes,
5524
        category: 'font',
5525
        getInitialValue: spec$$1.getInitialValue
5526
      });
5527
    };
5528
    var makeItems$1 = function (spec$$1) {
5529
      return [
5530
        spec('<span class="${prefix}-toolbar-button ${prefix}-icon-small-font ${prefix}-icon"></span>'),
5531
        makeSlider$1(spec$$1),
5532
        spec('<span class="${prefix}-toolbar-button ${prefix}-icon-large-font ${prefix}-icon"></span>')
5533
      ];
5534
    };
5535
    var sketch$4 = function (realm, editor) {
5536
      var spec$$1 = {
5537
        onChange: function (value) {
5538
          FontSizes.apply(editor, value);
5539
        },
5540
        getInitialValue: function () {
5541
          return FontSizes.get(editor);
5542
        }
5543
      };
5544
      return button(realm, 'font-size', function () {
5545
        return makeItems$1(spec$$1);
5546
      });
5547
    };
5548
5549
    var record = function (spec) {
5550
      var uid = isSketchSpec(spec) && hasKey$1(spec, 'uid') ? spec.uid : generate$3('memento');
5551
      var get = function (anyInSystem) {
5552
        return anyInSystem.getSystem().getByUid(uid).getOrDie();
5553
      };
5554
      var getOpt = function (anyInSystem) {
5555
        return anyInSystem.getSystem().getByUid(uid).fold(Option.none, Option.some);
5556
      };
5557
      var asSpec = function () {
5558
        return deepMerge(spec, { uid: uid });
5559
      };
5560
      return {
5561
        get: get,
5562
        getOpt: getOpt,
5563
        asSpec: asSpec
5564
      };
5565
    };
5566
5567
    function create$3(width, height) {
5568
      return resize(document.createElement('canvas'), width, height);
5569
    }
5570
    function clone$2(canvas) {
5571
      var tCanvas, ctx;
5572
      tCanvas = create$3(canvas.width, canvas.height);
5573
      ctx = get2dContext(tCanvas);
5574
      ctx.drawImage(canvas, 0, 0);
5575
      return tCanvas;
5576
    }
5577
    function get2dContext(canvas) {
5578
      return canvas.getContext('2d');
5579
    }
5580
    function get3dContext(canvas) {
5581
      var gl = null;
5582
      try {
5583
        gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
5584
      } catch (e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
5585
      }
5586
      if (!gl) {
5587
        gl = null;
5588
      }
5589
      return gl;
5590
    }
5591
    function resize(canvas, width, height) {
5592
      canvas.width = width;
5593
      canvas.height = height;
5594
      return canvas;
5595
    }
5596
    var Canvas = {
5597
      create: create$3,
5598
      clone: clone$2,
5599
      resize: resize,
5600
      get2dContext: get2dContext,
5601
      get3dContext: get3dContext
5602
    };
5603
5604
    function getWidth(image) {
5605
      return image.naturalWidth || image.width;
5606
    }
5607
    function getHeight(image) {
5608
      return image.naturalHeight || image.height;
5609
    }
5610
    var ImageSize = {
5611
      getWidth: getWidth,
5612
      getHeight: getHeight
5613
    };
5614
5615 View Code Duplication
    var promise = function () {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5616
      var Promise = function (fn) {
5617
        if (typeof this !== 'object')
5618
          throw new TypeError('Promises must be constructed via new');
5619
        if (typeof fn !== 'function')
5620
          throw new TypeError('not a function');
5621
        this._state = null;
5622
        this._value = null;
5623
        this._deferreds = [];
5624
        doResolve(fn, bind(resolve, this), bind(reject, this));
5625
      };
5626
      var asap = Promise.immediateFn || typeof window.setImmediate === 'function' && window.setImmediate || function (fn) {
5627
        setTimeout(fn, 1);
5628
      };
5629
      function bind(fn, thisArg) {
5630
        return function () {
5631
          fn.apply(thisArg, arguments);
5632
        };
5633
      }
5634
      var isArray = Array.isArray || function (value) {
5635
        return Object.prototype.toString.call(value) === '[object Array]';
5636
      };
5637
      function handle(deferred) {
5638
        var me = this;
5639
        if (this._state === null) {
5640
          this._deferreds.push(deferred);
5641
          return;
5642
        }
5643
        asap(function () {
5644
          var cb = me._state ? deferred.onFulfilled : deferred.onRejected;
5645
          if (cb === null) {
5646
            (me._state ? deferred.resolve : deferred.reject)(me._value);
5647
            return;
5648
          }
5649
          var ret;
5650
          try {
5651
            ret = cb(me._value);
5652
          } catch (e) {
5653
            deferred.reject(e);
5654
            return;
5655
          }
5656
          deferred.resolve(ret);
5657
        });
5658
      }
5659
      function resolve(newValue) {
5660
        try {
5661
          if (newValue === this)
5662
            throw new TypeError('A promise cannot be resolved with itself.');
5663
          if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
5664
            var then = newValue.then;
5665
            if (typeof then === 'function') {
5666
              doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
5667
              return;
5668
            }
5669
          }
5670
          this._state = true;
5671
          this._value = newValue;
5672
          finale.call(this);
5673
        } catch (e) {
5674
          reject.call(this, e);
5675
        }
5676
      }
5677
      function reject(newValue) {
5678
        this._state = false;
5679
        this._value = newValue;
5680
        finale.call(this);
5681
      }
5682
      function finale() {
5683
        for (var i = 0, len = this._deferreds.length; i < len; i++) {
5684
          handle.call(this, this._deferreds[i]);
5685
        }
5686
        this._deferreds = null;
5687
      }
5688
      function Handler(onFulfilled, onRejected, resolve, reject) {
5689
        this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
5690
        this.onRejected = typeof onRejected === 'function' ? onRejected : null;
5691
        this.resolve = resolve;
5692
        this.reject = reject;
5693
      }
5694
      function doResolve(fn, onFulfilled, onRejected) {
5695
        var done = false;
5696
        try {
5697
          fn(function (value) {
5698
            if (done)
5699
              return;
5700
            done = true;
5701
            onFulfilled(value);
5702
          }, function (reason) {
5703
            if (done)
5704
              return;
5705
            done = true;
5706
            onRejected(reason);
5707
          });
5708
        } catch (ex) {
5709
          if (done)
5710
            return;
5711
          done = true;
5712
          onRejected(ex);
5713
        }
5714
      }
5715
      Promise.prototype['catch'] = function (onRejected) {
5716
        return this.then(null, onRejected);
5717
      };
5718
      Promise.prototype.then = function (onFulfilled, onRejected) {
5719
        var me = this;
5720
        return new Promise(function (resolve, reject) {
5721
          handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
5722
        });
5723
      };
5724
      Promise.all = function () {
5725
        var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
5726
        return new Promise(function (resolve, reject) {
5727
          if (args.length === 0)
5728
            return resolve([]);
5729
          var remaining = args.length;
5730
          function res(i, val) {
5731
            try {
5732
              if (val && (typeof val === 'object' || typeof val === 'function')) {
5733
                var then = val.then;
5734
                if (typeof then === 'function') {
5735
                  then.call(val, function (val) {
5736
                    res(i, val);
5737
                  }, reject);
5738
                  return;
5739
                }
5740
              }
5741
              args[i] = val;
5742
              if (--remaining === 0) {
5743
                resolve(args);
5744
              }
5745
            } catch (ex) {
5746
              reject(ex);
5747
            }
5748
          }
5749
          for (var i = 0; i < args.length; i++) {
5750
            res(i, args[i]);
5751
          }
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
5752
        });
5753
      };
5754
      Promise.resolve = function (value) {
5755
        if (value && typeof value === 'object' && value.constructor === Promise) {
5756
          return value;
5757
        }
5758
        return new Promise(function (resolve) {
5759
          resolve(value);
5760
        });
5761
      };
5762
      Promise.reject = function (value) {
5763
        return new Promise(function (resolve, reject) {
5764
          reject(value);
5765
        });
5766
      };
5767
      Promise.race = function (values) {
5768
        return new Promise(function (resolve, reject) {
5769
          for (var i = 0, len = values.length; i < len; i++) {
5770
            values[i].then(resolve, reject);
5771
          }
5772
        });
5773
      };
5774
      return Promise;
5775
    };
5776
    var Promise = window.Promise ? window.Promise : promise();
5777
5778
    function Blob (parts, properties) {
5779
      var f = Global$1.getOrDie('Blob');
5780
      return new f(parts, properties);
5781
    }
5782
5783
    function FileReader () {
5784
      var f = Global$1.getOrDie('FileReader');
5785
      return new f();
5786
    }
5787
5788
    function Uint8Array (arr) {
5789
      var f = Global$1.getOrDie('Uint8Array');
5790
      return new f(arr);
5791
    }
5792
5793
    var requestAnimationFrame = function (callback) {
5794
      var f = Global$1.getOrDie('requestAnimationFrame');
5795
      f(callback);
5796
    };
5797
    var atob = function (base64) {
5798
      var f = Global$1.getOrDie('atob');
5799
      return f(base64);
5800
    };
5801
    var Window = {
5802
      atob: atob,
5803
      requestAnimationFrame: requestAnimationFrame
5804
    };
5805
5806
    function imageToBlob(image) {
5807
      var src = image.src;
5808
      if (src.indexOf('data:') === 0) {
5809
        return dataUriToBlob(src);
5810
      }
5811
      return anyUriToBlob(src);
5812
    }
5813 View Code Duplication
    function blobToImage(blob) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5814
      return new Promise(function (resolve, reject) {
5815
        var blobUrl = URL.createObjectURL(blob);
5816
        var image = new Image();
5817
        var removeListeners = function () {
5818
          image.removeEventListener('load', loaded);
5819
          image.removeEventListener('error', error);
5820
        };
5821
        function loaded() {
5822
          removeListeners();
5823
          resolve(image);
5824
        }
5825
        function error() {
5826
          removeListeners();
5827
          reject('Unable to load data of type ' + blob.type + ': ' + blobUrl);
5828
        }
5829
        image.addEventListener('load', loaded);
5830
        image.addEventListener('error', error);
5831
        image.src = blobUrl;
5832
        if (image.complete) {
5833
          loaded();
5834
        }
5835
      });
5836
    }
5837 View Code Duplication
    function anyUriToBlob(url) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5838
      return new Promise(function (resolve, reject) {
5839
        var xhr = new XMLHttpRequest();
5840
        xhr.open('GET', url, true);
5841
        xhr.responseType = 'blob';
5842
        xhr.onload = function () {
5843
          if (this.status == 200) {
5844
            resolve(this.response);
5845
          }
5846
        };
5847
        xhr.onerror = function () {
5848
          var _this = this;
5849
          var corsError = function () {
5850
            var obj = new Error('No access to download image');
5851
            obj.code = 18;
5852
            obj.name = 'SecurityError';
5853
            return obj;
5854
          };
5855
          var genericError = function () {
5856
            return new Error('Error ' + _this.status + ' downloading image');
5857
          };
5858
          reject(this.status === 0 ? corsError() : genericError());
5859
        };
5860
        xhr.send();
5861
      });
5862
    }
5863 View Code Duplication
    function dataUriToBlobSync(uri) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
5864
      var data = uri.split(',');
5865
      var matches = /data:([^;]+)/.exec(data[0]);
5866
      if (!matches)
5867
        return Option.none();
5868
      var mimetype = matches[1];
5869
      var base64 = data[1];
5870
      var sliceSize = 1024;
5871
      var byteCharacters = Window.atob(base64);
5872
      var bytesLength = byteCharacters.length;
5873
      var slicesCount = Math.ceil(bytesLength / sliceSize);
5874
      var byteArrays = new Array(slicesCount);
5875
      for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
5876
        var begin = sliceIndex * sliceSize;
5877
        var end = Math.min(begin + sliceSize, bytesLength);
5878
        var bytes = new Array(end - begin);
5879
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
5880
          bytes[i] = byteCharacters[offset].charCodeAt(0);
5881
        }
5882
        byteArrays[sliceIndex] = Uint8Array(bytes);
5883
      }
5884
      return Option.some(Blob(byteArrays, { type: mimetype }));
5885
    }
5886
    function dataUriToBlob(uri) {
5887
      return new Promise(function (resolve, reject) {
5888
        dataUriToBlobSync(uri).fold(function () {
5889
          reject('uri is not base64: ' + uri);
5890
        }, resolve);
5891
      });
5892
    }
5893
    function uriToBlob(url) {
5894
      if (url.indexOf('blob:') === 0) {
5895
        return anyUriToBlob(url);
5896
      }
5897
      if (url.indexOf('data:') === 0) {
5898
        return dataUriToBlob(url);
5899
      }
5900
      return null;
5901
    }
5902
    function canvasToBlob(canvas, type, quality) {
5903
      type = type || 'image/png';
5904
      if (HTMLCanvasElement.prototype.toBlob) {
5905
        return new Promise(function (resolve) {
5906
          canvas.toBlob(function (blob) {
5907
            resolve(blob);
5908
          }, type, quality);
5909
        });
5910
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
5911
        return dataUriToBlob(canvas.toDataURL(type, quality));
5912
      }
5913
    }
5914
    function canvasToDataURL(getCanvas, type, quality) {
5915
      type = type || 'image/png';
5916
      return getCanvas.then(function (canvas) {
5917
        return canvas.toDataURL(type, quality);
5918
      });
5919
    }
5920
    function blobToCanvas(blob) {
5921
      return blobToImage(blob).then(function (image) {
5922
        revokeImageUrl(image);
5923
        var context, canvas;
5924
        canvas = Canvas.create(ImageSize.getWidth(image), ImageSize.getHeight(image));
5925
        context = Canvas.get2dContext(canvas);
5926
        context.drawImage(image, 0, 0);
5927
        return canvas;
5928
      });
5929
    }
5930
    function blobToDataUri(blob) {
5931
      return new Promise(function (resolve) {
5932
        var reader = FileReader();
5933
        reader.onloadend = function () {
5934
          resolve(reader.result);
5935
        };
5936
        reader.readAsDataURL(blob);
5937
      });
5938
    }
5939
    function blobToArrayBuffer(blob) {
5940
      return new Promise(function (resolve) {
5941
        var reader = FileReader();
5942
        reader.onloadend = function () {
5943
          resolve(reader.result);
5944
        };
5945
        reader.readAsArrayBuffer(blob);
5946
      });
5947
    }
5948
    function blobToBase64(blob) {
5949
      return blobToDataUri(blob).then(function (dataUri) {
5950
        return dataUri.split(',')[1];
5951
      });
5952
    }
5953
    function revokeImageUrl(image) {
5954
      URL.revokeObjectURL(image.src);
5955
    }
5956
    var Conversions = {
5957
      blobToImage: blobToImage,
5958
      imageToBlob: imageToBlob,
5959
      blobToArrayBuffer: blobToArrayBuffer,
5960
      blobToDataUri: blobToDataUri,
5961
      blobToBase64: blobToBase64,
5962
      dataUriToBlobSync: dataUriToBlobSync,
5963
      canvasToBlob: canvasToBlob,
5964
      canvasToDataURL: canvasToDataURL,
5965
      blobToCanvas: blobToCanvas,
5966
      uriToBlob: uriToBlob
5967
    };
5968
5969
    var blobToImage$1 = function (image) {
5970
      return Conversions.blobToImage(image);
5971
    };
5972
    var imageToBlob$1 = function (blob) {
5973
      return Conversions.imageToBlob(blob);
5974
    };
5975
    var blobToDataUri$1 = function (blob) {
5976
      return Conversions.blobToDataUri(blob);
5977
    };
5978
    var blobToBase64$1 = function (blob) {
5979
      return Conversions.blobToBase64(blob);
5980
    };
5981
    var dataUriToBlobSync$1 = function (uri) {
5982
      return Conversions.dataUriToBlobSync(uri);
5983
    };
5984
    var uriToBlob$1 = function (uri) {
5985
      return Option.from(Conversions.uriToBlob(uri));
5986
    };
5987
    var BlobConversions = {
5988
      blobToImage: blobToImage$1,
5989
      imageToBlob: imageToBlob$1,
5990
      blobToDataUri: blobToDataUri$1,
5991
      blobToBase64: blobToBase64$1,
5992
      dataUriToBlobSync: dataUriToBlobSync$1,
5993
      uriToBlob: uriToBlob$1
5994
    };
5995
5996
    var addImage = function (editor, blob) {
5997
      BlobConversions.blobToBase64(blob).then(function (base64) {
5998
        editor.undoManager.transact(function () {
5999
          var cache = editor.editorUpload.blobCache;
6000
          var info = cache.create(generate$1('mceu'), blob, base64);
6001
          cache.add(info);
6002
          var img = editor.dom.createHTML('img', { src: info.blobUri() });
6003
          editor.insertContent(img);
6004
        });
6005
      });
6006
    };
6007
    var extractBlob = function (simulatedEvent) {
6008
      var event = simulatedEvent.event();
6009
      var files = event.raw().target.files || event.raw().dataTransfer.files;
6010
      return Option.from(files[0]);
6011
    };
6012
    var sketch$5 = function (editor) {
6013
      var pickerDom = {
6014
        tag: 'input',
6015
        attributes: {
6016
          accept: 'image/*',
6017
          type: 'file',
6018
          title: ''
6019
        },
6020
        styles: {
6021
          visibility: 'hidden',
6022
          position: 'absolute'
6023
        }
6024
      };
6025
      var memPicker = record({
6026
        dom: pickerDom,
6027
        events: derive([
6028
          cutter(click()),
6029
          run(change(), function (picker, simulatedEvent) {
6030
            extractBlob(simulatedEvent).each(function (blob) {
6031
              addImage(editor, blob);
6032
            });
6033
          })
6034
        ])
6035
      });
6036
      return Button.sketch({
6037
        dom: dom$1('<span class="${prefix}-toolbar-button ${prefix}-icon-image ${prefix}-icon"></span>'),
6038
        components: [memPicker.asSpec()],
6039
        action: function (button) {
6040
          var picker = memPicker.get(button);
6041
          picker.element().dom().click();
6042
        }
6043
      });
6044
    };
6045
6046
    var get$9 = function (element) {
6047
      return element.dom().textContent;
6048
    };
6049
    var set$5 = function (element, value) {
6050
      element.dom().textContent = value;
6051
    };
6052
6053
    var isNotEmpty = function (val) {
6054
      return val.length > 0;
6055
    };
6056
    var defaultToEmpty = function (str) {
6057
      return str === undefined || str === null ? '' : str;
6058
    };
6059
    var noLink = function (editor) {
6060
      var text = editor.selection.getContent({ format: 'text' });
6061
      return {
6062
        url: '',
6063
        text: text,
6064
        title: '',
6065
        target: '',
6066
        link: Option.none()
6067
      };
6068
    };
6069
    var fromLink = function (link) {
6070
      var text = get$9(link);
6071
      var url = get$1(link, 'href');
6072
      var title = get$1(link, 'title');
6073
      var target = get$1(link, 'target');
6074
      return {
6075
        url: defaultToEmpty(url),
6076
        text: text !== url ? defaultToEmpty(text) : '',
6077
        title: defaultToEmpty(title),
6078
        target: defaultToEmpty(target),
6079
        link: Option.some(link)
6080
      };
6081
    };
6082
    var getInfo = function (editor) {
6083
      return query(editor).fold(function () {
6084
        return noLink(editor);
6085
      }, function (link) {
6086
        return fromLink(link);
6087
      });
6088
    };
6089
    var wasSimple = function (link) {
6090
      var prevHref = get$1(link, 'href');
6091
      var prevText = get$9(link);
6092
      return prevHref === prevText;
6093
    };
6094
    var getTextToApply = function (link, url, info) {
6095
      return info.text.filter(isNotEmpty).fold(function () {
6096
        return wasSimple(link) ? Option.some(url) : Option.none();
6097
      }, Option.some);
6098
    };
6099
    var unlinkIfRequired = function (editor, info) {
6100
      var activeLink = info.link.bind(identity);
6101
      activeLink.each(function (link) {
6102
        editor.execCommand('unlink');
6103
      });
6104
    };
6105
    var getAttrs$1 = function (url, info) {
6106
      var attrs = {};
6107
      attrs.href = url;
6108
      info.title.filter(isNotEmpty).each(function (title) {
6109
        attrs.title = title;
6110
      });
6111
      info.target.filter(isNotEmpty).each(function (target) {
6112
        attrs.target = target;
6113
      });
6114
      return attrs;
6115
    };
6116
    var applyInfo = function (editor, info) {
6117
      info.url.filter(isNotEmpty).fold(function () {
6118
        unlinkIfRequired(editor, info);
6119
      }, function (url) {
6120
        var attrs = getAttrs$1(url, info);
6121
        var activeLink = info.link.bind(identity);
6122
        activeLink.fold(function () {
6123
          var text = info.text.filter(isNotEmpty).getOr(url);
6124
          editor.insertContent(editor.dom.createHTML('a', attrs, editor.dom.encode(text)));
6125
        }, function (link) {
6126
          var text = getTextToApply(link, url, info);
6127
          setAll(link, attrs);
6128
          text.each(function (newText) {
6129
            set$5(link, newText);
6130
          });
6131
        });
6132
      });
6133
    };
6134
    var query = function (editor) {
6135
      var start = Element$$1.fromDom(editor.selection.getStart());
6136
      return closest$2(start, 'a');
6137
    };
6138
    var LinkBridge = {
6139
      getInfo: getInfo,
6140
      applyInfo: applyInfo,
6141
      query: query
6142
    };
6143
6144
    var platform$1 = PlatformDetection$1.detect();
6145
    var preserve$1 = function (f, editor) {
6146
      var rng = editor.selection.getRng();
6147
      f();
6148
      editor.selection.setRng(rng);
6149
    };
6150
    var forAndroid = function (editor, f) {
6151
      var wrapper = platform$1.os.isAndroid() ? preserve$1 : apply;
6152
      wrapper(f, editor);
6153
    };
6154
    var RangePreserver = { forAndroid: forAndroid };
6155
6156
    var events$6 = function (name, eventHandlers) {
6157
      var events = derive(eventHandlers);
6158
      return create$1({
6159
        fields: [strict$1('enabled')],
6160
        name: name,
6161
        active: { events: constant(events) }
6162
      });
6163
    };
6164
    var config = function (name, eventHandlers) {
6165
      var me = events$6(name, eventHandlers);
6166
      return {
6167
        key: name,
6168
        value: {
6169
          config: {},
6170
          me: me,
6171
          configAsRaw: constant({}),
6172
          initialConfig: {},
6173
          state: NoState
6174
        }
6175
      };
6176
    };
6177
6178
    var getCurrent = function (component, composeConfig, composeState) {
6179
      return composeConfig.find()(component);
6180
    };
6181
6182
    var ComposeApis = /*#__PURE__*/Object.freeze({
6183
        getCurrent: getCurrent
6184
    });
6185
6186
    var ComposeSchema = [strict$1('find')];
6187
6188
    var Composing = create$1({
6189
      fields: ComposeSchema,
6190
      name: 'composing',
6191
      apis: ComposeApis
6192
    });
6193
6194
    var factory$1 = function (detail) {
6195
      return {
6196
        uid: detail.uid(),
6197
        dom: deepMerge({
6198
          tag: 'div',
6199
          attributes: { role: 'presentation' }
6200
        }, detail.dom()),
6201
        components: detail.components(),
6202
        behaviours: get$6(detail.containerBehaviours()),
6203
        events: detail.events(),
6204
        domModification: detail.domModification(),
6205
        eventOrder: detail.eventOrder()
6206
      };
6207
    };
6208
    var Container = single$2({
6209
      name: 'Container',
6210
      factory: factory$1,
6211
      configFields: [
6212
        defaulted$1('components', []),
6213
        field$1('containerBehaviours', []),
6214
        defaulted$1('events', {}),
6215
        defaulted$1('domModification', {}),
6216
        defaulted$1('eventOrder', {})
6217
      ]
6218
    });
6219
6220
    var factory$2 = function (detail) {
6221
      return {
6222
        uid: detail.uid(),
6223
        dom: detail.dom(),
6224
        behaviours: deepMerge(derive$2([
6225
          Representing.config({
6226
            store: {
6227
              mode: 'memory',
6228
              initialValue: detail.getInitialValue()()
6229
            }
6230
          }),
6231
          Composing.config({ find: Option.some })
6232
        ]), get$6(detail.dataBehaviours())),
6233
        events: derive([runOnAttached(function (component, simulatedEvent) {
6234
            Representing.setValue(component, detail.getInitialValue()());
6235
          })])
6236
      };
6237
    };
6238
    var DataField = single$2({
6239
      name: 'DataField',
6240
      factory: factory$2,
6241
      configFields: [
6242
        strict$1('uid'),
6243
        strict$1('dom'),
6244
        strict$1('getInitialValue'),
6245
        field$1('dataBehaviours', [
6246
          Representing,
6247
          Composing
6248
        ])
6249
      ]
6250
    });
6251
6252
    var get$a = function (element) {
6253
      return element.dom().value;
6254
    };
6255
    var set$6 = function (element, value) {
6256
      if (value === undefined)
6257
        throw new Error('Value.set was undefined');
6258
      element.dom().value = value;
6259
    };
6260
6261
    var schema$8 = constant([
6262
      option('data'),
6263
      defaulted$1('inputAttributes', {}),
6264
      defaulted$1('inputStyles', {}),
6265
      defaulted$1('type', 'input'),
6266
      defaulted$1('tag', 'input'),
6267
      defaulted$1('inputClasses', []),
6268
      onHandler('onSetValue'),
6269
      defaulted$1('styles', {}),
6270
      option('placeholder'),
6271
      defaulted$1('eventOrder', {}),
6272
      field$1('inputBehaviours', [
6273
        Representing,
6274
        Focusing
6275
      ]),
6276
      defaulted$1('selectOnFocus', true)
6277
    ]);
6278
    var focusBehaviours = function (detail) {
6279
      return derive$2([Focusing.config({
6280
          onFocus: detail.selectOnFocus() === false ? noop : function (component) {
6281
            var input = component.element();
6282
            var value = get$a(input);
6283
            input.dom().setSelectionRange(0, value.length);
6284
          }
6285
        })]);
6286
    };
6287
    var behaviours = function (detail) {
6288
      return deepMerge(derive$2([Representing.config({
6289
          store: {
6290
            mode: 'manual',
6291
            initialValue: detail.data().getOr(undefined),
6292
            getValue: function (input) {
6293
              return get$a(input.element());
6294
            },
6295
            setValue: function (input, data) {
6296
              var current = get$a(input.element());
6297
              if (current !== data) {
6298
                set$6(input.element(), data);
6299
              }
6300
            }
6301
          },
6302
          onSetValue: detail.onSetValue()
6303
        })]), focusBehaviours(detail), get$6(detail.inputBehaviours()));
6304
    };
6305
    var dom$2 = function (detail) {
6306
      return {
6307
        tag: detail.tag(),
6308
        attributes: deepMerge(wrapAll$1([{
6309
            key: 'type',
6310
            value: detail.type()
6311
          }].concat(detail.placeholder().map(function (pc) {
6312
          return {
6313
            key: 'placeholder',
6314
            value: pc
6315
          };
6316
        }).toArray())), detail.inputAttributes()),
6317
        styles: detail.inputStyles(),
6318
        classes: detail.inputClasses()
6319
      };
6320
    };
6321
6322
    var factory$3 = function (detail, spec) {
6323
      return {
6324
        uid: detail.uid(),
6325
        dom: dom$2(detail),
6326
        components: [],
6327
        behaviours: behaviours(detail),
6328
        eventOrder: detail.eventOrder()
6329
      };
6330
    };
6331
    var Input = single$2({
6332
      name: 'Input',
6333
      configFields: schema$8(),
6334
      factory: factory$3
6335
    });
6336
6337
    var exhibit$3 = function (base, tabConfig) {
6338
      return nu$6({
6339
        attributes: wrapAll$1([{
6340
            key: tabConfig.tabAttr(),
6341
            value: 'true'
6342
          }])
6343
      });
6344
    };
6345
6346
    var ActiveTabstopping = /*#__PURE__*/Object.freeze({
6347
        exhibit: exhibit$3
6348
    });
6349
6350
    var TabstopSchema = [defaulted$1('tabAttr', 'data-alloy-tabstop')];
6351
6352
    var Tabstopping = create$1({
6353
      fields: TabstopSchema,
6354
      name: 'tabstopping',
6355
      active: ActiveTabstopping
6356
    });
6357
6358
    var clearInputBehaviour = 'input-clearing';
6359
    var field$2 = function (name, placeholder) {
6360
      var inputSpec = record(Input.sketch({
6361
        placeholder: placeholder,
6362
        onSetValue: function (input$$1, data) {
6363
          emit(input$$1, input());
6364
        },
6365
        inputBehaviours: derive$2([
6366
          Composing.config({ find: Option.some }),
6367
          Tabstopping.config({}),
6368
          Keying.config({ mode: 'execution' })
6369
        ]),
6370
        selectOnFocus: false
6371
      }));
6372
      var buttonSpec = record(Button.sketch({
6373
        dom: dom$1('<button class="${prefix}-input-container-x ${prefix}-icon-cancel-circle ${prefix}-icon"></button>'),
6374
        action: function (button) {
6375
          var input$$1 = inputSpec.get(button);
6376
          Representing.setValue(input$$1, '');
6377
        }
6378
      }));
6379
      return {
6380
        name: name,
6381
        spec: Container.sketch({
6382
          dom: dom$1('<div class="${prefix}-input-container"></div>'),
6383
          components: [
6384
            inputSpec.asSpec(),
6385
            buttonSpec.asSpec()
6386
          ],
6387
          containerBehaviours: derive$2([
6388
            Toggling.config({ toggleClass: Styles.resolve('input-container-empty') }),
6389
            Composing.config({
6390
              find: function (comp) {
6391
                return Option.some(inputSpec.get(comp));
6392
              }
6393
            }),
6394
            config(clearInputBehaviour, [run(input(), function (iContainer) {
6395
                var input$$1 = inputSpec.get(iContainer);
6396
                var val = Representing.getValue(input$$1);
6397
                var f = val.length > 0 ? Toggling.off : Toggling.on;
6398
                f(iContainer);
6399
              })])
6400
          ])
6401
        })
6402
      };
6403
    };
6404
    var hidden = function (name) {
6405
      return {
6406
        name: name,
6407
        spec: DataField.sketch({
6408
          dom: {
6409
            tag: 'span',
6410
            styles: { display: 'none' }
6411
          },
6412
          getInitialValue: function () {
6413
            return Option.none();
6414
          }
6415
        })
6416
      };
6417
    };
6418
6419
    var nativeDisabled = [
6420
      'input',
6421
      'button',
6422
      'textarea'
6423
    ];
6424
    var onLoad$5 = function (component, disableConfig, disableState) {
6425
      if (disableConfig.disabled()) {
6426
        disable(component, disableConfig, disableState);
6427
      }
6428
    };
6429
    var hasNative = function (component) {
6430
      return contains(nativeDisabled, name(component.element()));
6431
    };
6432
    var nativeIsDisabled = function (component) {
6433
      return has$1(component.element(), 'disabled');
6434
    };
6435
    var nativeDisable = function (component) {
6436
      set(component.element(), 'disabled', 'disabled');
6437
    };
6438
    var nativeEnable = function (component) {
6439
      remove$1(component.element(), 'disabled');
6440
    };
6441
    var ariaIsDisabled = function (component) {
6442
      return get$1(component.element(), 'aria-disabled') === 'true';
6443
    };
6444
    var ariaDisable = function (component) {
6445
      set(component.element(), 'aria-disabled', 'true');
6446
    };
6447
    var ariaEnable = function (component) {
6448
      set(component.element(), 'aria-disabled', 'false');
6449
    };
6450
    var disable = function (component, disableConfig, disableState) {
6451
      disableConfig.disableClass().each(function (disableClass) {
6452
        add$2(component.element(), disableClass);
6453
      });
6454
      var f = hasNative(component) ? nativeDisable : ariaDisable;
6455
      f(component);
6456
    };
6457
    var enable = function (component, disableConfig, disableState) {
6458
      disableConfig.disableClass().each(function (disableClass) {
6459
        remove$4(component.element(), disableClass);
6460
      });
6461
      var f = hasNative(component) ? nativeEnable : ariaEnable;
6462
      f(component);
6463
    };
6464
    var isDisabled = function (component) {
6465
      return hasNative(component) ? nativeIsDisabled(component) : ariaIsDisabled(component);
6466
    };
6467
6468
    var DisableApis = /*#__PURE__*/Object.freeze({
6469
        enable: enable,
6470
        disable: disable,
6471
        isDisabled: isDisabled,
6472
        onLoad: onLoad$5
6473
    });
6474
6475
    var exhibit$4 = function (base, disableConfig, disableState) {
6476
      return nu$6({ classes: disableConfig.disabled() ? disableConfig.disableClass().map(pure).getOr([]) : [] });
6477
    };
6478
    var events$7 = function (disableConfig, disableState) {
6479
      return derive([
6480
        abort(execute(), function (component, simulatedEvent) {
6481
          return isDisabled(component);
6482
        }),
6483
        loadEvent(disableConfig, disableState, onLoad$5)
6484
      ]);
6485
    };
6486
6487
    var ActiveDisable = /*#__PURE__*/Object.freeze({
6488
        exhibit: exhibit$4,
6489
        events: events$7
6490
    });
6491
6492
    var DisableSchema = [
6493
      defaulted$1('disabled', false),
6494
      option('disableClass')
6495
    ];
6496
6497
    var Disabling = create$1({
6498
      fields: DisableSchema,
6499
      name: 'disabling',
6500
      active: ActiveDisable,
6501
      apis: DisableApis
6502
    });
6503
6504
    var owner$1 = 'form';
6505
    var schema$9 = [field$1('formBehaviours', [Representing])];
6506
    var getPartName = function (name) {
6507
      return '<alloy.field.' + name + '>';
6508
    };
6509
    var sketch$6 = function (fSpec) {
6510
      var parts = function () {
6511
        var record = [];
6512
        var field = function (name, config) {
6513
          record.push(name);
6514
          return generateOne(owner$1, getPartName(name), config);
6515
        };
6516
        return {
6517
          field: field,
6518
          record: function () {
6519
            return record;
6520
          }
6521
        };
6522
      }();
6523
      var spec = fSpec(parts);
6524
      var partNames = parts.record();
6525
      var fieldParts = map$1(partNames, function (n) {
6526
        return required({
6527
          name: n,
6528
          pname: getPartName(n)
6529
        });
6530
      });
6531
      return composite(owner$1, schema$9, fieldParts, make, spec);
6532
    };
6533
    var make = function (detail, components$$1, spec) {
6534
      return deepMerge({
6535
        'debug.sketcher': { Form: spec },
6536
        'uid': detail.uid(),
6537
        'dom': detail.dom(),
6538
        'components': components$$1,
6539
        'behaviours': deepMerge(derive$2([Representing.config({
6540
            store: {
6541
              mode: 'manual',
6542
              getValue: function (form) {
6543
                var optPs = getAllParts(form, detail);
6544
                return map(optPs, function (optPThunk, pName) {
6545
                  return optPThunk().bind(Composing.getCurrent).map(Representing.getValue);
6546
                });
6547
              },
6548
              setValue: function (form, values$$1) {
6549
                each(values$$1, function (newValue, key) {
6550
                  getPart(form, detail, key).each(function (wrapper) {
6551
                    Composing.getCurrent(wrapper).each(function (field) {
6552
                      Representing.setValue(field, newValue);
6553
                    });
6554
                  });
6555
                });
6556
              }
6557
            }
6558
          })]), get$6(detail.formBehaviours())),
6559
        'apis': {
6560
          getField: function (form, key) {
6561
            return getPart(form, detail, key).bind(Composing.getCurrent);
6562
          }
6563
        }
6564
      });
6565
    };
6566
    var Form = {
6567
      getField: makeApi(function (apis, component, key) {
6568
        return apis.getField(component, key);
6569
      }),
6570
      sketch: sketch$6
6571
    };
6572
6573
    var api$2 = function () {
6574
      var subject = Cell(Option.none());
6575
      var revoke = function () {
6576
        subject.get().each(function (s) {
6577
          s.destroy();
6578
        });
6579
      };
6580
      var clear = function () {
6581
        revoke();
6582
        subject.set(Option.none());
6583
      };
6584
      var set = function (s) {
6585
        revoke();
6586
        subject.set(Option.some(s));
6587
      };
6588
      var run = function (f) {
6589
        subject.get().each(f);
6590
      };
6591
      var isSet = function () {
6592
        return subject.get().isSome();
6593
      };
6594
      return {
6595
        clear: clear,
6596
        isSet: isSet,
6597
        set: set,
6598
        run: run
6599
      };
6600
    };
6601
    var value$3 = function () {
6602
      var subject = Cell(Option.none());
6603
      var clear = function () {
6604
        subject.set(Option.none());
6605
      };
6606
      var set = function (s) {
6607
        subject.set(Option.some(s));
6608
      };
6609
      var on = function (f) {
6610
        subject.get().each(f);
6611
      };
6612
      var isSet = function () {
6613
        return subject.get().isSome();
6614
      };
6615
      return {
6616
        clear: clear,
6617
        set: set,
6618
        isSet: isSet,
6619
        on: on
6620
      };
6621
    };
6622
6623
    var SWIPING_LEFT = 1;
6624
    var SWIPING_RIGHT = -1;
6625
    var SWIPING_NONE = 0;
6626
    var init$2 = function (xValue) {
6627
      return {
6628
        xValue: xValue,
6629
        points: []
6630
      };
6631
    };
6632
    var move$1 = function (model, xValue) {
6633
      if (xValue === model.xValue) {
6634
        return model;
6635
      }
6636
      var currentDirection = xValue - model.xValue > 0 ? SWIPING_LEFT : SWIPING_RIGHT;
6637
      var newPoint = {
6638
        direction: currentDirection,
6639
        xValue: xValue
6640
      };
6641
      var priorPoints = function () {
6642
        if (model.points.length === 0) {
6643
          return [];
6644
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
6645
          var prev = model.points[model.points.length - 1];
6646
          return prev.direction === currentDirection ? model.points.slice(0, model.points.length - 1) : model.points;
6647
        }
6648
      }();
6649
      return {
6650
        xValue: xValue,
6651
        points: priorPoints.concat([newPoint])
6652
      };
6653
    };
6654
    var complete = function (model) {
6655
      if (model.points.length === 0) {
6656
        return SWIPING_NONE;
6657
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
6658
        var firstDirection = model.points[0].direction;
6659
        var lastDirection = model.points[model.points.length - 1].direction;
6660
        return firstDirection === SWIPING_RIGHT && lastDirection === SWIPING_RIGHT ? SWIPING_RIGHT : firstDirection === SWIPING_LEFT && lastDirection === SWIPING_LEFT ? SWIPING_LEFT : SWIPING_NONE;
6661
      }
6662
    };
6663
    var SwipingModel = {
6664
      init: init$2,
6665
      move: move$1,
6666
      complete: complete
6667
    };
6668
6669
    var sketch$7 = function (rawSpec) {
6670
      var navigateEvent = 'navigateEvent';
6671
      var wrapperAdhocEvents = 'serializer-wrapper-events';
6672
      var formAdhocEvents = 'form-events';
6673
      var schema = objOf([
6674
        strict$1('fields'),
6675
        defaulted$1('maxFieldIndex', rawSpec.fields.length - 1),
6676
        strict$1('onExecute'),
6677
        strict$1('getInitialValue'),
6678
        state$1('state', function () {
6679
          return {
6680
            dialogSwipeState: value$3(),
6681
            currentScreen: Cell(0)
6682
          };
6683
        })
6684
      ]);
6685
      var spec$$1 = asRawOrDie('SerialisedDialog', schema, rawSpec);
6686
      var navigationButton = function (direction, directionName, enabled) {
6687
        return Button.sketch({
6688
          dom: dom$1('<span class="${prefix}-icon-' + directionName + ' ${prefix}-icon"></span>'),
6689
          action: function (button) {
6690
            emitWith(button, navigateEvent, { direction: direction });
6691
          },
6692
          buttonBehaviours: derive$2([Disabling.config({
6693
              disableClass: Styles.resolve('toolbar-navigation-disabled'),
6694
              disabled: !enabled
6695
            })])
6696
        });
6697
      };
6698
      var reposition = function (dialog, message) {
6699
        descendant$2(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
6700
          set$2(parent, 'left', -spec$$1.state.currentScreen.get() * message.width + 'px');
6701
        });
6702
      };
6703
      var navigate = function (dialog, direction) {
6704
        var screens = descendants$1(dialog.element(), '.' + Styles.resolve('serialised-dialog-screen'));
6705
        descendant$2(dialog.element(), '.' + Styles.resolve('serialised-dialog-chain')).each(function (parent) {
6706
          if (spec$$1.state.currentScreen.get() + direction >= 0 && spec$$1.state.currentScreen.get() + direction < screens.length) {
6707
            getRaw(parent, 'left').each(function (left) {
6708
              var currentLeft = parseInt(left, 10);
6709
              var w = get$7(screens[0]);
6710
              set$2(parent, 'left', currentLeft - direction * w + 'px');
6711
            });
6712
            spec$$1.state.currentScreen.set(spec$$1.state.currentScreen.get() + direction);
6713
          }
6714
        });
6715
      };
6716
      var focusInput = function (dialog) {
6717
        var inputs = descendants$1(dialog.element(), 'input');
6718
        var optInput = Option.from(inputs[spec$$1.state.currentScreen.get()]);
6719
        optInput.each(function (input$$1) {
6720
          dialog.getSystem().getByDom(input$$1).each(function (inputComp) {
6721
            dispatchFocus(dialog, inputComp.element());
6722
          });
6723
        });
6724
        var dotitems = memDots.get(dialog);
6725
        Highlighting.highlightAt(dotitems, spec$$1.state.currentScreen.get());
6726
      };
6727
      var resetState = function () {
6728
        spec$$1.state.currentScreen.set(0);
6729
        spec$$1.state.dialogSwipeState.clear();
6730
      };
6731
      var memForm = record(Form.sketch(function (parts) {
6732
        return {
6733
          dom: dom$1('<div class="${prefix}-serialised-dialog"></div>'),
6734
          components: [Container.sketch({
6735
              dom: dom$1('<div class="${prefix}-serialised-dialog-chain" style="left: 0px; position: absolute;"></div>'),
6736
              components: map$1(spec$$1.fields, function (field$$1, i) {
6737
                return i <= spec$$1.maxFieldIndex ? Container.sketch({
6738
                  dom: dom$1('<div class="${prefix}-serialised-dialog-screen"></div>'),
6739
                  components: flatten([
6740
                    [navigationButton(-1, 'previous', i > 0)],
6741
                    [parts.field(field$$1.name, field$$1.spec)],
6742
                    [navigationButton(+1, 'next', i < spec$$1.maxFieldIndex)]
6743
                  ])
6744
                }) : parts.field(field$$1.name, field$$1.spec);
6745
              })
6746
            })],
6747
          formBehaviours: derive$2([
6748
            Receivers.orientation(function (dialog, message) {
6749
              reposition(dialog, message);
6750
            }),
6751
            Keying.config({
6752
              mode: 'special',
6753
              focusIn: function (dialog) {
6754
                focusInput(dialog);
6755
              },
6756
              onTab: function (dialog) {
6757
                navigate(dialog, +1);
6758
                return Option.some(true);
6759
              },
6760
              onShiftTab: function (dialog) {
6761
                navigate(dialog, -1);
6762
                return Option.some(true);
6763
              }
6764
            }),
6765
            config(formAdhocEvents, [
6766
              runOnAttached(function (dialog, simulatedEvent) {
6767
                resetState();
6768
                var dotitems = memDots.get(dialog);
6769
                Highlighting.highlightFirst(dotitems);
6770
                spec$$1.getInitialValue(dialog).each(function (v) {
6771
                  Representing.setValue(dialog, v);
6772
                });
6773
              }),
6774
              runOnExecute(spec$$1.onExecute),
6775
              run(transitionend(), function (dialog, simulatedEvent) {
6776
                var event = simulatedEvent.event();
6777
                if (event.raw().propertyName === 'left') {
6778
                  focusInput(dialog);
6779
                }
6780
              }),
6781
              run(navigateEvent, function (dialog, simulatedEvent) {
6782
                var event = simulatedEvent.event();
6783
                var direction = event.direction();
6784
                navigate(dialog, direction);
6785
              })
6786
            ])
6787
          ])
6788
        };
6789
      }));
6790
      var memDots = record({
6791
        dom: dom$1('<div class="${prefix}-dot-container"></div>'),
6792
        behaviours: derive$2([Highlighting.config({
6793
            highlightClass: Styles.resolve('dot-active'),
6794
            itemClass: Styles.resolve('dot-item')
6795
          })]),
6796
        components: bind(spec$$1.fields, function (_f, i) {
6797
          return i <= spec$$1.maxFieldIndex ? [spec('<div class="${prefix}-dot-item ${prefix}-icon-full-dot ${prefix}-icon"></div>')] : [];
6798
        })
6799
      });
6800
      return {
6801
        dom: dom$1('<div class="${prefix}-serializer-wrapper"></div>'),
6802
        components: [
6803
          memForm.asSpec(),
6804
          memDots.asSpec()
6805
        ],
6806
        behaviours: derive$2([
6807
          Keying.config({
6808
            mode: 'special',
6809
            focusIn: function (wrapper) {
6810
              var form = memForm.get(wrapper);
6811
              Keying.focusIn(form);
6812
            }
6813
          }),
6814
          config(wrapperAdhocEvents, [
6815
            run(touchstart(), function (wrapper, simulatedEvent) {
6816
              var event = simulatedEvent.event();
6817
              spec$$1.state.dialogSwipeState.set(SwipingModel.init(event.touches[0].clientX));
6818
            }),
6819
            run(touchmove(), function (wrapper, simulatedEvent) {
6820
              var event = simulatedEvent.event();
6821
              spec$$1.state.dialogSwipeState.on(function (state) {
6822
                simulatedEvent.event().prevent();
6823
                spec$$1.state.dialogSwipeState.set(SwipingModel.move(state, event.raw().touches[0].clientX));
6824
              });
6825
            }),
6826
            run(touchend(), function (wrapper) {
6827
              spec$$1.state.dialogSwipeState.on(function (state) {
6828
                var dialog = memForm.get(wrapper);
6829
                var direction = -1 * SwipingModel.complete(state);
6830
                navigate(dialog, direction);
6831
              });
6832
            })
6833
          ])
6834
        ])
6835
      };
6836
    };
6837
6838
    var getGroups = cached(function (realm, editor) {
6839
      return [{
6840
          label: 'the link group',
6841
          items: [sketch$7({
6842
              fields: [
6843
                field$2('url', 'Type or paste URL'),
6844
                field$2('text', 'Link text'),
6845
                field$2('title', 'Link title'),
6846
                field$2('target', 'Link target'),
6847
                hidden('link')
6848
              ],
6849
              maxFieldIndex: [
6850
                'url',
6851
                'text',
6852
                'title',
6853
                'target'
6854
              ].length - 1,
6855
              getInitialValue: function () {
6856
                return Option.some(LinkBridge.getInfo(editor));
6857
              },
6858
              onExecute: function (dialog) {
6859
                var info = Representing.getValue(dialog);
6860
                LinkBridge.applyInfo(editor, info);
6861
                realm.restoreToolbar();
6862
                editor.focus();
6863
              }
6864
            })]
6865
        }];
6866
    });
6867
    var sketch$8 = function (realm, editor) {
6868
      return Buttons.forToolbarStateAction(editor, 'link', 'link', function () {
6869
        var groups = getGroups(realm, editor);
6870
        realm.setContextToolbar(groups);
6871
        RangePreserver.forAndroid(editor, function () {
6872
          realm.focusToolbar();
6873
        });
6874
        LinkBridge.query(editor).each(function (link) {
6875
          editor.selection.select(link.dom());
6876
        });
6877
      });
6878
    };
6879
6880
    var DefaultStyleFormats = [
6881
      {
6882
        title: 'Headings',
6883
        items: [
6884
          {
6885
            title: 'Heading 1',
6886
            format: 'h1'
6887
          },
6888
          {
6889
            title: 'Heading 2',
6890
            format: 'h2'
6891
          },
6892
          {
6893
            title: 'Heading 3',
6894
            format: 'h3'
6895
          },
6896
          {
6897
            title: 'Heading 4',
6898
            format: 'h4'
6899
          },
6900
          {
6901
            title: 'Heading 5',
6902
            format: 'h5'
6903
          },
6904
          {
6905
            title: 'Heading 6',
6906
            format: 'h6'
6907
          }
6908
        ]
6909
      },
6910
      {
6911
        title: 'Inline',
6912
        items: [
6913
          {
6914
            title: 'Bold',
6915
            icon: 'bold',
6916
            format: 'bold'
6917
          },
6918
          {
6919
            title: 'Italic',
6920
            icon: 'italic',
6921
            format: 'italic'
6922
          },
6923
          {
6924
            title: 'Underline',
6925
            icon: 'underline',
6926
            format: 'underline'
6927
          },
6928
          {
6929
            title: 'Strikethrough',
6930
            icon: 'strikethrough',
6931
            format: 'strikethrough'
6932
          },
6933
          {
6934
            title: 'Superscript',
6935
            icon: 'superscript',
6936
            format: 'superscript'
6937
          },
6938
          {
6939
            title: 'Subscript',
6940
            icon: 'subscript',
6941
            format: 'subscript'
6942
          },
6943
          {
6944
            title: 'Code',
6945
            icon: 'code',
6946
            format: 'code'
6947
          }
6948
        ]
6949
      },
6950
      {
6951
        title: 'Blocks',
6952
        items: [
6953
          {
6954
            title: 'Paragraph',
6955
            format: 'p'
6956
          },
6957
          {
6958
            title: 'Blockquote',
6959
            format: 'blockquote'
6960
          },
6961
          {
6962
            title: 'Div',
6963
            format: 'div'
6964
          },
6965
          {
6966
            title: 'Pre',
6967
            format: 'pre'
6968
          }
6969
        ]
6970
      },
6971
      {
6972
        title: 'Alignment',
6973
        items: [
6974
          {
6975
            title: 'Left',
6976
            icon: 'alignleft',
6977
            format: 'alignleft'
6978
          },
6979
          {
6980
            title: 'Center',
6981
            icon: 'aligncenter',
6982
            format: 'aligncenter'
6983
          },
6984
          {
6985
            title: 'Right',
6986
            icon: 'alignright',
6987
            format: 'alignright'
6988
          },
6989
          {
6990
            title: 'Justify',
6991
            icon: 'alignjustify',
6992
            format: 'alignjustify'
6993
          }
6994
        ]
6995
      }
6996
    ];
6997
6998
    var isRecursive = function (component, originator, target) {
6999
      return eq(originator, component.element()) && !eq(originator, target);
7000
    };
7001
    var events$8 = derive([can(focus$1(), function (component, simulatedEvent) {
7002
        var originator = simulatedEvent.event().originator();
7003
        var target = simulatedEvent.event().target();
7004
        if (isRecursive(component, originator, target)) {
7005
          console.warn(focus$1() + ' did not get interpreted by the desired target. ' + '\nOriginator: ' + element(originator) + '\nTarget: ' + element(target) + '\nCheck the ' + focus$1() + ' event handlers');
7006
          return false;
7007
        } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
7008
          return true;
7009
        }
7010
      })]);
7011
7012
    var DefaultEvents = /*#__PURE__*/Object.freeze({
7013
        events: events$8
7014
    });
7015
7016
    var make$1 = identity;
7017
7018
    var SystemApi = exactly([
7019
      'debugInfo',
7020
      'triggerFocus',
7021
      'triggerEvent',
7022
      'triggerEscape',
7023
      'addToWorld',
7024
      'removeFromWorld',
7025
      'addToGui',
7026
      'removeFromGui',
7027
      'build',
7028
      'getByUid',
7029
      'getByDom',
7030
      'broadcast',
7031
      'broadcastOn',
7032
      'isConnected'
7033
    ]);
7034
7035
    var NoContextApi = function (getComp) {
7036
      var fail = function (event) {
7037
        return function () {
7038
          throw new Error('The component must be in a context to send: ' + event + '\n' + element(getComp().element()) + ' is not in context.');
7039
        };
7040
      };
7041
      return SystemApi({
7042
        debugInfo: constant('fake'),
7043
        triggerEvent: fail('triggerEvent'),
7044
        triggerFocus: fail('triggerFocus'),
7045
        triggerEscape: fail('triggerEscape'),
7046
        build: fail('build'),
7047
        addToWorld: fail('addToWorld'),
7048
        removeFromWorld: fail('removeFromWorld'),
7049
        addToGui: fail('addToGui'),
7050
        removeFromGui: fail('removeFromGui'),
7051
        getByUid: fail('getByUid'),
7052
        getByDom: fail('getByDom'),
7053
        broadcast: fail('broadcast'),
7054
        broadcastOn: fail('broadcastOn'),
7055
        isConnected: constant(false)
7056
      });
7057
    };
7058
7059
    var generateFrom = function (spec, all) {
7060
      var schema = map$1(all, function (a) {
7061
        return optionObjOf(a.name(), [
7062
          strict$1('config'),
7063
          defaulted$1('state', NoState)
7064
        ]);
7065
      });
7066
      var validated = asStruct('component.behaviours', objOf(schema), spec.behaviours).fold(function (errInfo) {
7067
        throw new Error(formatError(errInfo) + '\nComplete spec:\n' + Json.stringify(spec, null, 2));
7068
      }, function (v) {
7069
        return v;
7070
      });
7071
      return {
7072
        list: all,
7073
        data: map(validated, function (optBlobThunk) {
7074
          var optBlob = optBlobThunk();
7075
          var output = optBlob.map(function (blob) {
7076
            return {
7077
              config: blob.config(),
7078
              state: blob.state().init(blob.config())
7079
            };
7080
          });
7081
          return function () {
7082
            return output;
7083
          };
7084
        })
7085
      };
7086
    };
7087
    var getBehaviours = function (bData) {
7088
      return bData.list;
7089
    };
7090
    var getData = function (bData) {
7091
      return bData.data;
7092
    };
7093
7094
    var byInnerKey = function (data, tuple) {
7095
      var r = {};
7096
      each(data, function (detail, key) {
7097
        each(detail, function (value, indexKey) {
7098
          var chain = readOr$1(indexKey, [])(r);
7099
          r[indexKey] = chain.concat([tuple(key, value)]);
7100
        });
7101
      });
7102
      return r;
7103
    };
7104
7105
    var concat = function (chain, aspect) {
7106
      var values$$1 = bind(chain, function (c) {
7107
        return c.modification().getOr([]);
7108
      });
7109
      return Result.value(wrap$2(aspect, values$$1));
7110
    };
7111
    var onlyOne = function (chain, aspect) {
7112
      if (chain.length > 1) {
7113
        return Result.error('Multiple behaviours have tried to change DOM "' + aspect + '". The guilty behaviours are: ' + Json.stringify(map$1(chain, function (b) {
7114
          return b.name();
7115
        })) + '. At this stage, this ' + 'is not supported. Future releases might provide strategies for resolving this.');
7116
      } else if (chain.length === 0) {
7117
        return Result.value({});
7118
      } else {
7119
        return Result.value(chain[0].modification().fold(function () {
7120
          return {};
7121
        }, function (m) {
7122
          return wrap$2(aspect, m);
7123
        }));
7124
      }
7125
    };
7126
    var duplicate = function (aspect, k, obj, behaviours) {
7127
      return Result.error('Mulitple behaviours have tried to change the _' + k + '_ "' + aspect + '"' + '. The guilty behaviours are: ' + Json.stringify(bind(behaviours, function (b) {
7128
        return b.modification().getOr({})[k] !== undefined ? [b.name()] : [];
7129
      }), null, 2) + '. This is not currently supported.');
7130
    };
7131
    var objSafeMerge = function (chain, aspect) {
7132
      var y = foldl(chain, function (acc, c) {
7133
        var obj = c.modification().getOr({});
7134
        return acc.bind(function (accRest) {
7135
          var parts = mapToArray(obj, function (v, k) {
7136
            return accRest[k] !== undefined ? duplicate(aspect, k, obj, chain) : Result.value(wrap$2(k, v));
7137
          });
7138
          return consolidate(parts, accRest);
7139
        });
7140
      }, Result.value({}));
7141
      return y.map(function (yValue) {
7142
        return wrap$2(aspect, yValue);
7143
      });
7144
    };
7145
    var mergeTypes = {
7146
      classes: concat,
7147
      attributes: objSafeMerge,
7148
      styles: objSafeMerge,
7149
      domChildren: onlyOne,
7150
      defChildren: onlyOne,
7151
      innerHtml: onlyOne,
7152
      value: onlyOne
7153
    };
7154
    var combine$1 = function (info, baseMod, behaviours, base) {
7155
      var modsByBehaviour = deepMerge({}, baseMod);
7156
      each$1(behaviours, function (behaviour) {
7157
        modsByBehaviour[behaviour.name()] = behaviour.exhibit(info, base);
7158
      });
7159
      var nameAndMod = function (name, modification) {
7160
        return {
7161
          name: function () {
7162
            return name;
7163
          },
7164
          modification: modification
7165
        };
7166
      };
7167
      var byAspect = byInnerKey(modsByBehaviour, nameAndMod);
7168
      var usedAspect = map(byAspect, function (values$$1, aspect) {
7169
        return bind(values$$1, function (value) {
7170
          return value.modification().fold(function () {
7171
            return [];
7172
          }, function (v) {
7173
            return [value];
7174
          });
7175
        });
7176
      });
7177
      var modifications = mapToArray(usedAspect, function (values$$1, aspect) {
7178
        return readOptFrom$1(mergeTypes, aspect).fold(function () {
7179
          return Result.error('Unknown field type: ' + aspect);
7180
        }, function (merger) {
7181
          return merger(values$$1, aspect);
7182
        });
7183
      });
7184
      var consolidated = consolidate(modifications, {});
7185
      return consolidated.map(nu$6);
7186
    };
7187
7188
    var sortKeys = function (label, keyName, array, order) {
7189
      var sliced = array.slice(0);
7190
      try {
7191
        var sorted = sliced.sort(function (a, b) {
7192
          var aKey = a[keyName]();
7193
          var bKey = b[keyName]();
7194
          var aIndex = order.indexOf(aKey);
7195
          var bIndex = order.indexOf(bKey);
7196
          if (aIndex === -1) {
7197
            throw new Error('The ordering for ' + label + ' does not have an entry for ' + aKey + '.\nOrder specified: ' + Json.stringify(order, null, 2));
7198
          }
7199
          if (bIndex === -1) {
7200
            throw new Error('The ordering for ' + label + ' does not have an entry for ' + bKey + '.\nOrder specified: ' + Json.stringify(order, null, 2));
7201
          }
7202
          if (aIndex < bIndex) {
7203
            return -1;
7204
          } else if (bIndex < aIndex) {
7205
            return 1;
7206
          } else {
7207
            return 0;
7208
          }
7209
        });
7210
        return Result.value(sorted);
7211
      } catch (err) {
7212
        return Result.error([err]);
7213
      }
7214
    };
7215
7216
    var uncurried = function (handler, purpose) {
7217
      return {
7218
        handler: handler,
7219
        purpose: constant(purpose)
7220
      };
7221
    };
7222
    var curried = function (handler, purpose) {
7223
      return {
7224
        cHandler: handler,
7225
        purpose: constant(purpose)
7226
      };
7227
    };
7228
    var curryArgs = function (descHandler, extraArgs) {
7229
      return curried(curry.apply(undefined, [descHandler.handler].concat(extraArgs)), descHandler.purpose());
7230
    };
7231
    var getCurried = function (descHandler) {
7232
      return descHandler.cHandler;
7233
    };
7234
7235
    var behaviourTuple = function (name, handler) {
7236
      return {
7237
        name: constant(name),
7238
        handler: constant(handler)
7239
      };
7240
    };
7241
    var nameToHandlers = function (behaviours, info) {
7242
      var r = {};
7243
      each$1(behaviours, function (behaviour) {
7244
        r[behaviour.name()] = behaviour.handlers(info);
7245
      });
7246
      return r;
7247
    };
7248
    var groupByEvents = function (info, behaviours, base) {
7249
      var behaviourEvents = deepMerge(base, nameToHandlers(behaviours, info));
7250
      return byInnerKey(behaviourEvents, behaviourTuple);
7251
    };
7252
    var combine$2 = function (info, eventOrder, behaviours, base) {
7253
      var byEventName = groupByEvents(info, behaviours, base);
7254
      return combineGroups(byEventName, eventOrder);
7255
    };
7256
    var assemble = function (rawHandler) {
7257
      var handler = read(rawHandler);
7258
      return function (component, simulatedEvent) {
7259
        var rest = [];
7260
        for (var _i = 2; _i < arguments.length; _i++) {
7261
          rest[_i - 2] = arguments[_i];
7262
        }
7263
        var args = [
7264
          component,
7265
          simulatedEvent
7266
        ].concat(rest);
7267
        if (handler.abort.apply(undefined, args)) {
7268
          simulatedEvent.stop();
7269
        } else if (handler.can.apply(undefined, args)) {
7270
          handler.run.apply(undefined, args);
7271
        }
7272
      };
7273
    };
7274
    var missingOrderError = function (eventName, tuples) {
7275
      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$1(tuples, function (c) {
7276
          return c.name();
7277
        }), null, 2)]);
7278
    };
7279
    var fuse$1 = function (tuples, eventOrder, eventName) {
7280
      var order = eventOrder[eventName];
7281
      if (!order) {
7282
        return missingOrderError(eventName, tuples);
7283
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
7284
        return sortKeys('Event: ' + eventName, 'name', tuples, order).map(function (sortedTuples) {
7285
          var handlers = map$1(sortedTuples, function (tuple) {
7286
            return tuple.handler();
7287
          });
7288
          return fuse(handlers);
7289
        });
7290
      }
7291
    };
7292
    var combineGroups = function (byEventName, eventOrder) {
7293
      var r = mapToArray(byEventName, function (tuples, eventName) {
7294
        var combined = tuples.length === 1 ? Result.value(tuples[0].handler()) : fuse$1(tuples, eventOrder, eventName);
7295
        return combined.map(function (handler) {
7296
          var assembled = assemble(handler);
7297
          var purpose = tuples.length > 1 ? filter(eventOrder, function (o) {
7298
            return contains(tuples, function (t) {
7299
              return t.name() === o;
7300
            });
7301
          }).join(' > ') : tuples[0].name();
7302
          return wrap$2(eventName, uncurried(assembled, purpose));
7303
        });
7304
      });
7305
      return consolidate(r, {});
7306
    };
7307
7308
    var toInfo = function (spec) {
7309
      return asStruct('custom.definition', objOfOnly([
7310
        field('dom', 'dom', strict(), objOfOnly([
7311
          strict$1('tag'),
7312
          defaulted$1('styles', {}),
7313
          defaulted$1('classes', []),
7314
          defaulted$1('attributes', {}),
7315
          option('value'),
7316
          option('innerHtml')
7317
        ])),
7318
        strict$1('components'),
7319
        strict$1('uid'),
7320
        defaulted$1('events', {}),
7321
        defaulted$1('apis', constant({})),
7322
        field('eventOrder', 'eventOrder', mergeWith({
7323
          'alloy.execute': [
7324
            'disabling',
7325
            'alloy.base.behaviour',
7326
            'toggling'
7327
          ],
7328
          'alloy.focus': [
7329
            'alloy.base.behaviour',
7330
            'focusing',
7331
            'keying'
7332
          ],
7333
          'alloy.system.init': [
7334
            'alloy.base.behaviour',
7335
            'disabling',
7336
            'toggling',
7337
            'representing'
7338
          ],
7339
          'input': [
7340
            'alloy.base.behaviour',
7341
            'representing',
7342
            'streaming',
7343
            'invalidating'
7344
          ],
7345
          'alloy.system.detached': [
7346
            'alloy.base.behaviour',
7347
            'representing'
7348
          ]
7349
        }), anyValue$1()),
7350
        option('domModification'),
7351
        snapshot$1('originalSpec'),
7352
        defaulted$1('debug.sketcher', 'unknown')
7353
      ]), spec);
7354
    };
7355
    var getUid = function (detail) {
7356
      return wrap$2(idAttr(), detail.uid());
7357
    };
7358
    var toDefinition = function (detail) {
7359
      var base = {
7360
        tag: detail.dom().tag(),
7361
        classes: detail.dom().classes(),
7362
        attributes: deepMerge(getUid(detail), detail.dom().attributes()),
7363
        styles: detail.dom().styles(),
7364
        domChildren: map$1(detail.components(), function (comp) {
7365
          return comp.element();
7366
        })
7367
      };
7368
      return nu$5(deepMerge(base, detail.dom().innerHtml().map(function (h) {
7369
        return wrap$2('innerHtml', h);
7370
      }).getOr({}), detail.dom().value().map(function (h) {
7371
        return wrap$2('value', h);
7372
      }).getOr({})));
7373
    };
7374
    var toModification = function (detail) {
7375
      return detail.domModification().fold(function () {
7376
        return nu$6({});
7377
      }, nu$6);
7378
    };
7379
    var toEvents = function (info) {
7380
      return info.events();
7381
    };
7382
7383
    var add$3 = function (element, classes) {
7384
      each$1(classes, function (x) {
7385
        add$2(element, x);
7386
      });
7387
    };
7388
    var remove$6 = function (element, classes) {
7389
      each$1(classes, function (x) {
7390
        remove$4(element, x);
7391
      });
7392
    };
7393
7394
    var getChildren = function (definition) {
7395
      if (definition.domChildren().isSome() && definition.defChildren().isSome()) {
7396
        throw new Error('Cannot specify children and child specs! Must be one or the other.\nDef: ' + defToStr(definition));
7397
      } else {
7398
        return definition.domChildren().fold(function () {
7399
          var defChildren = definition.defChildren().getOr([]);
7400
          return map$1(defChildren, renderDef);
7401
        }, function (domChildren) {
7402
          return domChildren;
7403
        });
7404
      }
7405
    };
7406
    var renderToDom = function (definition) {
7407
      var subject = Element$$1.fromTag(definition.tag());
7408
      setAll(subject, definition.attributes().getOr({}));
7409
      add$3(subject, definition.classes().getOr([]));
7410
      setAll$1(subject, definition.styles().getOr({}));
7411
      set$1(subject, definition.innerHtml().getOr(''));
7412
      var children = getChildren(definition);
7413
      append$1(subject, children);
7414
      definition.value().each(function (value) {
7415
        set$6(subject, value);
7416
      });
7417
      return subject;
7418
    };
7419
    var renderDef = function (spec) {
7420
      var definition = nu$5(spec);
7421
      return renderToDom(definition);
7422
    };
7423
7424
    var getBehaviours$1 = function (spec) {
7425
      var behaviours = readOptFrom$1(spec, 'behaviours').getOr({});
7426
      var keys$$1 = filter(keys(behaviours), function (k) {
7427
        return behaviours[k] !== undefined;
7428
      });
7429
      return map$1(keys$$1, function (k) {
7430
        return behaviours[k].me;
7431
      });
7432
    };
7433
    var generateFrom$1 = function (spec, all) {
7434
      return generateFrom(spec, all);
7435
    };
7436
    var generate$4 = function (spec) {
7437
      var all = getBehaviours$1(spec);
7438
      return generateFrom$1(spec, all);
7439
    };
7440
7441
    var ComponentApi = exactly([
7442
      'getSystem',
7443
      'config',
7444
      'hasConfigured',
7445
      'spec',
7446
      'connect',
7447
      'disconnect',
7448
      'element',
7449
      'syncComponents',
7450
      'readState',
7451
      'components',
7452
      'events'
7453
    ]);
7454
7455
    var getDomDefinition = function (info, bList, bData) {
7456
      var definition = toDefinition(info);
7457
      var baseModification = { 'alloy.base.modification': toModification(info) };
7458
      var modification = combine$1(bData, baseModification, bList, definition).getOrDie();
7459
      return merge$1(definition, modification);
7460
    };
7461
    var getEvents$6 = function (info, bList, bData) {
7462
      var baseEvents = { 'alloy.base.behaviour': toEvents(info) };
7463
      return combine$2(bData, info.eventOrder(), bList, baseEvents).getOrDie();
7464
    };
7465
    var build = function (spec) {
7466
      var getMe = function () {
7467
        return me;
7468
      };
7469
      var systemApi = Cell(NoContextApi(getMe));
7470
      var info = getOrDie$1(toInfo(deepMerge(spec, { behaviours: undefined })));
7471
      var bBlob = generate$4(spec);
7472
      var bList = getBehaviours(bBlob);
7473
      var bData = getData(bBlob);
7474
      var modDefinition = getDomDefinition(info, bList, bData);
7475
      var item = renderToDom(modDefinition);
7476
      var events = getEvents$6(info, bList, bData);
7477
      var subcomponents = Cell(info.components());
7478
      var connect = function (newApi) {
7479
        systemApi.set(newApi);
7480
      };
7481
      var disconnect = function () {
7482
        systemApi.set(NoContextApi(getMe));
7483
      };
7484
      var syncComponents = function () {
7485
        var children$$1 = children(item);
7486
        var subs = bind(children$$1, function (child$$1) {
7487
          return systemApi.get().getByDom(child$$1).fold(function () {
7488
            return [];
7489
          }, function (c) {
7490
            return [c];
7491
          });
7492
        });
7493
        subcomponents.set(subs);
7494
      };
7495
      var config = function (behaviour) {
7496
        if (behaviour === apiConfig()) {
7497
          return info.apis();
7498
        } else if (isString(behaviour)) {
7499
          throw new Error('Invalid input: only API constant is allowed');
7500
        }
7501
        var b = bData;
7502
        var f = isFunction(b[behaviour.name()]) ? b[behaviour.name()] : function () {
7503
          throw new Error('Could not find ' + behaviour.name() + ' in ' + Json.stringify(spec, null, 2));
7504
        };
7505
        return f();
7506
      };
7507
      var hasConfigured = function (behaviour) {
7508
        return isFunction(bData[behaviour.name()]);
7509
      };
7510
      var readState = function (behaviourName) {
7511
        return bData[behaviourName]().map(function (b) {
7512
          return b.state.readState();
7513
        }).getOr('not enabled');
7514
      };
7515
      var me = ComponentApi({
7516
        getSystem: systemApi.get,
7517
        config: config,
7518
        hasConfigured: hasConfigured,
7519
        spec: constant(spec),
7520
        readState: readState,
7521
        connect: connect,
7522
        disconnect: disconnect,
7523
        element: constant(item),
7524
        syncComponents: syncComponents,
7525
        components: subcomponents.get,
7526
        events: constant(events)
7527
      });
7528
      return me;
7529
    };
7530
7531
    var buildSubcomponents = function (spec) {
7532
      var components = readOr$1('components', [])(spec);
7533
      return map$1(components, build$1);
7534
    };
7535
    var buildFromSpec = function (userSpec) {
7536
      var spec = make$1(userSpec);
7537
      var components = buildSubcomponents(spec);
7538
      var completeSpec = deepMerge(DefaultEvents, spec, wrap$2('components', components));
7539
      return Result.value(build(completeSpec));
7540
    };
7541
    var text = function (textContent) {
7542
      var element = Element$$1.fromText(textContent);
7543
      return external$1({ element: element });
7544
    };
7545
    var external$1 = function (spec) {
7546
      var extSpec = asStructOrDie('external.component', objOfOnly([
7547
        strict$1('element'),
7548
        option('uid')
7549
      ]), spec);
7550
      var systemApi = Cell(NoContextApi());
7551
      var connect = function (newApi) {
7552
        systemApi.set(newApi);
7553
      };
7554
      var disconnect = function () {
7555
        systemApi.set(NoContextApi(function () {
7556
          return me;
7557
        }));
7558
      };
7559
      extSpec.uid().each(function (uid) {
7560
        writeOnly(extSpec.element(), uid);
7561
      });
7562
      var me = ComponentApi({
7563
        getSystem: systemApi.get,
7564
        config: Option.none,
7565
        hasConfigured: constant(false),
7566
        connect: connect,
7567
        disconnect: disconnect,
7568
        element: constant(extSpec.element()),
7569
        spec: constant(spec),
7570
        readState: constant('No state'),
7571
        syncComponents: noop,
7572
        components: constant([]),
7573
        events: constant({})
7574
      });
7575
      return premade(me);
7576
    };
7577
    var build$1 = function (spec) {
7578
      return getPremade(spec).fold(function () {
7579
        var userSpecWithUid = deepMerge({ uid: generate$3('') }, spec);
7580
        return buildFromSpec(userSpecWithUid).getOrDie();
7581
      }, function (prebuilt) {
7582
        return prebuilt;
7583
      });
7584
    };
7585
    var premade$1 = premade;
7586
7587
    var hoverEvent = 'alloy.item-hover';
7588
    var focusEvent = 'alloy.item-focus';
7589
    var onHover = function (item) {
7590
      if (search(item.element()).isNone() || Focusing.isFocused(item)) {
7591
        if (!Focusing.isFocused(item)) {
7592
          Focusing.focus(item);
7593
        }
7594
        emitWith(item, hoverEvent, { item: item });
7595
      }
7596
    };
7597
    var onFocus = function (item) {
7598
      emitWith(item, focusEvent, { item: item });
7599
    };
7600
    var hover = constant(hoverEvent);
7601
    var focus$4 = constant(focusEvent);
7602
7603
    var builder = function (detail) {
7604
      return {
7605
        dom: deepMerge(detail.dom(), { attributes: { role: detail.toggling().isSome() ? 'menuitemcheckbox' : 'menuitem' } }),
7606
        behaviours: deepMerge(derive$2([
7607
          detail.toggling().fold(Toggling.revoke, function (tConfig) {
7608
            return Toggling.config(deepMerge({ aria: { mode: 'checked' } }, tConfig));
7609
          }),
7610
          Focusing.config({
7611
            ignore: detail.ignoreFocus(),
7612
            onFocus: function (component) {
7613
              onFocus(component);
7614
            }
7615
          }),
7616
          Keying.config({ mode: 'execution' }),
7617
          Representing.config({
7618
            store: {
7619
              mode: 'memory',
7620
              initialValue: detail.data()
7621
            }
7622
          })
7623
        ]), detail.itemBehaviours()),
7624
        events: derive([
7625
          runWithTarget(tapOrClick(), emitExecute),
7626
          cutter(mousedown()),
7627
          run(mouseover(), onHover),
7628
          run(focusItem(), Focusing.focus)
7629
        ]),
7630
        components: detail.components(),
7631
        domModification: detail.domModification(),
7632
        eventOrder: detail.eventOrder()
7633
      };
7634
    };
7635
    var schema$a = [
7636
      strict$1('data'),
7637
      strict$1('components'),
7638
      strict$1('dom'),
7639
      option('toggling'),
7640
      defaulted$1('itemBehaviours', {}),
7641
      defaulted$1('ignoreFocus', false),
7642
      defaulted$1('domModification', {}),
7643
      output$1('builder', builder),
7644
      defaulted$1('eventOrder', {})
7645
    ];
7646
7647
    var builder$1 = function (detail) {
7648
      return {
7649
        dom: detail.dom(),
7650
        components: detail.components(),
7651
        events: derive([stopper(focusItem())])
7652
      };
7653
    };
7654
    var schema$b = [
7655
      strict$1('dom'),
7656
      strict$1('components'),
7657
      output$1('builder', builder$1)
7658
    ];
7659
7660
    var owner$2 = function () {
7661
      return 'item-widget';
7662
    };
7663
    var parts = constant([required({
7664
        name: 'widget',
7665
        overrides: function (detail) {
7666
          return {
7667
            behaviours: derive$2([Representing.config({
7668
                store: {
7669
                  mode: 'manual',
7670
                  getValue: function (component) {
7671
                    return detail.data();
7672
                  },
7673
                  setValue: function () {
7674
                  }
7675
                }
7676
              })])
7677
          };
7678
        }
7679
      })]);
7680
7681
    var builder$2 = function (detail) {
7682
      var subs = substitutes(owner$2(), detail, parts());
7683
      var components$$1 = components(owner$2(), detail, subs.internals());
7684
      var focusWidget = function (component) {
7685
        return getPart(component, detail, 'widget').map(function (widget) {
7686
          Keying.focusIn(widget);
7687
          return widget;
7688
        });
7689
      };
7690
      var onHorizontalArrow = function (component, simulatedEvent) {
7691
        return inside(simulatedEvent.event().target()) ? Option.none() : function () {
7692
          if (detail.autofocus()) {
7693
            simulatedEvent.setSource(component.element());
7694
            return Option.none();
7695
          } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
7696
            return Option.none();
7697
          }
7698
        }();
7699
      };
7700
      return deepMerge({
7701
        dom: detail.dom(),
7702
        components: components$$1,
7703
        domModification: detail.domModification(),
7704
        events: derive([
7705
          runOnExecute(function (component, simulatedEvent) {
7706
            focusWidget(component).each(function (widget) {
7707
              simulatedEvent.stop();
7708
            });
7709
          }),
7710
          run(mouseover(), onHover),
7711
          run(focusItem(), function (component, simulatedEvent) {
7712
            if (detail.autofocus()) {
7713
              focusWidget(component);
7714
            } else {
7715
              Focusing.focus(component);
7716
            }
7717
          })
7718
        ]),
7719
        behaviours: derive$2([
7720
          Representing.config({
7721
            store: {
7722
              mode: 'memory',
7723
              initialValue: detail.data()
7724
            }
7725
          }),
7726
          Focusing.config({
7727
            onFocus: function (component) {
7728
              onFocus(component);
7729
            }
7730
          }),
7731
          Keying.config({
7732
            mode: 'special',
7733
            focusIn: detail.autofocus() ? function (component) {
7734
              focusWidget(component);
7735
            } : revoke(),
7736
            onLeft: onHorizontalArrow,
7737
            onRight: onHorizontalArrow,
7738
            onEscape: function (component, simulatedEvent) {
7739
              if (!Focusing.isFocused(component) && !detail.autofocus()) {
7740
                Focusing.focus(component);
7741
                return Option.some(true);
7742
              } else if (detail.autofocus()) {
7743
                simulatedEvent.setSource(component.element());
7744
                return Option.none();
7745
              } else {
7746
                return Option.none();
7747
              }
7748
            }
7749
          })
7750
        ])
7751
      });
7752
    };
7753
    var schema$c = [
7754
      strict$1('uid'),
7755
      strict$1('data'),
7756
      strict$1('components'),
7757
      strict$1('dom'),
7758
      defaulted$1('autofocus', false),
7759
      defaulted$1('domModification', {}),
7760
      defaultUidsSchema(parts()),
7761
      output$1('builder', builder$2)
7762
    ];
7763
7764
    var itemSchema$1 = choose$1('type', {
7765
      widget: schema$c,
7766
      item: schema$a,
7767
      separator: schema$b
7768
    });
7769
    var configureGrid = function (detail, movementInfo) {
7770
      return {
7771
        mode: 'flatgrid',
7772
        selector: '.' + detail.markers().item(),
7773
        initSize: {
7774
          numColumns: movementInfo.initSize().numColumns(),
7775
          numRows: movementInfo.initSize().numRows()
7776
        },
7777
        focusManager: detail.focusManager()
7778
      };
7779
    };
7780
    var configureMenu = function (detail, movementInfo) {
7781
      return {
7782
        mode: 'menu',
7783
        selector: '.' + detail.markers().item(),
7784
        moveOnTab: movementInfo.moveOnTab(),
7785
        focusManager: detail.focusManager()
7786
      };
7787
    };
7788
    var parts$1 = constant([group({
7789
        factory: {
7790
          sketch: function (spec) {
7791
            var itemInfo = asStructOrDie('menu.spec item', itemSchema$1, spec);
7792
            return itemInfo.builder()(itemInfo);
7793
          }
7794
        },
7795
        name: 'items',
7796
        unit: 'item',
7797
        defaults: function (detail, u) {
7798
          var fallbackUid = generate$3('');
7799
          return deepMerge({ uid: fallbackUid }, u);
7800
        },
7801
        overrides: function (detail, u) {
7802
          return {
7803
            type: u.type,
7804
            ignoreFocus: detail.fakeFocus(),
7805
            domModification: { classes: [detail.markers().item()] }
7806
          };
7807
        }
7808
      })]);
7809
    var schema$d = constant([
7810
      strict$1('value'),
7811
      strict$1('items'),
7812
      strict$1('dom'),
7813
      strict$1('components'),
7814
      defaulted$1('eventOrder', {}),
7815
      field$1('menuBehaviours', [
7816
        Highlighting,
7817
        Representing,
7818
        Composing,
7819
        Keying
7820
      ]),
7821
      defaultedOf('movement', {
7822
        mode: 'menu',
7823
        moveOnTab: true
7824
      }, choose$1('mode', {
7825
        grid: [
7826
          initSize(),
7827
          output$1('config', configureGrid)
7828
        ],
7829
        menu: [
7830
          defaulted$1('moveOnTab', true),
7831
          output$1('config', configureMenu)
7832
        ]
7833
      })),
7834
      itemMarkers(),
7835
      defaulted$1('fakeFocus', false),
7836
      defaulted$1('focusManager', dom()),
7837
      onHandler('onHighlight')
7838
    ]);
7839
7840
    var focus$5 = constant('alloy.menu-focus');
7841
7842
    var make$2 = function (detail, components, spec, externals) {
7843
      return deepMerge({
7844
        dom: deepMerge(detail.dom(), { attributes: { role: 'menu' } }),
7845
        uid: detail.uid(),
7846
        behaviours: deepMerge(derive$2([
7847
          Highlighting.config({
7848
            highlightClass: detail.markers().selectedItem(),
7849
            itemClass: detail.markers().item(),
7850
            onHighlight: detail.onHighlight()
7851
          }),
7852
          Representing.config({
7853
            store: {
7854
              mode: 'memory',
7855
              initialValue: detail.value()
7856
            }
7857
          }),
7858
          Composing.config({ find: Option.some }),
7859
          Keying.config(detail.movement().config()(detail, detail.movement()))
7860
        ]), get$6(detail.menuBehaviours())),
7861
        events: derive([
7862
          run(focus$4(), function (menu, simulatedEvent) {
7863
            var event = simulatedEvent.event();
7864
            menu.getSystem().getByDom(event.target()).each(function (item) {
7865
              Highlighting.highlight(menu, item);
7866
              simulatedEvent.stop();
7867
              emitWith(menu, focus$5(), {
7868
                menu: menu,
7869
                item: item
7870
              });
7871
            });
7872
          }),
7873
          run(hover(), function (menu, simulatedEvent) {
7874
            var item = simulatedEvent.event().item();
7875
            Highlighting.highlight(menu, item);
7876
          })
7877
        ]),
7878
        components: components,
7879
        eventOrder: detail.eventOrder()
7880
      });
7881
    };
7882
7883
    var Menu = composite$1({
7884
      name: 'Menu',
7885
      configFields: schema$d(),
7886
      partFields: parts$1(),
7887
      factory: make$2
7888
    });
7889
7890
    var preserve$2 = function (f, container) {
7891
      var ownerDoc = owner(container);
7892
      var refocus = active(ownerDoc).bind(function (focused) {
7893
        var hasFocus$$1 = function (elem) {
7894
          return eq(focused, elem);
7895
        };
7896
        return hasFocus$$1(container) ? Option.some(container) : descendant(container, hasFocus$$1);
7897
      });
7898
      var result = f(container);
7899
      refocus.each(function (oldFocus) {
7900
        active(ownerDoc).filter(function (newFocus) {
7901
          return eq(newFocus, oldFocus);
7902
        }).fold(function () {
7903
          focus$2(oldFocus);
7904
        }, noop);
7905
      });
7906
      return result;
7907
    };
7908
7909
    var set$7 = function (component, replaceConfig, replaceState, data) {
7910
      detachChildren(component);
7911
      preserve$2(function () {
7912
        var children = map$1(data, component.getSystem().build);
7913
        each$1(children, function (l) {
7914
          attach(component, l);
7915
        });
7916
      }, component.element());
7917
    };
7918
    var insert = function (component, replaceConfig, insertion, childSpec) {
7919
      var child = component.getSystem().build(childSpec);
7920
      attachWith(component, child, insertion);
7921
    };
7922
    var append$2 = function (component, replaceConfig, replaceState, appendee) {
7923
      insert(component, replaceConfig, append, appendee);
7924
    };
7925
    var prepend$2 = function (component, replaceConfig, replaceState, prependee) {
7926
      insert(component, replaceConfig, prepend, prependee);
7927
    };
7928
    var remove$7 = function (component, replaceConfig, replaceState, removee) {
7929
      var children = contents(component, replaceConfig);
7930
      var foundChild = find$2(children, function (child) {
7931
        return eq(removee.element(), child.element());
7932
      });
7933
      foundChild.each(detach);
7934
    };
7935
    var contents = function (component, replaceConfig) {
7936
      return component.components();
7937
    };
7938
7939
    var ReplaceApis = /*#__PURE__*/Object.freeze({
7940
        append: append$2,
7941
        prepend: prepend$2,
7942
        remove: remove$7,
7943
        set: set$7,
7944
        contents: contents
7945
    });
7946
7947
    var Replacing = create$1({
7948
      fields: [],
7949
      name: 'replacing',
7950
      apis: ReplaceApis
7951
    });
7952
7953
    var transpose = function (obj) {
7954
      return tupleMap(obj, function (v, k) {
7955
        return {
7956
          k: v,
7957
          v: k
7958
        };
7959
      });
7960
    };
7961
    var trace = function (items, byItem, byMenu, finish) {
7962
      return readOptFrom$1(byMenu, finish).bind(function (triggerItem) {
7963
        return readOptFrom$1(items, triggerItem).bind(function (triggerMenu) {
7964
          var rest = trace(items, byItem, byMenu, triggerMenu);
7965
          return Option.some([triggerMenu].concat(rest));
7966
        });
7967
      }).getOr([]);
7968
    };
7969
    var generate$5 = function (menus, expansions) {
7970
      var items = {};
7971
      each(menus, function (menuItems, menu) {
7972
        each$1(menuItems, function (item) {
7973
          items[item] = menu;
7974
        });
7975
      });
7976
      var byItem = expansions;
7977
      var byMenu = transpose(expansions);
7978
      var menuPaths = map(byMenu, function (_triggerItem, submenu) {
7979
        return [submenu].concat(trace(items, byItem, byMenu, submenu));
7980
      });
7981
      return map(items, function (menu) {
7982
        return readOptFrom$1(menuPaths, menu).getOr([menu]);
7983
      });
7984
    };
7985
7986
    var init$3 = function () {
7987
      var expansions = Cell({});
7988
      var menus = Cell({});
7989
      var paths = Cell({});
7990
      var primary = Cell(Option.none());
7991
      var directory = Cell({});
7992
      var clear = function () {
7993
        expansions.set({});
7994
        menus.set({});
7995
        paths.set({});
7996
        primary.set(Option.none());
7997
      };
7998
      var isClear = function () {
7999
        return primary.get().isNone();
8000
      };
8001
      var setContents = function (sPrimary, sMenus, sExpansions, dir) {
8002
        primary.set(Option.some(sPrimary));
8003
        expansions.set(sExpansions);
8004
        menus.set(sMenus);
8005
        directory.set(dir);
8006
        var sPaths = generate$5(dir, sExpansions);
8007
        paths.set(sPaths);
8008
      };
8009
      var expand = function (itemValue) {
8010
        return readOptFrom$1(expansions.get(), itemValue).map(function (menu) {
8011
          var current = readOptFrom$1(paths.get(), itemValue).getOr([]);
8012
          return [menu].concat(current);
8013
        });
8014
      };
8015
      var collapse = function (itemValue) {
8016
        return readOptFrom$1(paths.get(), itemValue).bind(function (path) {
8017
          return path.length > 1 ? Option.some(path.slice(1)) : Option.none();
8018
        });
8019
      };
8020
      var refresh = function (itemValue) {
8021
        return readOptFrom$1(paths.get(), itemValue);
8022
      };
8023
      var lookupMenu = function (menuValue) {
8024
        return readOptFrom$1(menus.get(), menuValue);
8025
      };
8026
      var otherMenus = function (path) {
8027
        var menuValues = directory.get();
8028
        return difference(keys(menuValues), path);
8029
      };
8030
      var getPrimary = function () {
8031
        return primary.get().bind(lookupMenu);
8032
      };
8033
      var getMenus = function () {
8034
        return menus.get();
8035
      };
8036
      return {
8037
        setContents: setContents,
8038
        expand: expand,
8039
        refresh: refresh,
8040
        collapse: collapse,
8041
        lookupMenu: lookupMenu,
8042
        otherMenus: otherMenus,
8043
        getPrimary: getPrimary,
8044
        getMenus: getMenus,
8045
        clear: clear,
8046
        isClear: isClear
8047
      };
8048
    };
8049
    var LayeredState = { init: init$3 };
8050
8051
    var make$3 = function (detail, rawUiSpec) {
8052
      var buildMenus = function (container, menus) {
8053
        return map(menus, function (spec, name) {
8054
          var data = Menu.sketch(deepMerge(spec, {
8055
            value: name,
8056
            items: spec.items,
8057
            markers: narrow$1(rawUiSpec.markers, [
8058
              'item',
8059
              'selectedItem'
8060
            ]),
8061
            fakeFocus: detail.fakeFocus(),
8062
            onHighlight: detail.onHighlight(),
8063
            focusManager: detail.fakeFocus() ? highlights() : dom()
8064
          }));
8065
          return container.getSystem().build(data);
8066
        });
8067
      };
8068
      var layeredState = LayeredState.init();
8069
      var setup = function (container) {
8070
        var componentMap = buildMenus(container, detail.data().menus());
8071
        var directory = toDirectory(container);
8072
        layeredState.setContents(detail.data().primary(), componentMap, detail.data().expansions(), directory);
8073
        return layeredState.getPrimary();
8074
      };
8075
      var getItemValue = function (item) {
8076
        return Representing.getValue(item).value;
8077
      };
8078
      var toDirectory = function (container) {
8079
        return map(detail.data().menus(), function (data, menuName) {
8080
          return bind(data.items, function (item) {
8081
            return item.type === 'separator' ? [] : [item.data.value];
8082
          });
8083
        });
8084
      };
8085
      var setActiveMenu = function (container, menu) {
8086
        Highlighting.highlight(container, menu);
8087
        Highlighting.getHighlighted(menu).orThunk(function () {
8088
          return Highlighting.getFirst(menu);
8089
        }).each(function (item) {
8090
          dispatch(container, item.element(), focusItem());
8091
        });
8092
      };
8093
      var getMenus = function (state, menuValues) {
8094
        return cat(map$1(menuValues, state.lookupMenu));
8095
      };
8096
      var updateMenuPath = function (container, state, path) {
8097
        return Option.from(path[0]).bind(state.lookupMenu).map(function (activeMenu) {
8098
          var rest = getMenus(state, path.slice(1));
8099
          each$1(rest, function (r) {
8100
            add$2(r.element(), detail.markers().backgroundMenu());
8101
          });
8102
          if (!inBody(activeMenu.element())) {
8103
            Replacing.append(container, premade$1(activeMenu));
8104
          }
8105
          remove$6(activeMenu.element(), [detail.markers().backgroundMenu()]);
8106
          setActiveMenu(container, activeMenu);
8107
          var others = getMenus(state, state.otherMenus(path));
8108
          each$1(others, function (o) {
8109
            remove$6(o.element(), [detail.markers().backgroundMenu()]);
8110
            if (!detail.stayInDom()) {
8111
              Replacing.remove(container, o);
8112
            }
8113
          });
8114
          return activeMenu;
8115
        });
8116
      };
8117
      var expandRight = function (container, item) {
8118
        var value = getItemValue(item);
8119
        return layeredState.expand(value).bind(function (path) {
8120
          Option.from(path[0]).bind(layeredState.lookupMenu).each(function (activeMenu) {
8121
            if (!inBody(activeMenu.element())) {
8122
              Replacing.append(container, premade$1(activeMenu));
8123
            }
8124
            detail.onOpenSubmenu()(container, item, activeMenu);
8125
            Highlighting.highlightFirst(activeMenu);
8126
          });
8127
          return updateMenuPath(container, layeredState, path);
8128
        });
8129
      };
8130
      var collapseLeft = function (container, item) {
8131
        var value = getItemValue(item);
8132
        return layeredState.collapse(value).bind(function (path) {
8133
          return updateMenuPath(container, layeredState, path).map(function (activeMenu) {
8134
            detail.onCollapseMenu()(container, item, activeMenu);
8135
            return activeMenu;
8136
          });
8137
        });
8138
      };
8139
      var updateView = function (container, item) {
8140
        var value = getItemValue(item);
8141
        return layeredState.refresh(value).bind(function (path) {
8142
          return updateMenuPath(container, layeredState, path);
8143
        });
8144
      };
8145
      var onRight = function (container, item) {
8146
        return inside(item.element()) ? Option.none() : expandRight(container, item);
8147
      };
8148
      var onLeft = function (container, item) {
8149
        return inside(item.element()) ? Option.none() : collapseLeft(container, item);
8150
      };
8151
      var onEscape = function (container, item) {
8152
        return collapseLeft(container, item).orThunk(function () {
8153
          return detail.onEscape()(container, item).map(function () {
8154
            return container;
8155
          });
8156
        });
8157
      };
8158
      var keyOnItem = function (f) {
8159
        return function (container, simulatedEvent) {
8160
          return closest$2(simulatedEvent.getSource(), '.' + detail.markers().item()).bind(function (target) {
8161
            return container.getSystem().getByDom(target).toOption().bind(function (item) {
8162
              return f(container, item).map(function () {
8163
                return true;
8164
              });
8165
            });
8166
          });
8167
        };
8168
      };
8169
      var events = derive([
8170
        run(focus$5(), function (sandbox, simulatedEvent) {
8171
          var menu = simulatedEvent.event().menu();
8172
          Highlighting.highlight(sandbox, menu);
8173
        }),
8174
        runOnExecute(function (component, simulatedEvent) {
8175
          var target = simulatedEvent.event().target();
8176
          component.getSystem().getByDom(target).each(function (item) {
8177
            var itemValue = getItemValue(item);
8178
            if (itemValue.indexOf('collapse-item') === 0) {
8179
              collapseLeft(component, item);
8180
            }
8181
            expandRight(component, item).fold(function () {
8182
              detail.onExecute()(component, item);
8183
            }, function () {
8184
            });
8185
          });
8186
        }),
8187
        runOnAttached(function (container, simulatedEvent) {
8188
          setup(container).each(function (primary) {
8189
            Replacing.append(container, premade$1(primary));
8190
            if (detail.openImmediately()) {
8191
              setActiveMenu(container, primary);
8192
              detail.onOpenMenu()(container, primary);
8193
            }
8194
          });
8195
        })
8196
      ].concat(detail.navigateOnHover() ? [run(hover(), function (sandbox, simulatedEvent) {
8197
          var item = simulatedEvent.event().item();
8198
          updateView(sandbox, item);
8199
          expandRight(sandbox, item);
8200
          detail.onHover()(sandbox, item);
8201
        })] : []));
8202
      var collapseMenuApi = function (container) {
8203
        Highlighting.getHighlighted(container).each(function (currentMenu) {
8204
          Highlighting.getHighlighted(currentMenu).each(function (currentItem) {
8205
            collapseLeft(container, currentItem);
8206
          });
8207
        });
8208
      };
8209
      return {
8210
        uid: detail.uid(),
8211
        dom: detail.dom(),
8212
        behaviours: deepMerge(derive$2([
8213
          Keying.config({
8214
            mode: 'special',
8215
            onRight: keyOnItem(onRight),
8216
            onLeft: keyOnItem(onLeft),
8217
            onEscape: keyOnItem(onEscape),
8218
            focusIn: function (container, keyInfo) {
8219
              layeredState.getPrimary().each(function (primary) {
8220
                dispatch(container, primary.element(), focusItem());
8221
              });
8222
            }
8223
          }),
8224
          Highlighting.config({
8225
            highlightClass: detail.markers().selectedMenu(),
8226
            itemClass: detail.markers().menu()
8227
          }),
8228
          Composing.config({
8229
            find: function (container) {
8230
              return Highlighting.getHighlighted(container);
8231
            }
8232
          }),
8233
          Replacing.config({})
8234
        ]), get$6(detail.tmenuBehaviours())),
8235
        eventOrder: detail.eventOrder(),
8236
        apis: { collapseMenu: collapseMenuApi },
8237
        events: events
8238
      };
8239
    };
8240
    var collapseItem = constant('collapse-item');
8241
8242
    var tieredData = function (primary, menus, expansions) {
8243
      return {
8244
        primary: primary,
8245
        menus: menus,
8246
        expansions: expansions
8247
      };
8248
    };
8249
    var singleData = function (name, menu) {
8250
      return {
8251
        primary: name,
8252
        menus: wrap$2(name, menu),
8253
        expansions: {}
8254
      };
8255
    };
8256
    var collapseItem$1 = function (text) {
8257
      return {
8258
        value: generate$1(collapseItem()),
8259
        text: text
8260
      };
8261
    };
8262
    var tieredMenu = single$2({
8263
      name: 'TieredMenu',
8264
      configFields: [
8265
        onStrictKeyboardHandler('onExecute'),
8266
        onStrictKeyboardHandler('onEscape'),
8267
        onStrictHandler('onOpenMenu'),
8268
        onStrictHandler('onOpenSubmenu'),
8269
        onHandler('onCollapseMenu'),
8270
        defaulted$1('openImmediately', true),
8271
        strictObjOf('data', [
8272
          strict$1('primary'),
8273
          strict$1('menus'),
8274
          strict$1('expansions')
8275
        ]),
8276
        defaulted$1('fakeFocus', false),
8277
        onHandler('onHighlight'),
8278
        onHandler('onHover'),
8279
        tieredMenuMarkers(),
8280
        strict$1('dom'),
8281
        defaulted$1('navigateOnHover', true),
8282
        defaulted$1('stayInDom', false),
8283
        field$1('tmenuBehaviours', [
8284
          Keying,
8285
          Highlighting,
8286
          Composing,
8287
          Replacing
8288
        ]),
8289
        defaulted$1('eventOrder', {})
8290
      ],
8291
      apis: {
8292
        collapseMenu: function (apis, tmenu) {
8293
          apis.collapseMenu(tmenu);
8294
        }
8295
      },
8296
      factory: make$3,
8297
      extraApis: {
8298
        tieredData: tieredData,
8299
        singleData: singleData,
8300
        collapseItem: collapseItem$1
8301
      }
8302
    });
8303
8304
    var findRoute = function (component, transConfig, transState, route) {
8305
      return readOptFrom$1(transConfig.routes(), route.start()).map(apply).bind(function (sConfig) {
8306
        return readOptFrom$1(sConfig, route.destination()).map(apply);
8307
      });
8308
    };
8309
    var getTransition = function (comp, transConfig, transState) {
8310
      var route = getCurrentRoute(comp, transConfig, transState);
8311
      return route.bind(function (r) {
8312
        return getTransitionOf(comp, transConfig, transState, r);
8313
      });
8314
    };
8315
    var getTransitionOf = function (comp, transConfig, transState, route) {
8316
      return findRoute(comp, transConfig, transState, route).bind(function (r) {
8317
        return r.transition().map(function (t) {
8318
          return {
8319
            transition: constant(t),
8320
            route: constant(r)
8321
          };
8322
        });
8323
      });
8324
    };
8325
    var disableTransition = function (comp, transConfig, transState) {
8326
      getTransition(comp, transConfig, transState).each(function (routeTransition) {
8327
        var t = routeTransition.transition();
8328
        remove$4(comp.element(), t.transitionClass());
8329
        remove$1(comp.element(), transConfig.destinationAttr());
8330
      });
8331
    };
8332
    var getNewRoute = function (comp, transConfig, transState, destination) {
8333
      return {
8334
        start: constant(get$1(comp.element(), transConfig.stateAttr())),
8335
        destination: constant(destination)
8336
      };
8337
    };
8338
    var getCurrentRoute = function (comp, transConfig, transState) {
8339
      var el = comp.element();
8340
      return has$1(el, transConfig.destinationAttr()) ? Option.some({
8341
        start: constant(get$1(comp.element(), transConfig.stateAttr())),
8342
        destination: constant(get$1(comp.element(), transConfig.destinationAttr()))
8343
      }) : Option.none();
8344
    };
8345
    var jumpTo = function (comp, transConfig, transState, destination) {
8346
      disableTransition(comp, transConfig, transState);
8347
      if (has$1(comp.element(), transConfig.stateAttr()) && get$1(comp.element(), transConfig.stateAttr()) !== destination) {
8348
        transConfig.onFinish()(comp, destination);
8349
      }
8350
      set(comp.element(), transConfig.stateAttr(), destination);
8351
    };
8352
    var fasttrack = function (comp, transConfig, transState, destination) {
8353
      if (has$1(comp.element(), transConfig.destinationAttr())) {
8354
        set(comp.element(), transConfig.stateAttr(), get$1(comp.element(), transConfig.destinationAttr()));
8355
        remove$1(comp.element(), transConfig.destinationAttr());
8356
      }
8357
    };
8358
    var progressTo = function (comp, transConfig, transState, destination) {
8359
      fasttrack(comp, transConfig, transState, destination);
8360
      var route = getNewRoute(comp, transConfig, transState, destination);
8361
      getTransitionOf(comp, transConfig, transState, route).fold(function () {
8362
        jumpTo(comp, transConfig, transState, destination);
8363
      }, function (routeTransition) {
8364
        disableTransition(comp, transConfig, transState);
8365
        var t = routeTransition.transition();
8366
        add$2(comp.element(), t.transitionClass());
8367
        set(comp.element(), transConfig.destinationAttr(), destination);
8368
      });
8369
    };
8370
    var getState = function (comp, transConfig, transState) {
8371
      var e = comp.element();
8372
      return has$1(e, transConfig.stateAttr()) ? Option.some(get$1(e, transConfig.stateAttr())) : Option.none();
8373
    };
8374
8375
    var TransitionApis = /*#__PURE__*/Object.freeze({
8376
        findRoute: findRoute,
8377
        disableTransition: disableTransition,
8378
        getCurrentRoute: getCurrentRoute,
8379
        jumpTo: jumpTo,
8380
        progressTo: progressTo,
8381
        getState: getState
8382
    });
8383
8384
    var events$9 = function (transConfig, transState) {
8385
      return derive([
8386
        run(transitionend(), function (component, simulatedEvent) {
8387
          var raw = simulatedEvent.event().raw();
8388
          getCurrentRoute(component, transConfig, transState).each(function (route) {
8389
            findRoute(component, transConfig, transState, route).each(function (rInfo) {
8390
              rInfo.transition().each(function (rTransition) {
8391
                if (raw.propertyName === rTransition.property()) {
8392
                  jumpTo(component, transConfig, transState, route.destination());
8393
                  transConfig.onTransition()(component, route);
8394
                }
8395
              });
8396
            });
8397
          });
8398
        }),
8399
        runOnAttached(function (comp, se) {
8400
          jumpTo(comp, transConfig, transState, transConfig.initialState());
8401
        })
8402
      ]);
8403
    };
8404
8405
    var ActiveTransitioning = /*#__PURE__*/Object.freeze({
8406
        events: events$9
8407
    });
8408
8409
    var TransitionSchema = [
8410
      defaulted$1('destinationAttr', 'data-transitioning-destination'),
8411
      defaulted$1('stateAttr', 'data-transitioning-state'),
8412
      strict$1('initialState'),
8413
      onHandler('onTransition'),
8414
      onHandler('onFinish'),
8415
      strictOf('routes', setOf(Result.value, setOf(Result.value, objOfOnly([optionObjOfOnly('transition', [
8416
          strict$1('property'),
8417
          strict$1('transitionClass')
8418
        ])]))))
8419
    ];
8420
8421
    var createRoutes = function (routes) {
8422
      var r = {};
8423
      each(routes, function (v, k) {
8424
        var waypoints = k.split('<->');
8425
        r[waypoints[0]] = wrap$2(waypoints[1], v);
8426
        r[waypoints[1]] = wrap$2(waypoints[0], v);
8427
      });
8428
      return r;
8429
    };
8430
    var createBistate = function (first, second, transitions) {
8431
      return wrapAll$1([
8432
        {
8433
          key: first,
8434
          value: wrap$2(second, transitions)
8435
        },
8436
        {
8437
          key: second,
8438
          value: wrap$2(first, transitions)
8439
        }
8440
      ]);
8441
    };
8442
    var createTristate = function (first, second, third, transitions) {
8443
      return wrapAll$1([
8444
        {
8445
          key: first,
8446
          value: wrapAll$1([
8447
            {
8448
              key: second,
8449
              value: transitions
8450
            },
8451
            {
8452
              key: third,
8453
              value: transitions
8454
            }
8455
          ])
8456
        },
8457
        {
8458
          key: second,
8459
          value: wrapAll$1([
8460
            {
8461
              key: first,
8462
              value: transitions
8463
            },
8464
            {
8465
              key: third,
8466
              value: transitions
8467
            }
8468
          ])
8469
        },
8470
        {
8471
          key: third,
8472
          value: wrapAll$1([
8473
            {
8474
              key: first,
8475
              value: transitions
8476
            },
8477
            {
8478
              key: second,
8479
              value: transitions
8480
            }
8481
          ])
8482
        }
8483
      ]);
8484
    };
8485
    var Transitioning = create$1({
8486
      fields: TransitionSchema,
8487
      name: 'transitioning',
8488
      active: ActiveTransitioning,
8489
      apis: TransitionApis,
8490
      extra: {
8491
        createRoutes: createRoutes,
8492
        createBistate: createBistate,
8493
        createTristate: createTristate
8494
      }
8495
    });
8496
8497
    var scrollable = Styles.resolve('scrollable');
8498
    var register = function (element) {
8499
      add$2(element, scrollable);
8500
    };
8501
    var deregister = function (element) {
8502
      remove$4(element, scrollable);
8503
    };
8504
    var Scrollable = {
8505
      register: register,
8506
      deregister: deregister,
8507
      scrollable: constant(scrollable)
8508
    };
8509
8510
    var getValue$4 = function (item) {
8511
      return readOptFrom$1(item, 'format').getOr(item.title);
8512
    };
8513
    var convert$1 = function (formats, memMenuThunk) {
8514
      var mainMenu = makeMenu('Styles', [].concat(map$1(formats.items, function (k) {
8515
        return makeItem(getValue$4(k), k.title, k.isSelected(), k.getPreview(), hasKey$1(formats.expansions, getValue$4(k)));
8516
      })), memMenuThunk, false);
8517
      var submenus = map(formats.menus, function (menuItems, menuName) {
8518
        var items = map$1(menuItems, function (item) {
8519
          return makeItem(getValue$4(item), item.title, item.isSelected !== undefined ? item.isSelected() : false, item.getPreview !== undefined ? item.getPreview() : '', hasKey$1(formats.expansions, getValue$4(item)));
8520
        });
8521
        return makeMenu(menuName, items, memMenuThunk, true);
8522
      });
8523
      var menus = deepMerge(submenus, wrap$2('styles', mainMenu));
8524
      var tmenu = tieredMenu.tieredData('styles', menus, formats.expansions);
8525
      return { tmenu: tmenu };
8526
    };
8527
    var makeItem = function (value, text$$1, selected, preview, isMenu) {
8528
      return {
8529
        data: {
8530
          value: value,
8531
          text: text$$1
8532
        },
8533
        type: 'item',
8534
        dom: {
8535
          tag: 'div',
8536
          classes: isMenu ? [Styles.resolve('styles-item-is-menu')] : []
8537
        },
8538
        toggling: {
8539
          toggleOnExecute: false,
8540
          toggleClass: Styles.resolve('format-matches'),
8541
          selected: selected
8542
        },
8543
        itemBehaviours: derive$2(isMenu ? [] : [Receivers.format(value, function (comp, status) {
8544
            var toggle = status ? Toggling.on : Toggling.off;
8545
            toggle(comp);
8546
          })]),
8547
        components: [{
8548
            dom: {
8549
              tag: 'div',
8550
              attributes: { style: preview },
8551
              innerHtml: text$$1
8552
            }
8553
          }]
8554
      };
8555
    };
8556
    var makeMenu = function (value, items, memMenuThunk, collapsable) {
8557
      return {
8558
        value: value,
8559
        dom: { tag: 'div' },
8560
        components: [
8561
          Button.sketch({
8562
            dom: {
8563
              tag: 'div',
8564
              classes: [Styles.resolve('styles-collapser')]
8565
            },
8566
            components: collapsable ? [
8567
              {
8568
                dom: {
8569
                  tag: 'span',
8570
                  classes: [Styles.resolve('styles-collapse-icon')]
8571
                }
8572
              },
8573
              text(value)
8574
            ] : [text(value)],
8575
            action: function (item) {
8576
              if (collapsable) {
8577
                var comp = memMenuThunk().get(item);
8578
                tieredMenu.collapseMenu(comp);
8579
              }
8580
            }
8581
          }),
8582
          {
8583
            dom: {
8584
              tag: 'div',
8585
              classes: [Styles.resolve('styles-menu-items-container')]
8586
            },
8587
            components: [Menu.parts().items({})],
8588
            behaviours: derive$2([config('adhoc-scrollable-menu', [
8589
                runOnAttached(function (component, simulatedEvent) {
8590
                  set$2(component.element(), 'overflow-y', 'auto');
8591
                  set$2(component.element(), '-webkit-overflow-scrolling', 'touch');
8592
                  Scrollable.register(component.element());
8593
                }),
8594
                runOnDetached(function (component) {
8595
                  remove$5(component.element(), 'overflow-y');
8596
                  remove$5(component.element(), '-webkit-overflow-scrolling');
8597
                  Scrollable.deregister(component.element());
8598
                })
8599
              ])])
8600
          }
8601
        ],
8602
        items: items,
8603
        menuBehaviours: derive$2([Transitioning.config({
8604
            initialState: 'after',
8605
            routes: Transitioning.createTristate('before', 'current', 'after', {
8606
              transition: {
8607
                property: 'transform',
8608
                transitionClass: 'transitioning'
8609
              }
8610
            })
8611
          })])
8612
      };
8613
    };
8614
    var sketch$9 = function (settings) {
8615
      var dataset = convert$1(settings.formats, function () {
8616
        return memMenu;
8617
      });
8618
      var memMenu = record(tieredMenu.sketch({
8619
        dom: {
8620
          tag: 'div',
8621
          classes: [Styles.resolve('styles-menu')]
8622
        },
8623
        components: [],
8624
        fakeFocus: true,
8625
        stayInDom: true,
8626
        onExecute: function (tmenu, item) {
8627
          var v = Representing.getValue(item);
8628
          settings.handle(item, v.value);
8629
          return Option.none();
8630
        },
8631
        onEscape: function () {
8632
          return Option.none();
8633
        },
8634
        onOpenMenu: function (container, menu) {
8635
          var w = get$7(container.element());
8636
          set$4(menu.element(), w);
8637
          Transitioning.jumpTo(menu, 'current');
8638
        },
8639
        onOpenSubmenu: function (container, item, submenu) {
8640
          var w = get$7(container.element());
8641
          var menu = ancestor$2(item.element(), '[role="menu"]').getOrDie('hacky');
8642
          var menuComp = container.getSystem().getByDom(menu).getOrDie();
8643
          set$4(submenu.element(), w);
8644
          Transitioning.progressTo(menuComp, 'before');
8645
          Transitioning.jumpTo(submenu, 'after');
8646
          Transitioning.progressTo(submenu, 'current');
8647
        },
8648
        onCollapseMenu: function (container, item, menu) {
8649
          var submenu = ancestor$2(item.element(), '[role="menu"]').getOrDie('hacky');
8650
          var submenuComp = container.getSystem().getByDom(submenu).getOrDie();
8651
          Transitioning.progressTo(submenuComp, 'after');
8652
          Transitioning.progressTo(menu, 'current');
8653
        },
8654
        navigateOnHover: false,
8655
        openImmediately: true,
8656
        data: dataset.tmenu,
8657
        markers: {
8658
          backgroundMenu: Styles.resolve('styles-background-menu'),
8659
          menu: Styles.resolve('styles-menu'),
8660
          selectedMenu: Styles.resolve('styles-selected-menu'),
8661
          item: Styles.resolve('styles-item'),
8662
          selectedItem: Styles.resolve('styles-selected-item')
8663
        }
8664
      }));
8665
      return memMenu.asSpec();
8666
    };
8667
    var StylesMenu = { sketch: sketch$9 };
8668
8669
    var getFromExpandingItem = function (item) {
8670
      var newItem = deepMerge(exclude$1(item, ['items']), { menu: true });
8671
      var rest = expand(item.items);
8672
      var newMenus = deepMerge(rest.menus, wrap$2(item.title, rest.items));
8673
      var newExpansions = deepMerge(rest.expansions, wrap$2(item.title, item.title));
8674
      return {
8675
        item: newItem,
8676
        menus: newMenus,
8677
        expansions: newExpansions
8678
      };
8679
    };
8680
    var getFromItem = function (item) {
8681
      return hasKey$1(item, 'items') ? getFromExpandingItem(item) : {
8682
        item: item,
8683
        menus: {},
8684
        expansions: {}
8685
      };
8686
    };
8687
    var expand = function (items) {
8688
      return foldr(items, function (acc, item) {
8689
        var newData = getFromItem(item);
8690
        return {
8691
          menus: deepMerge(acc.menus, newData.menus),
8692
          items: [newData.item].concat(acc.items),
8693
          expansions: deepMerge(acc.expansions, newData.expansions)
8694
        };
8695
      }, {
8696
        menus: {},
8697
        expansions: {},
8698
        items: []
8699
      });
8700
    };
8701
    var StyleConversions = { expand: expand };
8702
8703
    var register$1 = function (editor, settings) {
8704
      var isSelectedFor = function (format) {
8705
        return function () {
8706
          return editor.formatter.match(format);
8707
        };
8708
      };
8709
      var getPreview = function (format) {
8710
        return function () {
8711
          var styles = editor.formatter.getCssText(format);
8712
          return styles;
8713
        };
8714
      };
8715
      var enrichSupported = function (item) {
8716
        return deepMerge(item, {
8717
          isSelected: isSelectedFor(item.format),
8718
          getPreview: getPreview(item.format)
8719
        });
8720
      };
8721
      var enrichMenu = function (item) {
8722
        return deepMerge(item, {
8723
          isSelected: constant(false),
8724
          getPreview: constant('')
8725
        });
8726
      };
8727
      var enrichCustom = function (item) {
8728
        var formatName = generate$1(item.title);
8729
        var newItem = deepMerge(item, {
8730
          format: formatName,
8731
          isSelected: isSelectedFor(formatName),
8732
          getPreview: getPreview(formatName)
8733
        });
8734
        editor.formatter.register(formatName, newItem);
8735
        return newItem;
8736
      };
8737
      var formats = readOptFrom$1(settings, 'style_formats').getOr(DefaultStyleFormats);
8738
      var doEnrich = function (items) {
8739
        return map$1(items, function (item) {
8740
          if (hasKey$1(item, 'items')) {
8741
            var newItems = doEnrich(item.items);
8742
            return deepMerge(enrichMenu(item), { items: newItems });
8743
          } else if (hasKey$1(item, 'format')) {
8744
            return enrichSupported(item);
8745
          } else {
8746
            return enrichCustom(item);
8747
          }
8748
        });
8749
      };
8750
      return doEnrich(formats);
8751
    };
8752
    var prune = function (editor, formats) {
8753
      var doPrune = function (items) {
8754
        return bind(items, function (item) {
8755
          if (item.items !== undefined) {
8756
            var newItems = doPrune(item.items);
8757
            return newItems.length > 0 ? [item] : [];
8758
          } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
8759
            var keep = hasKey$1(item, 'format') ? editor.formatter.canApply(item.format) : true;
8760
            return keep ? [item] : [];
8761
          }
8762
        });
8763
      };
8764
      var prunedItems = doPrune(formats);
8765
      return StyleConversions.expand(prunedItems);
8766
    };
8767
    var ui = function (editor, formats, onDone) {
8768
      var pruned = prune(editor, formats);
8769
      return StylesMenu.sketch({
8770
        formats: pruned,
8771
        handle: function (item, value) {
8772
          editor.undoManager.transact(function () {
8773
            if (Toggling.isOn(item)) {
8774
              editor.formatter.remove(value);
8775
            } else {
8776
              editor.formatter.apply(value);
8777
            }
8778
          });
8779
          onDone();
8780
        }
8781
      });
8782
    };
8783
    var StyleFormats = {
8784
      register: register$1,
8785
      ui: ui
8786
    };
8787
8788
    var defaults = [
8789
      'undo',
8790
      'bold',
8791
      'italic',
8792
      'link',
8793
      'image',
8794
      'bullist',
8795
      'styleselect'
8796
    ];
8797
    var extract$1 = function (rawToolbar) {
8798
      var toolbar = rawToolbar.replace(/\|/g, ' ').trim();
8799
      return toolbar.length > 0 ? toolbar.split(/\s+/) : [];
8800
    };
8801
    var identifyFromArray = function (toolbar) {
8802
      return bind(toolbar, function (item) {
8803
        return isArray(item) ? identifyFromArray(item) : extract$1(item);
8804
      });
8805
    };
8806
    var identify = function (settings) {
8807
      var toolbar = settings.toolbar !== undefined ? settings.toolbar : defaults;
8808
      return isArray(toolbar) ? identifyFromArray(toolbar) : extract$1(toolbar);
8809
    };
8810
    var setup = function (realm, editor) {
8811
      var commandSketch = function (name) {
8812
        return function () {
8813
          return Buttons.forToolbarCommand(editor, name);
8814
        };
8815
      };
8816
      var stateCommandSketch = function (name) {
8817
        return function () {
8818
          return Buttons.forToolbarStateCommand(editor, name);
8819
        };
8820
      };
8821
      var actionSketch = function (name, query, action) {
8822
        return function () {
8823
          return Buttons.forToolbarStateAction(editor, name, query, action);
8824
        };
8825
      };
8826
      var undo = commandSketch('undo');
8827
      var redo = commandSketch('redo');
8828
      var bold = stateCommandSketch('bold');
8829
      var italic = stateCommandSketch('italic');
8830
      var underline = stateCommandSketch('underline');
8831
      var removeformat = commandSketch('removeformat');
8832
      var link = function () {
8833
        return sketch$8(realm, editor);
8834
      };
8835
      var unlink = actionSketch('unlink', 'link', function () {
8836
        editor.execCommand('unlink', null, false);
8837
      });
8838
      var image = function () {
8839
        return sketch$5(editor);
8840
      };
8841
      var bullist = actionSketch('unordered-list', 'ul', function () {
8842
        editor.execCommand('InsertUnorderedList', null, false);
8843
      });
8844
      var numlist = actionSketch('ordered-list', 'ol', function () {
8845
        editor.execCommand('InsertOrderedList', null, false);
8846
      });
8847
      var fontsizeselect = function () {
8848
        return sketch$4(realm, editor);
8849
      };
8850
      var forecolor = function () {
8851
        return ColorSlider.sketch(realm, editor);
8852
      };
8853
      var styleFormats = StyleFormats.register(editor, editor.settings);
8854
      var styleFormatsMenu = function () {
8855
        return StyleFormats.ui(editor, styleFormats, function () {
8856
          editor.fire('scrollIntoView');
8857
        });
8858
      };
8859
      var styleselect = function () {
8860
        return Buttons.forToolbar('style-formats', function (button) {
8861
          editor.fire('toReading');
8862
          realm.dropup().appear(styleFormatsMenu, Toggling.on, button);
8863
        }, derive$2([
8864
          Toggling.config({
8865
            toggleClass: Styles.resolve('toolbar-button-selected'),
8866
            toggleOnExecute: false,
8867
            aria: { mode: 'pressed' }
8868
          }),
8869
          Receiving.config({
8870
            channels: wrapAll$1([
8871
              Receivers.receive(TinyChannels.orientationChanged(), Toggling.off),
8872
              Receivers.receive(TinyChannels.dropupDismissed(), Toggling.off)
8873
            ])
8874
          })
8875
        ]));
8876
      };
8877
      var feature = function (prereq, sketch) {
8878
        return {
8879
          isSupported: function () {
8880
            return prereq.forall(function (p) {
8881
              return hasKey$1(editor.buttons, p);
8882
            });
8883
          },
8884
          sketch: sketch
8885
        };
8886
      };
8887
      return {
8888
        undo: feature(Option.none(), undo),
8889
        redo: feature(Option.none(), redo),
8890
        bold: feature(Option.none(), bold),
8891
        italic: feature(Option.none(), italic),
8892
        underline: feature(Option.none(), underline),
8893
        removeformat: feature(Option.none(), removeformat),
8894
        link: feature(Option.none(), link),
8895
        unlink: feature(Option.none(), unlink),
8896
        image: feature(Option.none(), image),
8897
        bullist: feature(Option.some('bullist'), bullist),
8898
        numlist: feature(Option.some('numlist'), numlist),
8899
        fontsizeselect: feature(Option.none(), fontsizeselect),
8900
        forecolor: feature(Option.none(), forecolor),
8901
        styleselect: feature(Option.none(), styleselect)
8902
      };
8903
    };
8904
    var detect$4 = function (settings, features) {
8905
      var itemNames = identify(settings);
8906
      var present = {};
8907
      return bind(itemNames, function (iName) {
8908
        var r = !hasKey$1(present, iName) && hasKey$1(features, iName) && features[iName].isSupported() ? [features[iName].sketch()] : [];
8909
        present[iName] = true;
8910
        return r;
8911
      });
8912
    };
8913
    var Features = {
8914
      identify: identify,
8915
      setup: setup,
8916
      detect: detect$4
8917
    };
8918
8919
    var mkEvent = function (target, x, y, stop, prevent, kill, raw) {
8920
      return {
8921
        'target': constant(target),
8922
        'x': constant(x),
8923
        'y': constant(y),
8924
        'stop': stop,
8925
        'prevent': prevent,
8926
        'kill': kill,
8927
        'raw': constant(raw)
8928
      };
8929
    };
8930
    var handle = function (filter, handler) {
8931
      return function (rawEvent) {
8932
        if (!filter(rawEvent))
8933
          return;
8934
        var target = Element$$1.fromDom(rawEvent.target);
8935
        var stop = function () {
8936
          rawEvent.stopPropagation();
8937
        };
8938
        var prevent = function () {
8939
          rawEvent.preventDefault();
8940
        };
8941
        var kill = compose(prevent, stop);
8942
        var evt = mkEvent(target, rawEvent.clientX, rawEvent.clientY, stop, prevent, kill, rawEvent);
8943
        handler(evt);
8944
      };
8945
    };
8946
    var binder = function (element, event, filter, handler, useCapture) {
8947
      var wrapped = handle(filter, handler);
8948
      element.dom().addEventListener(event, wrapped, useCapture);
8949
      return { unbind: curry(unbind, element, event, wrapped, useCapture) };
8950
    };
8951
    var bind$1 = function (element, event, filter, handler) {
8952
      return binder(element, event, filter, handler, false);
8953
    };
8954
    var capture = function (element, event, filter, handler) {
8955
      return binder(element, event, filter, handler, true);
8956
    };
8957
    var unbind = function (element, event, handler, useCapture) {
8958
      element.dom().removeEventListener(event, handler, useCapture);
8959
    };
8960
8961
    var filter$1 = constant(true);
8962
    var bind$2 = function (element, event, handler) {
8963
      return bind$1(element, event, filter$1, handler);
8964
    };
8965
    var capture$1 = function (element, event, handler) {
8966
      return capture(element, event, filter$1, handler);
8967
    };
8968
8969
    var INTERVAL = 50;
8970
    var INSURANCE = 1000 / INTERVAL;
8971
    var get$c = function (outerWindow) {
8972
      var isPortrait = outerWindow.matchMedia('(orientation: portrait)').matches;
8973
      return { isPortrait: constant(isPortrait) };
8974
    };
8975
    var getActualWidth = function (outerWindow) {
8976
      var isIos = PlatformDetection$1.detect().os.isiOS();
8977
      var isPortrait = get$c(outerWindow).isPortrait();
8978
      return isIos && !isPortrait ? outerWindow.screen.height : outerWindow.screen.width;
8979
    };
8980
    var onChange = function (outerWindow, listeners) {
8981
      var win = Element$$1.fromDom(outerWindow);
8982
      var poller = null;
8983
      var change = function () {
8984
        clearInterval(poller);
8985
        var orientation = get$c(outerWindow);
8986
        listeners.onChange(orientation);
8987
        onAdjustment(function () {
8988
          listeners.onReady(orientation);
8989
        });
8990
      };
8991
      var orientationHandle = bind$2(win, 'orientationchange', change);
8992
      var onAdjustment = function (f) {
8993
        clearInterval(poller);
8994
        var flag = outerWindow.innerHeight;
8995
        var insurance = 0;
8996
        poller = setInterval(function () {
8997
          if (flag !== outerWindow.innerHeight) {
8998
            clearInterval(poller);
8999
            f(Option.some(outerWindow.innerHeight));
9000
          } else if (insurance > INSURANCE) {
9001
            clearInterval(poller);
9002
            f(Option.none());
9003
          }
9004
          insurance++;
9005
        }, INTERVAL);
9006
      };
9007
      var destroy = function () {
9008
        orientationHandle.unbind();
9009
      };
9010
      return {
9011
        onAdjustment: onAdjustment,
9012
        destroy: destroy
9013
      };
9014
    };
9015
    var Orientation = {
9016
      get: get$c,
9017
      onChange: onChange,
9018
      getActualWidth: getActualWidth
9019
    };
9020
9021
    function DelayedFunction (fun, delay) {
9022
      var ref = null;
9023
      var schedule = function () {
9024
        var args = [];
9025
        for (var _i = 0; _i < arguments.length; _i++) {
9026
          args[_i] = arguments[_i];
9027
        }
9028
        ref = setTimeout(function () {
9029
          fun.apply(null, args);
9030
          ref = null;
9031
        }, delay);
9032
      };
9033
      var cancel = function () {
9034
        if (ref !== null) {
9035
          clearTimeout(ref);
9036
          ref = null;
9037
        }
9038
      };
9039
      return {
9040
        cancel: cancel,
9041
        schedule: schedule
9042
      };
9043
    }
9044
9045
    var SIGNIFICANT_MOVE = 5;
9046
    var LONGPRESS_DELAY = 400;
9047
    var getTouch = function (event) {
9048
      var raw = event.raw();
9049
      if (raw.touches === undefined || raw.touches.length !== 1) {
9050
        return Option.none();
9051
      }
9052
      return Option.some(raw.touches[0]);
9053
    };
9054
    var isFarEnough = function (touch, data) {
9055
      var distX = Math.abs(touch.clientX - data.x());
9056
      var distY = Math.abs(touch.clientY - data.y());
9057
      return distX > SIGNIFICANT_MOVE || distY > SIGNIFICANT_MOVE;
9058
    };
9059
    var monitor = function (settings) {
9060
      var startData = Cell(Option.none());
9061
      var longpress$$1 = DelayedFunction(function (event) {
9062
        startData.set(Option.none());
9063
        settings.triggerEvent(longpress(), event);
9064
      }, LONGPRESS_DELAY);
9065
      var handleTouchstart = function (event) {
9066
        getTouch(event).each(function (touch) {
9067
          longpress$$1.cancel();
9068
          var data = {
9069
            x: constant(touch.clientX),
9070
            y: constant(touch.clientY),
9071
            target: event.target
9072
          };
9073
          longpress$$1.schedule(event);
9074
          startData.set(Option.some(data));
9075
        });
9076
        return Option.none();
9077
      };
9078
      var handleTouchmove = function (event) {
9079
        longpress$$1.cancel();
9080
        getTouch(event).each(function (touch) {
9081
          startData.get().each(function (data) {
9082
            if (isFarEnough(touch, data)) {
9083
              startData.set(Option.none());
9084
            }
9085
          });
9086
        });
9087
        return Option.none();
9088
      };
9089
      var handleTouchend = function (event) {
9090
        longpress$$1.cancel();
9091
        var isSame = function (data) {
9092
          return eq(data.target(), event.target());
9093
        };
9094
        return startData.get().filter(isSame).map(function (data) {
9095
          return settings.triggerEvent(tap(), event);
9096
        });
9097
      };
9098
      var handlers = wrapAll$1([
9099
        {
9100
          key: touchstart(),
9101
          value: handleTouchstart
9102
        },
9103
        {
9104
          key: touchmove(),
9105
          value: handleTouchmove
9106
        },
9107
        {
9108
          key: touchend(),
9109
          value: handleTouchend
9110
        }
9111
      ]);
9112
      var fireIfReady = function (event, type) {
9113
        return readOptFrom$1(handlers, type).bind(function (handler) {
9114
          return handler(event);
9115
        });
9116
      };
9117
      return { fireIfReady: fireIfReady };
9118
    };
9119
9120
    var monitor$1 = function (editorApi) {
9121
      var tapEvent = monitor({
9122
        triggerEvent: function (type, evt) {
9123
          editorApi.onTapContent(evt);
9124
        }
9125
      });
9126
      var onTouchend = function () {
9127
        return bind$2(editorApi.body(), 'touchend', function (evt) {
9128
          tapEvent.fireIfReady(evt, 'touchend');
9129
        });
9130
      };
9131
      var onTouchmove = function () {
9132
        return bind$2(editorApi.body(), 'touchmove', function (evt) {
9133
          tapEvent.fireIfReady(evt, 'touchmove');
9134
        });
9135
      };
9136
      var fireTouchstart = function (evt) {
9137
        tapEvent.fireIfReady(evt, 'touchstart');
9138
      };
9139
      return {
9140
        fireTouchstart: fireTouchstart,
9141
        onTouchend: onTouchend,
9142
        onTouchmove: onTouchmove
9143
      };
9144
    };
9145
    var TappingEvent = { monitor: monitor$1 };
9146
9147
    var isAndroid6 = PlatformDetection$1.detect().os.version.major >= 6;
9148
    var initEvents = function (editorApi, toolstrip, alloy) {
9149
      var tapping = TappingEvent.monitor(editorApi);
9150
      var outerDoc = owner(toolstrip);
9151
      var isRanged = function (sel) {
9152
        return !eq(sel.start(), sel.finish()) || sel.soffset() !== sel.foffset();
9153
      };
9154
      var hasRangeInUi = function () {
9155
        return active(outerDoc).filter(function (input) {
9156
          return name(input) === 'input';
9157
        }).exists(function (input) {
9158
          return input.dom().selectionStart !== input.dom().selectionEnd;
9159
        });
9160
      };
9161
      var updateMargin = function () {
9162
        var rangeInContent = editorApi.doc().dom().hasFocus() && editorApi.getSelection().exists(isRanged);
9163
        alloy.getByDom(toolstrip).each((rangeInContent || hasRangeInUi()) === true ? Toggling.on : Toggling.off);
9164
      };
9165
      var listeners = [
9166
        bind$2(editorApi.body(), 'touchstart', function (evt) {
9167
          editorApi.onTouchContent();
9168
          tapping.fireTouchstart(evt);
9169
        }),
9170
        tapping.onTouchmove(),
9171
        tapping.onTouchend(),
9172
        bind$2(toolstrip, 'touchstart', function (evt) {
9173
          editorApi.onTouchToolstrip();
9174
        }),
9175
        editorApi.onToReading(function () {
9176
          blur$$1(editorApi.body());
9177
        }),
9178
        editorApi.onToEditing(noop),
9179
        editorApi.onScrollToCursor(function (tinyEvent) {
9180
          tinyEvent.preventDefault();
9181
          editorApi.getCursorBox().each(function (bounds) {
9182
            var cWin = editorApi.win();
9183
            var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
9184
            var cScrollBy = isOutside ? bounds.bottom() - cWin.innerHeight + 50 : 0;
9185
            if (cScrollBy !== 0) {
9186
              cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
9187
            }
9188
          });
9189
        })
9190
      ].concat(isAndroid6 === true ? [] : [
9191
        bind$2(Element$$1.fromDom(editorApi.win()), 'blur', function () {
9192
          alloy.getByDom(toolstrip).each(Toggling.off);
9193
        }),
9194
        bind$2(outerDoc, 'select', updateMargin),
9195
        bind$2(editorApi.doc(), 'selectionchange', updateMargin)
9196
      ]);
9197
      var destroy = function () {
9198
        each$1(listeners, function (l) {
9199
          l.unbind();
9200
        });
9201
      };
9202
      return { destroy: destroy };
9203
    };
9204
    var AndroidEvents = { initEvents: initEvents };
9205
9206
    var safeParse = function (element, attribute) {
9207
      var parsed = parseInt(get$1(element, attribute), 10);
9208
      return isNaN(parsed) ? 0 : parsed;
9209
    };
9210
    var DataAttributes = { safeParse: safeParse };
9211
9212
    function NodeValue (is, name) {
9213
      var get = function (element) {
9214
        if (!is(element))
9215
          throw new Error('Can only get ' + name + ' value of a ' + name + ' node');
9216
        return getOption(element).getOr('');
9217
      };
9218
      var getOptionIE10 = function (element) {
9219
        try {
9220
          return getOptionSafe(element);
9221
        } catch (e) {
9222
          return Option.none();
9223
        }
9224
      };
9225
      var getOptionSafe = function (element) {
9226
        return is(element) ? Option.from(element.dom().nodeValue) : Option.none();
9227
      };
9228
      var browser = PlatformDetection$1.detect().browser;
9229
      var getOption = browser.isIE() && browser.version.major === 10 ? getOptionIE10 : getOptionSafe;
9230
      var set = function (element, value) {
9231
        if (!is(element))
9232
          throw new Error('Can only set raw ' + name + ' value of a ' + name + ' node');
9233
        element.dom().nodeValue = value;
9234
      };
9235
      return {
9236
        get: get,
9237
        getOption: getOption,
9238
        set: set
9239
      };
9240
    }
9241
9242
    var api$3 = NodeValue(isText, 'text');
9243
    var get$d = function (element) {
9244
      return api$3.get(element);
9245
    };
9246
    var getOption = function (element) {
9247
      return api$3.getOption(element);
9248
    };
9249
9250
    var getEnd = function (element) {
9251
      return name(element) === 'img' ? 1 : getOption(element).fold(function () {
9252
        return children(element).length;
9253
      }, function (v) {
9254
        return v.length;
9255
      });
9256
    };
9257
    var NBSP = '\xA0';
9258
    var isTextNodeWithCursorPosition = function (el) {
9259
      return getOption(el).filter(function (text) {
9260
        return text.trim().length !== 0 || text.indexOf(NBSP) > -1;
9261
      }).isSome();
9262
    };
9263
    var elementsWithCursorPosition = [
9264
      'img',
9265
      'br'
9266
    ];
9267
    var isCursorPosition = function (elem) {
9268
      var hasCursorPosition = isTextNodeWithCursorPosition(elem);
9269
      return hasCursorPosition || contains(elementsWithCursorPosition, name(elem));
9270
    };
9271
9272
    var adt$4 = Adt.generate([
9273
      { 'before': ['element'] },
9274
      {
9275
        'on': [
9276
          'element',
9277
          'offset'
9278
        ]
9279
      },
9280
      { after: ['element'] }
9281
    ]);
9282
    var cata = function (subject, onBefore, onOn, onAfter) {
9283
      return subject.fold(onBefore, onOn, onAfter);
9284
    };
9285
    var getStart = function (situ) {
9286
      return situ.fold(identity, identity, identity);
9287
    };
9288
    var before$2 = adt$4.before;
9289
    var on$1 = adt$4.on;
9290
    var after$2 = adt$4.after;
9291
    var Situ = {
9292
      before: before$2,
9293
      on: on$1,
9294
      after: after$2,
9295
      cata: cata,
9296
      getStart: getStart
9297
    };
9298
9299
    var type$1 = Adt.generate([
9300
      { domRange: ['rng'] },
9301
      {
9302
        relative: [
9303
          'startSitu',
9304
          'finishSitu'
9305
        ]
9306
      },
9307
      {
9308
        exact: [
9309
          'start',
9310
          'soffset',
9311
          'finish',
9312
          'foffset'
9313
        ]
9314
      }
9315
    ]);
9316
    var range$1 = Immutable('start', 'soffset', 'finish', 'foffset');
9317
    var relative = type$1.relative;
9318
    var exact = type$1.exact;
9319
9320
    var makeRange = function (start, soffset, finish, foffset) {
9321
      var doc = owner(start);
9322
      var rng = doc.dom().createRange();
9323
      rng.setStart(start.dom(), soffset);
9324
      rng.setEnd(finish.dom(), foffset);
9325
      return rng;
9326
    };
9327
    var after$3 = function (start, soffset, finish, foffset) {
9328
      var r = makeRange(start, soffset, finish, foffset);
9329
      var same = eq(start, finish) && soffset === foffset;
9330
      return r.collapsed && !same;
9331
    };
9332
9333
    var setStart = function (rng, situ) {
9334
      situ.fold(function (e) {
9335
        rng.setStartBefore(e.dom());
9336
      }, function (e, o) {
9337
        rng.setStart(e.dom(), o);
9338
      }, function (e) {
9339
        rng.setStartAfter(e.dom());
9340
      });
9341
    };
9342
    var setFinish = function (rng, situ) {
9343
      situ.fold(function (e) {
9344
        rng.setEndBefore(e.dom());
9345
      }, function (e, o) {
9346
        rng.setEnd(e.dom(), o);
9347
      }, function (e) {
9348
        rng.setEndAfter(e.dom());
9349
      });
9350
    };
9351
    var relativeToNative = function (win, startSitu, finishSitu) {
9352
      var range = win.document.createRange();
9353
      setStart(range, startSitu);
9354
      setFinish(range, finishSitu);
9355
      return range;
9356
    };
9357
    var exactToNative = function (win, start, soffset, finish, foffset) {
9358
      var rng = win.document.createRange();
9359
      rng.setStart(start.dom(), soffset);
9360
      rng.setEnd(finish.dom(), foffset);
9361
      return rng;
9362
    };
9363
    var toRect = function (rect) {
9364
      return {
9365
        left: constant(rect.left),
9366
        top: constant(rect.top),
9367
        right: constant(rect.right),
9368
        bottom: constant(rect.bottom),
9369
        width: constant(rect.width),
9370
        height: constant(rect.height)
9371
      };
9372
    };
9373
    var getFirstRect = function (rng) {
9374
      var rects = rng.getClientRects();
9375
      var rect = rects.length > 0 ? rects[0] : rng.getBoundingClientRect();
9376
      return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect) : Option.none();
9377
    };
9378
9379
    var adt$5 = Adt.generate([
9380
      {
9381
        ltr: [
9382
          'start',
9383
          'soffset',
9384
          'finish',
9385
          'foffset'
9386
        ]
9387
      },
9388
      {
9389
        rtl: [
9390
          'start',
9391
          'soffset',
9392
          'finish',
9393
          'foffset'
9394
        ]
9395
      }
9396
    ]);
9397
    var fromRange = function (win, type, range) {
9398
      return type(Element$$1.fromDom(range.startContainer), range.startOffset, Element$$1.fromDom(range.endContainer), range.endOffset);
9399
    };
9400
    var getRanges = function (win, selection) {
9401
      return selection.match({
9402
        domRange: function (rng) {
9403
          return {
9404
            ltr: constant(rng),
9405
            rtl: Option.none
9406
          };
9407
        },
9408
        relative: function (startSitu, finishSitu) {
9409
          return {
9410
            ltr: cached(function () {
9411
              return relativeToNative(win, startSitu, finishSitu);
9412
            }),
9413
            rtl: cached(function () {
9414
              return Option.some(relativeToNative(win, finishSitu, startSitu));
9415
            })
9416
          };
9417
        },
9418
        exact: function (start, soffset, finish, foffset) {
9419
          return {
9420
            ltr: cached(function () {
9421
              return exactToNative(win, start, soffset, finish, foffset);
9422
            }),
9423
            rtl: cached(function () {
9424
              return Option.some(exactToNative(win, finish, foffset, start, soffset));
9425
            })
9426
          };
9427
        }
9428
      });
9429
    };
9430
    var doDiagnose = function (win, ranges) {
9431
      var rng = ranges.ltr();
9432
      if (rng.collapsed) {
9433
        var reversed = ranges.rtl().filter(function (rev) {
9434
          return rev.collapsed === false;
9435
        });
9436
        return reversed.map(function (rev) {
9437
          return adt$5.rtl(Element$$1.fromDom(rev.endContainer), rev.endOffset, Element$$1.fromDom(rev.startContainer), rev.startOffset);
9438
        }).getOrThunk(function () {
9439
          return fromRange(win, adt$5.ltr, rng);
9440
        });
9441
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
9442
        return fromRange(win, adt$5.ltr, rng);
9443
      }
9444
    };
9445
    var diagnose = function (win, selection) {
9446
      var ranges = getRanges(win, selection);
9447
      return doDiagnose(win, ranges);
9448
    };
9449
    var asLtrRange = function (win, selection) {
9450
      var diagnosis = diagnose(win, selection);
9451
      return diagnosis.match({
9452
        ltr: function (start, soffset, finish, foffset) {
9453
          var rng = win.document.createRange();
9454
          rng.setStart(start.dom(), soffset);
9455
          rng.setEnd(finish.dom(), foffset);
9456
          return rng;
9457
        },
9458
        rtl: function (start, soffset, finish, foffset) {
9459
          var rng = win.document.createRange();
9460
          rng.setStart(finish.dom(), foffset);
9461
          rng.setEnd(start.dom(), soffset);
9462
          return rng;
9463
        }
9464
      });
9465
    };
9466
9467
    var searchForPoint = function (rectForOffset, x, y, maxX, length) {
9468
      if (length === 0)
9469
        return 0;
9470
      else if (x === maxX)
9471
        return length - 1;
9472
      var xDelta = maxX;
9473
      for (var i = 1; i < length; i++) {
9474
        var rect = rectForOffset(i);
9475
        var curDeltaX = Math.abs(x - rect.left);
9476
        if (y <= rect.bottom) {
9477
          if (y < rect.top || curDeltaX > xDelta) {
9478
            return i - 1;
9479
          } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
9480
            xDelta = curDeltaX;
9481
          }
9482
        }
9483
      }
9484
      return 0;
9485
    };
9486
    var inRect = function (rect, x, y) {
9487
      return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
9488
    };
9489
9490
    var locateOffset = function (doc, textnode, x, y, rect) {
9491
      var rangeForOffset = function (offset) {
9492
        var r = doc.dom().createRange();
9493
        r.setStart(textnode.dom(), offset);
9494
        r.collapse(true);
9495
        return r;
9496
      };
9497
      var rectForOffset = function (offset) {
9498
        var r = rangeForOffset(offset);
9499
        return r.getBoundingClientRect();
9500
      };
9501
      var length = get$d(textnode).length;
9502
      var offset = searchForPoint(rectForOffset, x, y, rect.right, length);
9503
      return rangeForOffset(offset);
9504
    };
9505
    var locate$1 = function (doc, node, x, y) {
9506
      var r = doc.dom().createRange();
9507
      r.selectNode(node.dom());
9508
      var rects = r.getClientRects();
9509
      var foundRect = findMap(rects, function (rect) {
9510
        return inRect(rect, x, y) ? Option.some(rect) : Option.none();
9511
      });
9512
      return foundRect.map(function (rect) {
9513
        return locateOffset(doc, node, x, y, rect);
9514
      });
9515
    };
9516
9517
    var searchInChildren = function (doc, node, x, y) {
9518
      var r = doc.dom().createRange();
9519
      var nodes = children(node);
9520
      return findMap(nodes, function (n) {
9521
        r.selectNode(n.dom());
9522
        return inRect(r.getBoundingClientRect(), x, y) ? locateNode(doc, n, x, y) : Option.none();
9523
      });
9524
    };
9525
    var locateNode = function (doc, node, x, y) {
9526
      var locator = isText(node) ? locate$1 : searchInChildren;
9527
      return locator(doc, node, x, y);
9528
    };
9529
    var locate$2 = function (doc, node, x, y) {
9530
      var r = doc.dom().createRange();
9531
      r.selectNode(node.dom());
9532
      var rect = r.getBoundingClientRect();
9533
      var boundedX = Math.max(rect.left, Math.min(rect.right, x));
9534
      var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
9535
      return locateNode(doc, node, boundedX, boundedY);
9536
    };
9537
9538
    var first$3 = function (element) {
9539
      return descendant(element, isCursorPosition);
9540
    };
9541
    var last$2 = function (element) {
9542
      return descendantRtl(element, isCursorPosition);
9543
    };
9544
    var descendantRtl = function (scope, predicate) {
9545
      var descend = function (element) {
9546
        var children$$1 = children(element);
9547
        for (var i = children$$1.length - 1; i >= 0; i--) {
9548
          var child$$1 = children$$1[i];
9549
          if (predicate(child$$1))
9550
            return Option.some(child$$1);
9551
          var res = descend(child$$1);
9552
          if (res.isSome())
9553
            return res;
9554
        }
9555
        return Option.none();
9556
      };
9557
      return descend(scope);
9558
    };
9559
9560
    var COLLAPSE_TO_LEFT = true;
9561
    var COLLAPSE_TO_RIGHT = false;
9562
    var getCollapseDirection = function (rect, x) {
9563
      return x - rect.left < rect.right - x ? COLLAPSE_TO_LEFT : COLLAPSE_TO_RIGHT;
9564
    };
9565
    var createCollapsedNode = function (doc, target, collapseDirection) {
9566
      var r = doc.dom().createRange();
9567
      r.selectNode(target.dom());
9568
      r.collapse(collapseDirection);
9569
      return r;
9570
    };
9571
    var locateInElement = function (doc, node, x) {
9572
      var cursorRange = doc.dom().createRange();
9573
      cursorRange.selectNode(node.dom());
9574
      var rect = cursorRange.getBoundingClientRect();
9575
      var collapseDirection = getCollapseDirection(rect, x);
9576
      var f = collapseDirection === COLLAPSE_TO_LEFT ? first$3 : last$2;
9577
      return f(node).map(function (target) {
9578
        return createCollapsedNode(doc, target, collapseDirection);
9579
      });
9580
    };
9581
    var locateInEmpty = function (doc, node, x) {
9582
      var rect = node.dom().getBoundingClientRect();
9583
      var collapseDirection = getCollapseDirection(rect, x);
9584
      return Option.some(createCollapsedNode(doc, node, collapseDirection));
9585
    };
9586
    var search$1 = function (doc, node, x) {
9587
      var f = children(node).length === 0 ? locateInEmpty : locateInElement;
9588
      return f(doc, node, x);
9589
    };
9590
9591
    var caretPositionFromPoint = function (doc, x, y) {
9592
      return Option.from(doc.dom().caretPositionFromPoint(x, y)).bind(function (pos) {
9593
        if (pos.offsetNode === null)
9594
          return Option.none();
9595
        var r = doc.dom().createRange();
9596
        r.setStart(pos.offsetNode, pos.offset);
9597
        r.collapse();
9598
        return Option.some(r);
9599
      });
9600
    };
9601
    var caretRangeFromPoint = function (doc, x, y) {
9602
      return Option.from(doc.dom().caretRangeFromPoint(x, y));
9603
    };
9604
    var searchTextNodes = function (doc, node, x, y) {
9605
      var r = doc.dom().createRange();
9606
      r.selectNode(node.dom());
9607
      var rect = r.getBoundingClientRect();
9608
      var boundedX = Math.max(rect.left, Math.min(rect.right, x));
9609
      var boundedY = Math.max(rect.top, Math.min(rect.bottom, y));
9610
      return locate$2(doc, node, boundedX, boundedY);
9611
    };
9612
    var searchFromPoint = function (doc, x, y) {
9613
      return Element$$1.fromPoint(doc, x, y).bind(function (elem) {
9614
        var fallback = function () {
9615
          return search$1(doc, elem, x);
9616
        };
9617
        return children(elem).length === 0 ? fallback() : searchTextNodes(doc, elem, x, y).orThunk(fallback);
9618
      });
9619
    };
9620
    var availableSearch = document.caretPositionFromPoint ? caretPositionFromPoint : document.caretRangeFromPoint ? caretRangeFromPoint : searchFromPoint;
9621
9622
    var beforeSpecial = function (element, offset) {
9623
      var name$$1 = name(element);
9624
      if ('input' === name$$1)
9625
        return Situ.after(element);
9626
      else if (!contains([
9627
          'br',
9628
          'img'
9629
        ], name$$1))
9630
        return Situ.on(element, offset);
9631
      else
9632
        return offset === 0 ? Situ.before(element) : Situ.after(element);
9633
    };
9634
    var preprocessExact = function (start, soffset, finish, foffset) {
9635
      var startSitu = beforeSpecial(start, soffset);
9636
      var finishSitu = beforeSpecial(finish, foffset);
9637
      return relative(startSitu, finishSitu);
9638
    };
9639
9640
    var doSetNativeRange = function (win, rng) {
9641
      Option.from(win.getSelection()).each(function (selection) {
9642
        selection.removeAllRanges();
9643
        selection.addRange(rng);
9644
      });
9645
    };
9646
    var doSetRange = function (win, start, soffset, finish, foffset) {
9647
      var rng = exactToNative(win, start, soffset, finish, foffset);
9648
      doSetNativeRange(win, rng);
9649
    };
9650
    var setLegacyRtlRange = function (win, selection, start, soffset, finish, foffset) {
9651
      selection.collapse(start.dom(), soffset);
9652
      selection.extend(finish.dom(), foffset);
9653
    };
9654
    var setRangeFromRelative = function (win, relative$$1) {
9655
      return diagnose(win, relative$$1).match({
9656
        ltr: function (start, soffset, finish, foffset) {
9657
          doSetRange(win, start, soffset, finish, foffset);
9658
        },
9659
        rtl: function (start, soffset, finish, foffset) {
9660
          var selection = win.getSelection();
9661
          if (selection.setBaseAndExtent) {
9662
            selection.setBaseAndExtent(start.dom(), soffset, finish.dom(), foffset);
9663
          } else if (selection.extend) {
9664
            try {
9665
              setLegacyRtlRange(win, selection, start, soffset, finish, foffset);
9666
            } catch (e) {
9667
              doSetRange(win, finish, foffset, start, soffset);
9668
            }
9669
          } else {
9670
            doSetRange(win, finish, foffset, start, soffset);
9671
          }
9672
        }
9673
      });
9674
    };
9675
    var setExact = function (win, start, soffset, finish, foffset) {
9676
      var relative$$1 = preprocessExact(start, soffset, finish, foffset);
9677
      setRangeFromRelative(win, relative$$1);
9678
    };
9679
    var readRange = function (selection) {
9680
      if (selection.rangeCount > 0) {
9681
        var firstRng = selection.getRangeAt(0);
9682
        var lastRng = selection.getRangeAt(selection.rangeCount - 1);
9683
        return Option.some(range$1(Element$$1.fromDom(firstRng.startContainer), firstRng.startOffset, Element$$1.fromDom(lastRng.endContainer), lastRng.endOffset));
9684
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
9685
        return Option.none();
9686
      }
9687
    };
9688
    var doGetExact = function (selection) {
9689
      var anchorNode = Element$$1.fromDom(selection.anchorNode);
9690
      var focusNode = Element$$1.fromDom(selection.focusNode);
9691
      return after$3(anchorNode, selection.anchorOffset, focusNode, selection.focusOffset) ? Option.some(range$1(Element$$1.fromDom(selection.anchorNode), selection.anchorOffset, Element$$1.fromDom(selection.focusNode), selection.focusOffset)) : readRange(selection);
9692
    };
9693
    var getExact = function (win) {
9694
      return Option.from(win.getSelection()).filter(function (sel) {
9695
        return sel.rangeCount > 0;
9696
      }).bind(doGetExact);
9697
    };
9698
    var get$e = function (win) {
9699
      return getExact(win).map(function (range) {
9700
        return exact(range.start(), range.soffset(), range.finish(), range.foffset());
9701
      });
9702
    };
9703
    var getFirstRect$1 = function (win, selection) {
9704
      var rng = asLtrRange(win, selection);
9705
      return getFirstRect(rng);
9706
    };
9707
    var clear$1 = function (win) {
9708
      var selection = win.getSelection();
9709
      selection.removeAllRanges();
9710
    };
9711
9712
    var COLLAPSED_WIDTH = 2;
9713
    var collapsedRect = function (rect) {
9714
      return {
9715
        left: rect.left,
9716
        top: rect.top,
9717
        right: rect.right,
9718
        bottom: rect.bottom,
9719
        width: constant(COLLAPSED_WIDTH),
9720
        height: rect.height
9721
      };
9722
    };
9723
    var toRect$1 = function (rawRect) {
9724
      return {
9725
        left: constant(rawRect.left),
9726
        top: constant(rawRect.top),
9727
        right: constant(rawRect.right),
9728
        bottom: constant(rawRect.bottom),
9729
        width: constant(rawRect.width),
9730
        height: constant(rawRect.height)
9731
      };
9732
    };
9733
    var getRectsFromRange = function (range$$1) {
9734
      if (!range$$1.collapsed) {
9735
        return map$1(range$$1.getClientRects(), toRect$1);
9736
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
9737
        var start_1 = Element$$1.fromDom(range$$1.startContainer);
9738
        return parent(start_1).bind(function (parent$$1) {
9739
          var selection = exact(start_1, range$$1.startOffset, parent$$1, getEnd(parent$$1));
9740
          var optRect = getFirstRect$1(range$$1.startContainer.ownerDocument.defaultView, selection);
9741
          return optRect.map(collapsedRect).map(pure);
9742
        }).getOr([]);
9743
      }
9744
    };
9745
    var getRectangles = function (cWin) {
9746
      var sel = cWin.getSelection();
9747
      return sel !== undefined && sel.rangeCount > 0 ? getRectsFromRange(sel.getRangeAt(0)) : [];
9748
    };
9749
    var Rectangles = { getRectangles: getRectangles };
9750
9751
    var autocompleteHack = function () {
9752
      return function (f) {
9753
        setTimeout(function () {
9754
          f();
9755
        }, 0);
9756
      };
9757
    };
9758
    var resume = function (cWin) {
9759
      cWin.focus();
9760
      var iBody = Element$$1.fromDom(cWin.document.body);
9761
      var inInput = active().exists(function (elem) {
9762
        return contains([
9763
          'input',
9764
          'textarea'
9765
        ], name(elem));
9766
      });
9767
      var transaction = inInput ? autocompleteHack() : apply;
9768
      transaction(function () {
9769
        active().each(blur$$1);
9770
        focus$2(iBody);
9771
      });
9772
    };
9773
    var ResumeEditing = { resume: resume };
9774
9775
    var EXTRA_SPACING = 50;
9776
    var data = 'data-' + Styles.resolve('last-outer-height');
9777
    var setLastHeight = function (cBody, value) {
9778
      set(cBody, data, value);
9779
    };
9780
    var getLastHeight = function (cBody) {
9781
      return DataAttributes.safeParse(cBody, data);
9782
    };
9783
    var getBoundsFrom = function (rect) {
9784
      return {
9785
        top: constant(rect.top()),
9786
        bottom: constant(rect.top() + rect.height())
9787
      };
9788
    };
9789
    var getBounds$2 = function (cWin) {
9790
      var rects = Rectangles.getRectangles(cWin);
9791
      return rects.length > 0 ? Option.some(rects[0]).map(getBoundsFrom) : Option.none();
9792
    };
9793
    var findDelta = function (outerWindow, cBody) {
9794
      var last = getLastHeight(cBody);
9795
      var current = outerWindow.innerHeight;
9796
      return last > current ? Option.some(last - current) : Option.none();
9797
    };
9798
    var calculate = function (cWin, bounds, delta) {
9799
      var isOutside = bounds.top() > cWin.innerHeight || bounds.bottom() > cWin.innerHeight;
9800
      return isOutside ? Math.min(delta, bounds.bottom() - cWin.innerHeight + EXTRA_SPACING) : 0;
9801
    };
9802
    var setup$1 = function (outerWindow, cWin) {
9803
      var cBody = Element$$1.fromDom(cWin.document.body);
9804
      var toEditing = function () {
9805
        ResumeEditing.resume(cWin);
9806
      };
9807
      var onResize = bind$2(Element$$1.fromDom(outerWindow), 'resize', function () {
9808
        findDelta(outerWindow, cBody).each(function (delta) {
9809
          getBounds$2(cWin).each(function (bounds) {
9810
            var cScrollBy = calculate(cWin, bounds, delta);
9811
            if (cScrollBy !== 0) {
9812
              cWin.scrollTo(cWin.pageXOffset, cWin.pageYOffset + cScrollBy);
9813
            }
9814
          });
9815
        });
9816
        setLastHeight(cBody, outerWindow.innerHeight);
9817
      });
9818
      setLastHeight(cBody, outerWindow.innerHeight);
9819
      var destroy = function () {
9820
        onResize.unbind();
9821
      };
9822
      return {
9823
        toEditing: toEditing,
9824
        destroy: destroy
9825
      };
9826
    };
9827
    var AndroidSetup = { setup: setup$1 };
9828
9829
    var getBodyFromFrame = function (frame) {
9830
      return Option.some(Element$$1.fromDom(frame.dom().contentWindow.document.body));
9831
    };
9832
    var getDocFromFrame = function (frame) {
9833
      return Option.some(Element$$1.fromDom(frame.dom().contentWindow.document));
9834
    };
9835
    var getWinFromFrame = function (frame) {
9836
      return Option.from(frame.dom().contentWindow);
9837
    };
9838
    var getSelectionFromFrame = function (frame) {
9839
      var optWin = getWinFromFrame(frame);
9840
      return optWin.bind(getExact);
9841
    };
9842
    var getFrame = function (editor) {
9843
      return editor.getFrame();
9844
    };
9845
    var getOrDerive = function (name, f) {
9846
      return function (editor) {
9847
        var g = editor[name].getOrThunk(function () {
9848
          var frame = getFrame(editor);
9849
          return function () {
9850
            return f(frame);
9851
          };
9852
        });
9853
        return g();
9854
      };
9855
    };
9856
    var getOrListen = function (editor, doc, name, type) {
9857
      return editor[name].getOrThunk(function () {
9858
        return function (handler) {
9859
          return bind$2(doc, type, handler);
9860
        };
9861
      });
9862
    };
9863
    var toRect$2 = function (rect) {
9864
      return {
9865
        left: constant(rect.left),
9866
        top: constant(rect.top),
9867
        right: constant(rect.right),
9868
        bottom: constant(rect.bottom),
9869
        width: constant(rect.width),
9870
        height: constant(rect.height)
9871
      };
9872
    };
9873
    var getActiveApi = function (editor) {
9874
      var frame = getFrame(editor);
9875
      var tryFallbackBox = function (win) {
9876
        var isCollapsed$$1 = function (sel) {
9877
          return eq(sel.start(), sel.finish()) && sel.soffset() === sel.foffset();
9878
        };
9879
        var toStartRect = function (sel) {
9880
          var rect = sel.start().dom().getBoundingClientRect();
9881
          return rect.width > 0 || rect.height > 0 ? Option.some(rect).map(toRect$2) : Option.none();
9882
        };
9883
        return getExact(win).filter(isCollapsed$$1).bind(toStartRect);
9884
      };
9885
      return getBodyFromFrame(frame).bind(function (body) {
9886
        return getDocFromFrame(frame).bind(function (doc) {
9887
          return getWinFromFrame(frame).map(function (win) {
9888
            var html = Element$$1.fromDom(doc.dom().documentElement);
9889
            var getCursorBox = editor.getCursorBox.getOrThunk(function () {
9890
              return function () {
9891
                return get$e(win).bind(function (sel) {
9892
                  return getFirstRect$1(win, sel).orThunk(function () {
9893
                    return tryFallbackBox(win);
9894
                  });
9895
                });
9896
              };
9897
            });
9898
            var setSelection = editor.setSelection.getOrThunk(function () {
9899
              return function (start, soffset, finish, foffset) {
9900
                setExact(win, start, soffset, finish, foffset);
9901
              };
9902
            });
9903
            var clearSelection = editor.clearSelection.getOrThunk(function () {
9904
              return function () {
9905
                clear$1(win);
9906
              };
9907
            });
9908
            return {
9909
              body: constant(body),
9910
              doc: constant(doc),
9911
              win: constant(win),
9912
              html: constant(html),
9913
              getSelection: curry(getSelectionFromFrame, frame),
9914
              setSelection: setSelection,
9915
              clearSelection: clearSelection,
9916
              frame: constant(frame),
9917
              onKeyup: getOrListen(editor, doc, 'onKeyup', 'keyup'),
9918
              onNodeChanged: getOrListen(editor, doc, 'onNodeChanged', 'selectionchange'),
9919
              onDomChanged: editor.onDomChanged,
9920
              onScrollToCursor: editor.onScrollToCursor,
9921
              onScrollToElement: editor.onScrollToElement,
9922
              onToReading: editor.onToReading,
9923
              onToEditing: editor.onToEditing,
9924
              onToolbarScrollStart: editor.onToolbarScrollStart,
9925
              onTouchContent: editor.onTouchContent,
9926
              onTapContent: editor.onTapContent,
9927
              onTouchToolstrip: editor.onTouchToolstrip,
9928
              getCursorBox: getCursorBox
9929
            };
9930
          });
9931
        });
9932
      });
9933
    };
9934
    var PlatformEditor = {
9935
      getBody: getOrDerive('getBody', getBodyFromFrame),
9936
      getDoc: getOrDerive('getDoc', getDocFromFrame),
9937
      getWin: getOrDerive('getWin', getWinFromFrame),
9938
      getSelection: getOrDerive('getSelection', getSelectionFromFrame),
9939
      getFrame: getFrame,
9940
      getActiveApi: getActiveApi
9941
    };
9942
9943
    var attr = 'data-ephox-mobile-fullscreen-style';
9944
    var siblingStyles = 'display:none!important;';
9945
    var ancestorPosition = 'position:absolute!important;';
9946
    var ancestorStyles = 'top:0!important;left:0!important;margin:0' + '!important;padding:0!important;width:100%!important;';
9947
    var bgFallback = 'background-color:rgb(255,255,255)!important;';
9948
    var isAndroid = PlatformDetection$1.detect().os.isAndroid();
9949
    var matchColor = function (editorBody) {
9950
      var color = get$4(editorBody, 'background-color');
9951
      return color !== undefined && color !== '' ? 'background-color:' + color + '!important' : bgFallback;
9952
    };
9953
    var clobberStyles = function (container, editorBody) {
9954
      var gatherSibilings = function (element) {
9955
        var siblings = siblings$2(element, '*');
9956
        return siblings;
9957
      };
9958
      var clobber = function (clobberStyle) {
9959
        return function (element) {
9960
          var styles = get$1(element, 'style');
9961
          var backup = styles === undefined ? 'no-styles' : styles.trim();
9962
          if (backup === clobberStyle) {
9963
            return;
0 ignored issues
show
Unused Code introduced by
This return has no effect and can be removed.
Loading history...
9964
          } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
9965
            set(element, attr, backup);
9966
            set(element, 'style', clobberStyle);
9967
          }
9968
        };
9969
      };
9970
      var ancestors = ancestors$1(container, '*');
9971
      var siblings = bind(ancestors, gatherSibilings);
9972
      var bgColor = matchColor(editorBody);
9973
      each$1(siblings, clobber(siblingStyles));
9974
      each$1(ancestors, clobber(ancestorPosition + ancestorStyles + bgColor));
9975
      var containerStyles = isAndroid === true ? '' : ancestorPosition;
9976
      clobber(containerStyles + ancestorStyles + bgColor)(container);
9977
    };
9978
    var restoreStyles = function () {
9979
      var clobberedEls = all$3('[' + attr + ']');
9980
      each$1(clobberedEls, function (element) {
9981
        var restore = get$1(element, attr);
9982
        if (restore !== 'no-styles') {
9983
          set(element, 'style', restore);
9984
        } else {
9985
          remove$1(element, 'style');
9986
        }
9987
        remove$1(element, attr);
9988
      });
9989
    };
9990
    var Thor = {
9991
      clobberStyles: clobberStyles,
9992
      restoreStyles: restoreStyles
9993
    };
9994
9995
    var tag = function () {
9996
      var head = first$2('head').getOrDie();
9997
      var nu = function () {
9998
        var meta = Element$$1.fromTag('meta');
9999
        set(meta, 'name', 'viewport');
10000
        append(head, meta);
10001
        return meta;
10002
      };
10003
      var element = first$2('meta[name="viewport"]').getOrThunk(nu);
10004
      var backup = get$1(element, 'content');
10005
      var maximize = function () {
10006
        set(element, 'content', 'width=device-width, initial-scale=1.0, user-scalable=no, maximum-scale=1.0');
10007
      };
10008
      var restore = function () {
10009
        if (backup !== undefined && backup !== null && backup.length > 0) {
10010
          set(element, 'content', backup);
10011
        } else {
10012
          set(element, 'content', 'user-scalable=yes');
10013
        }
10014
      };
10015
      return {
10016
        maximize: maximize,
10017
        restore: restore
10018
      };
10019
    };
10020
    var MetaViewport = { tag: tag };
10021
10022
    var create$5 = function (platform, mask) {
10023
      var meta = MetaViewport.tag();
10024
      var androidApi = api$2();
10025
      var androidEvents = api$2();
10026
      var enter = function () {
10027
        mask.hide();
10028
        add$2(platform.container, Styles.resolve('fullscreen-maximized'));
10029
        add$2(platform.container, Styles.resolve('android-maximized'));
10030
        meta.maximize();
10031
        add$2(platform.body, Styles.resolve('android-scroll-reload'));
10032
        androidApi.set(AndroidSetup.setup(platform.win, PlatformEditor.getWin(platform.editor).getOrDie('no')));
10033
        PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
10034
          Thor.clobberStyles(platform.container, editorApi.body());
10035
          androidEvents.set(AndroidEvents.initEvents(editorApi, platform.toolstrip, platform.alloy));
10036
        });
10037
      };
10038
      var exit = function () {
10039
        meta.restore();
10040
        mask.show();
10041
        remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
10042
        remove$4(platform.container, Styles.resolve('android-maximized'));
10043
        Thor.restoreStyles();
10044
        remove$4(platform.body, Styles.resolve('android-scroll-reload'));
10045
        androidEvents.clear();
10046
        androidApi.clear();
10047
      };
10048
      return {
10049
        enter: enter,
10050
        exit: exit
10051
      };
10052
    };
10053
    var AndroidMode = { create: create$5 };
10054
10055 View Code Duplication
    var first$4 = function (fn, rate) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10056
      var timer = null;
10057
      var cancel = function () {
10058
        if (timer !== null) {
10059
          clearTimeout(timer);
10060
          timer = null;
10061
        }
10062
      };
10063
      var throttle = function () {
10064
        var args = [];
10065
        for (var _i = 0; _i < arguments.length; _i++) {
10066
          args[_i] = arguments[_i];
10067
        }
10068
        if (timer === null) {
10069
          timer = setTimeout(function () {
10070
            fn.apply(null, args);
10071
            timer = null;
10072
          }, rate);
10073
        }
10074
      };
10075
      return {
10076
        cancel: cancel,
10077
        throttle: throttle
10078
      };
10079
    };
10080 View Code Duplication
    var last$3 = function (fn, rate) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10081
      var timer = null;
10082
      var cancel = function () {
10083
        if (timer !== null) {
10084
          clearTimeout(timer);
10085
          timer = null;
10086
        }
10087
      };
10088
      var throttle = function () {
10089
        var args = [];
10090
        for (var _i = 0; _i < arguments.length; _i++) {
10091
          args[_i] = arguments[_i];
10092
        }
10093
        if (timer !== null)
10094
          clearTimeout(timer);
10095
        timer = setTimeout(function () {
10096
          fn.apply(null, args);
10097
          timer = null;
10098
        }, rate);
10099
      };
10100
      return {
10101
        cancel: cancel,
10102
        throttle: throttle
10103
      };
10104
    };
10105
10106
    var sketch$a = function (onView, translate) {
10107
      var memIcon = record(Container.sketch({
10108
        dom: dom$1('<div aria-hidden="true" class="${prefix}-mask-tap-icon"></div>'),
10109
        containerBehaviours: derive$2([Toggling.config({
10110
            toggleClass: Styles.resolve('mask-tap-icon-selected'),
10111
            toggleOnExecute: false
10112
          })])
10113
      }));
10114
      var onViewThrottle = first$4(onView, 200);
10115
      return Container.sketch({
10116
        dom: dom$1('<div class="${prefix}-disabled-mask"></div>'),
10117
        components: [Container.sketch({
10118
            dom: dom$1('<div class="${prefix}-content-container"></div>'),
10119
            components: [Button.sketch({
10120
                dom: dom$1('<div class="${prefix}-content-tap-section"></div>'),
10121
                components: [memIcon.asSpec()],
10122
                action: function (button) {
10123
                  onViewThrottle.throttle();
10124
                },
10125
                buttonBehaviours: derive$2([Toggling.config({ toggleClass: Styles.resolve('mask-tap-icon-selected') })])
10126
              })]
10127
          })]
10128
      });
10129
    };
10130
    var TapToEditMask = { sketch: sketch$a };
10131
10132
    var MobileSchema = objOf([
10133
      strictObjOf('editor', [
10134
        strict$1('getFrame'),
10135
        option('getBody'),
10136
        option('getDoc'),
10137
        option('getWin'),
10138
        option('getSelection'),
10139
        option('setSelection'),
10140
        option('clearSelection'),
10141
        option('cursorSaver'),
10142
        option('onKeyup'),
10143
        option('onNodeChanged'),
10144
        option('getCursorBox'),
10145
        strict$1('onDomChanged'),
10146
        defaulted$1('onTouchContent', noop),
10147
        defaulted$1('onTapContent', noop),
10148
        defaulted$1('onTouchToolstrip', noop),
10149
        defaulted$1('onScrollToCursor', constant({ unbind: noop })),
10150
        defaulted$1('onScrollToElement', constant({ unbind: noop })),
10151
        defaulted$1('onToEditing', constant({ unbind: noop })),
10152
        defaulted$1('onToReading', constant({ unbind: noop })),
10153
        defaulted$1('onToolbarScrollStart', identity)
10154
      ]),
10155
      strict$1('socket'),
10156
      strict$1('toolstrip'),
10157
      strict$1('dropup'),
10158
      strict$1('toolbar'),
10159
      strict$1('container'),
10160
      strict$1('alloy'),
10161
      state$1('win', function (spec) {
10162
        return owner(spec.socket).dom().defaultView;
10163
      }),
10164
      state$1('body', function (spec) {
10165
        return Element$$1.fromDom(spec.socket.dom().ownerDocument.body);
10166
      }),
10167
      defaulted$1('translate', identity),
10168
      defaulted$1('setReadOnly', noop),
10169
      defaulted$1('readOnlyOnInit', constant(true))
10170
    ]);
10171
10172
    var produce = function (raw) {
10173
      var mobile = asRawOrDie('Getting AndroidWebapp schema', MobileSchema, raw);
10174
      set$2(mobile.toolstrip, 'width', '100%');
10175
      var onTap = function () {
10176
        mobile.setReadOnly(mobile.readOnlyOnInit());
10177
        mode.enter();
10178
      };
10179
      var mask = build$1(TapToEditMask.sketch(onTap, mobile.translate));
10180
      mobile.alloy.add(mask);
10181
      var maskApi = {
10182
        show: function () {
10183
          mobile.alloy.add(mask);
10184
        },
10185
        hide: function () {
10186
          mobile.alloy.remove(mask);
10187
        }
10188
      };
10189
      append(mobile.container, mask.element());
10190
      var mode = AndroidMode.create(mobile, maskApi);
10191
      return {
10192
        setReadOnly: mobile.setReadOnly,
10193
        refreshStructure: noop,
10194
        enter: mode.enter,
10195
        exit: mode.exit,
10196
        destroy: noop
10197
      };
10198
    };
10199
    var AndroidWebapp = { produce: produce };
10200
10201
    var schema$e = constant([
10202
      defaulted$1('shell', true),
10203
      field$1('toolbarBehaviours', [Replacing])
10204
    ]);
10205
    var enhanceGroups = function (detail) {
10206
      return { behaviours: derive$2([Replacing.config({})]) };
10207
    };
10208
    var parts$2 = constant([optional({
10209
        name: 'groups',
10210
        overrides: enhanceGroups
10211
      })]);
10212
10213
    var factory$4 = function (detail, components$$1, spec, _externals) {
10214
      var setGroups = function (toolbar$$1, groups) {
10215
        getGroupContainer(toolbar$$1).fold(function () {
10216
          console.error('Toolbar was defined to not be a shell, but no groups container was specified in components');
10217
          throw new Error('Toolbar was defined to not be a shell, but no groups container was specified in components');
10218
        }, function (container) {
10219
          Replacing.set(container, groups);
10220
        });
10221
      };
10222
      var getGroupContainer = function (component) {
10223
        return detail.shell() ? Option.some(component) : getPart(component, detail, 'groups');
10224
      };
10225
      var extra = detail.shell() ? {
10226
        behaviours: [Replacing.config({})],
10227
        components: []
10228
      } : {
10229
        behaviours: [],
10230
        components: components$$1
10231
      };
10232
      return {
10233
        uid: detail.uid(),
10234
        dom: detail.dom(),
10235
        components: extra.components,
10236
        behaviours: deepMerge(derive$2(extra.behaviours), get$6(detail.toolbarBehaviours())),
10237
        apis: { setGroups: setGroups },
10238
        domModification: { attributes: { role: 'group' } }
10239
      };
10240
    };
10241
    var Toolbar = composite$1({
10242
      name: 'Toolbar',
10243
      configFields: schema$e(),
10244
      partFields: parts$2(),
10245
      factory: factory$4,
10246
      apis: {
10247
        setGroups: function (apis, toolbar$$1, groups) {
10248
          apis.setGroups(toolbar$$1, groups);
10249
        }
10250
      }
10251
    });
10252
10253
    var schema$f = constant([
10254
      strict$1('items'),
10255
      markers(['itemClass']),
10256
      field$1('tgroupBehaviours', [Keying])
10257
    ]);
10258
    var parts$3 = constant([group({
10259
        name: 'items',
10260
        unit: 'item',
10261
        overrides: function (detail) {
10262
          return { domModification: { classes: [detail.markers().itemClass()] } };
10263
        }
10264
      })]);
10265
10266
    var factory$5 = function (detail, components, spec, _externals) {
10267
      return deepMerge({ dom: { attributes: { role: 'toolbar' } } }, {
10268
        'uid': detail.uid(),
10269
        'dom': detail.dom(),
10270
        'components': components,
10271
        'behaviours': deepMerge(derive$2([Keying.config({
10272
            mode: 'flow',
10273
            selector: '.' + detail.markers().itemClass()
10274
          })]), get$6(detail.tgroupBehaviours())),
10275
        'debug.sketcher': spec['debug.sketcher']
10276
      });
10277
    };
10278
    var ToolbarGroup = composite$1({
10279
      name: 'ToolbarGroup',
10280
      configFields: schema$f(),
10281
      partFields: parts$3(),
10282
      factory: factory$5
10283
    });
10284
10285
    var dataHorizontal = 'data-' + Styles.resolve('horizontal-scroll');
10286
    var canScrollVertically = function (container) {
10287
      container.dom().scrollTop = 1;
10288
      var result = container.dom().scrollTop !== 0;
10289
      container.dom().scrollTop = 0;
10290
      return result;
10291
    };
10292
    var canScrollHorizontally = function (container) {
10293
      container.dom().scrollLeft = 1;
10294
      var result = container.dom().scrollLeft !== 0;
10295
      container.dom().scrollLeft = 0;
10296
      return result;
10297
    };
10298
    var hasVerticalScroll = function (container) {
10299
      return container.dom().scrollTop > 0 || canScrollVertically(container);
10300
    };
10301
    var hasHorizontalScroll = function (container) {
10302
      return container.dom().scrollLeft > 0 || canScrollHorizontally(container);
10303
    };
10304
    var markAsHorizontal = function (container) {
10305
      set(container, dataHorizontal, 'true');
10306
    };
10307
    var hasScroll = function (container) {
10308
      return get$1(container, dataHorizontal) === 'true' ? hasHorizontalScroll(container) : hasVerticalScroll(container);
10309
    };
10310
    var exclusive = function (scope, selector) {
10311
      return bind$2(scope, 'touchmove', function (event) {
10312
        closest$2(event.target(), selector).filter(hasScroll).fold(function () {
10313
          event.raw().preventDefault();
10314
        }, noop);
10315
      });
10316
    };
10317
    var Scrollables = {
10318
      exclusive: exclusive,
10319
      markAsHorizontal: markAsHorizontal
10320
    };
10321
10322
    function ScrollingToolbar () {
10323
      var makeGroup = function (gSpec) {
10324
        var scrollClass = gSpec.scrollable === true ? '${prefix}-toolbar-scrollable-group' : '';
10325
        return {
10326
          dom: dom$1('<div aria-label="' + gSpec.label + '" class="${prefix}-toolbar-group ' + scrollClass + '"></div>'),
10327
          tgroupBehaviours: derive$2([config('adhoc-scrollable-toolbar', gSpec.scrollable === true ? [runOnInit(function (component, simulatedEvent) {
10328
                set$2(component.element(), 'overflow-x', 'auto');
10329
                Scrollables.markAsHorizontal(component.element());
10330
                Scrollable.register(component.element());
10331
              })] : [])]),
10332
          components: [Container.sketch({ components: [ToolbarGroup.parts().items({})] })],
10333
          markers: { itemClass: Styles.resolve('toolbar-group-item') },
10334
          items: gSpec.items
10335
        };
10336
      };
10337
      var toolbar = build$1(Toolbar.sketch({
10338
        dom: dom$1('<div class="${prefix}-toolbar"></div>'),
10339
        components: [Toolbar.parts().groups({})],
10340
        toolbarBehaviours: derive$2([
10341
          Toggling.config({
10342
            toggleClass: Styles.resolve('context-toolbar'),
10343
            toggleOnExecute: false,
10344
            aria: { mode: 'none' }
10345
          }),
10346
          Keying.config({ mode: 'cyclic' })
10347
        ]),
10348
        shell: true
10349
      }));
10350
      var wrapper = build$1(Container.sketch({
10351
        dom: { classes: [Styles.resolve('toolstrip')] },
10352
        components: [premade$1(toolbar)],
10353
        containerBehaviours: derive$2([Toggling.config({
10354
            toggleClass: Styles.resolve('android-selection-context-toolbar'),
10355
            toggleOnExecute: false
10356
          })])
10357
      }));
10358
      var resetGroups = function () {
10359
        Toolbar.setGroups(toolbar, initGroups.get());
10360
        Toggling.off(toolbar);
10361
      };
10362
      var initGroups = Cell([]);
10363
      var setGroups = function (gs) {
10364
        initGroups.set(gs);
10365
        resetGroups();
10366
      };
10367
      var createGroups = function (gs) {
10368
        return map$1(gs, compose(ToolbarGroup.sketch, makeGroup));
10369
      };
10370
      var refresh = function () {
10371
      };
10372
      var setContextToolbar = function (gs) {
10373
        Toggling.on(toolbar);
10374
        Toolbar.setGroups(toolbar, gs);
10375
      };
10376
      var restoreToolbar = function () {
10377
        if (Toggling.isOn(toolbar)) {
10378
          resetGroups();
10379
        }
10380
      };
10381
      var focus = function () {
10382
        Keying.focusIn(toolbar);
10383
      };
10384
      return {
10385
        wrapper: constant(wrapper),
10386
        toolbar: constant(toolbar),
10387
        createGroups: createGroups,
10388
        setGroups: setGroups,
10389
        setContextToolbar: setContextToolbar,
10390
        restoreToolbar: restoreToolbar,
10391
        refresh: refresh,
10392
        focus: focus
10393
      };
10394
    }
10395
10396
    var makeEditSwitch = function (webapp) {
10397
      return build$1(Button.sketch({
10398
        dom: dom$1('<div class="${prefix}-mask-edit-icon ${prefix}-icon"></div>'),
10399
        action: function () {
10400
          webapp.run(function (w) {
10401
            w.setReadOnly(false);
10402
          });
10403
        }
10404
      }));
10405
    };
10406
    var makeSocket = function () {
10407
      return build$1(Container.sketch({
10408
        dom: dom$1('<div class="${prefix}-editor-socket"></div>'),
10409
        components: [],
10410
        containerBehaviours: derive$2([Replacing.config({})])
10411
      }));
10412
    };
10413
    var showEdit = function (socket, switchToEdit) {
10414
      Replacing.append(socket, premade$1(switchToEdit));
10415
    };
10416
    var hideEdit = function (socket, switchToEdit) {
10417
      Replacing.remove(socket, switchToEdit);
10418
    };
10419
    var updateMode = function (socket, switchToEdit, readOnly, root) {
10420
      var swap = readOnly === true ? Swapping.toAlpha : Swapping.toOmega;
10421
      swap(root);
10422
      var f = readOnly ? showEdit : hideEdit;
10423
      f(socket, switchToEdit);
10424
    };
10425
    var CommonRealm = {
10426
      makeEditSwitch: makeEditSwitch,
10427
      makeSocket: makeSocket,
10428
      updateMode: updateMode
10429
    };
10430
10431
    var getAnimationRoot = function (component, slideConfig) {
10432
      return slideConfig.getAnimationRoot().fold(function () {
10433
        return component.element();
10434
      }, function (get) {
10435
        return get(component);
10436
      });
10437
    };
10438
    var getDimensionProperty = function (slideConfig) {
10439
      return slideConfig.dimension().property();
10440
    };
10441
    var getDimension = function (slideConfig, elem) {
10442
      return slideConfig.dimension().getDimension()(elem);
10443
    };
10444
    var disableTransitions = function (component, slideConfig) {
10445
      var root = getAnimationRoot(component, slideConfig);
10446
      remove$6(root, [
10447
        slideConfig.shrinkingClass(),
10448
        slideConfig.growingClass()
10449
      ]);
10450
    };
10451
    var setShrunk = function (component, slideConfig) {
10452
      remove$4(component.element(), slideConfig.openClass());
10453
      add$2(component.element(), slideConfig.closedClass());
10454
      set$2(component.element(), getDimensionProperty(slideConfig), '0px');
10455
      reflow(component.element());
10456
    };
10457
    var measureTargetSize = function (component, slideConfig) {
10458
      setGrown(component, slideConfig);
10459
      var expanded = getDimension(slideConfig, component.element());
10460
      setShrunk(component, slideConfig);
10461
      return expanded;
10462
    };
10463
    var setGrown = function (component, slideConfig) {
10464
      remove$4(component.element(), slideConfig.closedClass());
10465
      add$2(component.element(), slideConfig.openClass());
10466
      remove$5(component.element(), getDimensionProperty(slideConfig));
10467
    };
10468
    var doImmediateShrink = function (component, slideConfig, slideState) {
10469
      slideState.setCollapsed();
10470
      set$2(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
10471
      reflow(component.element());
10472
      disableTransitions(component, slideConfig);
10473
      setShrunk(component, slideConfig);
10474
      slideConfig.onStartShrink()(component);
10475
      slideConfig.onShrunk()(component);
10476
    };
10477
    var doStartShrink = function (component, slideConfig, slideState) {
10478
      slideState.setCollapsed();
10479
      set$2(component.element(), getDimensionProperty(slideConfig), getDimension(slideConfig, component.element()));
10480
      reflow(component.element());
10481
      var root = getAnimationRoot(component, slideConfig);
10482
      add$2(root, slideConfig.shrinkingClass());
10483
      setShrunk(component, slideConfig);
10484
      slideConfig.onStartShrink()(component);
10485
    };
10486
    var doStartGrow = function (component, slideConfig, slideState) {
10487
      var fullSize = measureTargetSize(component, slideConfig);
10488
      var root = getAnimationRoot(component, slideConfig);
10489
      add$2(root, slideConfig.growingClass());
10490
      setGrown(component, slideConfig);
10491
      set$2(component.element(), getDimensionProperty(slideConfig), fullSize);
10492
      slideState.setExpanded();
10493
      slideConfig.onStartGrow()(component);
10494
    };
10495
    var grow = function (component, slideConfig, slideState) {
10496
      if (!slideState.isExpanded()) {
10497
        doStartGrow(component, slideConfig, slideState);
10498
      }
10499
    };
10500
    var shrink = function (component, slideConfig, slideState) {
10501
      if (slideState.isExpanded()) {
10502
        doStartShrink(component, slideConfig, slideState);
10503
      }
10504
    };
10505
    var immediateShrink = function (component, slideConfig, slideState) {
10506
      if (slideState.isExpanded()) {
10507
        doImmediateShrink(component, slideConfig, slideState);
10508
      }
10509
    };
10510
    var hasGrown = function (component, slideConfig, slideState) {
10511
      return slideState.isExpanded();
10512
    };
10513
    var hasShrunk = function (component, slideConfig, slideState) {
10514
      return slideState.isCollapsed();
10515
    };
10516
    var isGrowing = function (component, slideConfig, slideState) {
10517
      var root = getAnimationRoot(component, slideConfig);
10518
      return has$2(root, slideConfig.growingClass()) === true;
10519
    };
10520
    var isShrinking = function (component, slideConfig, slideState) {
10521
      var root = getAnimationRoot(component, slideConfig);
10522
      return has$2(root, slideConfig.shrinkingClass()) === true;
10523
    };
10524
    var isTransitioning = function (component, slideConfig, slideState) {
10525
      return isGrowing(component, slideConfig, slideState) === true || isShrinking(component, slideConfig, slideState) === true;
10526
    };
10527
    var toggleGrow = function (component, slideConfig, slideState) {
10528
      var f = slideState.isExpanded() ? doStartShrink : doStartGrow;
10529
      f(component, slideConfig, slideState);
10530
    };
10531
10532
    var SlidingApis = /*#__PURE__*/Object.freeze({
10533
        grow: grow,
10534
        shrink: shrink,
10535
        immediateShrink: immediateShrink,
10536
        hasGrown: hasGrown,
10537
        hasShrunk: hasShrunk,
10538
        isGrowing: isGrowing,
10539
        isShrinking: isShrinking,
10540
        isTransitioning: isTransitioning,
10541
        toggleGrow: toggleGrow,
10542
        disableTransitions: disableTransitions
10543
    });
10544
10545
    var exhibit$5 = function (base, slideConfig) {
10546
      var expanded = slideConfig.expanded();
10547
      return expanded ? nu$6({
10548
        classes: [slideConfig.openClass()],
10549
        styles: {}
10550
      }) : nu$6({
10551
        classes: [slideConfig.closedClass()],
10552
        styles: wrap$2(slideConfig.dimension().property(), '0px')
10553
      });
10554
    };
10555
    var events$a = function (slideConfig, slideState) {
10556
      return derive([run(transitionend(), function (component, simulatedEvent) {
10557
          var raw = simulatedEvent.event().raw();
10558
          if (raw.propertyName === slideConfig.dimension().property()) {
10559
            disableTransitions(component, slideConfig);
10560
            if (slideState.isExpanded()) {
10561
              remove$5(component.element(), slideConfig.dimension().property());
10562
            }
10563
            var notify = slideState.isExpanded() ? slideConfig.onGrown() : slideConfig.onShrunk();
10564
            notify(component);
10565
          }
10566
        })]);
10567
    };
10568
10569
    var ActiveSliding = /*#__PURE__*/Object.freeze({
10570
        exhibit: exhibit$5,
10571
        events: events$a
10572
    });
10573
10574
    var SlidingSchema = [
10575
      strict$1('closedClass'),
10576
      strict$1('openClass'),
10577
      strict$1('shrinkingClass'),
10578
      strict$1('growingClass'),
10579
      option('getAnimationRoot'),
10580
      onHandler('onShrunk'),
10581
      onHandler('onStartShrink'),
10582
      onHandler('onGrown'),
10583
      onHandler('onStartGrow'),
10584
      defaulted$1('expanded', false),
10585
      strictOf('dimension', choose$1('property', {
10586
        width: [
10587
          output$1('property', 'width'),
10588
          output$1('getDimension', function (elem) {
10589
            return get$7(elem) + 'px';
10590
          })
10591
        ],
10592
        height: [
10593
          output$1('property', 'height'),
10594
          output$1('getDimension', function (elem) {
10595
            return get$5(elem) + 'px';
10596
          })
10597
        ]
10598
      }))
10599
    ];
10600
10601
    var init$4 = function (spec) {
10602
      var state = Cell(spec.expanded());
10603
      var readState = function () {
10604
        return 'expanded: ' + state.get();
10605
      };
10606
      return nu$7({
10607
        isExpanded: function () {
10608
          return state.get() === true;
10609
        },
10610
        isCollapsed: function () {
10611
          return state.get() === false;
10612
        },
10613
        setCollapsed: curry(state.set, false),
10614
        setExpanded: curry(state.set, true),
10615
        readState: readState
10616
      });
10617
    };
10618
10619
    var SlidingState = /*#__PURE__*/Object.freeze({
10620
        init: init$4
10621
    });
10622
10623
    var Sliding = create$1({
10624
      fields: SlidingSchema,
10625
      name: 'sliding',
10626
      active: ActiveSliding,
10627
      apis: SlidingApis,
10628
      state: SlidingState
10629
    });
10630
10631
    var build$2 = function (refresh, scrollIntoView) {
10632
      var dropup = build$1(Container.sketch({
10633
        dom: {
10634
          tag: 'div',
10635
          classes: [Styles.resolve('dropup')]
10636
        },
10637
        components: [],
10638
        containerBehaviours: derive$2([
10639
          Replacing.config({}),
10640
          Sliding.config({
10641
            closedClass: Styles.resolve('dropup-closed'),
10642
            openClass: Styles.resolve('dropup-open'),
10643
            shrinkingClass: Styles.resolve('dropup-shrinking'),
10644
            growingClass: Styles.resolve('dropup-growing'),
10645
            dimension: { property: 'height' },
10646
            onShrunk: function (component) {
10647
              refresh();
10648
              scrollIntoView();
10649
              Replacing.set(component, []);
10650
            },
10651
            onGrown: function (component) {
10652
              refresh();
10653
              scrollIntoView();
10654
            }
10655
          }),
10656
          Receivers.orientation(function (component, data) {
10657
            disappear(noop);
10658
          })
10659
        ])
10660
      }));
10661
      var appear = function (menu, update, component) {
10662
        if (Sliding.hasShrunk(dropup) === true && Sliding.isTransitioning(dropup) === false) {
10663
          window.requestAnimationFrame(function () {
10664
            update(component);
10665
            Replacing.set(dropup, [menu()]);
10666
            Sliding.grow(dropup);
10667
          });
10668
        }
10669
      };
10670
      var disappear = function (onReadyToShrink) {
10671
        window.requestAnimationFrame(function () {
10672
          onReadyToShrink();
10673
          Sliding.shrink(dropup);
10674
        });
10675
      };
10676
      return {
10677
        appear: appear,
10678
        disappear: disappear,
10679
        component: constant(dropup),
10680
        element: dropup.element
10681
      };
10682
    };
10683
10684
    var isDangerous = function (event$$1) {
10685
      var keyEv = event$$1.raw();
10686
      return keyEv.which === BACKSPACE()[0] && !contains([
10687
        'input',
10688
        'textarea'
10689
      ], name(event$$1.target()));
10690
    };
10691
    var isFirefox = PlatformDetection$1.detect().browser.isFirefox();
10692
    var settingsSchema = objOfOnly([
10693
      strictFunction('triggerEvent'),
10694
      strictFunction('broadcastEvent'),
10695
      defaulted$1('stopBackspace', true)
10696
    ]);
10697
    var bindFocus = function (container, handler) {
10698
      if (isFirefox) {
10699
        return capture$1(container, 'focus', handler);
10700
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
10701
        return bind$2(container, 'focusin', handler);
10702
      }
10703
    };
10704
    var bindBlur = function (container, handler) {
10705
      if (isFirefox) {
10706
        return capture$1(container, 'blur', handler);
10707
      } else {
0 ignored issues
show
Comprehensibility introduced by
else is not necessary here since all if branches return, consider removing it to reduce nesting and make code more readable.
Loading history...
10708
        return bind$2(container, 'focusout', handler);
10709
      }
10710
    };
10711
    var setup$2 = function (container, rawSettings) {
10712
      var settings = asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);
10713
      var pointerEvents = PlatformDetection$1.detect().deviceType.isTouch() ? [
10714
        'touchstart',
10715
        'touchmove',
10716
        'touchend',
10717
        'gesturestart'
10718
      ] : [
10719
        'mousedown',
10720
        'mouseup',
10721
        'mouseover',
10722
        'mousemove',
10723
        'mouseout',
10724
        'click'
10725
      ];
10726
      var tapEvent = monitor(settings);
10727
      var simpleEvents = map$1(pointerEvents.concat([
10728
        'selectstart',
10729
        'input',
10730
        'contextmenu',
10731
        'change',
10732
        'transitionend',
10733
        'drag',
10734
        'dragstart',
10735
        'dragend',
10736
        'dragenter',
10737
        'dragleave',
10738
        'dragover',
10739
        'drop'
10740
      ]), function (type$$1) {
10741
        return bind$2(container, type$$1, function (event$$1) {
10742
          tapEvent.fireIfReady(event$$1, type$$1).each(function (tapStopped) {
10743
            if (tapStopped) {
10744
              event$$1.kill();
10745
            }
10746
          });
10747
          var stopped = settings.triggerEvent(type$$1, event$$1);
10748
          if (stopped) {
10749
            event$$1.kill();
10750
          }
10751
        });
10752
      });
10753
      var onKeydown = bind$2(container, 'keydown', function (event$$1) {
10754
        var stopped = settings.triggerEvent('keydown', event$$1);
10755
        if (stopped) {
10756
          event$$1.kill();
10757
        } else if (settings.stopBackspace === true && isDangerous(event$$1)) {
10758
          event$$1.prevent();
10759
        }
10760
      });
10761
      var onFocusIn = bindFocus(container, function (event$$1) {
10762
        var stopped = settings.triggerEvent('focusin', event$$1);
10763
        if (stopped) {
10764
          event$$1.kill();
10765
        }
10766
      });
10767
      var onFocusOut = bindBlur(container, function (event$$1) {
10768
        var stopped = settings.triggerEvent('focusout', event$$1);
10769
        if (stopped) {
10770
          event$$1.kill();
10771
        }
10772
        setTimeout(function () {
10773
          settings.triggerEvent(postBlur(), event$$1);
10774
        }, 0);
10775
      });
10776
      var defaultView$$1 = defaultView(container);
10777
      var onWindowScroll = bind$2(defaultView$$1, 'scroll', function (event$$1) {
10778
        var stopped = settings.broadcastEvent(windowScroll(), event$$1);
10779
        if (stopped) {
10780
          event$$1.kill();
10781
        }
10782
      });
10783
      var unbind = function () {
10784
        each$1(simpleEvents, function (e) {
10785
          e.unbind();
10786
        });
10787
        onKeydown.unbind();
10788
        onFocusIn.unbind();
10789
        onFocusOut.unbind();
10790
        onWindowScroll.unbind();
10791
      };
10792
      return { unbind: unbind };
10793
    };
10794
10795
    var derive$3 = function (rawEvent, rawTarget) {
10796
      var source = readOptFrom$1(rawEvent, 'target').map(function (getTarget) {
10797
        return getTarget();
10798
      }).getOr(rawTarget);
10799
      return Cell(source);
10800
    };
10801
10802
    var fromSource = function (event, source) {
10803
      var stopper = Cell(false);
10804
      var cutter = Cell(false);
10805
      var stop = function () {
10806
        stopper.set(true);
10807
      };
10808
      var cut = function () {
10809
        cutter.set(true);
10810
      };
10811
      return {
10812
        stop: stop,
10813
        cut: cut,
10814
        isStopped: stopper.get,
10815
        isCut: cutter.get,
10816
        event: constant(event),
10817
        setSource: source.set,
10818
        getSource: source.get
10819
      };
10820
    };
10821
    var fromExternal = function (event) {
10822
      var stopper = Cell(false);
10823
      var stop = function () {
10824
        stopper.set(true);
10825
      };
10826
      return {
10827
        stop: stop,
10828
        cut: noop,
10829
        isStopped: stopper.get,
10830
        isCut: constant(false),
10831
        event: constant(event),
10832
        setSource: die('Cannot set source of a broadcasted event'),
10833
        getSource: die('Cannot get source of a broadcasted event')
10834
      };
10835
    };
10836
10837
    var adt$6 = Adt.generate([
10838
      { stopped: [] },
10839
      { resume: ['element'] },
10840
      { complete: [] }
10841
    ]);
10842
    var doTriggerHandler = function (lookup, eventType, rawEvent, target, source, logger) {
10843
      var handler = lookup(eventType, target);
10844
      var simulatedEvent = fromSource(rawEvent, source);
10845
      return handler.fold(function () {
10846
        logger.logEventNoHandlers(eventType, target);
10847
        return adt$6.complete();
10848
      }, function (handlerInfo) {
10849
        var descHandler = handlerInfo.descHandler();
10850
        var eventHandler = getCurried(descHandler);
10851
        eventHandler(simulatedEvent);
10852
        if (simulatedEvent.isStopped()) {
10853
          logger.logEventStopped(eventType, handlerInfo.element(), descHandler.purpose());
10854
          return adt$6.stopped();
10855
        } else if (simulatedEvent.isCut()) {
10856
          logger.logEventCut(eventType, handlerInfo.element(), descHandler.purpose());
10857
          return adt$6.complete();
10858
        } else {
10859
          return parent(handlerInfo.element()).fold(function () {
10860
            logger.logNoParent(eventType, handlerInfo.element(), descHandler.purpose());
10861
            return adt$6.complete();
10862
          }, function (parent$$1) {
10863
            logger.logEventResponse(eventType, handlerInfo.element(), descHandler.purpose());
10864
            return adt$6.resume(parent$$1);
10865
          });
10866
        }
10867
      });
10868
    };
10869
    var doTriggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, source, logger) {
10870
      return doTriggerHandler(lookup, eventType, rawEvent, rawTarget, source, logger).fold(function () {
10871
        return true;
10872
      }, function (parent$$1) {
10873
        return doTriggerOnUntilStopped(lookup, eventType, rawEvent, parent$$1, source, logger);
10874
      }, function () {
10875
        return false;
10876
      });
10877
    };
10878
    var triggerHandler = function (lookup, eventType, rawEvent, target, logger) {
10879
      var source = derive$3(rawEvent, target);
10880
      return doTriggerHandler(lookup, eventType, rawEvent, target, source, logger);
10881
    };
10882
    var broadcast = function (listeners, rawEvent, logger) {
10883
      var simulatedEvent = fromExternal(rawEvent);
10884
      each$1(listeners, function (listener) {
10885
        var descHandler = listener.descHandler();
10886
        var handler = getCurried(descHandler);
10887
        handler(simulatedEvent);
10888
      });
10889
      return simulatedEvent.isStopped();
10890
    };
10891
    var triggerUntilStopped = function (lookup, eventType, rawEvent, logger) {
10892
      var rawTarget = rawEvent.target();
10893
      return triggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, logger);
10894
    };
10895
    var triggerOnUntilStopped = function (lookup, eventType, rawEvent, rawTarget, logger) {
10896
      var source = derive$3(rawEvent, rawTarget);
10897
      return doTriggerOnUntilStopped(lookup, eventType, rawEvent, rawTarget, source, logger);
10898
    };
10899
10900
    var closest$3 = function (target, transform, isRoot) {
10901
      var delegate = closest(target, function (elem) {
10902
        return transform(elem).isSome();
10903
      }, isRoot);
10904
      return delegate.bind(transform);
10905
    };
10906
10907
    var eventHandler = Immutable('element', 'descHandler');
10908
    var broadcastHandler = function (id, handler) {
10909
      return {
10910
        id: constant(id),
10911
        descHandler: constant(handler)
10912
      };
10913
    };
10914
    function EventRegistry () {
10915
      var registry = {};
10916
      var registerId = function (extraArgs, id, events) {
10917
        each(events, function (v, k) {
10918
          var handlers = registry[k] !== undefined ? registry[k] : {};
10919
          handlers[id] = curryArgs(v, extraArgs);
10920
          registry[k] = handlers;
10921
        });
10922
      };
10923
      var findHandler = function (handlers, elem) {
10924
        return read$2(elem).fold(function () {
10925
          return Option.none();
10926
        }, function (id) {
10927
          var reader = readOpt$1(id);
10928
          return handlers.bind(reader).map(function (descHandler) {
10929
            return eventHandler(elem, descHandler);
10930
          });
10931
        });
10932
      };
10933
      var filterByType = function (type) {
10934
        return readOptFrom$1(registry, type).map(function (handlers) {
10935
          return mapToArray(handlers, function (f, id) {
10936
            return broadcastHandler(id, f);
10937
          });
10938
        }).getOr([]);
10939
      };
10940
      var find$$1 = function (isAboveRoot, type, target) {
10941
        var readType = readOpt$1(type);
10942
        var handlers = readType(registry);
10943
        return closest$3(target, function (elem) {
10944
          return findHandler(handlers, elem);
10945
        }, isAboveRoot);
10946
      };
10947
      var unregisterId = function (id) {
10948
        each(registry, function (handlersById, eventName) {
10949
          if (handlersById.hasOwnProperty(id)) {
10950
            delete handlersById[id];
10951
          }
10952
        });
10953
      };
10954
      return {
10955
        registerId: registerId,
10956
        unregisterId: unregisterId,
10957
        filterByType: filterByType,
10958
        find: find$$1
10959
      };
10960
    }
10961
10962
    function Registry () {
10963
      var events = EventRegistry();
10964
      var components = {};
10965
      var readOrTag = function (component) {
10966
        var elem = component.element();
10967
        return read$2(elem).fold(function () {
10968
          return write('uid-', component.element());
10969
        }, function (uid) {
10970
          return uid;
10971
        });
10972
      };
10973
      var failOnDuplicate = function (component, tagId) {
10974
        var conflict = components[tagId];
10975
        if (conflict === component) {
10976
          unregister(component);
10977
        } else {
10978
          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');
10979
        }
10980
      };
10981
      var register = function (component) {
10982
        var tagId = readOrTag(component);
10983
        if (hasKey$1(components, tagId)) {
10984
          failOnDuplicate(component, tagId);
10985
        }
10986
        var extraArgs = [component];
10987
        events.registerId(extraArgs, tagId, component.events());
10988
        components[tagId] = component;
10989
      };
10990
      var unregister = function (component) {
10991
        read$2(component.element()).each(function (tagId) {
10992
          components[tagId] = undefined;
10993
          events.unregisterId(tagId);
10994
        });
10995
      };
10996
      var filter = function (type) {
10997
        return events.filterByType(type);
10998
      };
10999
      var find = function (isAboveRoot, type, target) {
11000
        return events.find(isAboveRoot, type, target);
11001
      };
11002
      var getById = function (id) {
11003
        return readOpt$1(id)(components);
11004
      };
11005
      return {
11006
        find: find,
11007
        filter: filter,
11008
        register: register,
11009
        unregister: unregister,
11010
        getById: getById
11011
      };
11012
    }
11013
11014
    var takeover = function (root) {
11015
      var isAboveRoot = function (el) {
11016
        return parent(root.element()).fold(function () {
11017
          return true;
11018
        }, function (parent$$1) {
11019
          return eq(el, parent$$1);
11020
        });
11021
      };
11022
      var registry = Registry();
11023
      var lookup = function (eventName, target) {
11024
        return registry.find(isAboveRoot, eventName, target);
11025
      };
11026
      var domEvents = setup$2(root.element(), {
11027
        triggerEvent: function (eventName, event) {
11028
          return monitorEvent(eventName, event.target(), function (logger) {
11029
            return triggerUntilStopped(lookup, eventName, event, logger);
11030
          });
11031
        },
11032
        broadcastEvent: function (eventName, event) {
11033
          var listeners = registry.filter(eventName);
11034
          return broadcast(listeners, event);
11035
        }
11036
      });
11037
      var systemApi = SystemApi({
11038
        debugInfo: constant('real'),
11039
        triggerEvent: function (eventName, target, data) {
11040
          monitorEvent(eventName, target, function (logger) {
11041
            triggerOnUntilStopped(lookup, eventName, data, target, logger);
11042
          });
11043
        },
11044
        triggerFocus: function (target, originator) {
11045
          read$2(target).fold(function () {
11046
            focus$2(target);
11047
          }, function (_alloyId) {
11048
            monitorEvent(focus$1(), target, function (logger) {
11049
              triggerHandler(lookup, focus$1(), {
11050
                originator: constant(originator),
11051
                kill: noop,
11052
                prevent: noop,
11053
                target: constant(target)
11054
              }, target, logger);
11055
            });
11056
          });
11057
        },
11058
        triggerEscape: function (comp, simulatedEvent) {
11059
          systemApi.triggerEvent('keydown', comp.element(), simulatedEvent.event());
11060
        },
11061
        getByUid: function (uid) {
11062
          return getByUid(uid);
11063
        },
11064
        getByDom: function (elem) {
11065
          return getByDom(elem);
11066
        },
11067
        build: build$1,
11068
        addToGui: function (c) {
11069
          add(c);
11070
        },
11071
        removeFromGui: function (c) {
11072
          remove$$1(c);
11073
        },
11074
        addToWorld: function (c) {
11075
          addToWorld(c);
11076
        },
11077
        removeFromWorld: function (c) {
11078
          removeFromWorld(c);
11079
        },
11080
        broadcast: function (message) {
11081
          broadcast$$1(message);
11082
        },
11083
        broadcastOn: function (channels, message) {
11084
          broadcastOn(channels, message);
11085
        },
11086
        isConnected: constant(true)
11087
      });
11088
      var addToWorld = function (component) {
11089
        component.connect(systemApi);
11090
        if (!isText(component.element())) {
11091
          registry.register(component);
11092
          each$1(component.components(), addToWorld);
11093
          systemApi.triggerEvent(systemInit(), component.element(), { target: constant(component.element()) });
11094
        }
11095
      };
11096
      var removeFromWorld = function (component) {
11097
        if (!isText(component.element())) {
11098
          each$1(component.components(), removeFromWorld);
11099
          registry.unregister(component);
11100
        }
11101
        component.disconnect();
11102
      };
11103
      var add = function (component) {
11104
        attach(root, component);
11105
      };
11106
      var remove$$1 = function (component) {
11107
        detach(component);
11108
      };
11109
      var destroy = function () {
11110
        domEvents.unbind();
11111
        remove(root.element());
11112
      };
11113
      var broadcastData = function (data) {
11114
        var receivers = registry.filter(receive());
11115
        each$1(receivers, function (receiver) {
11116
          var descHandler = receiver.descHandler();
11117
          var handler = getCurried(descHandler);
11118
          handler(data);
11119
        });
11120
      };
11121
      var broadcast$$1 = function (message) {
11122
        broadcastData({
11123
          universal: constant(true),
11124
          data: constant(message)
11125
        });
11126
      };
11127
      var broadcastOn = function (channels, message) {
11128
        broadcastData({
11129
          universal: constant(false),
11130
          channels: constant(channels),
11131
          data: constant(message)
11132
        });
11133
      };
11134
      var getByUid = function (uid) {
11135
        return registry.getById(uid).fold(function () {
11136
          return Result.error(new Error('Could not find component with uid: "' + uid + '" in system.'));
11137
        }, Result.value);
11138
      };
11139
      var getByDom = function (elem) {
11140
        var uid = read$2(elem).getOr('not found');
11141
        return getByUid(uid);
11142
      };
11143
      addToWorld(root);
11144
      return {
11145
        root: constant(root),
11146
        element: root.element,
11147
        destroy: destroy,
11148
        add: add,
11149
        remove: remove$$1,
11150
        getByUid: getByUid,
11151
        getByDom: getByDom,
11152
        addToWorld: addToWorld,
11153
        removeFromWorld: removeFromWorld,
11154
        broadcast: broadcast$$1,
11155
        broadcastOn: broadcastOn
11156
      };
11157
    };
11158
11159
    var READ_ONLY_MODE_CLASS = constant(Styles.resolve('readonly-mode'));
11160
    var EDIT_MODE_CLASS = constant(Styles.resolve('edit-mode'));
11161
    function OuterContainer (spec) {
11162
      var root = build$1(Container.sketch({
11163
        dom: { classes: [Styles.resolve('outer-container')].concat(spec.classes) },
11164
        containerBehaviours: derive$2([Swapping.config({
11165
            alpha: READ_ONLY_MODE_CLASS(),
11166
            omega: EDIT_MODE_CLASS()
11167
          })])
11168
      }));
11169
      return takeover(root);
11170
    }
11171
11172
    function AndroidRealm (scrollIntoView) {
11173
      var alloy = OuterContainer({ classes: [Styles.resolve('android-container')] });
11174
      var toolbar = ScrollingToolbar();
11175
      var webapp = api$2();
11176
      var switchToEdit = CommonRealm.makeEditSwitch(webapp);
11177
      var socket = CommonRealm.makeSocket();
11178
      var dropup = build$2(noop, scrollIntoView);
11179
      alloy.add(toolbar.wrapper());
11180
      alloy.add(socket);
11181
      alloy.add(dropup.component());
11182
      var setToolbarGroups = function (rawGroups) {
11183
        var groups = toolbar.createGroups(rawGroups);
11184
        toolbar.setGroups(groups);
11185
      };
11186
      var setContextToolbar = function (rawGroups) {
11187
        var groups = toolbar.createGroups(rawGroups);
11188
        toolbar.setContextToolbar(groups);
11189
      };
11190
      var focusToolbar = function () {
11191
        toolbar.focus();
11192
      };
11193
      var restoreToolbar = function () {
11194
        toolbar.restoreToolbar();
11195
      };
11196
      var init = function (spec) {
11197
        webapp.set(AndroidWebapp.produce(spec));
11198
      };
11199
      var exit = function () {
11200
        webapp.run(function (w) {
11201
          w.exit();
11202
          Replacing.remove(socket, switchToEdit);
11203
        });
11204
      };
11205
      var updateMode = function (readOnly) {
11206
        CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
11207
      };
11208
      return {
11209
        system: constant(alloy),
11210
        element: alloy.element,
11211
        init: init,
11212
        exit: exit,
11213
        setToolbarGroups: setToolbarGroups,
11214
        setContextToolbar: setContextToolbar,
11215
        focusToolbar: focusToolbar,
11216
        restoreToolbar: restoreToolbar,
11217
        updateMode: updateMode,
11218
        socket: constant(socket),
11219
        dropup: constant(dropup)
11220
      };
11221
    }
11222
11223
    var input$1 = function (parent, operation) {
11224
      var input = Element$$1.fromTag('input');
11225
      setAll$1(input, {
11226
        opacity: '0',
11227
        position: 'absolute',
11228
        top: '-1000px',
11229
        left: '-1000px'
11230
      });
11231
      append(parent, input);
11232
      focus$2(input);
11233
      operation(input);
11234
      remove(input);
11235
    };
11236
    var CaptureBin = { input: input$1 };
11237
11238
    var refreshInput = function (input) {
11239
      var start = input.dom().selectionStart;
11240
      var end = input.dom().selectionEnd;
11241
      var dir = input.dom().selectionDirection;
11242
      setTimeout(function () {
11243
        input.dom().setSelectionRange(start, end, dir);
11244
        focus$2(input);
11245
      }, 50);
11246
    };
11247
    var refresh = function (winScope) {
11248
      var sel = winScope.getSelection();
11249
      if (sel.rangeCount > 0) {
11250
        var br = sel.getRangeAt(0);
11251
        var r = winScope.document.createRange();
11252
        r.setStart(br.startContainer, br.startOffset);
11253
        r.setEnd(br.endContainer, br.endOffset);
11254
        sel.removeAllRanges();
11255
        sel.addRange(r);
11256
      }
11257
    };
11258
    var CursorRefresh = {
11259
      refreshInput: refreshInput,
11260
      refresh: refresh
11261
    };
11262
11263
    var resume$1 = function (cWin, frame) {
11264
      active().each(function (active$$1) {
11265
        if (!eq(active$$1, frame)) {
11266
          blur$$1(active$$1);
11267
        }
11268
      });
11269
      cWin.focus();
11270
      focus$2(Element$$1.fromDom(cWin.document.body));
11271
      CursorRefresh.refresh(cWin);
11272
    };
11273
    var ResumeEditing$1 = { resume: resume$1 };
11274
11275
    var stubborn = function (outerBody, cWin, page, frame) {
11276
      var toEditing = function () {
11277
        ResumeEditing$1.resume(cWin, frame);
11278
      };
11279
      var toReading = function () {
11280
        CaptureBin.input(outerBody, blur$$1);
11281
      };
11282
      var captureInput = bind$2(page, 'keydown', function (evt) {
11283
        if (!contains([
11284
            'input',
11285
            'textarea'
11286
          ], name(evt.target()))) {
11287
          toEditing();
11288
        }
11289
      });
11290
      var onToolbarTouch = function () {
11291
      };
11292
      var destroy = function () {
11293
        captureInput.unbind();
11294
      };
11295
      return {
11296
        toReading: toReading,
11297
        toEditing: toEditing,
11298
        onToolbarTouch: onToolbarTouch,
11299
        destroy: destroy
11300
      };
11301
    };
11302
    var timid = function (outerBody, cWin, page, frame) {
11303
      var dismissKeyboard = function () {
11304
        blur$$1(frame);
11305
      };
11306
      var onToolbarTouch = function () {
11307
        dismissKeyboard();
11308
      };
11309
      var toReading = function () {
11310
        dismissKeyboard();
11311
      };
11312
      var toEditing = function () {
11313
        ResumeEditing$1.resume(cWin, frame);
11314
      };
11315
      return {
11316
        toReading: toReading,
11317
        toEditing: toEditing,
11318
        onToolbarTouch: onToolbarTouch,
11319
        destroy: noop
11320
      };
11321
    };
11322
    var IosKeyboard = {
11323
      stubborn: stubborn,
11324
      timid: timid
11325
    };
11326
11327
    var initEvents$1 = function (editorApi, iosApi, toolstrip, socket, dropup) {
11328
      var saveSelectionFirst = function () {
11329
        iosApi.run(function (api) {
11330
          api.highlightSelection();
11331
        });
11332
      };
11333
      var refreshIosSelection = function () {
11334
        iosApi.run(function (api) {
11335
          api.refreshSelection();
11336
        });
11337
      };
11338
      var scrollToY = function (yTop, height) {
11339
        var y = yTop - socket.dom().scrollTop;
11340
        iosApi.run(function (api) {
11341
          api.scrollIntoView(y, y + height);
11342
        });
11343
      };
11344
      var scrollToElement = function (target) {
11345
        scrollToY(iosApi, socket);
11346
      };
11347
      var scrollToCursor = function () {
11348
        editorApi.getCursorBox().each(function (box) {
11349
          scrollToY(box.top(), box.height());
11350
        });
11351
      };
11352
      var clearSelection = function () {
11353
        iosApi.run(function (api) {
11354
          api.clearSelection();
11355
        });
11356
      };
11357
      var clearAndRefresh = function () {
11358
        clearSelection();
11359
        refreshThrottle.throttle();
11360
      };
11361
      var refreshView = function () {
11362
        scrollToCursor();
11363
        iosApi.run(function (api) {
11364
          api.syncHeight();
11365
        });
11366
      };
11367
      var reposition = function () {
11368
        var toolbarHeight = get$5(toolstrip);
11369
        iosApi.run(function (api) {
11370
          api.setViewportOffset(toolbarHeight);
11371
        });
11372
        refreshIosSelection();
11373
        refreshView();
11374
      };
11375
      var toEditing = function () {
11376
        iosApi.run(function (api) {
11377
          api.toEditing();
11378
        });
11379
      };
11380
      var toReading = function () {
11381
        iosApi.run(function (api) {
11382
          api.toReading();
11383
        });
11384
      };
11385
      var onToolbarTouch = function (event) {
11386
        iosApi.run(function (api) {
11387
          api.onToolbarTouch(event);
11388
        });
11389
      };
11390
      var tapping = TappingEvent.monitor(editorApi);
11391
      var refreshThrottle = last$3(refreshView, 300);
11392
      var listeners = [
11393
        editorApi.onKeyup(clearAndRefresh),
11394
        editorApi.onNodeChanged(refreshIosSelection),
11395
        editorApi.onDomChanged(refreshThrottle.throttle),
11396
        editorApi.onDomChanged(refreshIosSelection),
11397
        editorApi.onScrollToCursor(function (tinyEvent) {
11398
          tinyEvent.preventDefault();
11399
          refreshThrottle.throttle();
11400
        }),
11401
        editorApi.onScrollToElement(function (event) {
11402
          scrollToElement(event.element());
11403
        }),
11404
        editorApi.onToEditing(toEditing),
11405
        editorApi.onToReading(toReading),
11406
        bind$2(editorApi.doc(), 'touchend', function (touchEvent) {
11407
          if (eq(editorApi.html(), touchEvent.target()) || eq(editorApi.body(), touchEvent.target())) ;
11408
        }),
11409
        bind$2(toolstrip, 'transitionend', function (transitionEvent) {
11410
          if (transitionEvent.raw().propertyName === 'height') {
11411
            reposition();
11412
          }
11413
        }),
11414
        capture$1(toolstrip, 'touchstart', function (touchEvent) {
11415
          saveSelectionFirst();
11416
          onToolbarTouch(touchEvent);
11417
          editorApi.onTouchToolstrip();
11418
        }),
11419
        bind$2(editorApi.body(), 'touchstart', function (evt) {
11420
          clearSelection();
11421
          editorApi.onTouchContent();
11422
          tapping.fireTouchstart(evt);
11423
        }),
11424
        tapping.onTouchmove(),
11425
        tapping.onTouchend(),
11426
        bind$2(editorApi.body(), 'click', function (event) {
11427
          event.kill();
11428
        }),
11429
        bind$2(toolstrip, 'touchmove', function () {
11430
          editorApi.onToolbarScrollStart();
11431
        })
11432
      ];
11433
      var destroy = function () {
11434
        each$1(listeners, function (l) {
11435
          l.unbind();
11436
        });
11437
      };
11438
      return { destroy: destroy };
11439
    };
11440
    var IosEvents = { initEvents: initEvents$1 };
11441
11442
    function FakeSelection (win, frame) {
11443
      var doc = win.document;
11444
      var container = Element$$1.fromTag('div');
11445
      add$2(container, Styles.resolve('unfocused-selections'));
11446
      append(Element$$1.fromDom(doc.documentElement), container);
11447
      var onTouch = bind$2(container, 'touchstart', function (event) {
11448
        event.prevent();
11449
        ResumeEditing$1.resume(win, frame);
11450
        clear();
11451
      });
11452
      var make = function (rectangle) {
11453
        var span = Element$$1.fromTag('span');
11454
        add$3(span, [
11455
          Styles.resolve('layer-editor'),
11456
          Styles.resolve('unfocused-selection')
11457
        ]);
11458
        setAll$1(span, {
11459
          left: rectangle.left() + 'px',
11460
          top: rectangle.top() + 'px',
11461
          width: rectangle.width() + 'px',
11462
          height: rectangle.height() + 'px'
11463
        });
11464
        return span;
11465
      };
11466
      var update = function () {
11467
        clear();
11468
        var rectangles = Rectangles.getRectangles(win);
11469
        var spans = map$1(rectangles, make);
11470
        append$1(container, spans);
11471
      };
11472
      var clear = function () {
11473
        empty(container);
11474
      };
11475
      var destroy = function () {
11476
        onTouch.unbind();
11477
        remove(container);
11478
      };
11479
      var isActive = function () {
11480
        return children(container).length > 0;
11481
      };
11482
      return {
11483
        update: update,
11484
        isActive: isActive,
11485
        destroy: destroy,
11486
        clear: clear
11487
      };
11488
    }
11489
11490
    var nu$8 = function (baseFn) {
11491
      var data = Option.none();
11492
      var callbacks = [];
11493
      var map = function (f) {
11494
        return nu$8(function (nCallback) {
11495
          get(function (data) {
11496
            nCallback(f(data));
11497
          });
11498
        });
11499
      };
11500
      var get = function (nCallback) {
11501
        if (isReady())
11502
          call(nCallback);
11503
        else
11504
          callbacks.push(nCallback);
11505
      };
11506
      var set = function (x) {
11507
        data = Option.some(x);
11508
        run(callbacks);
11509
        callbacks = [];
11510
      };
11511
      var isReady = function () {
11512
        return data.isSome();
11513
      };
11514
      var run = function (cbs) {
11515
        each$1(cbs, call);
11516
      };
11517
      var call = function (cb) {
11518
        data.each(function (x) {
11519
          setTimeout(function () {
11520
            cb(x);
11521
          }, 0);
11522
        });
11523
      };
11524
      baseFn(set);
11525
      return {
11526
        get: get,
11527
        map: map,
11528
        isReady: isReady
11529
      };
11530
    };
11531
    var pure$1 = function (a) {
11532
      return nu$8(function (callback) {
11533
        callback(a);
11534
      });
11535
    };
11536
    var LazyValue = {
11537
      nu: nu$8,
11538
      pure: pure$1
11539
    };
11540
11541
    var bounce = function (f) {
11542
      return function () {
11543
        var args = [];
11544
        for (var _i = 0; _i < arguments.length; _i++) {
11545
          args[_i] = arguments[_i];
11546
        }
11547
        var me = this;
11548
        setTimeout(function () {
11549
          f.apply(me, args);
11550
        }, 0);
11551
      };
11552
    };
11553
11554
    var nu$9 = function (baseFn) {
11555
      var get = function (callback) {
11556
        baseFn(bounce(callback));
11557
      };
11558
      var map = function (fab) {
11559
        return nu$9(function (callback) {
11560
          get(function (a) {
11561
            var value = fab(a);
11562
            callback(value);
11563
          });
11564
        });
11565
      };
11566
      var bind = function (aFutureB) {
11567
        return nu$9(function (callback) {
11568
          get(function (a) {
11569
            aFutureB(a).get(callback);
11570
          });
11571
        });
11572
      };
11573
      var anonBind = function (futureB) {
11574
        return nu$9(function (callback) {
11575
          get(function (a) {
11576
            futureB.get(callback);
11577
          });
11578
        });
11579
      };
11580
      var toLazy = function () {
11581
        return LazyValue.nu(get);
11582
      };
11583
      var toCached = function () {
11584
        var cache = null;
11585
        return nu$9(function (callback) {
11586
          if (cache === null) {
11587
            cache = toLazy();
11588
          }
11589
          cache.get(callback);
11590
        });
11591
      };
11592
      return {
11593
        map: map,
11594
        bind: bind,
11595
        anonBind: anonBind,
11596
        toLazy: toLazy,
11597
        toCached: toCached,
11598
        get: get
11599
      };
11600
    };
11601
    var pure$2 = function (a) {
11602
      return nu$9(function (callback) {
11603
        callback(a);
11604
      });
11605
    };
11606
    var Future = {
11607
      nu: nu$9,
11608
      pure: pure$2
11609
    };
11610
11611
    var adjust = function (value, destination, amount) {
11612
      if (Math.abs(value - destination) <= amount) {
11613
        return Option.none();
11614
      } else if (value < destination) {
11615
        return Option.some(value + amount);
11616
      } else {
11617
        return Option.some(value - amount);
11618
      }
11619
    };
11620
    var create$7 = function () {
11621
      var interval = null;
11622
      var animate = function (getCurrent, destination, amount, increment, doFinish, rate) {
11623
        var finished = false;
11624
        var finish = function (v) {
11625
          finished = true;
11626
          doFinish(v);
11627
        };
11628
        clearInterval(interval);
11629
        var abort = function (v) {
11630
          clearInterval(interval);
11631
          finish(v);
11632
        };
11633
        interval = setInterval(function () {
11634
          var value = getCurrent();
11635
          adjust(value, destination, amount).fold(function () {
11636
            clearInterval(interval);
11637
            finish(destination);
11638
          }, function (s) {
11639
            increment(s, abort);
11640
            if (!finished) {
11641
              var newValue = getCurrent();
11642
              if (newValue !== s || Math.abs(newValue - destination) > Math.abs(value - destination)) {
11643
                clearInterval(interval);
11644
                finish(destination);
11645
              }
11646
            }
11647
          });
11648
        }, rate);
11649
      };
11650
      return { animate: animate };
11651
    };
11652
    var SmoothAnimation = {
11653
      create: create$7,
11654
      adjust: adjust
11655
    };
11656
11657
    var findDevice = function (deviceWidth, deviceHeight) {
11658
      var devices = [
11659
        {
11660
          width: 320,
11661
          height: 480,
11662
          keyboard: {
11663
            portrait: 300,
11664
            landscape: 240
11665
          }
11666
        },
11667
        {
11668
          width: 320,
11669
          height: 568,
11670
          keyboard: {
11671
            portrait: 300,
11672
            landscape: 240
11673
          }
11674
        },
11675
        {
11676
          width: 375,
11677
          height: 667,
11678
          keyboard: {
11679
            portrait: 305,
11680
            landscape: 240
11681
          }
11682
        },
11683
        {
11684
          width: 414,
11685
          height: 736,
11686
          keyboard: {
11687
            portrait: 320,
11688
            landscape: 240
11689
          }
11690
        },
11691
        {
11692
          width: 768,
11693
          height: 1024,
11694
          keyboard: {
11695
            portrait: 320,
11696
            landscape: 400
11697
          }
11698
        },
11699
        {
11700
          width: 1024,
11701
          height: 1366,
11702
          keyboard: {
11703
            portrait: 380,
11704
            landscape: 460
11705
          }
11706
        }
11707
      ];
11708
      return findMap(devices, function (device) {
11709
        return deviceWidth <= device.width && deviceHeight <= device.height ? Option.some(device.keyboard) : Option.none();
11710
      }).getOr({
11711
        portrait: deviceHeight / 5,
11712
        landscape: deviceWidth / 4
11713
      });
11714
    };
11715
    var Devices = { findDevice: findDevice };
11716
11717
    var softKeyboardLimits = function (outerWindow) {
11718
      return Devices.findDevice(outerWindow.screen.width, outerWindow.screen.height);
11719
    };
11720
    var accountableKeyboardHeight = function (outerWindow) {
11721
      var portrait = Orientation.get(outerWindow).isPortrait();
11722
      var limits = softKeyboardLimits(outerWindow);
11723
      var keyboard = portrait ? limits.portrait : limits.landscape;
11724
      var visualScreenHeight = portrait ? outerWindow.screen.height : outerWindow.screen.width;
11725
      return visualScreenHeight - outerWindow.innerHeight > keyboard ? 0 : keyboard;
11726
    };
11727
    var getGreenzone = function (socket, dropup) {
11728
      var outerWindow = owner(socket).dom().defaultView;
11729
      var viewportHeight = get$5(socket) + get$5(dropup);
11730
      var acc = accountableKeyboardHeight(outerWindow);
11731
      return viewportHeight - acc;
11732
    };
11733
    var updatePadding = function (contentBody, socket, dropup) {
11734
      var greenzoneHeight = getGreenzone(socket, dropup);
11735
      var deltaHeight = get$5(socket) + get$5(dropup) - greenzoneHeight;
11736
      set$2(contentBody, 'padding-bottom', deltaHeight + 'px');
11737
    };
11738
    var DeviceZones = {
11739
      getGreenzone: getGreenzone,
11740
      updatePadding: updatePadding
11741
    };
11742
11743
    var fixture = Adt.generate([
11744
      {
11745
        fixed: [
11746
          'element',
11747
          'property',
11748
          'offsetY'
11749
        ]
11750
      },
11751
      {
11752
        scroller: [
11753
          'element',
11754
          'offsetY'
11755
        ]
11756
      }
11757
    ]);
11758
    var yFixedData = 'data-' + Styles.resolve('position-y-fixed');
11759
    var yFixedProperty = 'data-' + Styles.resolve('y-property');
11760
    var yScrollingData = 'data-' + Styles.resolve('scrolling');
11761
    var windowSizeData = 'data-' + Styles.resolve('last-window-height');
11762
    var getYFixedData = function (element) {
11763
      return DataAttributes.safeParse(element, yFixedData);
11764
    };
11765
    var getYFixedProperty = function (element) {
11766
      return get$1(element, yFixedProperty);
11767
    };
11768
    var getLastWindowSize = function (element) {
11769
      return DataAttributes.safeParse(element, windowSizeData);
11770
    };
11771
    var classifyFixed = function (element, offsetY) {
11772
      var prop = getYFixedProperty(element);
11773
      return fixture.fixed(element, prop, offsetY);
11774
    };
11775
    var classifyScrolling = function (element, offsetY) {
11776
      return fixture.scroller(element, offsetY);
11777
    };
11778
    var classify = function (element) {
11779
      var offsetY = getYFixedData(element);
11780
      var classifier = get$1(element, yScrollingData) === 'true' ? classifyScrolling : classifyFixed;
11781
      return classifier(element, offsetY);
11782
    };
11783
    var findFixtures = function (container) {
11784
      var candidates = descendants$1(container, '[' + yFixedData + ']');
11785
      return map$1(candidates, classify);
11786
    };
11787
    var takeoverToolbar = function (toolbar) {
11788
      var oldToolbarStyle = get$1(toolbar, 'style');
11789
      setAll$1(toolbar, {
11790
        position: 'absolute',
11791
        top: '0px'
11792
      });
11793
      set(toolbar, yFixedData, '0px');
11794
      set(toolbar, yFixedProperty, 'top');
11795
      var restore = function () {
11796
        set(toolbar, 'style', oldToolbarStyle || '');
11797
        remove$1(toolbar, yFixedData);
11798
        remove$1(toolbar, yFixedProperty);
11799
      };
11800
      return { restore: restore };
11801
    };
11802
    var takeoverViewport = function (toolbarHeight, height, viewport) {
11803
      var oldViewportStyle = get$1(viewport, 'style');
11804
      Scrollable.register(viewport);
11805
      setAll$1(viewport, {
11806
        position: 'absolute',
11807
        height: height + 'px',
11808
        width: '100%',
11809
        top: toolbarHeight + 'px'
11810
      });
11811
      set(viewport, yFixedData, toolbarHeight + 'px');
11812
      set(viewport, yScrollingData, 'true');
11813
      set(viewport, yFixedProperty, 'top');
11814
      var restore = function () {
11815
        Scrollable.deregister(viewport);
11816
        set(viewport, 'style', oldViewportStyle || '');
11817
        remove$1(viewport, yFixedData);
11818
        remove$1(viewport, yScrollingData);
11819
        remove$1(viewport, yFixedProperty);
11820
      };
11821
      return { restore: restore };
11822
    };
11823
    var takeoverDropup = function (dropup, toolbarHeight, viewportHeight) {
11824
      var oldDropupStyle = get$1(dropup, 'style');
11825
      setAll$1(dropup, {
11826
        position: 'absolute',
11827
        bottom: '0px'
11828
      });
11829
      set(dropup, yFixedData, '0px');
11830
      set(dropup, yFixedProperty, 'bottom');
11831
      var restore = function () {
11832
        set(dropup, 'style', oldDropupStyle || '');
11833
        remove$1(dropup, yFixedData);
11834
        remove$1(dropup, yFixedProperty);
11835
      };
11836
      return { restore: restore };
11837
    };
11838
    var deriveViewportHeight = function (viewport, toolbarHeight, dropupHeight) {
11839
      var outerWindow = owner(viewport).dom().defaultView;
11840
      var winH = outerWindow.innerHeight;
11841
      set(viewport, windowSizeData, winH + 'px');
11842
      return winH - toolbarHeight - dropupHeight;
11843
    };
11844
    var takeover$1 = function (viewport, contentBody, toolbar, dropup) {
11845
      var outerWindow = owner(viewport).dom().defaultView;
11846
      var toolbarSetup = takeoverToolbar(toolbar);
11847
      var toolbarHeight = get$5(toolbar);
11848
      var dropupHeight = get$5(dropup);
11849
      var viewportHeight = deriveViewportHeight(viewport, toolbarHeight, dropupHeight);
11850
      var viewportSetup = takeoverViewport(toolbarHeight, viewportHeight, viewport);
11851
      var dropupSetup = takeoverDropup(dropup, toolbarHeight, viewportHeight);
11852
      var isActive = true;
11853
      var restore = function () {
11854
        isActive = false;
11855
        toolbarSetup.restore();
11856
        viewportSetup.restore();
11857
        dropupSetup.restore();
11858
      };
11859
      var isExpanding = function () {
11860
        var currentWinHeight = outerWindow.innerHeight;
11861
        var lastWinHeight = getLastWindowSize(viewport);
11862
        return currentWinHeight > lastWinHeight;
11863
      };
11864
      var refresh = function () {
11865
        if (isActive) {
11866
          var newToolbarHeight = get$5(toolbar);
11867
          var dropupHeight_1 = get$5(dropup);
11868
          var newHeight = deriveViewportHeight(viewport, newToolbarHeight, dropupHeight_1);
11869
          set(viewport, yFixedData, newToolbarHeight + 'px');
11870
          set$2(viewport, 'height', newHeight + 'px');
11871
          set$2(dropup, 'bottom', -(newToolbarHeight + newHeight + dropupHeight_1) + 'px');
11872
          DeviceZones.updatePadding(contentBody, viewport, dropup);
11873
        }
11874
      };
11875
      var setViewportOffset = function (newYOffset) {
11876
        var offsetPx = newYOffset + 'px';
11877
        set(viewport, yFixedData, offsetPx);
11878
        refresh();
11879
      };
11880
      DeviceZones.updatePadding(contentBody, viewport, dropup);
11881
      return {
11882
        setViewportOffset: setViewportOffset,
11883
        isExpanding: isExpanding,
11884
        isShrinking: not(isExpanding),
11885
        refresh: refresh,
11886
        restore: restore
11887
      };
11888
    };
11889
    var IosViewport = {
11890
      findFixtures: findFixtures,
11891
      takeover: takeover$1,
11892
      getYFixedData: getYFixedData
11893
    };
11894
11895
    var animator = SmoothAnimation.create();
11896
    var ANIMATION_STEP = 15;
11897
    var NUM_TOP_ANIMATION_FRAMES = 10;
11898
    var ANIMATION_RATE = 10;
11899
    var lastScroll = 'data-' + Styles.resolve('last-scroll-top');
11900
    var getTop = function (element) {
11901
      var raw = getRaw(element, 'top').getOr('0');
11902
      return parseInt(raw, 10);
11903
    };
11904
    var getScrollTop = function (element) {
11905
      return parseInt(element.dom().scrollTop, 10);
11906
    };
11907
    var moveScrollAndTop = function (element, destination, finalTop) {
11908
      return Future.nu(function (callback) {
11909
        var getCurrent = curry(getScrollTop, element);
11910
        var update = function (newScroll) {
11911
          element.dom().scrollTop = newScroll;
11912
          set$2(element, 'top', getTop(element) + ANIMATION_STEP + 'px');
11913
        };
11914
        var finish = function () {
11915
          element.dom().scrollTop = destination;
11916
          set$2(element, 'top', finalTop + 'px');
11917
          callback(destination);
11918
        };
11919
        animator.animate(getCurrent, destination, ANIMATION_STEP, update, finish, ANIMATION_RATE);
11920
      });
11921
    };
11922
    var moveOnlyScroll = function (element, destination) {
11923
      return Future.nu(function (callback) {
11924
        var getCurrent = curry(getScrollTop, element);
11925
        set(element, lastScroll, getCurrent());
11926
        var update = function (newScroll, abort) {
11927
          var previous = DataAttributes.safeParse(element, lastScroll);
11928
          if (previous !== element.dom().scrollTop) {
11929
            abort(element.dom().scrollTop);
11930
          } else {
11931
            element.dom().scrollTop = newScroll;
11932
            set(element, lastScroll, newScroll);
11933
          }
11934
        };
11935
        var finish = function () {
11936
          element.dom().scrollTop = destination;
11937
          set(element, lastScroll, destination);
11938
          callback(destination);
11939
        };
11940
        var distance = Math.abs(destination - getCurrent());
11941
        var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
11942
        animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
11943
      });
11944
    };
11945
    var moveOnlyTop = function (element, destination) {
11946
      return Future.nu(function (callback) {
11947
        var getCurrent = curry(getTop, element);
11948
        var update = function (newTop) {
11949
          set$2(element, 'top', newTop + 'px');
11950
        };
11951
        var finish = function () {
11952
          update(destination);
11953
          callback(destination);
11954
        };
11955
        var distance = Math.abs(destination - getCurrent());
11956
        var step = Math.ceil(distance / NUM_TOP_ANIMATION_FRAMES);
11957
        animator.animate(getCurrent, destination, step, update, finish, ANIMATION_RATE);
11958
      });
11959
    };
11960
    var updateTop = function (element, amount) {
11961
      var newTop = amount + IosViewport.getYFixedData(element) + 'px';
11962
      set$2(element, 'top', newTop);
11963
    };
11964
    var moveWindowScroll = function (toolbar, viewport, destY) {
11965
      var outerWindow = owner(toolbar).dom().defaultView;
11966
      return Future.nu(function (callback) {
11967
        updateTop(toolbar, destY);
11968
        updateTop(viewport, destY);
11969
        outerWindow.scrollTo(0, destY);
11970
        callback(destY);
11971
      });
11972
    };
11973
    var IosScrolling = {
11974
      moveScrollAndTop: moveScrollAndTop,
11975
      moveOnlyScroll: moveOnlyScroll,
11976
      moveOnlyTop: moveOnlyTop,
11977
      moveWindowScroll: moveWindowScroll
11978
    };
11979
11980
    function BackgroundActivity (doAction) {
11981
      var action = Cell(LazyValue.pure({}));
11982
      var start = function (value) {
11983
        var future = LazyValue.nu(function (callback) {
11984
          return doAction(value).get(callback);
11985
        });
11986
        action.set(future);
11987
      };
11988
      var idle = function (g) {
11989
        action.get().get(function () {
11990
          g();
11991
        });
11992
      };
11993
      return {
11994
        start: start,
11995
        idle: idle
11996
      };
11997
    }
11998
11999
    var scrollIntoView = function (cWin, socket, dropup, top, bottom) {
12000
      var greenzone = DeviceZones.getGreenzone(socket, dropup);
12001
      var refreshCursor = curry(CursorRefresh.refresh, cWin);
12002
      if (top > greenzone || bottom > greenzone) {
12003
        IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop - greenzone + bottom).get(refreshCursor);
12004
      } else if (top < 0) {
12005
        IosScrolling.moveOnlyScroll(socket, socket.dom().scrollTop + top).get(refreshCursor);
12006
      }
12007
    };
12008
    var Greenzone = { scrollIntoView: scrollIntoView };
12009
12010
    var par = function (asyncValues, nu) {
12011
      return nu(function (callback) {
12012
        var r = [];
12013
        var count = 0;
12014
        var cb = function (i) {
12015
          return function (value) {
12016
            r[i] = value;
12017
            count++;
12018
            if (count >= asyncValues.length) {
12019
              callback(r);
12020
            }
12021
          };
12022
        };
12023
        if (asyncValues.length === 0) {
12024
          callback([]);
12025
        } else {
12026
          each$1(asyncValues, function (asyncValue, i) {
12027
            asyncValue.get(cb(i));
12028
          });
12029
        }
12030
      });
12031
    };
12032
12033
    var par$1 = function (futures) {
12034
      return par(futures, Future.nu);
12035
    };
12036
12037
    var updateFixed = function (element, property, winY, offsetY) {
12038
      var destination = winY + offsetY;
12039
      set$2(element, property, destination + 'px');
12040
      return Future.pure(offsetY);
12041
    };
12042
    var updateScrollingFixed = function (element, winY, offsetY) {
12043
      var destTop = winY + offsetY;
12044
      var oldProp = getRaw(element, 'top').getOr(offsetY);
12045
      var delta = destTop - parseInt(oldProp, 10);
12046
      var destScroll = element.dom().scrollTop + delta;
12047
      return IosScrolling.moveScrollAndTop(element, destScroll, destTop);
12048
    };
12049
    var updateFixture = function (fixture, winY) {
12050
      return fixture.fold(function (element, property, offsetY) {
12051
        return updateFixed(element, property, winY, offsetY);
12052
      }, function (element, offsetY) {
12053
        return updateScrollingFixed(element, winY, offsetY);
12054
      });
12055
    };
12056
    var updatePositions = function (container, winY) {
12057
      var fixtures = IosViewport.findFixtures(container);
12058
      var updates = map$1(fixtures, function (fixture) {
12059
        return updateFixture(fixture, winY);
12060
      });
12061
      return par$1(updates);
12062
    };
12063
    var IosUpdates = { updatePositions: updatePositions };
12064
12065
    var VIEW_MARGIN = 5;
12066
    var register$2 = function (toolstrip, socket, container, outerWindow, structure, cWin) {
12067
      var scroller = BackgroundActivity(function (y) {
12068
        return IosScrolling.moveWindowScroll(toolstrip, socket, y);
12069
      });
12070
      var scrollBounds = function () {
12071
        var rects = Rectangles.getRectangles(cWin);
12072
        return Option.from(rects[0]).bind(function (rect) {
12073
          var viewTop = rect.top() - socket.dom().scrollTop;
12074
          var outside = viewTop > outerWindow.innerHeight + VIEW_MARGIN || viewTop < -VIEW_MARGIN;
12075
          return outside ? Option.some({
12076
            top: constant(viewTop),
12077
            bottom: constant(viewTop + rect.height())
12078
          }) : Option.none();
12079
        });
12080
      };
12081
      var scrollThrottle = last$3(function () {
12082
        scroller.idle(function () {
12083
          IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(function () {
12084
            var extraScroll = scrollBounds();
12085
            extraScroll.each(function (extra) {
12086
              socket.dom().scrollTop = socket.dom().scrollTop + extra.top();
12087
            });
12088
            scroller.start(0);
12089
            structure.refresh();
12090
          });
12091
        });
12092
      }, 1000);
12093
      var onScroll = bind$2(Element$$1.fromDom(outerWindow), 'scroll', function () {
12094
        if (outerWindow.pageYOffset < 0) {
12095
          return;
12096
        }
12097
        scrollThrottle.throttle();
12098
      });
12099
      IosUpdates.updatePositions(container, outerWindow.pageYOffset).get(identity);
12100
      return { unbind: onScroll.unbind };
12101
    };
12102
    var setup$3 = function (bag) {
12103
      var cWin = bag.cWin();
12104
      var ceBody = bag.ceBody();
12105
      var socket = bag.socket();
12106
      var toolstrip = bag.toolstrip();
12107
      var toolbar = bag.toolbar();
12108
      var contentElement = bag.contentElement();
12109
      var keyboardType = bag.keyboardType();
12110
      var outerWindow = bag.outerWindow();
12111
      var dropup = bag.dropup();
12112
      var structure = IosViewport.takeover(socket, ceBody, toolstrip, dropup);
12113
      var keyboardModel = keyboardType(bag.outerBody(), cWin, body(), contentElement, toolstrip, toolbar);
12114
      var toEditing = function () {
12115
        keyboardModel.toEditing();
12116
        clearSelection();
12117
      };
12118
      var toReading = function () {
12119
        keyboardModel.toReading();
12120
      };
12121
      var onToolbarTouch = function (event) {
12122
        keyboardModel.onToolbarTouch(event);
12123
      };
12124
      var onOrientation = Orientation.onChange(outerWindow, {
12125
        onChange: noop,
12126
        onReady: structure.refresh
12127
      });
12128
      onOrientation.onAdjustment(function () {
12129
        structure.refresh();
12130
      });
12131
      var onResize = bind$2(Element$$1.fromDom(outerWindow), 'resize', function () {
12132
        if (structure.isExpanding()) {
12133
          structure.refresh();
12134
        }
12135
      });
12136
      var onScroll = register$2(toolstrip, socket, bag.outerBody(), outerWindow, structure, cWin);
12137
      var unfocusedSelection = FakeSelection(cWin, contentElement);
12138
      var refreshSelection = function () {
12139
        if (unfocusedSelection.isActive()) {
12140
          unfocusedSelection.update();
12141
        }
12142
      };
12143
      var highlightSelection = function () {
12144
        unfocusedSelection.update();
12145
      };
12146
      var clearSelection = function () {
12147
        unfocusedSelection.clear();
12148
      };
12149
      var scrollIntoView = function (top, bottom) {
12150
        Greenzone.scrollIntoView(cWin, socket, dropup, top, bottom);
12151
      };
12152
      var syncHeight = function () {
12153
        set$2(contentElement, 'height', contentElement.dom().contentWindow.document.body.scrollHeight + 'px');
12154
      };
12155
      var setViewportOffset = function (newYOffset) {
12156
        structure.setViewportOffset(newYOffset);
12157
        IosScrolling.moveOnlyTop(socket, newYOffset).get(identity);
12158
      };
12159
      var destroy = function () {
12160
        structure.restore();
12161
        onOrientation.destroy();
12162
        onScroll.unbind();
12163
        onResize.unbind();
12164
        keyboardModel.destroy();
12165
        unfocusedSelection.destroy();
12166
        CaptureBin.input(body(), blur$$1);
12167
      };
12168
      return {
12169
        toEditing: toEditing,
12170
        toReading: toReading,
12171
        onToolbarTouch: onToolbarTouch,
12172
        refreshSelection: refreshSelection,
12173
        clearSelection: clearSelection,
12174
        highlightSelection: highlightSelection,
12175
        scrollIntoView: scrollIntoView,
12176
        updateToolbarPadding: noop,
12177
        setViewportOffset: setViewportOffset,
12178
        syncHeight: syncHeight,
12179
        refreshStructure: structure.refresh,
12180
        destroy: destroy
12181
      };
12182
    };
12183
    var IosSetup = { setup: setup$3 };
12184
12185
    var create$8 = function (platform, mask) {
12186
      var meta = MetaViewport.tag();
12187
      var priorState = value$3();
12188
      var scrollEvents = value$3();
12189
      var iosApi = api$2();
12190
      var iosEvents = api$2();
12191
      var enter = function () {
12192
        mask.hide();
12193
        var doc = Element$$1.fromDom(document);
12194
        PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
12195
          priorState.set({
12196
            socketHeight: getRaw(platform.socket, 'height'),
12197
            iframeHeight: getRaw(editorApi.frame(), 'height'),
12198
            outerScroll: document.body.scrollTop
12199
          });
12200
          scrollEvents.set({ exclusives: Scrollables.exclusive(doc, '.' + Scrollable.scrollable()) });
12201
          add$2(platform.container, Styles.resolve('fullscreen-maximized'));
12202
          Thor.clobberStyles(platform.container, editorApi.body());
12203
          meta.maximize();
12204
          set$2(platform.socket, 'overflow', 'scroll');
12205
          set$2(platform.socket, '-webkit-overflow-scrolling', 'touch');
12206
          focus$2(editorApi.body());
12207
          var setupBag = MixedBag([
12208
            'cWin',
12209
            'ceBody',
12210
            'socket',
12211
            'toolstrip',
12212
            'toolbar',
12213
            'dropup',
12214
            'contentElement',
12215
            'cursor',
12216
            'keyboardType',
12217
            'isScrolling',
12218
            'outerWindow',
12219
            'outerBody'
12220
          ], []);
12221
          iosApi.set(IosSetup.setup(setupBag({
12222
            cWin: editorApi.win(),
12223
            ceBody: editorApi.body(),
12224
            socket: platform.socket,
12225
            toolstrip: platform.toolstrip,
12226
            toolbar: platform.toolbar,
12227
            dropup: platform.dropup.element(),
12228
            contentElement: editorApi.frame(),
12229
            cursor: noop,
12230
            outerBody: platform.body,
12231
            outerWindow: platform.win,
12232
            keyboardType: IosKeyboard.stubborn,
12233
            isScrolling: function () {
12234
              var scrollValue = scrollEvents;
12235
              return scrollValue.get().exists(function (s) {
12236
                return s.socket.isScrolling();
12237
              });
12238
            }
12239
          })));
12240
          iosApi.run(function (api) {
12241
            api.syncHeight();
12242
          });
12243
          iosEvents.set(IosEvents.initEvents(editorApi, iosApi, platform.toolstrip, platform.socket, platform.dropup));
12244
        });
12245
      };
12246
      var exit = function () {
12247
        meta.restore();
12248
        iosEvents.clear();
12249
        iosApi.clear();
12250
        mask.show();
12251
        priorState.on(function (s) {
12252
          s.socketHeight.each(function (h) {
12253
            set$2(platform.socket, 'height', h);
12254
          });
12255
          s.iframeHeight.each(function (h) {
12256
            set$2(platform.editor.getFrame(), 'height', h);
12257
          });
12258
          document.body.scrollTop = s.scrollTop;
12259
        });
12260
        priorState.clear();
12261
        scrollEvents.on(function (s) {
12262
          s.exclusives.unbind();
12263
        });
12264
        scrollEvents.clear();
12265
        remove$4(platform.container, Styles.resolve('fullscreen-maximized'));
12266
        Thor.restoreStyles();
12267
        Scrollable.deregister(platform.toolbar);
12268
        remove$5(platform.socket, 'overflow');
12269
        remove$5(platform.socket, '-webkit-overflow-scrolling');
12270
        blur$$1(platform.editor.getFrame());
12271
        PlatformEditor.getActiveApi(platform.editor).each(function (editorApi) {
12272
          editorApi.clearSelection();
12273
        });
12274
      };
12275
      var refreshStructure = function () {
12276
        iosApi.run(function (api) {
12277
          api.refreshStructure();
12278
        });
12279
      };
12280
      return {
12281
        enter: enter,
12282
        refreshStructure: refreshStructure,
12283
        exit: exit
12284
      };
12285
    };
12286
    var IosMode = { create: create$8 };
12287
12288
    var produce$1 = function (raw) {
12289
      var mobile = asRawOrDie('Getting IosWebapp schema', MobileSchema, raw);
12290
      set$2(mobile.toolstrip, 'width', '100%');
12291
      set$2(mobile.container, 'position', 'relative');
12292
      var onView = function () {
12293
        mobile.setReadOnly(mobile.readOnlyOnInit());
12294
        mode.enter();
12295
      };
12296
      var mask = build$1(TapToEditMask.sketch(onView, mobile.translate));
12297
      mobile.alloy.add(mask);
12298
      var maskApi = {
12299
        show: function () {
12300
          mobile.alloy.add(mask);
12301
        },
12302
        hide: function () {
12303
          mobile.alloy.remove(mask);
12304
        }
12305
      };
12306
      var mode = IosMode.create(mobile, maskApi);
12307
      return {
12308
        setReadOnly: mobile.setReadOnly,
12309
        refreshStructure: mode.refreshStructure,
12310
        enter: mode.enter,
12311
        exit: mode.exit,
12312
        destroy: noop
12313
      };
12314
    };
12315
    var IosWebapp = { produce: produce$1 };
12316
12317
    function IosRealm (scrollIntoView) {
12318
      var alloy = OuterContainer({ classes: [Styles.resolve('ios-container')] });
12319
      var toolbar = ScrollingToolbar();
12320
      var webapp = api$2();
12321
      var switchToEdit = CommonRealm.makeEditSwitch(webapp);
12322
      var socket = CommonRealm.makeSocket();
12323
      var dropup = build$2(function () {
12324
        webapp.run(function (w) {
12325
          w.refreshStructure();
12326
        });
12327
      }, scrollIntoView);
12328
      alloy.add(toolbar.wrapper());
12329
      alloy.add(socket);
12330
      alloy.add(dropup.component());
12331
      var setToolbarGroups = function (rawGroups) {
12332
        var groups = toolbar.createGroups(rawGroups);
12333
        toolbar.setGroups(groups);
12334
      };
12335
      var setContextToolbar = function (rawGroups) {
12336
        var groups = toolbar.createGroups(rawGroups);
12337
        toolbar.setContextToolbar(groups);
12338
      };
12339
      var focusToolbar = function () {
12340
        toolbar.focus();
12341
      };
12342
      var restoreToolbar = function () {
12343
        toolbar.restoreToolbar();
12344
      };
12345
      var init = function (spec) {
12346
        webapp.set(IosWebapp.produce(spec));
12347
      };
12348
      var exit = function () {
12349
        webapp.run(function (w) {
12350
          Replacing.remove(socket, switchToEdit);
12351
          w.exit();
12352
        });
12353
      };
12354
      var updateMode = function (readOnly) {
12355
        CommonRealm.updateMode(socket, switchToEdit, readOnly, alloy.root());
12356
      };
12357
      return {
12358
        system: constant(alloy),
12359
        element: alloy.element,
12360
        init: init,
12361
        exit: exit,
12362
        setToolbarGroups: setToolbarGroups,
12363
        setContextToolbar: setContextToolbar,
12364
        focusToolbar: focusToolbar,
12365
        restoreToolbar: restoreToolbar,
12366
        updateMode: updateMode,
12367
        socket: constant(socket),
12368
        dropup: constant(dropup)
12369
      };
12370
    }
12371
12372
    var global$2 = tinymce.util.Tools.resolve('tinymce.EditorManager');
12373
12374
    var derive$4 = function (editor) {
12375
      var base = readOptFrom$1(editor.settings, 'skin_url').fold(function () {
12376
        return global$2.baseURL + '/skins/' + 'lightgray';
12377
      }, function (url) {
12378
        return url;
12379
      });
12380
      return {
12381
        content: base + '/content.mobile.min.css',
12382
        ui: base + '/skin.mobile.min.css'
12383
      };
12384
    };
12385
    var CssUrls = { derive: derive$4 };
12386
12387
    var fontSizes = [
12388
      'x-small',
12389
      'small',
12390
      'medium',
12391
      'large',
12392
      'x-large'
12393
    ];
12394
    var fireChange$1 = function (realm, command, state) {
12395
      realm.system().broadcastOn([TinyChannels.formatChanged()], {
12396
        command: command,
12397
        state: state
12398
      });
12399
    };
12400
    var init$5 = function (realm, editor) {
12401
      var allFormats = keys(editor.formatter.get());
12402
      each$1(allFormats, function (command) {
12403
        editor.formatter.formatChanged(command, function (state) {
12404
          fireChange$1(realm, command, state);
12405
        });
12406
      });
12407
      each$1([
12408
        'ul',
12409
        'ol'
12410
      ], function (command) {
12411
        editor.selection.selectorChanged(command, function (state, data) {
12412
          fireChange$1(realm, command, state);
12413
        });
12414
      });
12415
    };
12416
    var FormatChangers = {
12417
      init: init$5,
12418
      fontSizes: constant(fontSizes)
12419
    };
12420
12421
    var fireSkinLoaded = function (editor) {
12422
      var done = function () {
12423
        editor._skinLoaded = true;
12424
        editor.fire('SkinLoaded');
12425
      };
12426
      return function () {
12427
        if (editor.initialized) {
12428
          done();
12429
        } else {
12430
          editor.on('init', done);
12431
        }
12432
      };
12433
    };
12434
    var SkinLoaded = { fireSkinLoaded: fireSkinLoaded };
12435
12436
    var READING = constant('toReading');
12437
    var EDITING = constant('toEditing');
12438
    global$1.add('mobile', function (editor) {
12439
      var renderUI = function (args) {
12440
        var cssUrls = CssUrls.derive(editor);
12441
        if (isSkinDisabled(editor) === false) {
12442
          editor.contentCSS.push(cssUrls.content);
12443
          global.DOM.styleSheetLoader.load(cssUrls.ui, SkinLoaded.fireSkinLoaded(editor));
12444
        } else {
12445
          SkinLoaded.fireSkinLoaded(editor)();
12446
        }
12447
        var doScrollIntoView = function () {
12448
          editor.fire('scrollIntoView');
12449
        };
12450
        var wrapper = Element$$1.fromTag('div');
12451
        var realm = PlatformDetection$1.detect().os.isAndroid() ? AndroidRealm(doScrollIntoView) : IosRealm(doScrollIntoView);
12452
        var original = Element$$1.fromDom(args.targetNode);
12453
        after(original, wrapper);
12454
        attachSystem(wrapper, realm.system());
12455
        var findFocusIn = function (elem) {
12456
          return search(elem).bind(function (focused) {
12457
            return realm.system().getByDom(focused).toOption();
12458
          });
12459
        };
12460
        var outerWindow = args.targetNode.ownerDocument.defaultView;
12461
        var orientation = Orientation.onChange(outerWindow, {
12462
          onChange: function () {
12463
            var alloy = realm.system();
12464
            alloy.broadcastOn([TinyChannels.orientationChanged()], { width: Orientation.getActualWidth(outerWindow) });
12465
          },
12466
          onReady: noop
12467
        });
12468
        var setReadOnly = function (dynamicGroup, readOnlyGroups, mainGroups, ro) {
12469
          if (ro === false) {
12470
            editor.selection.collapse();
12471
          }
12472
          var toolbars = configureToolbar(dynamicGroup, readOnlyGroups, mainGroups);
12473
          realm.setToolbarGroups(ro === true ? toolbars.readOnly : toolbars.main);
12474
          editor.setMode(ro === true ? 'readonly' : 'design');
12475
          editor.fire(ro === true ? READING() : EDITING());
12476
          realm.updateMode(ro);
12477
        };
12478
        var configureToolbar = function (dynamicGroup, readOnlyGroups, mainGroups) {
12479
          var dynamic = dynamicGroup.get();
12480
          var toolbars = {
12481
            readOnly: dynamic.backToMask.concat(readOnlyGroups.get()),
12482
            main: dynamic.backToMask.concat(mainGroups.get())
12483
          };
12484
          return toolbars;
12485
        };
12486
        var bindHandler = function (label, handler) {
12487
          editor.on(label, handler);
12488
          return {
12489
            unbind: function () {
12490
              editor.off(label);
12491
            }
12492
          };
12493
        };
12494
        editor.on('init', function () {
12495
          realm.init({
12496
            editor: {
12497
              getFrame: function () {
12498
                return Element$$1.fromDom(editor.contentAreaContainer.querySelector('iframe'));
12499
              },
12500
              onDomChanged: function () {
12501
                return { unbind: noop };
12502
              },
12503
              onToReading: function (handler) {
12504
                return bindHandler(READING(), handler);
12505
              },
12506
              onToEditing: function (handler) {
12507
                return bindHandler(EDITING(), handler);
12508
              },
12509
              onScrollToCursor: function (handler) {
12510
                editor.on('scrollIntoView', function (tinyEvent) {
12511
                  handler(tinyEvent);
12512
                });
12513
                var unbind = function () {
12514
                  editor.off('scrollIntoView');
12515
                  orientation.destroy();
12516
                };
12517
                return { unbind: unbind };
12518
              },
12519
              onTouchToolstrip: function () {
12520
                hideDropup();
12521
              },
12522
              onTouchContent: function () {
12523
                var toolbar = Element$$1.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar')));
12524
                findFocusIn(toolbar).each(emitExecute);
12525
                realm.restoreToolbar();
12526
                hideDropup();
12527
              },
12528
              onTapContent: function (evt) {
12529
                var target = evt.target();
12530
                if (name(target) === 'img') {
12531
                  editor.selection.select(target.dom());
12532
                  evt.kill();
12533
                } else if (name(target) === 'a') {
12534
                  var component = realm.system().getByDom(Element$$1.fromDom(editor.editorContainer));
12535
                  component.each(function (container) {
12536
                    if (Swapping.isAlpha(container)) {
12537
                      TinyCodeDupe.openLink(target.dom());
12538
                    }
12539
                  });
12540
                }
12541
              }
12542
            },
12543
            container: Element$$1.fromDom(editor.editorContainer),
12544
            socket: Element$$1.fromDom(editor.contentAreaContainer),
12545
            toolstrip: Element$$1.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolstrip'))),
12546
            toolbar: Element$$1.fromDom(editor.editorContainer.querySelector('.' + Styles.resolve('toolbar'))),
12547
            dropup: realm.dropup(),
12548
            alloy: realm.system(),
12549
            translate: noop,
12550
            setReadOnly: function (ro) {
12551
              setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, ro);
12552
            },
12553
            readOnlyOnInit: function () {
12554
              return readOnlyOnInit(editor);
12555
            }
12556
          });
12557
          var hideDropup = function () {
12558
            realm.dropup().disappear(function () {
12559
              realm.system().broadcastOn([TinyChannels.dropupDismissed()], {});
12560
            });
12561
          };
12562
          var backToMaskGroup = {
12563
            label: 'The first group',
12564
            scrollable: false,
12565
            items: [Buttons.forToolbar('back', function () {
12566
                editor.selection.collapse();
12567
                realm.exit();
12568
              }, {})]
12569
          };
12570
          var backToReadOnlyGroup = {
12571
            label: 'Back to read only',
12572
            scrollable: false,
12573
            items: [Buttons.forToolbar('readonly-back', function () {
12574
                setReadOnly(dynamicGroup, readOnlyGroups, mainGroups, true);
12575
              }, {})]
12576
          };
12577
          var readOnlyGroup = {
12578
            label: 'The read only mode group',
12579
            scrollable: true,
12580
            items: []
12581
          };
12582
          var features = Features.setup(realm, editor);
12583
          var items = Features.detect(editor.settings, features);
12584
          var actionGroup = {
12585
            label: 'the action group',
12586
            scrollable: true,
12587
            items: items
12588
          };
12589
          var extraGroup = {
12590
            label: 'The extra group',
12591
            scrollable: false,
12592
            items: []
12593
          };
12594
          var mainGroups = Cell([
12595
            actionGroup,
12596
            extraGroup
12597
          ]);
12598
          var readOnlyGroups = Cell([
12599
            readOnlyGroup,
12600
            extraGroup
12601
          ]);
12602
          var dynamicGroup = Cell({
12603
            backToMask: [backToMaskGroup],
12604
            backToReadOnly: [backToReadOnlyGroup]
12605
          });
12606
          FormatChangers.init(realm, editor);
12607
        });
12608
        return {
12609
          iframeContainer: realm.socket().element().dom(),
12610
          editorContainer: realm.element().dom()
12611
        };
12612
      };
12613
      return {
12614
        getNotificationManagerImpl: function () {
12615
          return {
12616
            open: constant({
12617
              progressBar: { value: noop },
12618
              close: noop
12619
            }),
12620
            close: noop,
12621
            reposition: noop,
12622
            getArgs: identity
12623
          };
12624
        },
12625
        renderUI: renderUI
12626
      };
12627
    });
12628
    function Theme () {
12629
    }
12630
12631
    return Theme;
12632
12633
}());
12634
})();
12635