diff --git a/dist/blades.js b/dist/blades.js index 396a1b43..2ac50b77 100644 --- a/dist/blades.js +++ b/dist/blades.js @@ -26,8 +26,7 @@ var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; -var _ParseChildLinkData, ParseChildLinkData_fn, _ParseConfigToData, ParseConfigToData_fn, _updateTargetViaMerge, updateTargetViaMerge_fn, _updateTargetPropVal, updateTargetPropVal_fn, _apiKey, _id, _name, _instructions, _tools, _model, _fileIDs, _metadata; -import { gsap, MotionPathPlugin, TextPlugin, Flip, Draggable, SplitText, Observer as Observer$1, CustomEase, CustomWiggle, CustomBounce, EasePack } from "gsap/all"; +var _ParseChildLinkData, ParseChildLinkData_fn, _ParseConfigToData, ParseConfigToData_fn, _updateTargetViaMerge, updateTargetViaMerge_fn, _updateTargetPropVal, updateTargetPropVal_fn, _apiKey, _id2, _name, _instructions, _tools, _model, _fileIDs, _metadata; var BladesPermissions = ((BladesPermissions2) => { BladesPermissions2[BladesPermissions2["NONE"] = CONST.DOCUMENT_PERMISSION_LEVELS.NONE] = "NONE"; BladesPermissions2[BladesPermissions2["BASIC"] = CONST.DOCUMENT_PERMISSION_LEVELS.LIMITED] = "BASIC"; @@ -5357,9350 +5356,16524 @@ const SVGDATA = { } } }; -gsap.registerPlugin(MotionPathPlugin); -const _noCapWords = "a|above|after|an|and|at|below|but|by|down|for|for|from|in|nor|of|off|on|onto|or|out|so|the|to|under|up|with|yet".split("|").map((word) => new RegExp(`\\b${word}\\b`, "gui")); -const _capWords = [ - "I", - /[^a-z]{3,}|[.0-9]/gu -].map((word) => /RegExp/.test(Object.prototype.toString.call(word)) ? word : new RegExp(`\\b${word}\\b`, "gui")); -const _loremIpsumText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ultricies -nibh sed massa euismod lacinia. Aliquam nec est ac nunc ultricies scelerisque porta vulputate odio. -Integer gravida mattis odio, semper volutpat tellus. Ut elit leo, auctor eget fermentum hendrerit, -aliquet ac nunc. Suspendisse porta turpis vitae mi posuere molestie. Cras lectus lacus, vulputate a -vestibulum in, mattis vel mi. Mauris quis semper mauris. Praesent blandit nec diam eget tincidunt. Nunc -aliquet consequat massa ac lacinia. Ut posuere velit sagittis, vehicula nisl eget, fringilla nibh. Duis -volutpat mattis libero, a porttitor sapien viverra ut. Phasellus vulputate imperdiet ligula, eget -eleifend metus tempor nec. Nam eget sapien risus. Praesent id suscipit elit. Sed pellentesque ligula -diam, non aliquet magna feugiat vitae. Pellentesque ut tortor id erat placerat dignissim. Pellentesque -ut dui vel leo laoreet sodales nec ac tellus. In hac habitasse platea dictumst. Proin sed ex sed augue -sollicitudin interdum. Sed id lacus porttitor nisi vestibulum tincidunt. Nulla facilisi. Vestibulum -feugiat finibus magna in pretium. Proin consectetur lectus nisi, non commodo lectus tempor et. Cras -viverra, mi in consequat aliquet, justo mauris fringilla tellus, at accumsan magna metus in eros. Sed -vehicula, diam ut sagittis semper, purus massa mattis dolor, in posuere.`; -const _randomWords = ` -aboveboard|account|achiever|acoustics|act|action|activity|actor|addition|adjustment|advertisement|advice|afterglow|afterimage|afterlife|aftermath|afternoon|afterthought|agreement -air|aircraft|airfield|airlift|airline|airmen|airplane|airport|airtime|alarm|allover|allspice|alongside|also|amount|amusement|anger|angle|animal|another|ants|anyhow|anymore -anyone|anyplace|anytime|anywhere|apparatus|apparel|appliance|approval|arch|argument|arithmetic|arm|army|around|art|ashtray|attack|attraction|aunt|authority|babies|baby|babysitter -back|backache|backbone|backbreaker|backdrop|backfire|background|backhand|backlash|backlog|backpack|backside|backslap|backslide|backspace|backspin|backstroke|backtrack|backward -badge|bag|bait|balance|ball|ballroom|bankbook|bankroll|base|baseball|basin|basket|basketball|bat|bath|battle|beachcomb|bead|bear|because|become|bed|bedrock|bedroll|bedroom -beds|bee|beef|beginner|behavior|belief|believe|bell|bellboy|bellhop|bells|below|berry|bike|bikes|bird|birds|birth|birthday|bit|bite|blackball|blackberries|blackbird|blackboard -blackjack|blacklist|blackmail|blackout|blacksmith|blacktop|blade|blood|blow|blowgun|bluebell|blueberry|bluebird|bluefish|bluegrass|blueprint|board|boardwalk|boat|bodyguard -bomb|bone|book|bookcase|bookend|bookkeeper|bookmark|bookmobile|books|bookseller|bookshelf|bookworm|boot|border|bottle|boundary|bowlegs|bowtie|box|boy|brainchild|brake|branch -brass|breath|brick|bridge|brother|bubble|bucket|bugspray|building|bulb|burst|bushes|business|butter|butterball|buttercup|butterfingers|buttermilk|butternut|butterscotch|button -bypass|cabbage|cabdriver|cable|cactus|cake|cakes|calculator|calendar|camera|camp|can|cancan|candlelight|candlestick|cannon|cannot|canvas|cap|caption|car|card|cardsharp|care -carefree|careworn|carfare|carload|carpenter|carpool|carport|carriage|cars|carsick|cart|cartwheel|cast|cat|cats|cattle|catwalk|cause|cave|caveman|celery|cellar|cemetery|cent -centercut|chalk|chance|change|channel|cheese|cheeseburger|cherries|cherry|chess|chicken|chickens|children|chin|church|circle|clam|class|clockwise|cloth|clover|club|coach|coal -coast|coat|cobweb|coffeemaker|coil|collar|color|comeback|committee|commonplace|commonwealth|company|comparison|competition|condition|connection|control|cook|copper|corn|cornmeal -cough|country|courthouse|cover|cow|cows|crack|cracker|crate|crayon|cream|creator|creature|credit|crewcut|crib|crime|crook|crossbow|crossbreed|crosscut|crossover|crosswalk -crow|crowd|crown|cub|cup|current|curtain|curve|cushion|dad|dairymaid|daisywheel|daughter|day|daybed|daybook|daybreak|daydream|daylight|daytime|deadend|deadline|death|debt -decision|deer|degree|design|desire|desk|destruction|detail|development|digestion|dime|dinner|dinosaurs|direction|dirt|discovery|discussion|dishcloth|dishpan|dishwasher|dishwater -diskdrive|distance|distribution|division|dock|doctor|dog|dogs|doll|dolls|donkey|door|doorstop|downtown|downunder|drain|drawbridge|drawer|dress|drink|driveway|driving|drop -duck|duckbill|duckpin|ducks|dust|ear|earache|earring|earth|earthquake|earthward|earthworm|edge|education|effect|egg|egghead|eggnog|eggs|eggshell|elbow|end|engine|error|event -everything|example|exchange|existence|expansion|experience|expert|eye|eyeballs|eyecatching|eyeglasses|eyelash|eyelid|eyes|eyesight|eyewitness|face|fact|fairies|fall|fang|farm -fatherland|fear|feeling|field|finger|fire|fireball|fireboat|firebomb|firebreak|firecracker|firefighter|firehouse|fireman|fireproof|fireworks|fish|fishbowl|fisherman|fisheye -fishhook|fishmonger|fishnet|fishpond|fishtail|flag|flame|flavor|flesh|flight|flock|floor|flower|flowers|fly|fog|fold|food|foot|football|foothill|footlights|footlocker|footprints -forbearer|force|forearm|forebear|forebrain|forecast|foreclose|foreclosure|foredoom|forefather|forefeet|forefinger|forefoot|forego|foregone|forehand|forehead|foreknowledge -foreleg|foreman|forepaws|foresee|foreshadow|forestall|forethought|foretold|forever|forewarn|foreword|forget|fork|forklift|form|fowl|frame|friction|friend|friends|frog|frogs -front|fruit|fruitcup|fuel|furniture|gate|gearshift|geese|ghost|giants|giraffe|girl|girls|glass|glassmaking|glove|gold|goodbye|goodnight|government|governor|grade|grain|grandaunt -granddaughter|grandfather|grandmaster|grandmother|grandnephew|grandparent|grandson|grandstand|granduncle|grape|grass|grassland|graveyard|grip|ground|group|growth|guide|guitar -gumball|gun|hair|haircut|hall|hamburger|hammer|hand|handbook|handgun|handmade|handout|hands|harbor|harmony|hat|hate|head|headache|headlight|headline|headquarters|health|heat -hereafter|hereby|herein|hereupon|highchair|highland|highway|hill|himself|history|hobbies|hole|holiday|home|homemade|hometown|honey|honeybee|honeydew|honeysuckle|hook|hookup -hope|horn|horse|horseback|horsefly|horsehair|horseman|horseplay|horsepower|horseradish|horses|hose|hospital|hot|hour|house|houseboat|household|housekeeper|houses|housetop -however|humor|hydrant|ice|icicle|idea|impulse|income|increase|industry|ink|insect|inside|instrument|insurance|intake|interest|invention|iron|island|itself|jail|jailbait|jam -jar|jeans|jelly|jellybean|jellyfish|jetliner|jetport|jewel|join|judge|juice|jump|jumpshot|kettle|key|keyboard|keyhole|keynote|keypad|keypunch|keystone|keystroke|keyword|kick -kiss|kittens|kitty|knee|knife|knot|knowledge|laborer|lace|ladybug|lake|lamp|land|language|laugh|leather|leg|legs|letter|letters|lettuce|level|library|lifeblood|lifeguard|lifelike -lifeline|lifelong|lifetime|lifework|limelight|limestone|limit|line|linen|lip|liquid|loaf|lock|locket|longhand|look|loss|love|low|lukewarm|lumber|lunch|lunchroom|machine|magic -maid|mailbox|mainline|man|marble|mark|market|mask|mass|match|matchbox|meal|meantime|meanwhile|measure|meat|meeting|memory|men|metal|mice|middle|milk|mind|mine|minister|mint -minute|mist|mitten|mom|money|monkey|month|moon|moonbeam|moonlight|moonlit|moonscape|moonshine|moonstruck|moonwalk|moreover|morning|mother|motion|motorcycle|mountain|mouth -move|muscle|name|nation|nearby|neck|need|needle|nerve|nest|nevermore|newsboy|newsbreak|newscaster|newsdealer|newsletter|newsman|newspaper|newsprint|newsreel|newsroom|night -nightfall|nobody|noise|noisemaker|north|northeast|nose|note|notebook|nowhere|number|nursemaid|nut|nutcracker|oatmeal|observation|ocean|offer|office|oil|oneself|onetime|orange -oranges|order|oven|overboard|overcoat|overflow|overland|pacemaker|page|pail|pan|pancake|paper|parcel|part|partner|party|passbook|passenger|passkey|Passover|passport|payment -peace|pear|pen|pencil|peppermint|person|pest|pet|pets|pickle|pickup|picture|pie|pies|pig|pigs|pin|pinhole|pinstripe|pinup|pinwheel|pipe|pizzas|place|plane|planes|plant|plantation -plants|plastic|plate|play|playback|playground|playhouse|playthings|pleasure|plot|plough|pocket|point|poison|pollution|ponytail|popcorn|porter|position|postcard|pot|potato -powder|power|price|produce|profit|property|prose|protest|pull|pump|punishment|purpose|push|quarter|quartz|queen|question|quicksand|quiet|quill|quilt|quince|quiver|rabbit|rabbits -racquetball|rail|railroad|railway|rain|raincheck|raincoat|rainstorm|rainwater|rake|range|rat|rate|rattlesnake|rattletrap|ray|reaction|reading|reason|receipt|recess|record -regret|relation|religion|repairman|representative|request|respect|rest|reward|rhythm|rice|riddle|rifle|ring|rings|river|riverbanks|road|robin|rock|rod|roll|roof|room|root -rose|route|rub|rubberband|rule|run|sack|sail|sailboat|salesclerk|salt|sand|sandlot|sandstone|saucepan|scale|scapegoat|scarecrow|scarf|scene|scent|school|schoolbook|schoolboy -schoolbus|schoolhouse|science|scissors|screw|sea|seashore|seat|secretary|seed|selection|self|sense|servant|shade|shadyside|shake|shame|shape|sharecropper|sharpshooter|sheep -sheepskin|sheet|shelf|ship|shirt|shock|shoe|shoelace|shoemaker|shoes|shop|shortbread|show|showoff|showplace|side|sidekick|sidewalk|sign|silk|silver|silversmith|sink|sister -sisterhood|sisters|sixfold|size|skate|skateboard|skin|skintight|skirt|sky|skylark|skylight|slave|sleep|sleet|slip|slope|slowdown|slumlord|smash|smell|smile|smoke|snail|snails -snake|snakes|snakeskin|sneeze|snow|snowball|snowbank|snowbird|snowdrift|snowshovel|soap|society|sock|soda|sofa|softball|somebody|someday|somehow|someone|someplace|something -sometimes|somewhat|somewhere|son|song|songs|sort|sound|soundproof|soup|southeast|southwest|soybean|space|spacewalk|spade|spark|spearmint|spiders|spillway|spokesperson|sponge -spoon|spot|spring|spy|square|squirrel|stage|stagehand|stamp|standby|standoff|standout|standpoint|star|starfish|start|statement|station|steam|steamship|steel|stem|step|stepson -stew|stick|sticks|stitch|stocking|stockroom|stomach|stone|stop|stoplight|stopwatch|store|story|stove|stranger|straw|stream|street|stretch|string|stronghold|structure|substance -subway|sugar|suggestion|suit|summer|sun|sunbaked|sunbathe|sundial|sundown|sunfish|sunflower|sunglasses|sunlit|sunray|sunroof|sunup|supercargo|supercharge|supercool|superego -superfine|supergiant|superhero|superhighways|superhuman|superimpose|supermarket|supermen|supernatural|superpower|superscript|supersensitive|supersonic|superstar|superstrong -superstructure|supertanker|superweapon|superwoman|support|surprise|sweater|sweetheart|sweetmeat|swim|swing|system|table|tablecloth|tablespoon|tabletop|tableware|tail|tailcoat -tailgate|taillight|taillike|tailpiece|tailspin|takeoff|takeout|takeover|talebearer|taleteller|talk|tank|tapeworm|taproom|taproot|target|taskmaster|taste|tax|taxicab|taxpayer -teaching|teacup|team|teammate|teamwork|teapot|teaspoon|teenager|teeth|telltale|temper|tendency|tenderfoot|tenfold|tent|territory|test|textbook|texture|theory|therefore|thing -things|thought|thread|thrill|throat|throne|throwaway|throwback|thumb|thunder|thunderbird|thunderstorm|ticket|tiger|time|timekeeper|timesaving|timeshare|timetable|tin|title -toad|toe|toes|together|tomatoes|tongue|toolbox|tooth|toothbrush|toothpaste|toothpick|top|touch|touchdown|town|township|toy|toys|trade|trail|train|trains|tramp|transport|tray -treatment|tree|trees|trick|trip|trouble|trousers|truck|trucks|tub|turkey|turn|turnabout|turnaround|turnbuckle|turndown|turnkey|turnoff|turntable|twig|twist|typewriter|umbrella -uncle|underachieve|underage|underarm|underbelly|underbid|undercharge|underclothes|undercover|undercut|underdevelop|underestimate|underexpose|underfoot|underground|underwear -unit|upbeat|upbringing|upcoming|update|upend|upgrade|upheaval|uphill|uphold|upkeep|upland|uplift|upload|upmarket|upon|uppercase|upperclassman|uppercut|uproar|uproot|upset -upshot|upside|upstage|upstairs|upstanding|upstart|upstate|upstream|uptake|upthrust|uptight|uptime|uptown|upward|upwind|use|vacation|value|van|vase|vegetable|veil|vein|verse -vessel|vest|view|visitor|voice|volcano|volleyball|voyage|waistline|walk|walkways|wall|walleyed|wallpaper|war|wardroom|warfare|warmblooded|warpath|wash|washbowl|washcloth|washhouse -washout|washrag|washroom|washstand|washtub|waste|wastebasket|wasteland|wastepaper|wastewater|watch|watchband|watchdog|watchmaker|watchman|watchtower|watchword|water|watercolor -watercooler|watercraft|waterfall|waterfront|waterline|waterlog|watermelon|waterpower|waterproof|waterscape|watershed|waterside|waterspout|watertight|wave|wavelike|waves|wax -waxwork|way|waybill|wayfarer|waylaid|wayside|wayward|wealth|weather|weathercock|weatherman|weatherproof|week|weekday|weekend|weeknight|weight|whatever|whatsoever|wheel|wheelchair -wheelhouse|whip|whistle|whitecap|whitefish|whitewall|whitewash|widespread|wilderness|wind|window|wine|wing|winter|wipeout|wire|wish|without|woman|women|wood|woodshop|wool -word|work|worm|wound|wren|wrench|wrist|writer|writing|yak|yam|yard|yarn|year|yoke|zebra|zephyr|zinc|zipper|zoo -`.split("|"); -const _numberWords = { - ones: [ - "zero", - "one", - "two", - "three", - "four", - "five", - "six", - "seven", - "eight", - "nine", - "ten", - "eleven", - "twelve", - "thirteen", - "fourteen", - "fifteen", - "sixteen", - "seventeen", - "eighteen", - "nineteen", - "twenty" - ], - tens: ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"], - tiers: ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion"], - bigPrefixes: ["", "un", "duo", "tre", "quattuor", "quin", "sex", "octo", "novem"], - bigSuffixes: ["", "decillion", "vigintillion", "trigintillion", "quadragintillion", "quinquagintillion", "sexagintillion", "septuagintillion", "octogintillion", "nonagintillion", "centillion"] -}; -const _ordinals = { - zero: "zeroeth", - one: "first", - two: "second", - three: "third", - four: "fourth", - five: "fifth", - eight: "eighth", - nine: "ninth", - twelve: "twelfth", - twenty: "twentieth", - thirty: "thirtieth", - forty: "fortieth", - fifty: "fiftieth", - sixty: "sixtieth", - seventy: "seventieth", - eighty: "eightieth", - ninety: "ninetieth" -}; -const _romanNumerals = { - grouped: [ - ["", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ"], - ["", "Ⅹ", "ⅩⅩ", "ⅩⅩⅩ", "ⅩⅬ", "Ⅼ", "ⅬⅩ", "ⅬⅩⅩ", "ⅬⅩⅩⅩ", "ⅩⅭ"], - ["", "Ⅽ", "ⅭⅭ", "ⅭⅭⅭ", "ⅭⅮ", "Ⅾ", "ⅮⅭ", "ⅮⅭⅭ", "ⅮⅭⅭⅭ", "ⅭⅯ"], - ["", "Ⅿ", "ⅯⅯ", "ⅯⅯⅯ", "Ⅿↁ", "ↁ", "ↁⅯ", "ↁⅯⅯ", "ↁⅯⅯⅯ", "ↁↂ"], - ["", "ↂ", "ↂↂ", "ↂↂↂ", "ↂↇ", "ↇ", "ↇↂ", "ↇↂↂ", "ↇↂↂↂ", "ↇↈ"], - ["", "ↈ", "ↈↈ", "ↈↈↈ"] - ], - ungrouped: [ - ["", "Ⅰ", "ⅠⅠ", "ⅠⅠⅠ", "ⅠⅤ", "Ⅴ", "ⅤⅠ", "ⅤⅠⅠ", "ⅤⅠⅠⅠ", "ⅠⅩ"], - ["", "Ⅹ", "ⅩⅩ", "ⅩⅩⅩ", "ⅩⅬ", "Ⅼ", "ⅬⅩ", "ⅬⅩⅩ", "ⅬⅩⅩⅩ", "ⅩⅭ"], - ["", "Ⅽ", "ⅭⅭ", "ⅭⅭⅭ", "ⅭⅮ", "Ⅾ", "ⅮⅭ", "ⅮⅭⅭ", "ⅮⅭⅭⅭ", "ⅭⅯ"], - ["", "Ⅿ", "ⅯⅯ", "ⅯⅯⅯ", "Ⅿↁ", "ↁ", "ↁⅯ", "ↁⅯⅯ", "ↁⅯⅯⅯ", "ↁↂ"], - ["", "ↂ", "ↂↂ", "ↂↂↂ", "ↂↇ", "ↇ", "ↇↂ", "ↇↂↂ", "ↇↂↂↂ", "ↇↈ"], - ["", "ↈ", "ↈↈ", "ↈↈↈ"] - ] -}; -const UUIDLOG = []; -const GMID = () => { - var _a, _b; - return ((_b = (_a = game == null ? void 0 : game.user) == null ? void 0 : _a.find((user) => user.isGM)) == null ? void 0 : _b.id) ?? false; -}; -const isNumber = (ref) => typeof ref === "number" && !isNaN(ref); -const isNumString = (ref) => typeof ref === "string" && !isNaN(parseFloat(ref)) && isFinite(parseFloat(ref)); -const isBooleanString = (ref) => typeof ref === "string" && (ref === "true" || ref === "false"); -const isArray = (ref) => Array.isArray(ref); -const isSimpleObj = (ref) => ref === Object(ref) && !isArray(ref); -const isList = (ref) => ref === Object(ref) && !isArray(ref); -const isFunc = (ref) => typeof ref === "function"; -const isInt = (ref) => isNumber(ref) && Math.round(ref) === ref; -const isFloat = (ref) => isNumber(ref) && /\./.test(`${ref}`); -const isPosInt = (ref) => isInt(ref) && ref >= 0; -const isIndex = (ref) => isList(ref) || isArray(ref); -const isIterable = (ref) => typeof ref === "object" && ref !== null && Symbol.iterator in ref; -const isHTMLCode = (ref) => typeof ref === "string" && /^<.*>$/u.test(ref); -const isHexColor = (ref) => typeof ref === "string" && /^#(([0-9a-fA-F]{2}){3,4}|[0-9a-fA-F]{3,4})$/.test(ref); -const isRGBColor = (ref) => typeof ref === "string" && /^rgba?\((\d{1,3},\s*){1,2}?\d{1,3},\s*\d{1,3}(\.\d+)?\)$/.test(ref); -const isUndefined = (ref) => ref === void 0; -const isDefined = (ref) => !isUndefined(ref); -const isEmpty = (ref) => Object.keys(ref).length === 0; -const hasItems = (ref) => !isEmpty(ref); -const isInstance = (classRef, ref) => ref instanceof classRef; -const isNullish = (ref) => isUndefined(ref) || ref === null; -function assertNonNullType(val, type) { - let valStr; - try { - valStr = JSON.stringify(val); - } catch { - valStr = String(val); - } - if (val === void 0) { - throw new Error(`Value ${valStr} is undefined!`); - } - if (typeof type === "string") { - if (typeof val !== type) { - throw new Error(`Value ${valStr} is not a ${type}!`); - } - } else if (!(val instanceof type)) { - throw new Error(`Value ${valStr} is not a ${type.name}!`); - } +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; } -const areFuzzyEqual = (val1, val2) => { - if ([null, void 0].includes(val1) && [null, void 0].includes(val2)) { - return true; - } - if ([null, void 0].includes(val1) || [null, void 0].includes(val2)) { - return false; - } - if (typeof val1 === "number" && typeof val2 === "number") { - return val1 === val2; - } - if (typeof val1 === "boolean" && typeof val2 === "boolean") { - return val1 === val2; - } - if (typeof val1 === "string" && typeof val2 === "string") { - return val1 === val2; - } - if (typeof val1 === "number" && typeof val2 === "string") { - return val1 === Number(val2); - } - if (typeof val1 === "string" && typeof val2 === "number") { - return Number(val1) === val2; - } - if (typeof val1 === "boolean" && typeof val2 === "object") { - return false; - } - if (typeof val1 === "object" && typeof val2 === "boolean") { - return false; - } - if (typeof val1 === "boolean" && typeof val2 === "string") { - return val1 && val2 !== "" || !val1 && val2 === ""; - } - if (typeof val1 === "string" && typeof val2 === "boolean") { - return val2 && val1 !== "" || !val2 && val1 === ""; - } - if ((typeof val1 === "number" || typeof val1 === "string") && typeof val2 === "object") { - return false; - } - if (typeof val1 === "object" && (typeof val2 === "number" || typeof val2 === "string")) { - return false; - } - if (typeof val1 === "object" && typeof val2 === "object") { - return val1 === val2; - } - return false; -}; -const areEqual = (...refs) => { - do { - const ref = refs.pop(); - if (refs.length && !areFuzzyEqual(ref, refs[0])) { - return false; +var tagify_min = { exports: {} }; +(function(module, exports) { + !function(t, e) { + module.exports = e(); + }(commonjsGlobal, function() { + function t(t2, e2) { + var i2 = Object.keys(t2); + if (Object.getOwnPropertySymbols) { + var s2 = Object.getOwnPropertySymbols(t2); + e2 && (s2 = s2.filter(function(e3) { + return Object.getOwnPropertyDescriptor(t2, e3).enumerable; + })), i2.push.apply(i2, s2); + } + return i2; + } + function e(e2) { + for (var s2 = 1; s2 < arguments.length; s2++) { + var a2 = null != arguments[s2] ? arguments[s2] : {}; + s2 % 2 ? t(Object(a2), true).forEach(function(t2) { + i(e2, t2, a2[t2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(a2)) : t(Object(a2)).forEach(function(t2) { + Object.defineProperty(e2, t2, Object.getOwnPropertyDescriptor(a2, t2)); + }); + } + return e2; + } + function i(t2, e2, i2) { + return (e2 = function(t3) { + var e3 = function(t4, e4) { + if ("object" != typeof t4 || null === t4) + return t4; + var i3 = t4[Symbol.toPrimitive]; + if (void 0 !== i3) { + var s2 = i3.call(t4, e4 || "default"); + if ("object" != typeof s2) + return s2; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === e4 ? String : Number)(t4); + }(t3, "string"); + return "symbol" == typeof e3 ? e3 : String(e3); + }(e2)) in t2 ? Object.defineProperty(t2, e2, { value: i2, enumerable: true, configurable: true, writable: true }) : t2[e2] = i2, t2; + } + const s = (t2, e2, i2, s2) => (t2 = "" + t2, e2 = "" + e2, s2 && (t2 = t2.trim(), e2 = e2.trim()), i2 ? t2 == e2 : t2.toLowerCase() == e2.toLowerCase()), a = (t2, e2) => t2 && Array.isArray(t2) && t2.map((t3) => n(t3, e2)); + function n(t2, e2) { + var i2, s2 = {}; + for (i2 in t2) + e2.indexOf(i2) < 0 && (s2[i2] = t2[i2]); + return s2; + } + function o(t2) { + var e2 = document.createElement("div"); + return t2.replace(/\&#?[0-9a-z]+;/gi, function(t3) { + return e2.innerHTML = t3, e2.innerText; + }); } - } while (refs.length); - return true; -}; -const pFloat = (ref, sigDigits, isStrict = false) => { - if (typeof ref === "string") { - ref = parseFloat(ref); - } - if (typeof ref === "number") { - if (isNaN(ref)) { - return isStrict ? NaN : 0; + function r(t2) { + return new DOMParser().parseFromString(t2.trim(), "text/html").body.firstElementChild; } - if (isUndefined(sigDigits)) { - return ref; + function l(t2, e2) { + for (e2 = e2 || "previous"; t2 = t2[e2 + "Sibling"]; ) + if (3 == t2.nodeType) + return t2; } - return Math.round(ref * 10 ** sigDigits) / 10 ** sigDigits; - } - return isStrict ? NaN : 0; -}; -const pInt = (ref, isStrictOrIndex, _arr) => { - let isStrict = false; - if (typeof isStrictOrIndex === "boolean") { - isStrict = isStrictOrIndex; - } - return isNaN(pFloat(ref, 0, isStrict)) ? NaN : Math.round(pFloat(ref, 0, isStrict)); -}; -const pBool = (ref) => { - if (typeof ref === "boolean") { - return ref; - } - if ([0, null, void 0, ""].includes(ref)) { - return false; - } - if (typeof ref === "string") { - return !["0", "false", "null", "undefined", ""].includes(ref); - } - if (isArray(ref) && ref.length === 0) { - return false; - } - if (isList(ref) && isEmpty(ref)) { - return false; - } - return true; -}; -const radToDeg = (rad, isConstrained = true) => { - rad = isConstrained ? rad % (2 * Math.PI) : rad; - rad *= 180 / Math.PI; - return rad; -}; -const degToRad = (deg, isConstrained = true) => { - deg = isConstrained ? deg % 360 : deg; - deg *= Math.PI / 180; - return deg; -}; -const getKey = (key, obj) => { - if (key in obj) { - return obj[key]; - } - return null; -}; -const FILTERS = { - IsInstance: (classRef) => (item) => typeof classRef === "function" && item instanceof classRef -}; -const uCase = (str) => String(str).toUpperCase(); -const lCase = (str) => String(str).toLowerCase(); -const sCase = (str) => { - let [first, ...rest] = `${str ?? ""}`.split(/\s+/); - first = testRegExp(first, _capWords) ? first : `${uCase(first.charAt(0))}${lCase(first.slice(1))}`; - if (hasItems(rest)) { - rest = rest.map((word) => testRegExp(word, _capWords) ? word : lCase(word)); - } - return [first, ...rest].join(" ").trim(); -}; -const tCase = (str) => String(str).split(/\s/).map((word, i) => i && testRegExp(word, _noCapWords) ? lCase(word) : sCase(word)).join(" ").trim(); -const testRegExp = (str, patterns = [], flags = "gui", isTestingAll = false) => patterns.map((pattern) => pattern instanceof RegExp ? pattern : new RegExp(`\\b${pattern}\\b`, flags))[isTestingAll ? "every" : "some"]((pattern) => pattern.test(`${str}`)); -const regExtract = (ref, pattern, flags) => { - const splitFlags = []; - [...(flags ?? "").replace(/g/g, ""), "u"].forEach((flag) => { - if (flag && !splitFlags.includes(flag)) { - splitFlags.push(flag); + function d(t2) { + return "string" == typeof t2 ? t2.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/`|'/g, "'") : t2; } - }); - const isGrouping = /[)(]/.test(pattern.toString().replace(/\\\)|\\\(/g, "")); - if (isGrouping) { - splitFlags.push("g"); - } - flags = splitFlags.join(""); - pattern = new RegExp(pattern, flags); - const matches = `${ref}`.match(pattern) || []; - return isGrouping ? Array.from(matches) : matches.pop(); -}; -const unhyphenate = (str) => `${str}`.replace(/[\u00AD\u200B]/gu, ""); -const parseArticles = (str) => `${str}`.replace(/\b([aA])\s([aeiouAEIOU])/gu, "$1n $2"); -const pluralize = (singular, num = 2, plural) => { - if (pFloat(num) === 1) { - return singular; - } - return plural ?? `${singular.replace(/y$/, "ie").replace(/s$/, "se")}s`; -}; -const oxfordize = (items, useOxfordComma = true, andString = "and") => { - if (items.length === 0) { - return ""; - } - if (items.length === 1) { - return `${items[0]}`; - } - const lastItem = items.pop(); - return [ - items.join(", "), - useOxfordComma ? "," : "", - ` ${andString} `, - lastItem - ].join(""); -}; -const ellipsize = (text, maxLength) => { - const str = String(text); - return str.length > maxLength ? `${str.slice(0, maxLength - 3)}…` : str; -}; -const pad = (text, minLength, delim = " ") => { - const str = `${text}`; - if (str.length < minLength) { - return `${delim.repeat(minLength - str.length)}${str}`; - } - return str; -}; -const toKey = (text) => (text ?? "").toLowerCase().replace(/ /g, "-").replace(/default/, "DEFAULT"); -const signNum = (num, delim = "", zeroSign = "+") => { - let sign; - const parsedNum = pFloat(num); - if (parsedNum < 0) { - sign = "-"; - } else if (parsedNum === 0) { - sign = zeroSign; - } else { - sign = "+"; - } - return `${sign}${delim}${Math.abs(parsedNum)}`; -}; -const padNum = (num, numDecDigits, includePlus = false) => { - const prefix = includePlus && num >= 0 ? "+" : ""; - const [leftDigits, rightDigits] = `${pFloat(num)}`.split(/\./); - if (getType(rightDigits) === "int") { - if (rightDigits.length > numDecDigits) { - return `${prefix}${pFloat(num, numDecDigits)}`; - } else if (rightDigits.length < numDecDigits) { - return `${prefix}${leftDigits}.${rightDigits}${"0".repeat(numDecDigits - rightDigits.length)}`; - } else { - return `${prefix}${pFloat(num)}`; + function h(t2) { + var e2 = Object.prototype.toString.call(t2).split(" ")[1].slice(0, -1); + return t2 === Object(t2) && "Array" != e2 && "Function" != e2 && "RegExp" != e2 && "HTMLUnknownElement" != e2; } - } - return `${prefix}${leftDigits}.${"0".repeat(numDecDigits)}`; -}; -const stringifyNum = (num) => { - var _a; - if (pFloat(num) === 0) { - return "0"; - } - const stringyNum = lCase(num).replace(/[^\d.e+-]/g, ""); - const base = regExtract(stringyNum, /^-?[\d.]+/); - const exp = pInt(regExtract(stringyNum, /e([+-]?\d+)$/)); - if (typeof base === "string" && typeof exp === "string") { - let baseInts = regExtract(base, /^-?(\d+)/); - let baseDecs = regExtract(base, /\.(\d+)/); - if (isArray(baseInts) && isArray(baseDecs)) { - baseInts = (_a = baseInts.pop()) == null ? void 0 : _a.replace(/^0+/, ""); - baseDecs = lCase(baseDecs == null ? void 0 : baseDecs.pop()).replace(/0+$/, ""); - if (!isUndefined(baseInts) && !isUndefined(baseDecs)) { - const numFinalInts = Math.max(0, baseInts.length + exp); - const numFinalDecs = Math.max(0, baseDecs.length - exp); - const finalInts = [ - baseInts.slice(0, numFinalInts), - baseDecs.slice(0, Math.max(0, exp)) - ].join("") || "0"; - const finalDecs = [ - baseInts.length - numFinalInts > 0 ? baseInts.slice(baseInts.length - numFinalInts - 1) : "", - baseDecs.slice(baseDecs.length - numFinalDecs) - ].join(""); - return [ - stringyNum.charAt(0) === "-" ? "-" : "", - finalInts, - "0".repeat(Math.max(0, numFinalInts - finalInts.length)), - finalDecs.length ? "." : "", - "0".repeat(Math.max(0, numFinalDecs - finalDecs.length)), - finalDecs - ].join(""); + function g(t2, e2, i2) { + function s2(t3, e3) { + for (var i3 in e3) + if (e3.hasOwnProperty(i3)) { + if (h(e3[i3])) { + h(t3[i3]) ? s2(t3[i3], e3[i3]) : t3[i3] = Object.assign({}, e3[i3]); + continue; + } + if (Array.isArray(e3[i3])) { + t3[i3] = Object.assign([], e3[i3]); + continue; + } + t3[i3] = e3[i3]; + } } + return t2 instanceof Object || (t2 = {}), s2(t2, e2), i2 && s2(t2, i2), t2; } - } - return `${num}`; -}; -const verbalizeNum = (num) => { - var _a; - num = stringifyNum(num); - const getTier = (trioNum) => { - if (trioNum < _numberWords.tiers.length) { - return _numberWords.tiers[trioNum]; + function p() { + const t2 = [], e2 = {}; + for (let i2 of arguments) + for (let s2 of i2) + h(s2) ? e2[s2.value] || (t2.push(s2), e2[s2.value] = 1) : t2.includes(s2) || t2.push(s2); + return t2; } - return [ - _numberWords.bigPrefixes[trioNum % 10 - 1], - _numberWords.bigSuffixes[Math.floor(trioNum / 10)] - ].join(""); - }; - const parseThreeDigits = (trio) => { - if (pInt(trio) === 0) { - return ""; + function c(t2) { + return String.prototype.normalize ? "string" == typeof t2 ? t2.normalize("NFD").replace(/[\u0300-\u036f]/g, "") : void 0 : t2; } - const digits = `${trio}`.split("").map((digit) => pInt(digit)); - let result = ""; - if (digits.length === 3) { - const hundreds = digits.shift(); - if (isUndefined(hundreds)) { - throw new Error(`[U.verbalizeNum] Undefined digit in trio '${digits.join("")}'.`); - } - result += hundreds > 0 ? `${_numberWords.ones[hundreds]} hundred` : ""; - if (hundreds && (digits[0] || digits[1])) { - result += " and "; - } + var u = () => /(?=.*chrome)(?=.*android)/i.test(navigator.userAgent); + function m() { + return ("10000000-1000-4000-8000" + -1e11).replace(/[018]/g, (t2) => (t2 ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> t2 / 4).toString(16)); } - if (pInt(digits.join("")) <= _numberWords.ones.length) { - result += _numberWords.ones[pInt(digits.join(""))]; - } else { - const tens = _numberWords.tens[pInt(digits.shift())]; - const ones = pInt(digits[0]) > 0 ? `-${_numberWords.ones[pInt(digits[0])]}` : ""; - result += `${tens}${ones}`; + function v(t2) { + return t2 && t2.classList && t2.classList.contains(this.settings.classNames.tag); } - return result; - }; - const numWords = []; - if (num.charAt(0) === "-") { - numWords.push("negative"); - } - const [integers, decimals] = num.replace(/[,\s-]/g, "").split("."); - const intArray = ((_a = [...integers.split("")].reverse().join("").match(/.{1,3}/g)) == null ? void 0 : _a.map((v) => [...v.split("")].reverse().join(""))) ?? []; - const intStrings = []; - while (intArray.length) { - const thisTrio = intArray.pop(); - if (thisTrio) { - const theseWords = parseThreeDigits(thisTrio); - if (theseWords) { - intStrings.push(`${theseWords} ${getTier(intArray.length)}`); - } + function f(t2, e2) { + var i2 = window.getSelection(); + return e2 = e2 || i2.getRangeAt(0), "string" == typeof t2 && (t2 = document.createTextNode(t2)), e2 && (e2.deleteContents(), e2.insertNode(t2)), t2; } - } - numWords.push(intStrings.join(", ").trim()); - if (getType(decimals) === "int") { - if (integers === "0") { - numWords.push("zero"); + function T(t2, e2, i2) { + return t2 ? (e2 && (t2.__tagifyTagData = i2 ? e2 : g({}, t2.__tagifyTagData || {}, e2)), t2.__tagifyTagData) : (console.warn("tag element doesn't exist", t2, e2), e2); } - numWords.push("point"); - for (const digit of decimals.split("")) { - numWords.push(_numberWords.ones[pInt(digit)]); + function w(t2) { + if (t2 && t2.parentNode) { + var e2 = t2, i2 = window.getSelection(), s2 = i2.getRangeAt(0); + i2.rangeCount && (s2.setStartAfter(e2), s2.collapse(true), i2.removeAllRanges(), i2.addRange(s2)); + } } + function b(t2, e2) { + t2.forEach((t3) => { + if (T(t3.previousSibling) || !t3.previousSibling) { + var i2 = document.createTextNode("​"); + t3.before(i2), e2 && w(i2); + } + }); + } + var y = { delimiters: ",", pattern: null, tagTextProp: "value", maxTags: 1 / 0, callbacks: {}, addTagOnBlur: true, addTagOn: ["blur", "tab", "enter"], onChangeAfterBlur: true, duplicates: false, whitelist: [], blacklist: [], enforceWhitelist: false, userInput: true, keepInvalidTags: false, createInvalidTags: true, mixTagsAllowedAfter: /,|\.|\:|\s/, mixTagsInterpolator: ["[[", "]]"], backspace: true, skipInvalid: false, pasteAsTags: true, editTags: { clicks: 2, keepInvalid: true }, transformTag: () => { + }, trim: true, a11y: { focusableTags: false }, mixMode: { insertAfterTag: " " }, autoComplete: { enabled: true, rightKey: false, tabKey: false }, classNames: { namespace: "tagify", mixMode: "tagify--mix", selectMode: "tagify--select", input: "tagify__input", focus: "tagify--focus", tagNoAnimation: "tagify--noAnim", tagInvalid: "tagify--invalid", tagNotAllowed: "tagify--notAllowed", scopeLoading: "tagify--loading", hasMaxTags: "tagify--hasMaxTags", hasNoTags: "tagify--noTags", empty: "tagify--empty", inputInvalid: "tagify__input--invalid", dropdown: "tagify__dropdown", dropdownWrapper: "tagify__dropdown__wrapper", dropdownHeader: "tagify__dropdown__header", dropdownFooter: "tagify__dropdown__footer", dropdownItem: "tagify__dropdown__item", dropdownItemActive: "tagify__dropdown__item--active", dropdownItemHidden: "tagify__dropdown__item--hidden", dropdownInital: "tagify__dropdown--initial", tag: "tagify__tag", tagText: "tagify__tag-text", tagX: "tagify__tag__removeBtn", tagLoading: "tagify__tag--loading", tagEditing: "tagify__tag--editable", tagFlash: "tagify__tag--flash", tagHide: "tagify__tag--hide" }, dropdown: { classname: "", enabled: 2, maxItems: 10, searchKeys: ["value", "searchBy"], fuzzySearch: true, caseSensitive: false, accentedSearch: true, includeSelectedTags: false, escapeHTML: true, highlightFirst: true, closeOnSelect: true, clearOnSelect: true, position: "all", appendTarget: null }, hooks: { beforeRemoveTag: () => Promise.resolve(), beforePaste: () => Promise.resolve(), suggestionClick: () => Promise.resolve(), beforeKeyDown: () => Promise.resolve() } }, x = { events: { binding() { + let t2 = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0]; + var e2 = this.dropdown.events.callbacks, i2 = this.listeners.dropdown = this.listeners.dropdown || { position: this.dropdown.position.bind(this, null), onKeyDown: e2.onKeyDown.bind(this), onMouseOver: e2.onMouseOver.bind(this), onMouseLeave: e2.onMouseLeave.bind(this), onClick: e2.onClick.bind(this), onScroll: e2.onScroll.bind(this) }, s2 = t2 ? "addEventListener" : "removeEventListener"; + "manual" != this.settings.dropdown.position && (document[s2]("scroll", i2.position, true), window[s2]("resize", i2.position), window[s2]("keydown", i2.onKeyDown)), this.DOM.dropdown[s2]("mouseover", i2.onMouseOver), this.DOM.dropdown[s2]("mouseleave", i2.onMouseLeave), this.DOM.dropdown[s2]("mousedown", i2.onClick), this.DOM.dropdown.content[s2]("scroll", i2.onScroll); + }, callbacks: { onKeyDown(t2) { + if (this.state.hasFocus && !this.state.composing) { + var e2 = this.settings, i2 = this.DOM.dropdown.querySelector(e2.classNames.dropdownItemActiveSelector), s2 = this.dropdown.getSuggestionDataByNode(i2), a2 = "mix" == e2.mode; + e2.hooks.beforeKeyDown(t2, { tagify: this }).then((n2) => { + switch (t2.key) { + case "ArrowDown": + case "ArrowUp": + case "Down": + case "Up": + t2.preventDefault(); + var o2 = this.dropdown.getAllSuggestionsRefs(), r2 = "ArrowUp" == t2.key || "Up" == t2.key; + i2 && (i2 = this.dropdown.getNextOrPrevOption(i2, !r2)), i2 && i2.matches(e2.classNames.dropdownItemSelector) || (i2 = o2[r2 ? o2.length - 1 : 0]), this.dropdown.highlightOption(i2, true); + break; + case "Escape": + case "Esc": + this.dropdown.hide(); + break; + case "ArrowRight": + if (this.state.actions.ArrowLeft) + return; + case "Tab": { + let n3 = !e2.autoComplete.rightKey || !e2.autoComplete.tabKey; + if (!a2 && i2 && n3 && !this.state.editing) { + t2.preventDefault(); + var l2 = this.dropdown.getMappedValue(s2); + return this.input.autocomplete.set.call(this, l2), false; + } + return true; + } + case "Enter": + t2.preventDefault(), e2.hooks.suggestionClick(t2, { tagify: this, tagData: s2, suggestionElm: i2 }).then(() => { + if (i2) + return this.dropdown.selectOption(i2), i2 = this.dropdown.getNextOrPrevOption(i2, !r2), void this.dropdown.highlightOption(i2); + this.dropdown.hide(), a2 || this.addTags(this.state.inputText.trim(), true); + }).catch((t3) => console.warn(t3)); + break; + case "Backspace": { + if (a2 || this.state.editing.scope) + return; + const t3 = this.input.raw.call(this); + "" != t3 && 8203 != t3.charCodeAt(0) || (true === e2.backspace ? this.removeTags() : "edit" == e2.backspace && setTimeout(this.editTag.bind(this), 0)); + } + } + }); + } + }, onMouseOver(t2) { + var e2 = t2.target.closest(this.settings.classNames.dropdownItemSelector); + this.dropdown.highlightOption(e2); + }, onMouseLeave(t2) { + this.dropdown.highlightOption(); + }, onClick(t2) { + if (0 == t2.button && t2.target != this.DOM.dropdown && t2.target != this.DOM.dropdown.content) { + var e2 = t2.target.closest(this.settings.classNames.dropdownItemSelector), i2 = this.dropdown.getSuggestionDataByNode(e2); + this.state.actions.selectOption = true, setTimeout(() => this.state.actions.selectOption = false, 50), this.settings.hooks.suggestionClick(t2, { tagify: this, tagData: i2, suggestionElm: e2 }).then(() => { + e2 ? this.dropdown.selectOption(e2, t2) : this.dropdown.hide(); + }).catch((t3) => console.warn(t3)); + } + }, onScroll(t2) { + var e2 = t2.target, i2 = e2.scrollTop / (e2.scrollHeight - e2.parentNode.clientHeight) * 100; + this.trigger("dropdown:scroll", { percentage: Math.round(i2) }); + } } }, refilter(t2) { + t2 = t2 || this.state.dropdown.query || "", this.suggestedListItems = this.dropdown.filterListItems(t2), this.dropdown.fill(), this.suggestedListItems.length || this.dropdown.hide(), this.trigger("dropdown:updated", this.DOM.dropdown); + }, getSuggestionDataByNode(t2) { + var e2 = t2 && t2.getAttribute("value"); + return this.suggestedListItems.find((t3) => t3.value == e2) || null; + }, getNextOrPrevOption(t2) { + let e2 = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1]; + var i2 = this.dropdown.getAllSuggestionsRefs(), s2 = i2.findIndex((e3) => e3 === t2); + return e2 ? i2[s2 + 1] : i2[s2 - 1]; + }, highlightOption(t2, e2) { + var i2, s2 = this.settings.classNames.dropdownItemActive; + if (this.state.ddItemElm && (this.state.ddItemElm.classList.remove(s2), this.state.ddItemElm.removeAttribute("aria-selected")), !t2) + return this.state.ddItemData = null, this.state.ddItemElm = null, void this.input.autocomplete.suggest.call(this); + i2 = this.dropdown.getSuggestionDataByNode(t2), this.state.ddItemData = i2, this.state.ddItemElm = t2, t2.classList.add(s2), t2.setAttribute("aria-selected", true), e2 && (t2.parentNode.scrollTop = t2.clientHeight + t2.offsetTop - t2.parentNode.clientHeight), this.settings.autoComplete && (this.input.autocomplete.suggest.call(this, i2), this.dropdown.position()); + }, selectOption(t2, e2) { + var i2 = this.settings, s2 = i2.dropdown, a2 = s2.clearOnSelect, n2 = s2.closeOnSelect; + if (!t2) + return this.addTags(this.state.inputText, true), void (n2 && this.dropdown.hide()); + e2 = e2 || {}; + var o2 = t2.getAttribute("value"), r2 = "noMatch" == o2, l2 = "mix" == i2.mode, d2 = this.suggestedListItems.find((t3) => (t3.value ?? t3) == o2); + if (this.trigger("dropdown:select", { data: d2, elm: t2, event: e2 }), o2 && (d2 || r2)) { + if (this.state.editing) { + let t3 = this.normalizeTags([d2])[0]; + d2 = i2.transformTag.call(this, t3) || t3, this.onEditTagDone(null, g({ __isValid: true }, d2)); + } else + this[l2 ? "addMixTags" : "addTags"]([d2 || this.input.raw.call(this)], a2); + (l2 || this.DOM.input.parentNode) && (setTimeout(() => { + this.DOM.input.focus(), this.toggleFocusClass(true); + }), n2 && setTimeout(this.dropdown.hide.bind(this)), t2.addEventListener("transitionend", () => { + this.dropdown.fillHeaderFooter(), setTimeout(() => t2.remove(), 100); + }, { once: true }), t2.classList.add(this.settings.classNames.dropdownItemHidden)); + } else + n2 && setTimeout(this.dropdown.hide.bind(this)); + }, selectAll(t2) { + this.suggestedListItems.length = 0, this.dropdown.hide(), this.dropdown.filterListItems(""); + var e2 = this.dropdown.filterListItems(""); + return t2 || (e2 = this.state.dropdown.suggestions), this.addTags(e2, true), this; + }, filterListItems(t2, e2) { + var i2, s2, a2, n2, o2, r2 = this.settings, l2 = r2.dropdown, d2 = (e2 = e2 || {}, []), g2 = [], p2 = r2.whitelist, u2 = l2.maxItems >= 0 ? l2.maxItems : 1 / 0, m2 = l2.searchKeys, v2 = 0; + if (!(t2 = "select" == r2.mode && this.value.length && this.value[0][r2.tagTextProp] == t2 ? "" : t2) || !m2.length) + return d2 = l2.includeSelectedTags ? p2 : p2.filter((t3) => !this.isTagDuplicate(h(t3) ? t3.value : t3)), this.state.dropdown.suggestions = d2, d2.slice(0, u2); + function f2(t3, e3) { + return e3.toLowerCase().split(" ").every((e4) => t3.includes(e4.toLowerCase())); + } + for (o2 = l2.caseSensitive ? "" + t2 : ("" + t2).toLowerCase(); v2 < p2.length; v2++) { + let t3, r3; + i2 = p2[v2] instanceof Object ? p2[v2] : { value: p2[v2] }; + let u3 = !Object.keys(i2).some((t4) => m2.includes(t4)) ? ["value"] : m2; + l2.fuzzySearch && !e2.exact ? (a2 = u3.reduce((t4, e3) => t4 + " " + (i2[e3] || ""), "").toLowerCase().trim(), l2.accentedSearch && (a2 = c(a2), o2 = c(o2)), t3 = 0 == a2.indexOf(o2), r3 = a2 === o2, s2 = f2(a2, o2)) : (t3 = true, s2 = u3.some((t4) => { + var s3 = "" + (i2[t4] || ""); + return l2.accentedSearch && (s3 = c(s3), o2 = c(o2)), l2.caseSensitive || (s3 = s3.toLowerCase()), r3 = s3 === o2, e2.exact ? s3 === o2 : 0 == s3.indexOf(o2); + })), n2 = !l2.includeSelectedTags && this.isTagDuplicate(h(i2) ? i2.value : i2), s2 && !n2 && (r3 && t3 ? g2.push(i2) : "startsWith" == l2.sortby && t3 ? d2.unshift(i2) : d2.push(i2)); + } + return this.state.dropdown.suggestions = g2.concat(d2), "function" == typeof l2.sortby ? l2.sortby(g2.concat(d2), o2) : g2.concat(d2).slice(0, u2); + }, getMappedValue(t2) { + var e2 = this.settings.dropdown.mapValueTo; + return e2 ? "function" == typeof e2 ? e2(t2) : t2[e2] || t2.value : t2.value; + }, createListHTML(t2) { + return g([], t2).map((t3, i2) => { + "string" != typeof t3 && "number" != typeof t3 || (t3 = { value: t3 }); + var s2 = this.dropdown.getMappedValue(t3); + return s2 = "string" == typeof s2 && this.settings.dropdown.escapeHTML ? d(s2) : s2, this.settings.templates.dropdownItem.apply(this, [e(e({}, t3), {}, { mappedValue: s2 }), this]); + }).join(""); + } }; + function O() { + this.dropdown = {}; + for (let t2 in this._dropdown) + this.dropdown[t2] = "function" == typeof this._dropdown[t2] ? this._dropdown[t2].bind(this) : this._dropdown[t2]; + this.dropdown.refs(); + } + var D = e(e({}, x), {}, { refs() { + this.DOM.dropdown = this.parseTemplate("dropdown", [this.settings]), this.DOM.dropdown.content = this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-wrapper']"); + }, getHeaderRef() { + return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-header']"); + }, getFooterRef() { + return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-footer']"); + }, getAllSuggestionsRefs() { + return [...this.DOM.dropdown.content.querySelectorAll(this.settings.classNames.dropdownItemSelector)]; + }, show(t2) { + var e2, i2, a2, n2 = this.settings, o2 = "mix" == n2.mode && !n2.enforceWhitelist, r2 = !n2.whitelist || !n2.whitelist.length, l2 = "manual" == n2.dropdown.position; + if (t2 = void 0 === t2 ? this.state.inputText : t2, !(r2 && !o2 && !n2.templates.dropdownItemNoMatch || false === n2.dropdown.enable || this.state.isLoading || this.settings.readonly)) { + if (clearTimeout(this.dropdownHide__bindEventsTimeout), this.suggestedListItems = this.dropdown.filterListItems(t2), t2 && !this.suggestedListItems.length && (this.trigger("dropdown:noMatch", t2), n2.templates.dropdownItemNoMatch && (a2 = n2.templates.dropdownItemNoMatch.call(this, { value: t2 }))), !a2) { + if (this.suggestedListItems.length) + t2 && o2 && !this.state.editing.scope && !s(this.suggestedListItems[0].value, t2) && this.suggestedListItems.unshift({ value: t2 }); + else { + if (!t2 || !o2 || this.state.editing.scope) + return this.input.autocomplete.suggest.call(this), void this.dropdown.hide(); + this.suggestedListItems = [{ value: t2 }]; + } + i2 = "" + (h(e2 = this.suggestedListItems[0]) ? e2.value : e2), n2.autoComplete && i2 && 0 == i2.indexOf(t2) && this.input.autocomplete.suggest.call(this, e2); + } + this.dropdown.fill(a2), n2.dropdown.highlightFirst && this.dropdown.highlightOption(this.DOM.dropdown.content.querySelector(n2.classNames.dropdownItemSelector)), this.state.dropdown.visible || setTimeout(this.dropdown.events.binding.bind(this)), this.state.dropdown.visible = t2 || true, this.state.dropdown.query = t2, this.setStateSelection(), l2 || setTimeout(() => { + this.dropdown.position(), this.dropdown.render(); + }), setTimeout(() => { + this.trigger("dropdown:show", this.DOM.dropdown); + }); + } + }, hide(t2) { + var e2 = this.DOM, i2 = e2.scope, s2 = e2.dropdown, a2 = "manual" == this.settings.dropdown.position && !t2; + if (s2 && document.body.contains(s2) && !a2) + return window.removeEventListener("resize", this.dropdown.position), this.dropdown.events.binding.call(this, false), i2.setAttribute("aria-expanded", false), s2.parentNode.removeChild(s2), setTimeout(() => { + this.state.dropdown.visible = false; + }, 100), this.state.dropdown.query = this.state.ddItemData = this.state.ddItemElm = this.state.selection = null, this.state.tag && this.state.tag.value.length && (this.state.flaggedTags[this.state.tag.baseOffset] = this.state.tag), this.trigger("dropdown:hide", s2), this; + }, toggle(t2) { + this.dropdown[this.state.dropdown.visible && !t2 ? "hide" : "show"](); + }, getAppendTarget() { + var t2 = this.settings.dropdown; + return "function" == typeof t2.appendTarget ? t2.appendTarget() : t2.appendTarget; + }, render() { + var t2, e2, i2, s2 = (t2 = this.DOM.dropdown, (i2 = t2.cloneNode(true)).style.cssText = "position:fixed; top:-9999px; opacity:0", document.body.appendChild(i2), e2 = i2.clientHeight, i2.parentNode.removeChild(i2), e2), a2 = this.settings, n2 = "number" == typeof a2.dropdown.enabled && a2.dropdown.enabled >= 0, o2 = this.dropdown.getAppendTarget(); + return n2 ? (this.DOM.scope.setAttribute("aria-expanded", true), document.body.contains(this.DOM.dropdown) || (this.DOM.dropdown.classList.add(a2.classNames.dropdownInital), this.dropdown.position(s2), o2.appendChild(this.DOM.dropdown), setTimeout(() => this.DOM.dropdown.classList.remove(a2.classNames.dropdownInital))), this) : this; + }, fill(t2) { + t2 = "string" == typeof t2 ? t2 : this.dropdown.createListHTML(t2 || this.suggestedListItems); + var e2, i2 = this.settings.templates.dropdownContent.call(this, t2); + this.DOM.dropdown.content.innerHTML = (e2 = i2) ? e2.replace(/\>[\r\n ]+\<").split(/>\s+<").trim() : ""; + }, fillHeaderFooter() { + var t2 = this.dropdown.filterListItems(this.state.dropdown.query), e2 = this.parseTemplate("dropdownHeader", [t2]), i2 = this.parseTemplate("dropdownFooter", [t2]), s2 = this.dropdown.getHeaderRef(), a2 = this.dropdown.getFooterRef(); + e2 && (s2 == null ? void 0 : s2.parentNode.replaceChild(e2, s2)), i2 && (a2 == null ? void 0 : a2.parentNode.replaceChild(i2, a2)); + }, position(t2) { + var e2 = this.settings.dropdown, i2 = this.dropdown.getAppendTarget(); + if ("manual" != e2.position && i2) { + var s2, a2, n2, o2, r2, l2, d2, h2, g2, p2 = this.DOM.dropdown, c2 = e2.RTL, u2 = i2 === document.body, m2 = i2 === this.DOM.scope, v2 = u2 ? window.pageYOffset : i2.scrollTop, f2 = document.fullscreenElement || document.webkitFullscreenElement || document.documentElement, T2 = f2.clientHeight, w2 = Math.max(f2.clientWidth || 0, window.innerWidth || 0) > 480 ? e2.position : "all", b2 = this.DOM["input" == w2 ? "input" : "scope"]; + if (t2 = t2 || p2.clientHeight, this.state.dropdown.visible) { + if ("text" == w2 ? (n2 = (s2 = function() { + const t3 = document.getSelection(); + if (t3.rangeCount) { + const e3 = t3.getRangeAt(0), i3 = e3.startContainer, s3 = e3.startOffset; + let a3, n3; + if (s3 > 0) + return n3 = document.createRange(), n3.setStart(i3, s3 - 1), n3.setEnd(i3, s3), a3 = n3.getBoundingClientRect(), { left: a3.right, top: a3.top, bottom: a3.bottom }; + if (i3.getBoundingClientRect) + return i3.getBoundingClientRect(); + } + return { left: -9999, top: -9999 }; + }()).bottom, a2 = s2.top, o2 = s2.left, r2 = "auto") : (l2 = function(t3) { + var e3 = 0, i3 = 0; + for (t3 = t3.parentNode; t3 && t3 != f2; ) + e3 += t3.offsetTop || 0, i3 += t3.offsetLeft || 0, t3 = t3.parentNode; + return { top: e3, left: i3 }; + }(i2), s2 = b2.getBoundingClientRect(), a2 = m2 ? -1 : s2.top - l2.top, n2 = (m2 ? s2.height : s2.bottom - l2.top) - 1, o2 = m2 ? -1 : s2.left - l2.left, r2 = s2.width + "px"), !u2) { + let t3 = function() { + for (var t4 = 0, i3 = e2.appendTarget.parentNode; i3; ) + t4 += i3.scrollTop || 0, i3 = i3.parentNode; + return t4; + }(); + a2 += t3, n2 += t3; + } + a2 = Math.floor(a2), n2 = Math.ceil(n2), h2 = ((d2 = e2.placeAbove ?? T2 - s2.bottom < t2) ? a2 : n2) + v2, g2 = `left: ${o2 + (c2 && s2.width || 0) + window.pageXOffset}px;`, p2.style.cssText = `${g2}; top: ${h2}px; min-width: ${r2}; max-width: ${r2}`, p2.setAttribute("placement", d2 ? "top" : "bottom"), p2.setAttribute("position", w2); + } + } + } }); + const N = "@yaireo/tagify/"; + var M, I = { empty: "empty", exceed: "number of tags exceeded", pattern: "pattern mismatch", duplicate: "already exists", notAllowed: "not allowed" }, E = { wrapper: (t2, e2) => ` + + ​ + `, tag(t2, e2) { + let i2 = e2.settings; + return ` + +
+ ${t2[i2.tagTextProp] || t2.value} +
+
`; + }, dropdown(t2) { + var e2 = t2.dropdown; + return `
+
+
`; + }, dropdownContent(t2) { + var e2 = this.settings.templates, i2 = this.state.dropdown.suggestions; + return ` + ${e2.dropdownHeader.call(this, i2)} + ${t2} + ${e2.dropdownFooter.call(this, i2)} + `; + }, dropdownItem(t2) { + return `
${t2.mappedValue || t2.value}
`; + }, dropdownHeader(t2) { + return `
`; + }, dropdownFooter(t2) { + var e2 = t2.length - this.settings.dropdown.maxItems; + return e2 > 0 ? `` : ""; + }, dropdownItemNoMatch: null }; + var S = { customBinding() { + this.customEventsList.forEach((t2) => { + this.on(t2, this.settings.callbacks[t2]); + }); + }, binding() { + let t2 = !(arguments.length > 0 && void 0 !== arguments[0]) || arguments[0]; + var e2, i2 = this.settings, s2 = this.events.callbacks, a2 = t2 ? "addEventListener" : "removeEventListener"; + if (!this.state.mainEvents || !t2) { + for (var n2 in this.state.mainEvents = t2, t2 && !this.listeners.main && (this.events.bindGlobal.call(this), this.settings.isJQueryPlugin && jQuery(this.DOM.originalInput).on("tagify.removeAllTags", this.removeAllTags.bind(this))), e2 = this.listeners.main = this.listeners.main || { focus: ["input", s2.onFocusBlur.bind(this)], keydown: ["input", s2.onKeydown.bind(this)], click: ["scope", s2.onClickScope.bind(this)], dblclick: "select" != i2.mode && ["scope", s2.onDoubleClickScope.bind(this)], paste: ["input", s2.onPaste.bind(this)], drop: ["input", s2.onDrop.bind(this)], compositionstart: ["input", s2.onCompositionStart.bind(this)], compositionend: ["input", s2.onCompositionEnd.bind(this)] }) + e2[n2] && this.DOM[e2[n2][0]][a2](n2, e2[n2][1]); + clearInterval(this.listeners.main.originalInputValueObserverInterval), this.listeners.main.originalInputValueObserverInterval = setInterval(s2.observeOriginalInputValue.bind(this), 500); + var o2 = this.listeners.main.inputMutationObserver || new MutationObserver(s2.onInputDOMChange.bind(this)); + o2.disconnect(), "mix" == i2.mode && o2.observe(this.DOM.input, { childList: true }); + } + }, bindGlobal(t2) { + var e2, i2 = this.events.callbacks, s2 = t2 ? "removeEventListener" : "addEventListener"; + if (this.listeners && (t2 || !this.listeners.global)) + for (e2 of (this.listeners.global = this.listeners.global || [{ type: this.isIE ? "keydown" : "input", target: this.DOM.input, cb: i2[this.isIE ? "onInputIE" : "onInput"].bind(this) }, { type: "keydown", target: window, cb: i2.onWindowKeyDown.bind(this) }, { type: "blur", target: this.DOM.input, cb: i2.onFocusBlur.bind(this) }, { type: "click", target: document, cb: i2.onClickAnywhere.bind(this), useCapture: true }], this.listeners.global)) + e2.target[s2](e2.type, e2.cb, !!e2.useCapture); + }, unbindGlobal() { + this.events.bindGlobal.call(this, true); + }, callbacks: { onFocusBlur(t2) { + var _a, _b; + var e2 = this.settings, i2 = t2.target ? this.trim(t2.target.textContent) : "", s2 = (_b = (_a = this.value) == null ? void 0 : _a[0]) == null ? void 0 : _b[e2.tagTextProp], a2 = t2.type, n2 = e2.dropdown.enabled >= 0, o2 = { relatedTarget: t2.relatedTarget }, r2 = this.state.actions.selectOption && (n2 || !e2.dropdown.closeOnSelect), l2 = this.state.actions.addNew && n2; + if ("blur" == a2) { + if (t2.relatedTarget === this.DOM.scope) + return this.dropdown.hide(), void this.DOM.input.focus(); + this.postUpdate(), e2.onChangeAfterBlur && this.triggerChangeEvent(); + } + if (!r2 && !l2) + if (this.state.hasFocus = "focus" == a2 && +/* @__PURE__ */ new Date(), this.toggleFocusClass(this.state.hasFocus), "mix" != e2.mode) { + if ("focus" == a2) + return this.trigger("focus", o2), void (0 !== e2.dropdown.enabled && e2.userInput || this.state.dropdown.visible || this.dropdown.show(this.value.length ? "" : void 0)); + "blur" == a2 && (this.trigger("blur", o2), this.loading(false), "select" == e2.mode && s2 === i2 && (i2 = ""), i2 && !this.state.actions.selectOption && e2.addTagOnBlur && e2.addTagOn.includes("blur") && this.addTags(i2, true)), this.DOM.input.removeAttribute("style"), this.dropdown.hide(); + } else + "focus" == a2 ? this.trigger("focus", o2) : "blur" == t2.type && (this.trigger("blur", o2), this.loading(false), this.dropdown.hide(), this.state.dropdown.visible = void 0, this.setStateSelection()); + }, onCompositionStart(t2) { + this.state.composing = true; + }, onCompositionEnd(t2) { + this.state.composing = false; + }, onWindowKeyDown(t2) { + var e2, i2 = document.activeElement, s2 = v.call(this, i2) && this.DOM.scope.contains(document.activeElement), a2 = s2 && i2.hasAttribute("readonly"); + if (s2 && !a2) + switch (e2 = i2.nextElementSibling, t2.key) { + case "Backspace": + this.settings.readonly || (this.removeTags(i2), (e2 || this.DOM.input).focus()); + break; + case "Enter": + setTimeout(this.editTag.bind(this), 0, i2); + } + }, onKeydown(t2) { + var e2 = this.settings; + if (!this.state.composing && e2.userInput) { + "select" == e2.mode && e2.enforceWhitelist && this.value.length && "Tab" != t2.key && t2.preventDefault(); + var i2 = this.trim(t2.target.textContent); + this.trigger("keydown", { event: t2 }), e2.hooks.beforeKeyDown(t2, { tagify: this }).then((s2) => { + if ("mix" == e2.mode) { + switch (t2.key) { + case "Left": + case "ArrowLeft": + this.state.actions.ArrowLeft = true; + break; + case "Delete": + case "Backspace": + if (this.state.editing) + return; + var a2 = document.getSelection(), n2 = "Delete" == t2.key && a2.anchorOffset == (a2.anchorNode.length || 0), r2 = a2.anchorNode.previousSibling, d2 = 1 == a2.anchorNode.nodeType || !a2.anchorOffset && r2 && 1 == r2.nodeType && a2.anchorNode.previousSibling; + o(this.DOM.input.innerHTML); + var h2, g2, p2, c2 = this.getTagElms(), m2 = 1 === a2.anchorNode.length && a2.anchorNode.nodeValue == String.fromCharCode(8203); + if ("edit" == e2.backspace && d2) + return h2 = 1 == a2.anchorNode.nodeType ? null : a2.anchorNode.previousElementSibling, setTimeout(this.editTag.bind(this), 0, h2), void t2.preventDefault(); + if (u() && d2 instanceof Element) + return p2 = l(d2), d2.hasAttribute("readonly") || d2.remove(), this.DOM.input.focus(), void setTimeout(() => { + w(p2), this.DOM.input.click(); + }); + if ("BR" == a2.anchorNode.nodeName) + return; + if ((n2 || d2) && 1 == a2.anchorNode.nodeType ? g2 = 0 == a2.anchorOffset ? n2 ? c2[0] : null : c2[Math.min(c2.length, a2.anchorOffset) - 1] : n2 ? g2 = a2.anchorNode.nextElementSibling : d2 instanceof Element && (g2 = d2), 3 == a2.anchorNode.nodeType && !a2.anchorNode.nodeValue && a2.anchorNode.previousElementSibling && t2.preventDefault(), (d2 || n2) && !e2.backspace) + return void t2.preventDefault(); + if ("Range" != a2.type && !a2.anchorOffset && a2.anchorNode == this.DOM.input && "Delete" != t2.key) + return void t2.preventDefault(); + if ("Range" != a2.type && g2 && g2.hasAttribute("readonly")) + return void w(l(g2)); + "Delete" == t2.key && m2 && T(a2.anchorNode.nextSibling) && this.removeTags(a2.anchorNode.nextSibling), clearTimeout(M), M = setTimeout(() => { + var t3 = document.getSelection(); + o(this.DOM.input.innerHTML), !n2 && t3.anchorNode.previousSibling, this.value = [].map.call(c2, (t4, e3) => { + var i3 = T(t4); + if (t4.parentNode || i3.readonly) + return i3; + this.trigger("remove", { tag: t4, index: e3, data: i3 }); + }).filter((t4) => t4); + }, 20); + } + return true; + } + var v2 = "manual" == e2.dropdown.position; + switch (t2.key) { + case "Backspace": + "select" == e2.mode && e2.enforceWhitelist && this.value.length ? this.removeTags() : this.state.dropdown.visible && "manual" != e2.dropdown.position || "" != t2.target.textContent && 8203 != i2.charCodeAt(0) || (true === e2.backspace ? this.removeTags() : "edit" == e2.backspace && setTimeout(this.editTag.bind(this), 0)); + break; + case "Esc": + case "Escape": + if (this.state.dropdown.visible) + return; + t2.target.blur(); + break; + case "Down": + case "ArrowDown": + this.state.dropdown.visible || this.dropdown.show(); + break; + case "ArrowRight": { + let t3 = this.state.inputSuggestion || this.state.ddItemData; + if (t3 && e2.autoComplete.rightKey) + return void this.addTags([t3], true); + break; + } + case "Tab": { + let s3 = "select" == e2.mode; + if (!i2 || s3) + return true; + t2.preventDefault(); + } + case "Enter": + if (this.state.dropdown.visible && !v2) + return; + t2.preventDefault(), setTimeout(() => { + this.state.dropdown.visible && !v2 || this.state.actions.selectOption || !e2.addTagOn.includes(t2.key.toLowerCase()) || this.addTags(i2, true); + }); + } + }).catch((t3) => t3); + } + }, onInput(t2) { + this.postUpdate(); + var e2 = this.settings; + if ("mix" == e2.mode) + return this.events.callbacks.onMixTagsInput.call(this, t2); + var i2 = this.input.normalize.call(this, void 0, { trim: false }), s2 = i2.length >= e2.dropdown.enabled, a2 = { value: i2, inputElm: this.DOM.input }, n2 = this.validateTag({ value: i2 }); + "select" == e2.mode && this.toggleScopeValidation(n2), a2.isValid = n2, this.state.inputText != i2 && (this.input.set.call(this, i2, false), -1 != i2.search(e2.delimiters) ? this.addTags(i2) && this.input.set.call(this) : e2.dropdown.enabled >= 0 && this.dropdown[s2 ? "show" : "hide"](i2), this.trigger("input", a2)); + }, onMixTagsInput(t2) { + var e2, i2, s2, a2, n2, o2, r2, l2, d2 = this.settings, h2 = this.value.length, p2 = this.getTagElms(), c2 = document.createDocumentFragment(), m2 = window.getSelection().getRangeAt(0), v2 = [].map.call(p2, (t3) => T(t3).value); + if ("deleteContentBackward" == t2.inputType && u() && this.events.callbacks.onKeydown.call(this, { target: t2.target, key: "Backspace" }), b(this.getTagElms()), this.value.slice().forEach((t3) => { + t3.readonly && !v2.includes(t3.value) && c2.appendChild(this.createTagElem(t3)); + }), c2.childNodes.length && (m2.insertNode(c2), this.setRangeAtStartEnd(false, c2.lastChild)), p2.length != h2) + return this.value = [].map.call(this.getTagElms(), (t3) => T(t3)), void this.update({ withoutChangeEvent: true }); + if (this.hasMaxTags()) + return true; + if (window.getSelection && (o2 = window.getSelection()).rangeCount > 0 && 3 == o2.anchorNode.nodeType) { + if ((m2 = o2.getRangeAt(0).cloneRange()).collapse(true), m2.setStart(o2.focusNode, 0), s2 = (e2 = m2.toString().slice(0, m2.endOffset)).split(d2.pattern).length - 1, (i2 = e2.match(d2.pattern)) && (a2 = e2.slice(e2.lastIndexOf(i2[i2.length - 1]))), a2) { + if (this.state.actions.ArrowLeft = false, this.state.tag = { prefix: a2.match(d2.pattern)[0], value: a2.replace(d2.pattern, "") }, this.state.tag.baseOffset = o2.baseOffset - this.state.tag.value.length, l2 = this.state.tag.value.match(d2.delimiters)) + return this.state.tag.value = this.state.tag.value.replace(d2.delimiters, ""), this.state.tag.delimiters = l2[0], this.addTags(this.state.tag.value, d2.dropdown.clearOnSelect), void this.dropdown.hide(); + n2 = this.state.tag.value.length >= d2.dropdown.enabled; + try { + r2 = (r2 = this.state.flaggedTags[this.state.tag.baseOffset]).prefix == this.state.tag.prefix && r2.value[0] == this.state.tag.value[0], this.state.flaggedTags[this.state.tag.baseOffset] && !this.state.tag.value && delete this.state.flaggedTags[this.state.tag.baseOffset]; + } catch (t3) { + } + (r2 || s2 < this.state.mixMode.matchedPatternCount) && (n2 = false); + } else + this.state.flaggedTags = {}; + this.state.mixMode.matchedPatternCount = s2; + } + setTimeout(() => { + this.update({ withoutChangeEvent: true }), this.trigger("input", g({}, this.state.tag, { textContent: this.DOM.input.textContent })), this.state.tag && this.dropdown[n2 ? "show" : "hide"](this.state.tag.value); + }, 10); + }, onInputIE(t2) { + var e2 = this; + setTimeout(function() { + e2.events.callbacks.onInput.call(e2, t2); + }); + }, observeOriginalInputValue() { + this.DOM.originalInput.parentNode || this.destroy(), this.DOM.originalInput.value != this.DOM.originalInput.tagifyValue && this.loadOriginalValues(); + }, onClickAnywhere(t2) { + t2.target == this.DOM.scope || this.DOM.scope.contains(t2.target) || (this.toggleFocusClass(false), this.state.hasFocus = false, !this.settings.userInput && this.dropdown.hide()); + }, onClickScope(t2) { + var i2 = this.settings, s2 = t2.target.closest("." + i2.classNames.tag), a2 = t2.target === this.DOM.scope, n2 = +/* @__PURE__ */ new Date() - this.state.hasFocus; + if (a2 && "select" != i2.mode) + this.DOM.input.focus(); + else { + if (!t2.target.classList.contains(i2.classNames.tagX)) + return s2 && !this.state.editing ? (this.trigger("click", { tag: s2, index: this.getNodeIndex(s2), data: T(s2), event: t2 }), void (1 !== i2.editTags && 1 !== i2.editTags.clicks && "select" != i2.mode || this.events.callbacks.onDoubleClickScope.call(this, t2))) : void (t2.target == this.DOM.input && ("mix" == i2.mode && this.fixFirefoxLastTagNoCaret(), n2 > 500) ? this.state.dropdown.visible ? this.dropdown.hide() : 0 === i2.dropdown.enabled && "mix" != i2.mode && this.dropdown.show(this.value.length ? "" : void 0) : "select" != i2.mode || 0 !== i2.dropdown.enabled || this.state.dropdown.visible || (this.events.callbacks.onDoubleClickScope.call(this, e(e({}, t2), {}, { target: this.getTagElms()[0] })), !i2.userInput && this.dropdown.show())); + this.removeTags(t2.target.parentNode); + } + }, onPaste(t2) { + t2.preventDefault(); + var e2, i2, s2, a2 = this.settings; + if ("select" == a2.mode && a2.enforceWhitelist || !a2.userInput) + return false; + a2.readonly || (i2 = t2.clipboardData || window.clipboardData, s2 = i2.getData("Text"), a2.hooks.beforePaste(t2, { tagify: this, pastedText: s2, clipboardData: i2 }).then((a3) => { + void 0 === a3 && (a3 = s2), a3 && (this.injectAtCaret(a3, window.getSelection().getRangeAt(0)), "mix" == this.settings.mode ? this.events.callbacks.onMixTagsInput.call(this, t2) : this.settings.pasteAsTags ? e2 = this.addTags(this.state.inputText + a3, true) : (this.state.inputText = a3, this.dropdown.show(a3))), this.trigger("paste", { event: t2, pastedText: s2, clipboardData: i2, tagsElems: e2 }); + }).catch((t3) => t3)); + }, onDrop(t2) { + t2.preventDefault(); + }, onEditTagInput(t2, e2) { + var i2 = t2.closest("." + this.settings.classNames.tag), s2 = this.getNodeIndex(i2), a2 = T(i2), n2 = this.input.normalize.call(this, t2), o2 = { [this.settings.tagTextProp]: n2, __tagId: a2.__tagId }, r2 = this.validateTag(o2); + this.editTagChangeDetected(g(a2, o2)) || true !== t2.originalIsValid || (r2 = true), i2.classList.toggle(this.settings.classNames.tagInvalid, true !== r2), a2.__isValid = r2, i2.title = true === r2 ? a2.title || a2.value : r2, n2.length >= this.settings.dropdown.enabled && (this.state.editing && (this.state.editing.value = n2), this.dropdown.show(n2)), this.trigger("edit:input", { tag: i2, index: s2, data: g({}, this.value[s2], { newValue: n2 }), event: e2 }); + }, onEditTagPaste(t2, e2) { + var i2 = (e2.clipboardData || window.clipboardData).getData("Text"); + e2.preventDefault(); + var s2 = f(i2); + this.setRangeAtStartEnd(false, s2); + }, onEditTagClick(t2, e2) { + this.events.callbacks.onClickScope.call(this, e2); + }, onEditTagFocus(t2) { + this.state.editing = { scope: t2, input: t2.querySelector("[contenteditable]") }; + }, onEditTagBlur(t2, e2) { + if (v.call(this, e2.relatedTarget) && e2.relatedTarget.contains(e2.target)) + this.dropdown.hide(); + else if (this.state.editing && (this.state.hasFocus || this.toggleFocusClass(), this.DOM.scope.contains(t2))) { + var i2, s2, a2 = this.settings, n2 = t2.closest("." + a2.classNames.tag), o2 = T(n2), r2 = this.input.normalize.call(this, t2), l2 = { [a2.tagTextProp]: r2, __tagId: o2.__tagId }, d2 = o2.__originalData, h2 = this.editTagChangeDetected(g(o2, l2)), p2 = this.validateTag(l2); + if (r2) + if (h2) { + if (i2 = this.hasMaxTags(), s2 = g({}, d2, { [a2.tagTextProp]: this.trim(r2), __isValid: p2 }), a2.transformTag.call(this, s2, d2), true !== (p2 = (!i2 || true === d2.__isValid) && this.validateTag(s2))) { + if (this.trigger("invalid", { data: s2, tag: n2, message: p2 }), a2.editTags.keepInvalid) + return; + a2.keepInvalidTags ? s2.__isValid = p2 : s2 = d2; + } else + a2.keepInvalidTags && (delete s2.title, delete s2["aria-invalid"], delete s2.class); + this.onEditTagDone(n2, s2); + } else + this.onEditTagDone(n2, d2); + else + this.onEditTagDone(n2); + } + }, onEditTagkeydown(t2, e2) { + if (!this.state.composing) + switch (this.trigger("edit:keydown", { event: t2 }), t2.key) { + case "Esc": + case "Escape": + this.state.editing = false, !!e2.__tagifyTagData.__originalData.value ? e2.parentNode.replaceChild(e2.__tagifyTagData.__originalHTML, e2) : e2.remove(); + break; + case "Enter": + case "Tab": + t2.preventDefault(); + setTimeout(() => t2.target.blur(), 0); + } + }, onDoubleClickScope(t2) { + var e2, i2, s2 = t2.target.closest("." + this.settings.classNames.tag), a2 = T(s2), n2 = this.settings; + s2 && false !== a2.editable && (e2 = s2.classList.contains(this.settings.classNames.tagEditing), i2 = s2.hasAttribute("readonly"), n2.readonly || e2 || i2 || !this.settings.editTags || !n2.userInput || this.editTag(s2), this.toggleFocusClass(true), "select" != n2.mode && this.trigger("dblclick", { tag: s2, index: this.getNodeIndex(s2), data: T(s2) })); + }, onInputDOMChange(t2) { + t2.forEach((t3) => { + t3.addedNodes.forEach((t4) => { + var _a; + if ("

" == t4.outerHTML) + t4.replaceWith(document.createElement("br")); + else if (1 == t4.nodeType && t4.querySelector(this.settings.classNames.tagSelector)) { + let e3 = document.createTextNode(""); + 3 == t4.childNodes[0].nodeType && "BR" != t4.previousSibling.nodeName && (e3 = document.createTextNode("\n")), t4.replaceWith(e3, ...[...t4.childNodes].slice(0, -1)), w(e3); + } else if (v.call(this, t4)) + if (3 != ((_a = t4.previousSibling) == null ? void 0 : _a.nodeType) || t4.previousSibling.textContent || t4.previousSibling.remove(), t4.previousSibling && "BR" == t4.previousSibling.nodeName) { + t4.previousSibling.replaceWith("\n​"); + let e3 = t4.nextSibling, i2 = ""; + for (; e3; ) + i2 += e3.textContent, e3 = e3.nextSibling; + i2.trim() && w(t4.previousSibling); + } else + t4.previousSibling && !T(t4.previousSibling) || t4.before("​"); + }), t3.removedNodes.forEach((t4) => { + t4 && "BR" == t4.nodeName && v.call(this, e2) && (this.removeTags(e2), this.fixFirefoxLastTagNoCaret()); + }); + }); + var e2 = this.DOM.input.lastChild; + e2 && "" == e2.nodeValue && e2.remove(), e2 && "BR" == e2.nodeName || this.DOM.input.appendChild(document.createElement("br")); + } } }; + function _(t2, e2) { + if (!t2) { + console.warn("Tagify:", "input element not found", t2); + const e3 = new Proxy(this, { get: () => () => e3 }); + return e3; + } + if (t2.__tagify) + return console.warn("Tagify: ", "input element is already Tagified - Same instance is returned.", t2), t2.__tagify; + var i2; + g(this, function(t3) { + var e3 = document.createTextNode(""); + function i3(t4, i4, s2) { + s2 && i4.split(/\s+/g).forEach((i5) => e3[t4 + "EventListener"].call(e3, i5, s2)); + } + return { off(t4, e4) { + return i3("remove", t4, e4), this; + }, on(t4, e4) { + return e4 && "function" == typeof e4 && i3("add", t4, e4), this; + }, trigger(i4, s2, a2) { + var n2; + if (a2 = a2 || { cloneData: true }, i4) + if (t3.settings.isJQueryPlugin) + "remove" == i4 && (i4 = "removeTag"), jQuery(t3.DOM.originalInput).triggerHandler(i4, [s2]); + else { + try { + var o2 = "object" == typeof s2 ? s2 : { value: s2 }; + if ((o2 = a2.cloneData ? g({}, o2) : o2).tagify = this, s2.event && (o2.event = this.cloneEvent(s2.event)), s2 instanceof Object) + for (var r2 in s2) + s2[r2] instanceof HTMLElement && (o2[r2] = s2[r2]); + n2 = new CustomEvent(i4, { detail: o2 }); + } catch (t4) { + console.warn(t4); + } + e3.dispatchEvent(n2); + } + } }; + }(this)), this.isFirefox = /firefox|fxios/i.test(navigator.userAgent) && !/seamonkey/i.test(navigator.userAgent), this.isIE = window.document.documentMode, e2 = e2 || {}, this.getPersistedData = (i2 = e2.id, (t3) => { + let e3, s2 = "/" + t3; + if (1 == localStorage.getItem(N + i2 + "/v", 1)) + try { + e3 = JSON.parse(localStorage[N + i2 + s2]); + } catch (t4) { + } + return e3; + }), this.setPersistedData = ((t3) => t3 ? (localStorage.setItem(N + t3 + "/v", 1), (e3, i3) => { + let s2 = "/" + i3, a2 = JSON.stringify(e3); + e3 && i3 && (localStorage.setItem(N + t3 + s2, a2), dispatchEvent(new Event("storage"))); + }) : () => { + })(e2.id), this.clearPersistedData = /* @__PURE__ */ ((t3) => (e3) => { + const i3 = N + "/" + t3 + "/"; + if (e3) + localStorage.removeItem(i3 + e3); + else + for (let t4 in localStorage) + t4.includes(i3) && localStorage.removeItem(t4); + })(e2.id), this.applySettings(t2, e2), this.state = { inputText: "", editing: false, composing: false, actions: {}, mixMode: {}, dropdown: {}, flaggedTags: {} }, this.value = [], this.listeners = {}, this.DOM = {}, this.build(t2), O.call(this), this.getCSSVars(), this.loadOriginalValues(), this.events.customBinding.call(this), this.events.binding.call(this), t2.autofocus && this.DOM.input.focus(), t2.__tagify = this; + } + return _.prototype = { _dropdown: D, placeCaretAfterNode: w, getSetTagData: T, helpers: { sameStr: s, removeCollectionProp: a, omit: n, isObject: h, parseHTML: r, escapeHTML: d, extend: g, concatWithoutDups: p, getUID: m, isNodeTag: v }, customEventsList: ["change", "add", "remove", "invalid", "input", "paste", "click", "keydown", "focus", "blur", "edit:input", "edit:beforeUpdate", "edit:updated", "edit:start", "edit:keydown", "dropdown:show", "dropdown:hide", "dropdown:select", "dropdown:updated", "dropdown:noMatch", "dropdown:scroll"], dataProps: ["__isValid", "__removed", "__originalData", "__originalHTML", "__tagId"], trim(t2) { + return this.settings.trim && t2 && "string" == typeof t2 ? t2.trim() : t2; + }, parseHTML: r, templates: E, parseTemplate(t2, e2) { + return r((t2 = this.settings.templates[t2] || t2).apply(this, e2)); + }, set whitelist(t2) { + const e2 = t2 && Array.isArray(t2); + this.settings.whitelist = e2 ? t2 : [], this.setPersistedData(e2 ? t2 : [], "whitelist"); + }, get whitelist() { + return this.settings.whitelist; + }, generateClassSelectors(t2) { + for (let e2 in t2) { + let i2 = e2; + Object.defineProperty(t2, i2 + "Selector", { get() { + return "." + this[i2].split(" ")[0]; + } }); + } + }, applySettings(t2, i2) { + var _a, _b; + y.templates = this.templates; + var s2 = g({}, y, "mix" == i2.mode ? { dropdown: { position: "text" } } : {}), a2 = this.settings = g({}, s2, i2); + if (a2.disabled = t2.hasAttribute("disabled"), a2.readonly = a2.readonly || t2.hasAttribute("readonly"), a2.placeholder = d(t2.getAttribute("placeholder") || a2.placeholder || ""), a2.required = t2.hasAttribute("required"), this.generateClassSelectors(a2.classNames), void 0 === a2.dropdown.includeSelectedTags && (a2.dropdown.includeSelectedTags = a2.duplicates), this.isIE && (a2.autoComplete = false), ["whitelist", "blacklist"].forEach((e2) => { + var i3 = t2.getAttribute("data-" + e2); + i3 && (i3 = i3.split(a2.delimiters)) instanceof Array && (a2[e2] = i3); + }), "autoComplete" in i2 && !h(i2.autoComplete) && (a2.autoComplete = y.autoComplete, a2.autoComplete.enabled = i2.autoComplete), "mix" == a2.mode && (a2.pattern = a2.pattern || /@/, a2.autoComplete.rightKey = true, a2.delimiters = i2.delimiters || null, a2.tagTextProp && !a2.dropdown.searchKeys.includes(a2.tagTextProp) && a2.dropdown.searchKeys.push(a2.tagTextProp)), t2.pattern) + try { + a2.pattern = new RegExp(t2.pattern); + } catch (t3) { + } + if (a2.delimiters) { + a2._delimiters = a2.delimiters; + try { + a2.delimiters = new RegExp(this.settings.delimiters, "g"); + } catch (t3) { + } + } + a2.disabled && (a2.userInput = false), this.TEXTS = e(e({}, I), a2.texts || {}), ("select" != a2.mode || ((_a = i2.dropdown) == null ? void 0 : _a.enabled)) && a2.userInput || (a2.dropdown.enabled = 0), a2.dropdown.appendTarget = ((_b = i2.dropdown) == null ? void 0 : _b.appendTarget) || document.body; + let n2 = this.getPersistedData("whitelist"); + Array.isArray(n2) && (this.whitelist = Array.isArray(a2.whitelist) ? p(a2.whitelist, n2) : n2); + }, getAttributes(t2) { + var e2, i2 = this.getCustomAttributes(t2), s2 = ""; + for (e2 in i2) + s2 += " " + e2 + (void 0 !== t2[e2] ? `="${i2[e2]}"` : ""); + return s2; + }, getCustomAttributes(t2) { + if (!h(t2)) + return ""; + var e2, i2 = {}; + for (e2 in t2) + "__" != e2.slice(0, 2) && "class" != e2 && t2.hasOwnProperty(e2) && void 0 !== t2[e2] && (i2[e2] = d(t2[e2])); + return i2; + }, setStateSelection() { + var t2 = window.getSelection(), e2 = { anchorOffset: t2.anchorOffset, anchorNode: t2.anchorNode, range: t2.getRangeAt && t2.rangeCount && t2.getRangeAt(0) }; + return this.state.selection = e2, e2; + }, getCSSVars() { + var t2 = getComputedStyle(this.DOM.scope, null); + var e2; + this.CSSVars = { tagHideTransition: ((t3) => { + let e3 = t3.value; + return "s" == t3.unit ? 1e3 * e3 : e3; + })(function(t3) { + if (!t3) + return {}; + var e3 = (t3 = t3.trim().split(" ")[0]).split(/\d+/g).filter((t4) => t4).pop().trim(); + return { value: +t3.split(e3).filter((t4) => t4)[0].trim(), unit: e3 }; + }((e2 = "tag-hide-transition", t2.getPropertyValue("--" + e2)))) }; + }, build(t2) { + var e2 = this.DOM, i2 = t2.closest("label"); + this.settings.mixMode.integrated ? (e2.originalInput = null, e2.scope = t2, e2.input = t2) : (e2.originalInput = t2, e2.originalInput_tabIndex = t2.tabIndex, e2.scope = this.parseTemplate("wrapper", [t2, this.settings]), e2.input = e2.scope.querySelector(this.settings.classNames.inputSelector), t2.parentNode.insertBefore(e2.scope, t2), t2.tabIndex = -1), i2 && i2.setAttribute("for", ""); + }, destroy() { + this.events.unbindGlobal.call(this), this.DOM.scope.parentNode.removeChild(this.DOM.scope), this.DOM.originalInput.tabIndex = this.DOM.originalInput_tabIndex, delete this.DOM.originalInput.__tagify, this.dropdown.hide(true), clearTimeout(this.dropdownHide__bindEventsTimeout), clearInterval(this.listeners.main.originalInputValueObserverInterval); + }, loadOriginalValues(t2) { + var e2, i2 = this.settings; + if (this.state.blockChangeEvent = true, void 0 === t2) { + const e3 = this.getPersistedData("value"); + t2 = e3 && !this.DOM.originalInput.value ? e3 : i2.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value; + } + if (this.removeAllTags(), t2) + if ("mix" == i2.mode) + this.parseMixTags(t2), (e2 = this.DOM.input.lastChild) && "BR" == e2.tagName || this.DOM.input.insertAdjacentHTML("beforeend", "
"); + else { + try { + JSON.parse(t2) instanceof Array && (t2 = JSON.parse(t2)); + } catch (t3) { + } + this.addTags(t2, true).forEach((t3) => t3 && t3.classList.add(i2.classNames.tagNoAnimation)); + } + else + this.postUpdate(); + this.state.lastOriginalValueReported = i2.mixMode.integrated ? "" : this.DOM.originalInput.value; + }, cloneEvent(t2) { + var e2 = {}; + for (var i2 in t2) + "path" != i2 && (e2[i2] = t2[i2]); + return e2; + }, loading(t2) { + return this.state.isLoading = t2, this.DOM.scope.classList[t2 ? "add" : "remove"](this.settings.classNames.scopeLoading), this; + }, tagLoading(t2, e2) { + return t2 && t2.classList[e2 ? "add" : "remove"](this.settings.classNames.tagLoading), this; + }, toggleClass(t2, e2) { + "string" == typeof t2 && this.DOM.scope.classList.toggle(t2, e2); + }, toggleScopeValidation(t2) { + var e2 = true === t2 || void 0 === t2; + !this.settings.required && t2 && t2 === this.TEXTS.empty && (e2 = true), this.toggleClass(this.settings.classNames.tagInvalid, !e2), this.DOM.scope.title = e2 ? "" : t2; + }, toggleFocusClass(t2) { + this.toggleClass(this.settings.classNames.focus, !!t2); + }, triggerChangeEvent: function() { + if (!this.settings.mixMode.integrated) { + var t2 = this.DOM.originalInput, e2 = this.state.lastOriginalValueReported !== t2.value, i2 = new CustomEvent("change", { bubbles: true }); + e2 && (this.state.lastOriginalValueReported = t2.value, i2.simulated = true, t2._valueTracker && t2._valueTracker.setValue(Math.random()), t2.dispatchEvent(i2), this.trigger("change", this.state.lastOriginalValueReported), t2.value = this.state.lastOriginalValueReported); + } + }, events: S, fixFirefoxLastTagNoCaret() { + }, setRangeAtStartEnd(t2, e2) { + if (e2) { + t2 = "number" == typeof t2 ? t2 : !!t2, e2 = e2.lastChild || e2; + var i2 = document.getSelection(); + if (i2.focusNode instanceof Element && !this.DOM.input.contains(i2.focusNode)) + return true; + try { + i2.rangeCount >= 1 && ["Start", "End"].forEach((s2) => i2.getRangeAt(0)["set" + s2](e2, t2 || e2.length)); + } catch (t3) { + console.warn("Tagify: ", t3); + } + } + }, insertAfterTag(t2, e2) { + if (e2 = e2 || this.settings.mixMode.insertAfterTag, t2 && t2.parentNode && e2) + return e2 = "string" == typeof e2 ? document.createTextNode(e2) : e2, t2.parentNode.insertBefore(e2, t2.nextSibling), e2; + }, editTagChangeDetected(t2) { + var e2 = t2.__originalData; + for (var i2 in e2) + if (!this.dataProps.includes(i2) && t2[i2] != e2[i2]) + return true; + return false; + }, getTagTextNode(t2) { + return t2.querySelector(this.settings.classNames.tagTextSelector); + }, setTagTextNode(t2, e2) { + this.getTagTextNode(t2).innerHTML = d(e2); + }, editTag(t2, e2) { + t2 = t2 || this.getLastTag(), e2 = e2 || {}, this.dropdown.hide(); + var i2 = this.settings, s2 = this.getTagTextNode(t2), a2 = this.getNodeIndex(t2), n2 = T(t2), o2 = this.events.callbacks, r2 = true; + if (s2) { + if (!(n2 instanceof Object && "editable" in n2) || n2.editable) + return n2 = T(t2, { __originalData: g({}, n2), __originalHTML: t2.cloneNode(true) }), T(n2.__originalHTML, n2.__originalData), s2.setAttribute("contenteditable", true), t2.classList.add(i2.classNames.tagEditing), s2.addEventListener("click", o2.onEditTagClick.bind(this, t2)), s2.addEventListener("focus", o2.onEditTagFocus.bind(this, t2)), s2.addEventListener("blur", o2.onEditTagBlur.bind(this, this.getTagTextNode(t2))), s2.addEventListener("input", o2.onEditTagInput.bind(this, s2)), s2.addEventListener("paste", o2.onEditTagPaste.bind(this, s2)), s2.addEventListener("keydown", (e3) => o2.onEditTagkeydown.call(this, e3, t2)), s2.addEventListener("compositionstart", o2.onCompositionStart.bind(this)), s2.addEventListener("compositionend", o2.onCompositionEnd.bind(this)), e2.skipValidation || (r2 = this.editTagToggleValidity(t2)), s2.originalIsValid = r2, this.trigger("edit:start", { tag: t2, index: a2, data: n2, isValid: r2 }), s2.focus(), this.setRangeAtStartEnd(false, s2), 0 === i2.dropdown.enabled && this.dropdown.show(), this.state.hasFocus = true, this; + } else + console.warn("Cannot find element in Tag template: .", i2.classNames.tagTextSelector); + }, editTagToggleValidity(t2, e2) { + var i2; + if (e2 = e2 || T(t2)) + return (i2 = !("__isValid" in e2) || true === e2.__isValid) || this.removeTagsFromValue(t2), this.update(), t2.classList.toggle(this.settings.classNames.tagNotAllowed, !i2), e2.__isValid = i2, e2.__isValid; + console.warn("tag has no data: ", t2, e2); + }, onEditTagDone(t2, e2) { + var _a; + t2 = t2 || this.state.editing.scope, e2 = e2 || {}; + var i2, s2 = { tag: t2, index: this.getNodeIndex(t2), previousData: T(t2), data: e2 }, a2 = this.settings; + this.trigger("edit:beforeUpdate", s2, { cloneData: false }), this.state.editing = false, delete e2.__originalData, delete e2.__originalHTML, t2 && ((i2 = e2[a2.tagTextProp]) ? (_a = i2.trim) == null ? void 0 : _a.call(i2) : a2.tagTextProp in e2 ? void 0 : e2.value) ? (t2 = this.replaceTag(t2, e2), this.editTagToggleValidity(t2, e2), a2.a11y.focusableTags ? t2.focus() : w(t2)) : t2 && this.removeTags(t2), this.trigger("edit:updated", s2), this.dropdown.hide(), this.settings.keepInvalidTags && this.reCheckInvalidTags(); + }, replaceTag(t2, e2) { + e2 && "" !== e2.value && void 0 !== e2.value || (e2 = t2.__tagifyTagData), e2.__isValid && 1 != e2.__isValid && g(e2, this.getInvalidTagAttrs(e2, e2.__isValid)); + var i2 = this.createTagElem(e2); + return t2.parentNode.replaceChild(i2, t2), this.updateValueByDOMTags(), i2; + }, updateValueByDOMTags() { + this.value.length = 0, [].forEach.call(this.getTagElms(), (t2) => { + t2.classList.contains(this.settings.classNames.tagNotAllowed.split(" ")[0]) || this.value.push(T(t2)); + }), this.update(); + }, injectAtCaret(t2, e2) { + var _a; + if (!(e2 = e2 || ((_a = this.state.selection) == null ? void 0 : _a.range)) && t2) + return this.appendMixTags(t2), this; + let i2 = f(t2, e2); + return this.setRangeAtStartEnd(false, i2), this.updateValueByDOMTags(), this.update(), this; + }, input: { set() { + let t2 = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "", e2 = !(arguments.length > 1 && void 0 !== arguments[1]) || arguments[1]; + var i2 = this.settings.dropdown.closeOnSelect; + this.state.inputText = t2, e2 && (this.DOM.input.innerHTML = d("" + t2)), !t2 && i2 && this.dropdown.hide.bind(this), this.input.autocomplete.suggest.call(this), this.input.validate.call(this); + }, raw() { + return this.DOM.input.textContent; + }, validate() { + var t2 = !this.state.inputText || true === this.validateTag({ value: this.state.inputText }); + return this.DOM.input.classList.toggle(this.settings.classNames.inputInvalid, !t2), t2; + }, normalize(t2, e2) { + var i2 = t2 || this.DOM.input, s2 = []; + i2.childNodes.forEach((t3) => 3 == t3.nodeType && s2.push(t3.nodeValue)), s2 = s2.join("\n"); + try { + s2 = s2.replace(/(?:\r\n|\r|\n)/g, this.settings.delimiters.source.charAt(0)); + } catch (t3) { + } + return s2 = s2.replace(/\s/g, " "), (e2 == null ? void 0 : e2.trim) ? this.trim(s2) : s2; + }, autocomplete: { suggest(t2) { + if (this.settings.autoComplete.enabled) { + "object" != typeof (t2 = t2 || { value: "" }) && (t2 = { value: t2 }); + var e2 = this.dropdown.getMappedValue(t2); + if ("number" != typeof e2) { + var i2 = this.state.inputText.toLowerCase(), s2 = e2.substr(0, this.state.inputText.length).toLowerCase(), a2 = e2.substring(this.state.inputText.length); + e2 && this.state.inputText && s2 == i2 ? (this.DOM.input.setAttribute("data-suggest", a2), this.state.inputSuggestion = t2) : (this.DOM.input.removeAttribute("data-suggest"), delete this.state.inputSuggestion); + } + } + }, set(t2) { + var e2 = this.DOM.input.getAttribute("data-suggest"), i2 = t2 || (e2 ? this.state.inputText + e2 : null); + return !!i2 && ("mix" == this.settings.mode ? this.replaceTextWithNode(document.createTextNode(this.state.tag.prefix + i2)) : (this.input.set.call(this, i2), this.setRangeAtStartEnd(false, this.DOM.input)), this.input.autocomplete.suggest.call(this), this.dropdown.hide(), true); + } } }, getTagIdx(t2) { + return this.value.findIndex((e2) => e2.__tagId == (t2 || {}).__tagId); + }, getNodeIndex(t2) { + var e2 = 0; + if (t2) + for (; t2 = t2.previousElementSibling; ) + e2++; + return e2; + }, getTagElms() { + for (var t2 = arguments.length, e2 = new Array(t2), i2 = 0; i2 < t2; i2++) + e2[i2] = arguments[i2]; + var s2 = "." + [...this.settings.classNames.tag.split(" "), ...e2].join("."); + return [].slice.call(this.DOM.scope.querySelectorAll(s2)); + }, getLastTag() { + var t2 = this.DOM.scope.querySelectorAll(`${this.settings.classNames.tagSelector}:not(.${this.settings.classNames.tagHide}):not([readonly])`); + return t2[t2.length - 1]; + }, isTagDuplicate(t2, e2, i2) { + var a2 = 0; + if ("select" == this.settings.mode) + return false; + for (let n2 of this.value) { + s(this.trim("" + t2), n2.value, e2) && i2 != n2.__tagId && a2++; + } + return a2; + }, getTagIndexByValue(t2) { + var e2 = [], i2 = this.settings.dropdown.caseSensitive; + return this.getTagElms().forEach((a2, n2) => { + a2.__tagifyTagData && s(this.trim(a2.__tagifyTagData.value), t2, i2) && e2.push(n2); + }), e2; + }, getTagElmByValue(t2) { + var e2 = this.getTagIndexByValue(t2)[0]; + return this.getTagElms()[e2]; + }, flashTag(t2) { + t2 && (t2.classList.add(this.settings.classNames.tagFlash), setTimeout(() => { + t2.classList.remove(this.settings.classNames.tagFlash); + }, 100)); + }, isTagBlacklisted(t2) { + return t2 = this.trim(t2.toLowerCase()), this.settings.blacklist.filter((e2) => ("" + e2).toLowerCase() == t2).length; + }, isTagWhitelisted(t2) { + return !!this.getWhitelistItem(t2); + }, getWhitelistItem(t2, e2, i2) { + e2 = e2 || "value"; + var a2, n2 = this.settings; + return (i2 = i2 || n2.whitelist).some((i3) => { + var o2 = "string" == typeof i3 ? i3 : i3[e2] || i3.value; + if (s(o2, t2, n2.dropdown.caseSensitive, n2.trim)) + return a2 = "string" == typeof i3 ? { value: i3 } : i3, true; + }), a2 || "value" != e2 || "value" == n2.tagTextProp || (a2 = this.getWhitelistItem(t2, n2.tagTextProp, i2)), a2; + }, validateTag(t2) { + var e2 = this.settings, i2 = "value" in t2 ? "value" : e2.tagTextProp, s2 = this.trim(t2[i2] + ""); + return (t2[i2] + "").trim() ? "mix" != e2.mode && e2.pattern && e2.pattern instanceof RegExp && !e2.pattern.test(s2) ? this.TEXTS.pattern : !e2.duplicates && this.isTagDuplicate(s2, e2.dropdown.caseSensitive, t2.__tagId) ? this.TEXTS.duplicate : this.isTagBlacklisted(s2) || e2.enforceWhitelist && !this.isTagWhitelisted(s2) ? this.TEXTS.notAllowed : !e2.validate || e2.validate(t2) : this.TEXTS.empty; + }, getInvalidTagAttrs(t2, e2) { + return { "aria-invalid": true, class: `${t2.class || ""} ${this.settings.classNames.tagNotAllowed}`.trim(), title: e2 }; + }, hasMaxTags() { + return this.value.length >= this.settings.maxTags && this.TEXTS.exceed; + }, setReadonly(t2, e2) { + var i2 = this.settings; + document.activeElement.blur(), i2[e2 || "readonly"] = t2, this.DOM.scope[(t2 ? "set" : "remove") + "Attribute"](e2 || "readonly", true), this.settings.userInput = true, this.setContentEditable(!t2); + }, setContentEditable(t2) { + this.settings.userInput && (this.DOM.input.contentEditable = t2, this.DOM.input.tabIndex = t2 ? 0 : -1); + }, setDisabled(t2) { + this.setReadonly(t2, "disabled"); + }, normalizeTags(t2) { + var e2 = this.settings, i2 = e2.whitelist, s2 = e2.delimiters, a2 = e2.mode, n2 = e2.tagTextProp, o2 = [], r2 = !!i2 && i2[0] instanceof Object, l2 = Array.isArray(t2), d2 = l2 && t2[0].value, h2 = (t3) => (t3 + "").split(s2).filter((t4) => t4).map((t4) => ({ [n2]: this.trim(t4), value: this.trim(t4) })); + if ("number" == typeof t2 && (t2 = t2.toString()), "string" == typeof t2) { + if (!t2.trim()) + return []; + t2 = h2(t2); + } else + l2 && (t2 = [].concat(...t2.map((t3) => null != t3.value ? t3 : h2(t3)))); + return r2 && !d2 && (t2.forEach((t3) => { + var e3 = o2.map((t4) => t4.value), i3 = this.dropdown.filterListItems.call(this, t3[n2], { exact: true }); + this.settings.duplicates || (i3 = i3.filter((t4) => !e3.includes(t4.value))); + var s3 = i3.length > 1 ? this.getWhitelistItem(t3[n2], n2, i3) : i3[0]; + s3 && s3 instanceof Object ? o2.push(s3) : "mix" != a2 && (null == t3.value && (t3.value = t3[n2]), o2.push(t3)); + }), o2.length && (t2 = o2)), t2; + }, parseMixTags(t2) { + var e2 = this.settings, i2 = e2.mixTagsInterpolator, s2 = e2.duplicates, a2 = e2.transformTag, n2 = e2.enforceWhitelist, o2 = e2.maxTags, r2 = e2.tagTextProp, l2 = []; + t2 = t2.split(i2[0]).map((t3, e3) => { + var d3, h2, g2, p2 = t3.split(i2[1]), c2 = p2[0], u2 = l2.length == o2; + try { + if (c2 == +c2) + throw Error; + h2 = JSON.parse(c2); + } catch (t4) { + h2 = this.normalizeTags(c2)[0] || { value: c2 }; + } + if (a2.call(this, h2), u2 || !(p2.length > 1) || n2 && !this.isTagWhitelisted(h2.value) || !s2 && this.isTagDuplicate(h2.value)) { + if (t3) + return e3 ? i2[0] + t3 : t3; + } else + h2[d3 = h2[r2] ? r2 : "value"] = this.trim(h2[d3]), g2 = this.createTagElem(h2), l2.push(h2), g2.classList.add(this.settings.classNames.tagNoAnimation), p2[0] = g2.outerHTML, this.value.push(h2); + return p2.join(""); + }).join(""), this.DOM.input.innerHTML = t2, this.DOM.input.appendChild(document.createTextNode("")), this.DOM.input.normalize(); + var d2 = this.getTagElms(); + return d2.forEach((t3, e3) => T(t3, l2[e3])), this.update({ withoutChangeEvent: true }), b(d2, this.state.hasFocus), t2; + }, replaceTextWithNode(t2, e2) { + if (this.state.tag || e2) { + e2 = e2 || this.state.tag.prefix + this.state.tag.value; + var i2, s2, a2 = this.state.selection || window.getSelection(), n2 = a2.anchorNode, o2 = this.state.tag.delimiters ? this.state.tag.delimiters.length : 0; + return n2.splitText(a2.anchorOffset - o2), -1 == (i2 = n2.nodeValue.lastIndexOf(e2)) ? true : (s2 = n2.splitText(i2), t2 && n2.parentNode.replaceChild(t2, s2), true); + } + }, prepareNewTagNode(t2, e2) { + e2 = e2 || {}; + var i2 = this.settings, s2 = [], a2 = {}, n2 = Object.assign({}, t2, { value: t2.value + "" }); + if (t2 = Object.assign({}, n2), i2.transformTag.call(this, t2), t2.__isValid = this.hasMaxTags() || this.validateTag(t2), true !== t2.__isValid) { + if (e2.skipInvalid) + return; + if (g(a2, this.getInvalidTagAttrs(t2, t2.__isValid), { __preInvalidData: n2 }), t2.__isValid == this.TEXTS.duplicate && this.flashTag(this.getTagElmByValue(t2.value)), !i2.createInvalidTags) + return void s2.push(t2.value); + } + return "readonly" in t2 && (t2.readonly ? a2["aria-readonly"] = true : delete t2.readonly), { tagElm: this.createTagElem(t2, a2), tagData: t2, aggregatedInvalidInput: s2 }; + }, postProcessNewTagNode(t2, e2) { + var i2 = this.settings, s2 = e2.__isValid; + s2 && true === s2 ? (this.value.push(e2), this.trigger("add", { tag: t2, index: this.value.length - 1, data: e2 })) : (this.trigger("invalid", { data: e2, index: this.value.length, tag: t2, message: s2 }), i2.keepInvalidTags || setTimeout(() => this.removeTags(t2, true), 1e3)), this.dropdown.position(); + }, selectTag(t2, e2) { + if (!this.settings.enforceWhitelist || this.isTagWhitelisted(e2.value)) { + this.state.actions.selectOption && setTimeout(() => this.setRangeAtStartEnd(false, this.DOM.input)); + var i2 = this.getLastTag(); + return i2 ? this.replaceTag(i2, e2) : this.appendTag(t2), this.value[0] = e2, this.update(), this.trigger("add", { tag: t2, data: e2 }), [t2]; + } + }, addEmptyTag(t2) { + var e2 = g({ value: "" }, t2 || {}), i2 = this.createTagElem(e2); + T(i2, e2), this.appendTag(i2), this.editTag(i2, { skipValidation: true }), this.toggleFocusClass(true); + }, addTags(t2, e2, i2) { + var s2 = [], a2 = this.settings, n2 = [], o2 = document.createDocumentFragment(); + if (!t2 || 0 == t2.length) + return s2; + switch (t2 = this.normalizeTags(t2), a2.mode) { + case "mix": + return this.addMixTags(t2); + case "select": + e2 = false, this.removeAllTags(); + } + return this.DOM.input.removeAttribute("style"), t2.forEach((t3) => { + const e3 = this.prepareNewTagNode(t3, { skipInvalid: i2 || a2.skipInvalid }), r2 = e3.tagElm; + if (t3 = e3.tagData, n2 = e3.aggregatedInvalidInput, s2.push(r2), "select" == a2.mode) + return this.selectTag(r2, t3); + o2.appendChild(r2), this.postProcessNewTagNode(r2, t3); + }), this.appendTag(o2), this.update(), t2.length && e2 && (this.input.set.call(this, a2.createInvalidTags ? "" : n2.join(a2._delimiters)), this.setRangeAtStartEnd(false, this.DOM.input)), a2.dropdown.enabled && this.dropdown.refilter(), s2; + }, addMixTags(t2) { + if ((t2 = this.normalizeTags(t2))[0].prefix || this.state.tag) + return this.prefixedTextToTag(t2[0]); + var e2 = document.createDocumentFragment(); + return t2.forEach((t3) => { + const i2 = this.prepareNewTagNode(t3); + e2.appendChild(i2.tagElm), this.postProcessNewTagNode(tagElm, i2.tagData); + }), this.appendMixTags(e2), e2; + }, appendMixTags(t2) { + var e2 = !!this.state.selection; + e2 ? this.injectAtCaret(t2) : (this.DOM.input.focus(), (e2 = this.setStateSelection()).range.setStart(this.DOM.input, e2.range.endOffset), e2.range.setEnd(this.DOM.input, e2.range.endOffset), this.DOM.input.appendChild(t2), this.updateValueByDOMTags(), this.update()); + }, prefixedTextToTag(t2) { + var _a; + var e2, i2, s2 = this.settings, a2 = (_a = this.state.tag) == null ? void 0 : _a.delimiters; + if (t2.prefix = t2.prefix || this.state.tag ? this.state.tag.prefix : (s2.pattern.source || s2.pattern)[0], i2 = this.prepareNewTagNode(t2), e2 = i2.tagElm, this.replaceTextWithNode(e2) || this.DOM.input.appendChild(e2), setTimeout(() => e2.classList.add(this.settings.classNames.tagNoAnimation), 300), this.value.push(i2.tagData), this.update(), !a2) { + var n2 = this.insertAfterTag(e2) || e2; + setTimeout(w, 0, n2); + } + return this.state.tag = null, this.postProcessNewTagNode(e2, i2.tagData), e2; + }, appendTag(t2) { + var e2 = this.DOM, i2 = e2.input; + e2.scope.insertBefore(t2, i2); + }, createTagElem(t2, i2) { + t2.__tagId = m(); + var s2, a2 = g({}, t2, e({ value: d(t2.value + "") }, i2)); + return function(t3) { + for (var e2, i3 = document.createNodeIterator(t3, NodeFilter.SHOW_TEXT, null, false); e2 = i3.nextNode(); ) + e2.textContent.trim() || e2.parentNode.removeChild(e2); + }(s2 = this.parseTemplate("tag", [a2, this])), T(s2, t2), s2; + }, reCheckInvalidTags() { + var t2 = this.settings; + this.getTagElms(t2.classNames.tagNotAllowed).forEach((e2, i2) => { + var s2 = T(e2), a2 = this.hasMaxTags(), n2 = this.validateTag(s2), o2 = true === n2 && !a2; + if ("select" == t2.mode && this.toggleScopeValidation(n2), o2) + return s2 = s2.__preInvalidData ? s2.__preInvalidData : { value: s2.value }, this.replaceTag(e2, s2); + e2.title = a2 || n2; + }); + }, removeTags(t2, e2, i2) { + var s2, a2 = this.settings; + if (t2 = t2 && t2 instanceof HTMLElement ? [t2] : t2 instanceof Array ? t2 : t2 ? [t2] : [this.getLastTag()], s2 = t2.reduce((t3, e3) => { + e3 && "string" == typeof e3 && (e3 = this.getTagElmByValue(e3)); + var i3 = T(e3); + return e3 && i3 && !i3.readonly && t3.push({ node: e3, idx: this.getTagIdx(i3), data: T(e3, { __removed: true }) }), t3; + }, []), i2 = "number" == typeof i2 ? i2 : this.CSSVars.tagHideTransition, "select" == a2.mode && (i2 = 0, this.input.set.call(this)), 1 == s2.length && "select" != a2.mode && s2[0].node.classList.contains(a2.classNames.tagNotAllowed) && (e2 = true), s2.length) + return a2.hooks.beforeRemoveTag(s2, { tagify: this }).then(() => { + function t3(t4) { + t4.node.parentNode && (t4.node.parentNode.removeChild(t4.node), e2 ? a2.keepInvalidTags && this.trigger("remove", { tag: t4.node, index: t4.idx }) : (this.trigger("remove", { tag: t4.node, index: t4.idx, data: t4.data }), this.dropdown.refilter(), this.dropdown.position(), this.DOM.input.normalize(), a2.keepInvalidTags && this.reCheckInvalidTags())); + } + i2 && i2 > 10 && 1 == s2.length ? (function(e3) { + e3.node.style.width = parseFloat(window.getComputedStyle(e3.node).width) + "px", document.body.clientTop, e3.node.classList.add(a2.classNames.tagHide), setTimeout(t3.bind(this), i2, e3); + }).call(this, s2[0]) : s2.forEach(t3.bind(this)), e2 || (this.removeTagsFromValue(s2.map((t4) => t4.node)), this.update(), "select" == a2.mode && this.setContentEditable(true)); + }).catch((t3) => { + }); + }, removeTagsFromDOM() { + [].slice.call(this.getTagElms()).forEach((t2) => t2.parentNode.removeChild(t2)); + }, removeTagsFromValue(t2) { + (t2 = Array.isArray(t2) ? t2 : [t2]).forEach((t3) => { + var e2 = T(t3), i2 = this.getTagIdx(e2); + i2 > -1 && this.value.splice(i2, 1); + }); + }, removeAllTags(t2) { + t2 = t2 || {}, this.value = [], "mix" == this.settings.mode ? this.DOM.input.innerHTML = "" : this.removeTagsFromDOM(), this.dropdown.refilter(), this.dropdown.position(), this.state.dropdown.visible && setTimeout(() => { + this.DOM.input.focus(); + }), "select" == this.settings.mode && (this.input.set.call(this), this.setContentEditable(true)), this.update(t2); + }, postUpdate() { + var _a, _b; + this.state.blockChangeEvent = false; + var t2 = this.settings, e2 = t2.classNames, i2 = "mix" == t2.mode ? t2.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value.trim() : this.value.length + this.input.raw.call(this).length; + this.toggleClass(e2.hasMaxTags, this.value.length >= t2.maxTags), this.toggleClass(e2.hasNoTags, !this.value.length), this.toggleClass(e2.empty, !i2), "select" == t2.mode && this.toggleScopeValidation((_b = (_a = this.value) == null ? void 0 : _a[0]) == null ? void 0 : _b.__isValid); + }, setOriginalInputValue(t2) { + var e2 = this.DOM.originalInput; + this.settings.mixMode.integrated || (e2.value = t2, e2.tagifyValue = e2.value, this.setPersistedData(t2, "value")); + }, update(t2) { + clearTimeout(this.debouncedUpdateTimeout), this.debouncedUpdateTimeout = setTimeout((function() { + var e2 = this.getInputValue(); + this.setOriginalInputValue(e2), this.settings.onChangeAfterBlur && (t2 || {}).withoutChangeEvent || this.state.blockChangeEvent || this.triggerChangeEvent(); + this.postUpdate(); + }).bind(this), 100); + }, getInputValue() { + var t2 = this.getCleanValue(); + return "mix" == this.settings.mode ? this.getMixedTagsAsString(t2) : t2.length ? this.settings.originalInputValueFormat ? this.settings.originalInputValueFormat(t2) : JSON.stringify(t2) : ""; + }, getCleanValue(t2) { + return a(t2 || this.value, this.dataProps); + }, getMixedTagsAsString() { + var t2 = "", e2 = this, i2 = this.settings, s2 = i2.originalInputValueFormat || JSON.stringify, a2 = i2.mixTagsInterpolator; + return function i3(o2) { + o2.childNodes.forEach((o3) => { + if (1 == o3.nodeType) { + const r2 = T(o3); + if ("BR" == o3.tagName && (t2 += "\r\n"), r2 && v.call(e2, o3)) { + if (r2.__removed) + return; + t2 += a2[0] + s2(n(r2, e2.dataProps)) + a2[1]; + } else + o3.getAttribute("style") || ["B", "I", "U"].includes(o3.tagName) ? t2 += o3.textContent : "DIV" != o3.tagName && "P" != o3.tagName || (t2 += "\r\n", i3(o3)); + } else + t2 += o3.textContent; + }); + }(this.DOM.input), t2; + } }, _.prototype.removeTag = _.prototype.removeTags, _; + }); +})(tagify_min); +var tagify_minExports = tagify_min.exports; +const Tagify = /* @__PURE__ */ getDefaultExportFromCjs(tagify_minExports); +function _assertThisInitialized$1(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; +} +function _inheritsLoose$1(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} +/*! + * GSAP 3.12.5 + * https://gsap.com + * + * @license Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _config = { + autoSleep: 120, + force3D: "auto", + nullTargetWarn: 1, + units: { + lineHeight: "" + } +}, _defaults = { + duration: 0.5, + overwrite: false, + delay: 0 +}, _suppressOverwrites, _reverting$2, _context$2, _bigNum$3 = 1e8, _tinyNum = 1 / _bigNum$3, _2PI = Math.PI * 2, _HALF_PI = _2PI / 4, _gsID = 0, _sqrt$1 = Math.sqrt, _cos$1 = Math.cos, _sin$1 = Math.sin, _isString$1 = function _isString(value) { + return typeof value === "string"; +}, _isFunction$1 = function _isFunction(value) { + return typeof value === "function"; +}, _isNumber$1 = function _isNumber(value) { + return typeof value === "number"; +}, _isUndefined$2 = function _isUndefined(value) { + return typeof value === "undefined"; +}, _isObject$1 = function _isObject(value) { + return typeof value === "object"; +}, _isNotFalse = function _isNotFalse2(value) { + return value !== false; +}, _windowExists$2 = function _windowExists() { + return typeof window !== "undefined"; +}, _isFuncOrString = function _isFuncOrString2(value) { + return _isFunction$1(value) || _isString$1(value); +}, _isTypedArray = typeof ArrayBuffer === "function" && ArrayBuffer.isView || function() { +}, _isArray$1 = Array.isArray, _strictNumExp = /(?:-?\.?\d|\.)+/gi, _numExp$2 = /[-+=.]*\d+[.e\-+]*\d*[e\-+]*\d*/g, _numWithUnitExp = /[-+=.]*\d+[.e-]*\d*[a-z%]*/g, _complexStringNumExp = /[-+=.]*\d+\.?\d*(?:e-|e\+)?\d*/gi, _relExp = /[+-]=-?[.\d]+/, _delimitedValueExp = /[^,'"\[\]\s]+/gi, _unitExp = /^[+\-=e\s\d]*\d+[.\d]*([a-z]*|%)\s*$/i, _globalTimeline, _win$4, _coreInitted$3, _doc$4, _globals = {}, _installScope = {}, _coreReady, _install = function _install2(scope) { + return (_installScope = _merge(scope, _globals)) && gsap$6; +}, _missingPlugin = function _missingPlugin2(property, value) { + return console.warn("Invalid property", property, "set to", value, "Missing plugin? gsap.registerPlugin()"); +}, _warn = function _warn2(message, suppress) { + return !suppress && console.warn(message); +}, _addGlobal = function _addGlobal2(name, obj) { + return name && (_globals[name] = obj) && _installScope && (_installScope[name] = obj) || _globals; +}, _emptyFunc$2 = function _emptyFunc() { + return 0; +}, _startAtRevertConfig = { + suppressEvents: true, + isStart: true, + kill: false +}, _revertConfigNoKill = { + suppressEvents: true, + kill: false +}, _revertConfig = { + suppressEvents: true +}, _reservedProps = {}, _lazyTweens = [], _lazyLookup = {}, _lastRenderedFrame, _plugins = {}, _effects = {}, _nextGCFrame = 30, _harnessPlugins = [], _callbackNames = "", _harness = function _harness2(targets) { + var target = targets[0], harnessPlugin, i; + _isObject$1(target) || _isFunction$1(target) || (targets = [targets]); + if (!(harnessPlugin = (target._gsap || {}).harness)) { + i = _harnessPlugins.length; + while (i-- && !_harnessPlugins[i].targetTest(target)) { + } + harnessPlugin = _harnessPlugins[i]; + } + i = targets.length; + while (i--) { + targets[i] && (targets[i]._gsap || (targets[i]._gsap = new GSCache(targets[i], harnessPlugin))) || targets.splice(i, 1); + } + return targets; +}, _getCache = function _getCache2(target) { + return target._gsap || _harness(toArray$1(target))[0]._gsap; +}, _getProperty = function _getProperty2(target, property, v) { + return (v = target[property]) && _isFunction$1(v) ? target[property]() : _isUndefined$2(v) && target.getAttribute && target.getAttribute(property) || v; +}, _forEachName = function _forEachName2(names, func) { + return (names = names.split(",")).forEach(func) || names; +}, _round$4 = function _round(value) { + return Math.round(value * 1e5) / 1e5 || 0; +}, _roundPrecise$1 = function _roundPrecise(value) { + return Math.round(value * 1e7) / 1e7 || 0; +}, _parseRelative = function _parseRelative2(start, value) { + var operator = value.charAt(0), end = parseFloat(value.substr(2)); + start = parseFloat(start); + return operator === "+" ? start + end : operator === "-" ? start - end : operator === "*" ? start * end : start / end; +}, _arrayContainsAny = function _arrayContainsAny2(toSearch, toFind) { + var l = toFind.length, i = 0; + for (; toSearch.indexOf(toFind[i]) < 0 && ++i < l; ) { + } + return i < l; +}, _lazyRender = function _lazyRender2() { + var l = _lazyTweens.length, a = _lazyTweens.slice(0), i, tween; + _lazyLookup = {}; + _lazyTweens.length = 0; + for (i = 0; i < l; i++) { + tween = a[i]; + tween && tween._lazy && (tween.render(tween._lazy[0], tween._lazy[1], true)._lazy = 0); + } +}, _lazySafeRender = function _lazySafeRender2(animation, time, suppressEvents, force) { + _lazyTweens.length && !_reverting$2 && _lazyRender(); + animation.render(time, suppressEvents, force || _reverting$2 && time < 0 && (animation._initted || animation._startAt)); + _lazyTweens.length && !_reverting$2 && _lazyRender(); +}, _numericIfPossible = function _numericIfPossible2(value) { + var n = parseFloat(value); + return (n || n === 0) && (value + "").match(_delimitedValueExp).length < 2 ? n : _isString$1(value) ? value.trim() : value; +}, _passThrough = function _passThrough2(p) { + return p; +}, _setDefaults$1 = function _setDefaults(obj, defaults2) { + for (var p in defaults2) { + p in obj || (obj[p] = defaults2[p]); } - return numWords.join(" "); -}; -const ordinalizeNum = (num, isReturningWords = false) => { - if (isReturningWords) { - const [numText, suffix] = lCase(verbalizeNum(num)).match(/.*?[-\s]?(\w*)$/i) ?? ["", ""]; - return numText.replace( - new RegExp(`${suffix}$`), - suffix in _ordinals ? _ordinals[suffix] : `${suffix}th` - ); - } - if (/(\.)|(1[1-3]$)/.test(`${num}`)) { - return `${num}th`; - } - return `${num}${["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"][pInt(`${num}`.charAt(`${num}`.length - 1))]}`; -}; -const romanizeNum = (num, isUsingGroupedChars = true) => { - if (isFloat(num)) { - throw new Error(`Error: Can't Romanize Floats (${num})`); - } - if (num >= 4e5) { - throw new Error(`Error: Can't Romanize >= 400,000 (${num})`); - } - if (num < 0) { - throw new Error(`Error: Can't Romanize Negative Numbers (${num})`); - } - if (num === 0) { - return "0"; - } - const romanRef = _romanNumerals[isUsingGroupedChars ? "grouped" : "ungrouped"]; - const romanNum = [...stringifyNum(num).split("")].reverse().map((digit, i) => romanRef[i][pInt(digit)]).reverse().join(""); - return isUsingGroupedChars ? romanNum.replace(/ⅩⅠ/gu, "Ⅺ").replace(/ⅩⅡ/gu, "Ⅻ") : romanNum; -}; -const loremIpsum = (numWords = 200) => { - const lrWordList = _loremIpsumText.split(/\n?\s+/g); - const words = [...lrWordList[randNum(0, lrWordList.length - 1)]]; - while (words.length < numWords) { - words.push(...lrWordList); + return obj; +}, _setKeyframeDefaults = function _setKeyframeDefaults2(excludeDuration) { + return function(obj, defaults2) { + for (var p in defaults2) { + p in obj || p === "duration" && excludeDuration || p === "ease" || (obj[p] = defaults2[p]); + } + }; +}, _merge = function _merge2(base, toMerge) { + for (var p in toMerge) { + base[p] = toMerge[p]; + } + return base; +}, _mergeDeep = function _mergeDeep2(base, toMerge) { + for (var p in toMerge) { + p !== "__proto__" && p !== "constructor" && p !== "prototype" && (base[p] = _isObject$1(toMerge[p]) ? _mergeDeep2(base[p] || (base[p] = {}), toMerge[p]) : toMerge[p]); + } + return base; +}, _copyExcluding = function _copyExcluding2(obj, excluding) { + var copy = {}, p; + for (p in obj) { + p in excluding || (copy[p] = obj[p]); + } + return copy; +}, _inheritDefaults = function _inheritDefaults2(vars) { + var parent = vars.parent || _globalTimeline, func = vars.keyframes ? _setKeyframeDefaults(_isArray$1(vars.keyframes)) : _setDefaults$1; + if (_isNotFalse(vars.inherit)) { + while (parent) { + func(vars, parent.vars.defaults); + parent = parent.parent || parent._dp; + } + } + return vars; +}, _arraysMatch = function _arraysMatch2(a1, a2) { + var i = a1.length, match = i === a2.length; + while (match && i-- && a1[i] === a2[i]) { + } + return i < 0; +}, _addLinkedListItem = function _addLinkedListItem2(parent, child, firstProp, lastProp, sortBy) { + if (firstProp === void 0) { + firstProp = "_first"; + } + if (lastProp === void 0) { + lastProp = "_last"; + } + var prev = parent[lastProp], t; + if (sortBy) { + t = child[sortBy]; + while (prev && prev[sortBy] > t) { + prev = prev._prev; + } + } + if (prev) { + child._next = prev._next; + prev._next = child; + } else { + child._next = parent[firstProp]; + parent[firstProp] = child; } - words.length = numWords; - return `${sCase(words.join(" ")).trim().replace(/[^a-z\s]*$/ui, "")}.`; -}; -const randString = (length = 5) => Array.from({ length }).map(() => String.fromCharCode(randInt(...["a", "z"].map((char) => char.charCodeAt(0))))).join(""); -const randWord = (numWords = 1, wordList = _randomWords) => Array.from({ length: numWords }).map(() => randElem([...wordList])).join(" "); -const getUID$1 = (id) => { - const indexNum = Math.max( - 0, - ...UUIDLOG.filter(([genericID]) => genericID.startsWith(id)).map(([, , num]) => num) - ) + 1; - const uuid = indexNum === 1 ? id : `${id}_${indexNum}`; - UUIDLOG.push([id, uuid, indexNum]); - eLog.log(`UUIDify(${id}) --> [${uuid}, ${indexNum}]`); - Object.assign(globalThis, { UUIDLOG }); - return uuid; -}; -const fuzzyMatch = (val1, val2) => { - const [str1, str2] = [val1, val2].map((val) => lCase(String(val).replace(/[^a-zA-Z0-9.+-]/g, "").trim())); - return str1.length > 0 && str1 === str2; -}; -const isIn = (needle, haystack = [], fuzziness = 0) => { - const SearchTests = [ - (ndl, item) => new RegExp(`^${ndl}$`, "gu").test(`${item}`), - (ndl, item) => new RegExp(`^${ndl}$`, "gui").test(`${item}`) - ]; - if (fuzziness >= 1) { - const fuzzyTests = [ - (ndl, item) => new RegExp(`^${ndl}`, "gui").test(`${item}`), - (ndl, item) => new RegExp(`${ndl}$`, "gui").test(`${item}`), - (ndl, item) => new RegExp(`${ndl}`, "gui").test(`${item}`), - (ndl, item) => new RegExp(`${item}`, "gui").test(`${ndl}`) - ]; - SearchTests.push(...fuzzyTests); - if (fuzziness >= 2) { - SearchTests.push(...fuzzyTests.map((func) => (ndl, item) => func(`${ndl}`.replace(/\W/g, ""), `${item}`.replace(/\W/gu, "")))); - if (fuzziness >= 3) { - SearchTests.push(() => false); + if (child._next) { + child._next._prev = child; + } else { + parent[lastProp] = child; + } + child._prev = prev; + child.parent = child._dp = parent; + return child; +}, _removeLinkedListItem = function _removeLinkedListItem2(parent, child, firstProp, lastProp) { + if (firstProp === void 0) { + firstProp = "_first"; + } + if (lastProp === void 0) { + lastProp = "_last"; + } + var prev = child._prev, next = child._next; + if (prev) { + prev._next = next; + } else if (parent[firstProp] === child) { + parent[firstProp] = next; + } + if (next) { + next._prev = prev; + } else if (parent[lastProp] === child) { + parent[lastProp] = prev; + } + child._next = child._prev = child.parent = null; +}, _removeFromParent = function _removeFromParent2(child, onlyIfParentHasAutoRemove) { + child.parent && (!onlyIfParentHasAutoRemove || child.parent.autoRemoveChildren) && child.parent.remove && child.parent.remove(child); + child._act = 0; +}, _uncache = function _uncache2(animation, child) { + if (animation && (!child || child._end > animation._dur || child._start < 0)) { + var a = animation; + while (a) { + a._dirty = 1; + a = a.parent; + } + } + return animation; +}, _recacheAncestors = function _recacheAncestors2(animation) { + var parent = animation.parent; + while (parent && parent.parent) { + parent._dirty = 1; + parent.totalDuration(); + parent = parent.parent; + } + return animation; +}, _rewindStartAt = function _rewindStartAt2(tween, totalTime, suppressEvents, force) { + return tween._startAt && (_reverting$2 ? tween._startAt.revert(_revertConfigNoKill) : tween.vars.immediateRender && !tween.vars.autoRevert || tween._startAt.render(totalTime, true, force)); +}, _hasNoPausedAncestors = function _hasNoPausedAncestors2(animation) { + return !animation || animation._ts && _hasNoPausedAncestors2(animation.parent); +}, _elapsedCycleDuration = function _elapsedCycleDuration2(animation) { + return animation._repeat ? _animationCycle(animation._tTime, animation = animation.duration() + animation._rDelay) * animation : 0; +}, _animationCycle = function _animationCycle2(tTime, cycleDuration) { + var whole = Math.floor(tTime /= cycleDuration); + return tTime && whole === tTime ? whole - 1 : whole; +}, _parentToChildTotalTime = function _parentToChildTotalTime2(parentTime, child) { + return (parentTime - child._start) * child._ts + (child._ts >= 0 ? 0 : child._dirty ? child.totalDuration() : child._tDur); +}, _setEnd = function _setEnd2(animation) { + return animation._end = _roundPrecise$1(animation._start + (animation._tDur / Math.abs(animation._ts || animation._rts || _tinyNum) || 0)); +}, _alignPlayhead = function _alignPlayhead2(animation, totalTime) { + var parent = animation._dp; + if (parent && parent.smoothChildTiming && animation._ts) { + animation._start = _roundPrecise$1(parent._time - (animation._ts > 0 ? totalTime / animation._ts : ((animation._dirty ? animation.totalDuration() : animation._tDur) - totalTime) / -animation._ts)); + _setEnd(animation); + parent._dirty || _uncache(parent, animation); + } + return animation; +}, _postAddChecks = function _postAddChecks2(timeline2, child) { + var t; + if (child._time || !child._dur && child._initted || child._start < timeline2._time && (child._dur || !child.add)) { + t = _parentToChildTotalTime(timeline2.rawTime(), child); + if (!child._dur || _clamp(0, child.totalDuration(), t) - child._tTime > _tinyNum) { + child.render(t, true); + } + } + if (_uncache(timeline2, child)._dp && timeline2._initted && timeline2._time >= timeline2._dur && timeline2._ts) { + if (timeline2._dur < timeline2.duration()) { + t = timeline2; + while (t._dp) { + t.rawTime() >= 0 && t.totalTime(t._tTime); + t = t._dp; + } + } + timeline2._zTime = -_tinyNum; + } +}, _addToTimeline = function _addToTimeline2(timeline2, child, position, skipChecks) { + child.parent && _removeFromParent(child); + child._start = _roundPrecise$1((_isNumber$1(position) ? position : position || timeline2 !== _globalTimeline ? _parsePosition(timeline2, position, child) : timeline2._time) + child._delay); + child._end = _roundPrecise$1(child._start + (child.totalDuration() / Math.abs(child.timeScale()) || 0)); + _addLinkedListItem(timeline2, child, "_first", "_last", timeline2._sort ? "_start" : 0); + _isFromOrFromStart(child) || (timeline2._recent = child); + skipChecks || _postAddChecks(timeline2, child); + timeline2._ts < 0 && _alignPlayhead(timeline2, timeline2._tTime); + return timeline2; +}, _scrollTrigger = function _scrollTrigger2(animation, trigger) { + return (_globals.ScrollTrigger || _missingPlugin("scrollTrigger", trigger)) && _globals.ScrollTrigger.create(trigger, animation); +}, _attemptInitTween = function _attemptInitTween2(tween, time, force, suppressEvents, tTime) { + _initTween(tween, time, tTime); + if (!tween._initted) { + return 1; + } + if (!force && tween._pt && !_reverting$2 && (tween._dur && tween.vars.lazy !== false || !tween._dur && tween.vars.lazy) && _lastRenderedFrame !== _ticker.frame) { + _lazyTweens.push(tween); + tween._lazy = [tTime, suppressEvents]; + return 1; + } +}, _parentPlayheadIsBeforeStart = function _parentPlayheadIsBeforeStart2(_ref) { + var parent = _ref.parent; + return parent && parent._ts && parent._initted && !parent._lock && (parent.rawTime() < 0 || _parentPlayheadIsBeforeStart2(parent)); +}, _isFromOrFromStart = function _isFromOrFromStart2(_ref2) { + var data = _ref2.data; + return data === "isFromStart" || data === "isStart"; +}, _renderZeroDurationTween = function _renderZeroDurationTween2(tween, totalTime, suppressEvents, force) { + var prevRatio = tween.ratio, ratio = totalTime < 0 || !totalTime && (!tween._start && _parentPlayheadIsBeforeStart(tween) && !(!tween._initted && _isFromOrFromStart(tween)) || (tween._ts < 0 || tween._dp._ts < 0) && !_isFromOrFromStart(tween)) ? 0 : 1, repeatDelay = tween._rDelay, tTime = 0, pt, iteration, prevIteration; + if (repeatDelay && tween._repeat) { + tTime = _clamp(0, tween._tDur, totalTime); + iteration = _animationCycle(tTime, repeatDelay); + tween._yoyo && iteration & 1 && (ratio = 1 - ratio); + if (iteration !== _animationCycle(tween._tTime, repeatDelay)) { + prevRatio = 1 - ratio; + tween.vars.repeatRefresh && tween._initted && tween.invalidate(); + } + } + if (ratio !== prevRatio || _reverting$2 || force || tween._zTime === _tinyNum || !totalTime && tween._zTime) { + if (!tween._initted && _attemptInitTween(tween, totalTime, force, suppressEvents, tTime)) { + return; + } + prevIteration = tween._zTime; + tween._zTime = totalTime || (suppressEvents ? _tinyNum : 0); + suppressEvents || (suppressEvents = totalTime && !prevIteration); + tween.ratio = ratio; + tween._from && (ratio = 1 - ratio); + tween._time = 0; + tween._tTime = tTime; + pt = tween._pt; + while (pt) { + pt.r(ratio, pt.d); + pt = pt._next; + } + totalTime < 0 && _rewindStartAt(tween, totalTime, suppressEvents, true); + tween._onUpdate && !suppressEvents && _callback(tween, "onUpdate"); + tTime && tween._repeat && !suppressEvents && tween.parent && _callback(tween, "onRepeat"); + if ((totalTime >= tween._tDur || totalTime < 0) && tween.ratio === ratio) { + ratio && _removeFromParent(tween, 1); + if (!suppressEvents && !_reverting$2) { + _callback(tween, ratio ? "onComplete" : "onReverseComplete", true); + tween._prom && tween._prom(); + } + } + } else if (!tween._zTime) { + tween._zTime = totalTime; + } +}, _findNextPauseTween = function _findNextPauseTween2(animation, prevTime, time) { + var child; + if (time > prevTime) { + child = animation._first; + while (child && child._start <= time) { + if (child.data === "isPause" && child._start > prevTime) { + return child; + } + child = child._next; + } + } else { + child = animation._last; + while (child && child._start >= time) { + if (child.data === "isPause" && child._start < prevTime) { + return child; + } + child = child._prev; + } + } +}, _setDuration = function _setDuration2(animation, duration, skipUncache, leavePlayhead) { + var repeat = animation._repeat, dur = _roundPrecise$1(duration) || 0, totalProgress = animation._tTime / animation._tDur; + totalProgress && !leavePlayhead && (animation._time *= dur / animation._dur); + animation._dur = dur; + animation._tDur = !repeat ? dur : repeat < 0 ? 1e10 : _roundPrecise$1(dur * (repeat + 1) + animation._rDelay * repeat); + totalProgress > 0 && !leavePlayhead && _alignPlayhead(animation, animation._tTime = animation._tDur * totalProgress); + animation.parent && _setEnd(animation); + skipUncache || _uncache(animation.parent, animation); + return animation; +}, _onUpdateTotalDuration = function _onUpdateTotalDuration2(animation) { + return animation instanceof Timeline ? _uncache(animation) : _setDuration(animation, animation._dur); +}, _zeroPosition = { + _start: 0, + endTime: _emptyFunc$2, + totalDuration: _emptyFunc$2 +}, _parsePosition = function _parsePosition2(animation, position, percentAnimation) { + var labels = animation.labels, recent = animation._recent || _zeroPosition, clippedDuration = animation.duration() >= _bigNum$3 ? recent.endTime(false) : animation._dur, i, offset, isPercent; + if (_isString$1(position) && (isNaN(position) || position in labels)) { + offset = position.charAt(0); + isPercent = position.substr(-1) === "%"; + i = position.indexOf("="); + if (offset === "<" || offset === ">") { + i >= 0 && (position = position.replace(/=/, "")); + return (offset === "<" ? recent._start : recent.endTime(recent._repeat >= 0)) + (parseFloat(position.substr(1)) || 0) * (isPercent ? (i < 0 ? recent : percentAnimation).totalDuration() / 100 : 1); + } + if (i < 0) { + position in labels || (labels[position] = clippedDuration); + return labels[position]; + } + offset = parseFloat(position.charAt(i - 1) + position.substr(i + 1)); + if (isPercent && percentAnimation) { + offset = offset / 100 * (_isArray$1(percentAnimation) ? percentAnimation[0] : percentAnimation).totalDuration(); + } + return i > 1 ? _parsePosition2(animation, position.substr(0, i - 1), percentAnimation) + offset : clippedDuration + offset; + } + return position == null ? clippedDuration : +position; +}, _createTweenType = function _createTweenType2(type, params, timeline2) { + var isLegacy = _isNumber$1(params[1]), varsIndex = (isLegacy ? 2 : 1) + (type < 2 ? 0 : 1), vars = params[varsIndex], irVars, parent; + isLegacy && (vars.duration = params[1]); + vars.parent = timeline2; + if (type) { + irVars = vars; + parent = timeline2; + while (parent && !("immediateRender" in irVars)) { + irVars = parent.vars.defaults || {}; + parent = _isNotFalse(parent.vars.inherit) && parent.parent; + } + vars.immediateRender = _isNotFalse(irVars.immediateRender); + type < 2 ? vars.runBackwards = 1 : vars.startAt = params[varsIndex - 1]; + } + return new Tween(params[0], vars, params[varsIndex + 1]); +}, _conditionalReturn = function _conditionalReturn2(value, func) { + return value || value === 0 ? func(value) : func; +}, _clamp = function _clamp2(min, max, value) { + return value < min ? min : value > max ? max : value; +}, getUnit = function getUnit2(value, v) { + return !_isString$1(value) || !(v = _unitExp.exec(value)) ? "" : v[1]; +}, clamp = function clamp2(min, max, value) { + return _conditionalReturn(value, function(v) { + return _clamp(min, max, v); + }); +}, _slice = [].slice, _isArrayLike = function _isArrayLike2(value, nonEmpty) { + return value && _isObject$1(value) && "length" in value && (!nonEmpty && !value.length || value.length - 1 in value && _isObject$1(value[0])) && !value.nodeType && value !== _win$4; +}, _flatten = function _flatten2(ar, leaveStrings, accumulator) { + if (accumulator === void 0) { + accumulator = []; + } + return ar.forEach(function(value) { + var _accumulator; + return _isString$1(value) && !leaveStrings || _isArrayLike(value, 1) ? (_accumulator = accumulator).push.apply(_accumulator, toArray$1(value)) : accumulator.push(value); + }) || accumulator; +}, toArray$1 = function toArray(value, scope, leaveStrings) { + return _context$2 && !scope && _context$2.selector ? _context$2.selector(value) : _isString$1(value) && !leaveStrings && (_coreInitted$3 || !_wake()) ? _slice.call((scope || _doc$4).querySelectorAll(value), 0) : _isArray$1(value) ? _flatten(value, leaveStrings) : _isArrayLike(value) ? _slice.call(value, 0) : value ? [value] : []; +}, selector = function selector2(value) { + value = toArray$1(value)[0] || _warn("Invalid scope") || {}; + return function(v) { + var el = value.current || value.nativeElement || value; + return toArray$1(v, el.querySelectorAll ? el : el === value ? _warn("Invalid scope") || _doc$4.createElement("div") : value); + }; +}, shuffle$1 = function shuffle(a) { + return a.sort(function() { + return 0.5 - Math.random(); + }); +}, distribute = function distribute2(v) { + if (_isFunction$1(v)) { + return v; + } + var vars = _isObject$1(v) ? v : { + each: v + }, ease = _parseEase(vars.ease), from = vars.from || 0, base = parseFloat(vars.base) || 0, cache = {}, isDecimal = from > 0 && from < 1, ratios = isNaN(from) || isDecimal, axis = vars.axis, ratioX = from, ratioY = from; + if (_isString$1(from)) { + ratioX = ratioY = { + center: 0.5, + edges: 0.5, + end: 1 + }[from] || 0; + } else if (!isDecimal && ratios) { + ratioX = from[0]; + ratioY = from[1]; + } + return function(i, target, a) { + var l = (a || vars).length, distances = cache[l], originX, originY, x, y, d, j, max, min, wrapAt; + if (!distances) { + wrapAt = vars.grid === "auto" ? 0 : (vars.grid || [1, _bigNum$3])[1]; + if (!wrapAt) { + max = -_bigNum$3; + while (max < (max = a[wrapAt++].getBoundingClientRect().left) && wrapAt < l) { + } + wrapAt < l && wrapAt--; + } + distances = cache[l] = []; + originX = ratios ? Math.min(wrapAt, l) * ratioX - 0.5 : from % wrapAt; + originY = wrapAt === _bigNum$3 ? 0 : ratios ? l * ratioY / wrapAt - 0.5 : from / wrapAt | 0; + max = 0; + min = _bigNum$3; + for (j = 0; j < l; j++) { + x = j % wrapAt - originX; + y = originY - (j / wrapAt | 0); + distances[j] = d = !axis ? _sqrt$1(x * x + y * y) : Math.abs(axis === "y" ? y : x); + d > max && (max = d); + d < min && (min = d); + } + from === "random" && shuffle$1(distances); + distances.max = max - min; + distances.min = min; + distances.v = l = (parseFloat(vars.amount) || parseFloat(vars.each) * (wrapAt > l ? l - 1 : !axis ? Math.max(wrapAt, l / wrapAt) : axis === "y" ? l / wrapAt : wrapAt) || 0) * (from === "edges" ? -1 : 1); + distances.b = l < 0 ? base - l : base; + distances.u = getUnit(vars.amount || vars.each) || 0; + ease = ease && l < 0 ? _invertEase(ease) : ease; + } + l = (distances[i] - distances.min) / distances.max || 0; + return _roundPrecise$1(distances.b + (ease ? ease(l) : l) * distances.v) + distances.u; + }; +}, _roundModifier = function _roundModifier2(v) { + var p = Math.pow(10, ((v + "").split(".")[1] || "").length); + return function(raw) { + var n = _roundPrecise$1(Math.round(parseFloat(raw) / v) * v * p); + return (n - n % 1) / p + (_isNumber$1(raw) ? 0 : getUnit(raw)); + }; +}, snap = function snap2(snapTo, value) { + var isArray2 = _isArray$1(snapTo), radius, is2D; + if (!isArray2 && _isObject$1(snapTo)) { + radius = isArray2 = snapTo.radius || _bigNum$3; + if (snapTo.values) { + snapTo = toArray$1(snapTo.values); + if (is2D = !_isNumber$1(snapTo[0])) { + radius *= radius; + } + } else { + snapTo = _roundModifier(snapTo.increment); + } + } + return _conditionalReturn(value, !isArray2 ? _roundModifier(snapTo) : _isFunction$1(snapTo) ? function(raw) { + is2D = snapTo(raw); + return Math.abs(is2D - raw) <= radius ? is2D : raw; + } : function(raw) { + var x = parseFloat(is2D ? raw.x : raw), y = parseFloat(is2D ? raw.y : 0), min = _bigNum$3, closest = 0, i = snapTo.length, dx, dy; + while (i--) { + if (is2D) { + dx = snapTo[i].x - x; + dy = snapTo[i].y - y; + dx = dx * dx + dy * dy; + } else { + dx = Math.abs(snapTo[i] - x); + } + if (dx < min) { + min = dx; + closest = i; } } - } - const searchNeedle = `${needle}`; - const searchStack = (() => { - if (isArray(haystack)) { - return [...haystack]; + closest = !radius || min <= radius ? snapTo[closest] : raw; + return is2D || closest === raw || _isNumber$1(raw) ? closest : closest + getUnit(raw); + }); +}, random = function random2(min, max, roundingIncrement, returnFunction) { + return _conditionalReturn(_isArray$1(min) ? !max : roundingIncrement === true ? !!(roundingIncrement = 0) : !returnFunction, function() { + return _isArray$1(min) ? min[~~(Math.random() * min.length)] : (roundingIncrement = roundingIncrement || 1e-5) && (returnFunction = roundingIncrement < 1 ? Math.pow(10, (roundingIncrement + "").length - 2) : 1) && Math.floor(Math.round((min - roundingIncrement / 2 + Math.random() * (max - min + roundingIncrement * 0.99)) / roundingIncrement) * roundingIncrement * returnFunction) / returnFunction; + }); +}, pipe = function pipe2() { + for (var _len = arguments.length, functions = new Array(_len), _key = 0; _key < _len; _key++) { + functions[_key] = arguments[_key]; + } + return function(value) { + return functions.reduce(function(v, f) { + return f(v); + }, value); + }; +}, unitize = function unitize2(func, unit) { + return function(value) { + return func(parseFloat(value)) + (unit || getUnit(value)); + }; +}, normalize = function normalize2(min, max, value) { + return mapRange(min, max, 0, 1, value); +}, _wrapArray = function _wrapArray2(a, wrapper, value) { + return _conditionalReturn(value, function(index) { + return a[~~wrapper(index)]; + }); +}, wrap = function wrap2(min, max, value) { + var range = max - min; + return _isArray$1(min) ? _wrapArray(min, wrap2(0, min.length), max) : _conditionalReturn(value, function(value2) { + return (range + (value2 - min) % range) % range + min; + }); +}, wrapYoyo = function wrapYoyo2(min, max, value) { + var range = max - min, total = range * 2; + return _isArray$1(min) ? _wrapArray(min, wrapYoyo2(0, min.length - 1), max) : _conditionalReturn(value, function(value2) { + value2 = (total + (value2 - min) % total) % total || 0; + return min + (value2 > range ? total - value2 : value2); + }); +}, _replaceRandom = function _replaceRandom2(value) { + var prev = 0, s = "", i, nums, end, isArray2; + while (~(i = value.indexOf("random(", prev))) { + end = value.indexOf(")", i); + isArray2 = value.charAt(i + 7) === "["; + nums = value.substr(i + 7, end - i - 7).match(isArray2 ? _delimitedValueExp : _strictNumExp); + s += value.substr(prev, i - prev) + random(isArray2 ? nums : +nums[0], isArray2 ? 0 : +nums[1], +nums[2] || 1e-5); + prev = end + 1; + } + return s + value.substr(prev, value.length - prev); +}, mapRange = function mapRange2(inMin, inMax, outMin, outMax, value) { + var inRange = inMax - inMin, outRange = outMax - outMin; + return _conditionalReturn(value, function(value2) { + return outMin + ((value2 - inMin) / inRange * outRange || 0); + }); +}, interpolate = function interpolate2(start, end, progress, mutate) { + var func = isNaN(start + end) ? 0 : function(p2) { + return (1 - p2) * start + p2 * end; + }; + if (!func) { + var isString = _isString$1(start), master = {}, p, i, interpolators, l, il; + progress === true && (mutate = 1) && (progress = null); + if (isString) { + start = { + p: start + }; + end = { + p: end + }; + } else if (_isArray$1(start) && !_isArray$1(end)) { + interpolators = []; + l = start.length; + il = l - 2; + for (i = 1; i < l; i++) { + interpolators.push(interpolate2(start[i - 1], start[i])); + } + l--; + func = function func2(p2) { + p2 *= l; + var i2 = Math.min(il, ~~p2); + return interpolators[i2](p2 - i2); + }; + progress = end; + } else if (!mutate) { + start = _merge(_isArray$1(start) ? [] : {}, start); } - if (isList(haystack)) { - return Object.keys(haystack); + if (!interpolators) { + for (p in end) { + _addPropTween.call(master, start, p, "get", end[p]); + } + func = function func2(p2) { + return _renderPropTweens(p2, master) || (isString ? start.p : start); + }; } - try { - return Array.from(haystack); - } catch { - throw new Error(`Haystack type must be [list, array], not ${typeof haystack}: ${JSON.stringify(haystack)}`); + } + return _conditionalReturn(progress, func); +}, _getLabelInDirection = function _getLabelInDirection2(timeline2, fromTime, backward) { + var labels = timeline2.labels, min = _bigNum$3, p, distance, label; + for (p in labels) { + distance = labels[p] - fromTime; + if (distance < 0 === !!backward && distance && min > (distance = Math.abs(distance))) { + label = p; + min = distance; } - })(); - if (!isArray(searchStack)) { - return false; } - let matchIndex = -1; - while (!isPosInt(matchIndex)) { - const testFunc = SearchTests.shift(); - if (!testFunc) { - return false; + return label; +}, _callback = function _callback2(animation, type, executeLazyFirst) { + var v = animation.vars, callback = v[type], prevContext = _context$2, context3 = animation._ctx, params, scope, result; + if (!callback) { + return; + } + params = v[type + "Params"]; + scope = v.callbackScope || animation; + executeLazyFirst && _lazyTweens.length && _lazyRender(); + context3 && (_context$2 = context3); + result = params ? callback.apply(scope, params) : callback.call(scope); + _context$2 = prevContext; + return result; +}, _interrupt$1 = function _interrupt(animation) { + _removeFromParent(animation); + animation.scrollTrigger && animation.scrollTrigger.kill(!!_reverting$2); + animation.progress() < 1 && _callback(animation, "onInterrupt"); + return animation; +}, _quickTween, _registerPluginQueue = [], _createPlugin = function _createPlugin2(config3) { + if (!config3) + return; + config3 = !config3.name && config3["default"] || config3; + if (_windowExists$2() || config3.headless) { + var name = config3.name, isFunc2 = _isFunction$1(config3), Plugin = name && !isFunc2 && config3.init ? function() { + this._props = []; + } : config3, instanceDefaults = { + init: _emptyFunc$2, + render: _renderPropTweens, + add: _addPropTween, + kill: _killPropTweensOf, + modifier: _addPluginModifier, + rawVars: 0 + }, statics = { + targetTest: 0, + get: 0, + getSetter: _getSetter, + aliases: {}, + register: 0 + }; + _wake(); + if (config3 !== Plugin) { + if (_plugins[name]) { + return; + } + _setDefaults$1(Plugin, _setDefaults$1(_copyExcluding(config3, instanceDefaults), statics)); + _merge(Plugin.prototype, _merge(instanceDefaults, _copyExcluding(config3, statics))); + _plugins[Plugin.prop = name] = Plugin; + if (config3.targetTest) { + _harnessPlugins.push(Plugin); + _reservedProps[name] = 1; + } + name = (name === "css" ? "CSS" : name.charAt(0).toUpperCase() + name.substr(1)) + "Plugin"; } - matchIndex = searchStack.findIndex((item) => testFunc(searchNeedle, `${item}`)); + _addGlobal(name, Plugin); + config3.register && config3.register(gsap$6, Plugin, PropTween$1); + } else { + _registerPluginQueue.push(config3); + } +}, _255 = 255, _colorLookup = { + aqua: [0, _255, _255], + lime: [0, _255, 0], + silver: [192, 192, 192], + black: [0, 0, 0], + maroon: [128, 0, 0], + teal: [0, 128, 128], + blue: [0, 0, _255], + navy: [0, 0, 128], + white: [_255, _255, _255], + olive: [128, 128, 0], + yellow: [_255, _255, 0], + orange: [_255, 165, 0], + gray: [128, 128, 128], + purple: [128, 0, 128], + green: [0, 128, 0], + red: [_255, 0, 0], + pink: [_255, 192, 203], + cyan: [0, _255, _255], + transparent: [_255, _255, _255, 0] +}, _hue = function _hue2(h, m1, m2) { + h += h < 0 ? 1 : h > 1 ? -1 : 0; + return (h * 6 < 1 ? m1 + (m2 - m1) * h * 6 : h < 0.5 ? m2 : h * 3 < 2 ? m1 + (m2 - m1) * (2 / 3 - h) * 6 : m1) * _255 + 0.5 | 0; +}, splitColor = function splitColor2(v, toHSL, forceAlpha) { + var a = !v ? _colorLookup.black : _isNumber$1(v) ? [v >> 16, v >> 8 & _255, v & _255] : 0, r, g, b, h, s, l, max, min, d, wasHSL; + if (!a) { + if (v.substr(-1) === ",") { + v = v.substr(0, v.length - 1); + } + if (_colorLookup[v]) { + a = _colorLookup[v]; + } else if (v.charAt(0) === "#") { + if (v.length < 6) { + r = v.charAt(1); + g = v.charAt(2); + b = v.charAt(3); + v = "#" + r + r + g + g + b + b + (v.length === 5 ? v.charAt(4) + v.charAt(4) : ""); + } + if (v.length === 9) { + a = parseInt(v.substr(1, 6), 16); + return [a >> 16, a >> 8 & _255, a & _255, parseInt(v.substr(7), 16) / 255]; + } + v = parseInt(v.substr(1), 16); + a = [v >> 16, v >> 8 & _255, v & _255]; + } else if (v.substr(0, 3) === "hsl") { + a = wasHSL = v.match(_strictNumExp); + if (!toHSL) { + h = +a[0] % 360 / 360; + s = +a[1] / 100; + l = +a[2] / 100; + g = l <= 0.5 ? l * (s + 1) : l + s - l * s; + r = l * 2 - g; + a.length > 3 && (a[3] *= 1); + a[0] = _hue(h + 1 / 3, r, g); + a[1] = _hue(h, r, g); + a[2] = _hue(h - 1 / 3, r, g); + } else if (~v.indexOf("=")) { + a = v.match(_numExp$2); + forceAlpha && a.length < 4 && (a[3] = 1); + return a; + } + } else { + a = v.match(_strictNumExp) || _colorLookup.transparent; + } + a = a.map(Number); + } + if (toHSL && !wasHSL) { + r = a[0] / _255; + g = a[1] / _255; + b = a[2] / _255; + max = Math.max(r, g, b); + min = Math.min(r, g, b); + l = (max + min) / 2; + if (max === min) { + h = s = 0; + } else { + d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4; + h *= 60; + } + a[0] = ~~(h + 0.5); + a[1] = ~~(s * 100 + 0.5); + a[2] = ~~(l * 100 + 0.5); + } + forceAlpha && a.length < 4 && (a[3] = 1); + return a; +}, _colorOrderData = function _colorOrderData2(v) { + var values = [], c = [], i = -1; + v.split(_colorExp).forEach(function(v2) { + var a = v2.match(_numWithUnitExp) || []; + values.push.apply(values, a); + c.push(i += a.length + 1); + }); + values.c = c; + return values; +}, _formatColors = function _formatColors2(s, toHSL, orderMatchData) { + var result = "", colors = (s + result).match(_colorExp), type = toHSL ? "hsla(" : "rgba(", i = 0, c, shell, d, l; + if (!colors) { + return s; } - if (isPosInt(matchIndex)) { - return isList(haystack) ? Object.values(haystack)[matchIndex] : haystack[matchIndex]; + colors = colors.map(function(color) { + return (color = splitColor(color, toHSL, 1)) && type + (toHSL ? color[0] + "," + color[1] + "%," + color[2] + "%," + color[3] : color.join(",")) + ")"; + }); + if (orderMatchData) { + d = _colorOrderData(s); + c = orderMatchData.c; + if (c.join(result) !== d.c.join(result)) { + shell = s.replace(_colorExp, "1").split(_numWithUnitExp); + l = shell.length - 1; + for (; i < l; i++) { + result += shell[i] + (~c.indexOf(i) ? colors.shift() || type + "0,0,0,0)" : (d.length ? d : colors.length ? colors : orderMatchData).shift()); + } + } + } + if (!shell) { + shell = s.split(_colorExp); + l = shell.length - 1; + for (; i < l; i++) { + result += shell[i] + colors[i]; + } + } + return result + shell[l]; +}, _colorExp = function() { + var s = "(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3,4}){1,2}\\b", p; + for (p in _colorLookup) { + s += "|" + p + "\\b"; + } + return new RegExp(s + ")", "gi"); +}(), _hslExp = /hsl[a]?\(/, _colorStringFilter = function _colorStringFilter2(a) { + var combined = a.join(" "), toHSL; + _colorExp.lastIndex = 0; + if (_colorExp.test(combined)) { + toHSL = _hslExp.test(combined); + a[1] = _formatColors(a[1], toHSL); + a[0] = _formatColors(a[0], toHSL, _colorOrderData(a[1])); + return true; } - return false; -}; -const isInExact = (needle, haystack) => isIn(needle, haystack, 0); -const randNum = (min, max, snap = 0) => gsap.utils.random(min, max, snap); -const randInt = (min, max) => randNum(min, max, 1); -const coinFlip = () => randNum(0, 1, 1) === 1; -const cycleNum = (num, [min = 0, max = Infinity] = []) => gsap.utils.wrap(min, max, num); -const clampNum = (num, [min = 0, max = Infinity] = []) => gsap.utils.clamp(min, max, num); -const cycleAngle = (angle, range = [0, 360]) => cycleNum(angle, range); -const roundNum = (num, sigDigits = 0) => sigDigits === 0 ? pInt(num) : pFloat(num, sigDigits); -const sum = (...nums) => Object.values(nums.flat()).reduce((num, tot) => tot + num, 0); -const average = (...nums) => sum(...nums) / nums.flat().length; -const getDistance = ({ x: x1, y: y1 }, { x: x2, y: y2 }) => ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5; -const getAngle = ({ x: x1, y: y1 }, { x: x2, y: y2 }, { x: xO, y: yO } = { x: 0, y: 0 }, range = [0, 360]) => { - x1 -= xO; - y1 -= yO; - x2 -= xO; - y2 -= yO; - return cycleAngle(radToDeg(Math.atan2(y2 - y1, x2 - x1)), range); -}; -const getAngleDelta = (angleStart, angleEnd, range = [0, 360]) => cycleAngle(angleEnd - angleStart, range); -const getBoundingRectangle = (arrayOfShapes) => { - let minX = Infinity; - let minY = Infinity; - let maxX = -Infinity; - let maxY = -Infinity; - for (const shape of arrayOfShapes) { - let shapeMinX; - let shapeMinY; - let shapeMaxX; - let shapeMaxY; - if (shape.radius !== void 0) { - shapeMinX = shape.x - shape.radius; - shapeMinY = shape.y - shape.radius; - shapeMaxX = shape.x + shape.radius; - shapeMaxY = shape.y + shape.radius; - } else if (shape.size !== void 0) { - shapeMinX = (shape.x - shape.size) / 2; - shapeMinY = (shape.y - shape.size) / 2; - shapeMaxX = (shape.x + shape.size) / 2; - shapeMaxY = (shape.y + shape.size) / 2; - } else if (shape.width !== void 0 || shape.height !== void 0) { - shape.width ?? (shape.width = shape.height); - shape.height ?? (shape.height = shape.width); - shapeMinX = (shape.x - shape.width) / 2; - shapeMinY = (shape.y - shape.height) / 2; - shapeMaxX = (shape.x + shape.width) / 2; - shapeMaxY = (shape.y + shape.height) / 2; - } else { - throw new Error(`[getBoundingRectangle] Error: shape must be a circle, square, or rectangle, not ${JSON.stringify(shape)}`); - } - minX = Math.min(minX, shapeMinX); - minY = Math.min(minY, shapeMinY); - maxX = Math.max(maxX, shapeMaxX); - maxY = Math.max(maxY, shapeMaxY); - } - const width = maxX - minX; - const height = maxY - minY; - const x = (minX + width) / 2; - const y = (minY + height) / 2; - return { x, y, width, height }; -}; -const randElem = (array) => gsap.utils.random(array); -const randIndex = (array) => randInt(0, array.length - 1); -const makeIntRange = (min, max) => { - const intRange = []; - for (let i = min; i <= max; i++) { - intRange.push(i); - } - return intRange; -}; -const makeCycler = (array, index = 0) => { - const wrapper = gsap.utils.wrap(array); - index--; - return function* () { - while (true) { - index++; - yield wrapper(index); +}, _tickerActive, _ticker = function() { + var _getTime2 = Date.now, _lagThreshold = 500, _adjustedLag = 33, _startTime = _getTime2(), _lastUpdate = _startTime, _gap = 1e3 / 240, _nextTime = _gap, _listeners2 = [], _id3, _req, _raf, _self, _delta, _i, _tick = function _tick2(v) { + var elapsed = _getTime2() - _lastUpdate, manual = v === true, overlap, dispatch, time, frame; + (elapsed > _lagThreshold || elapsed < 0) && (_startTime += elapsed - _adjustedLag); + _lastUpdate += elapsed; + time = _lastUpdate - _startTime; + overlap = time - _nextTime; + if (overlap > 0 || manual) { + frame = ++_self.frame; + _delta = time - _self.time * 1e3; + _self.time = time = time / 1e3; + _nextTime += overlap + (overlap >= _gap ? 4 : _gap - overlap); + dispatch = 1; + } + manual || (_id3 = _req(_tick2)); + if (dispatch) { + for (_i = 0; _i < _listeners2.length; _i++) { + _listeners2[_i](time, _delta, frame, v); + } } - }(); -}; -function getLast(array) { - array = Object.values(array); - if (array.length === 0) { - throw new Error("Cannot get last element of an empty array."); + }; + _self = { + time: 0, + frame: 0, + tick: function tick() { + _tick(true); + }, + deltaRatio: function deltaRatio(fps) { + return _delta / (1e3 / (fps || 60)); + }, + wake: function wake() { + if (_coreReady) { + if (!_coreInitted$3 && _windowExists$2()) { + _win$4 = _coreInitted$3 = window; + _doc$4 = _win$4.document || {}; + _globals.gsap = gsap$6; + (_win$4.gsapVersions || (_win$4.gsapVersions = [])).push(gsap$6.version); + _install(_installScope || _win$4.GreenSockGlobals || !_win$4.gsap && _win$4 || {}); + _registerPluginQueue.forEach(_createPlugin); + } + _raf = typeof requestAnimationFrame !== "undefined" && requestAnimationFrame; + _id3 && _self.sleep(); + _req = _raf || function(f) { + return setTimeout(f, _nextTime - _self.time * 1e3 + 1 | 0); + }; + _tickerActive = 1; + _tick(2); + } + }, + sleep: function sleep2() { + (_raf ? cancelAnimationFrame : clearTimeout)(_id3); + _tickerActive = 0; + _req = _emptyFunc$2; + }, + lagSmoothing: function lagSmoothing(threshold, adjustedLag) { + _lagThreshold = threshold || Infinity; + _adjustedLag = Math.min(adjustedLag || 33, _lagThreshold); + }, + fps: function fps(_fps) { + _gap = 1e3 / (_fps || 240); + _nextTime = _self.time * 1e3 + _gap; + }, + add: function add(callback, once, prioritize) { + var func = once ? function(t, d, f, v) { + callback(t, d, f, v); + _self.remove(func); + } : callback; + _self.remove(callback); + _listeners2[prioritize ? "unshift" : "push"](func); + _wake(); + return func; + }, + remove: function remove2(callback, i) { + ~(i = _listeners2.indexOf(callback)) && _listeners2.splice(i, 1) && _i >= i && _i--; + }, + _listeners: _listeners2 + }; + return _self; +}(), _wake = function _wake2() { + return !_tickerActive && _ticker.wake(); +}, _easeMap = {}, _customEaseExp = /^[\d.\-M][\d.\-,\s]/, _quotesExp = /["']/g, _parseObjectInString = function _parseObjectInString2(value) { + var obj = {}, split = value.substr(1, value.length - 3).split(":"), key = split[0], i = 1, l = split.length, index, val, parsedVal; + for (; i < l; i++) { + val = split[i]; + index = i !== l - 1 ? val.lastIndexOf(",") : val.length; + parsedVal = val.substr(0, index); + obj[key] = isNaN(parsedVal) ? parsedVal.replace(_quotesExp, "").trim() : +parsedVal; + key = val.substr(index + 1).trim(); } - return array[array.length - 1]; -} -const unique = (array) => { - const returnArray = []; - array.forEach((item) => { - if (!returnArray.includes(item)) { - returnArray.push(item); - } - }); - return returnArray; -}; -const group = (array, key) => { - const returnObj = {}; - array.forEach((item) => { - const returnKey = item[key]; - let returnVal = returnObj[returnKey]; - if (!returnVal) { - returnVal = []; - returnObj[returnKey] = returnVal; - } - returnVal.push(item); - }); - return returnObj; -}; -const sample = (array, numElems = 1, isUniqueOnly = true, uniqueTestFunc = (e, a) => !a.includes(e)) => { - const elems = []; - let overloadCounter = 0; - while (elems.length < numElems && overloadCounter < 1e6) { - const randomElem = randElem(array); - if (isUniqueOnly && uniqueTestFunc(randomElem, elems)) { - elems.push(randomElem); + return obj; +}, _valueInParentheses = function _valueInParentheses2(value) { + var open = value.indexOf("(") + 1, close = value.indexOf(")"), nested = value.indexOf("(", open); + return value.substring(open, ~nested && nested < close ? value.indexOf(")", close + 1) : close); +}, _configEaseFromString = function _configEaseFromString2(name) { + var split = (name + "").split("("), ease = _easeMap[split[0]]; + return ease && split.length > 1 && ease.config ? ease.config.apply(null, ~name.indexOf("{") ? [_parseObjectInString(split[1])] : _valueInParentheses(name).split(",").map(_numericIfPossible)) : _easeMap._CE && _customEaseExp.test(name) ? _easeMap._CE("", name) : ease; +}, _invertEase = function _invertEase2(ease) { + return function(p) { + return 1 - ease(1 - p); + }; +}, _propagateYoyoEase = function _propagateYoyoEase2(timeline2, isYoyo) { + var child = timeline2._first, ease; + while (child) { + if (child instanceof Timeline) { + _propagateYoyoEase2(child, isYoyo); + } else if (child.vars.yoyoEase && (!child._yoyo || !child._repeat) && child._yoyo !== isYoyo) { + if (child.timeline) { + _propagateYoyoEase2(child.timeline, isYoyo); + } else { + ease = child._ease; + child._ease = child._yEase; + child._yEase = ease; + child._yoyo = isYoyo; + } } - overloadCounter++; + child = child._next; } - return elems; -}; -const removeFirst = (array, element) => array.splice(array.findIndex((v) => v === element)); -function pullElement(array, checkFunc) { - let testFunction; - if (typeof checkFunc !== "function") { - testFunction = (_v) => _v === checkFunc; - } else { - testFunction = checkFunc; +}, _parseEase = function _parseEase2(ease, defaultEase) { + return !ease ? defaultEase : (_isFunction$1(ease) ? ease : _easeMap[ease] || _configEaseFromString(ease)) || defaultEase; +}, _insertEase = function _insertEase2(names, easeIn, easeOut, easeInOut) { + if (easeOut === void 0) { + easeOut = function easeOut2(p) { + return 1 - easeIn(1 - p); + }; } - const index = array.findIndex((v, i, a) => testFunction(v, i, a)); - if (index === -1) { - return void 0; + if (easeInOut === void 0) { + easeInOut = function easeInOut2(p) { + return p < 0.5 ? easeIn(p * 2) / 2 : 1 - easeIn((1 - p) * 2) / 2; + }; } - return array.splice(index, 1).pop(); -} -const pullIndex = (array, index) => pullElement(array, (_, i) => i === index); -const subGroup = (array, groupSize) => { - const subArrays = []; - while (array.length > groupSize) { - const subArray = []; - while (subArray.length < groupSize) { - subArray.push(array.shift()); + var ease = { + easeIn, + easeOut, + easeInOut + }, lowercaseName; + _forEachName(names, function(name) { + _easeMap[name] = _globals[name] = ease; + _easeMap[lowercaseName = name.toLowerCase()] = easeOut; + for (var p in ease) { + _easeMap[lowercaseName + (p === "easeIn" ? ".in" : p === "easeOut" ? ".out" : ".inOut")] = _easeMap[name + "." + p] = ease[p]; } - subArrays.push(subArray); - } - subArrays.push(array); - return subArrays; + }); + return ease; +}, _easeInOutFromOut = function _easeInOutFromOut2(easeOut) { + return function(p) { + return p < 0.5 ? (1 - easeOut(1 - p * 2)) / 2 : 0.5 + easeOut((p - 0.5) * 2) / 2; + }; +}, _configElastic = function _configElastic2(type, amplitude, period) { + var p1 = amplitude >= 1 ? amplitude : 1, p2 = (period || (type ? 0.3 : 0.45)) / (amplitude < 1 ? amplitude : 1), p3 = p2 / _2PI * (Math.asin(1 / p1) || 0), easeOut = function easeOut2(p) { + return p === 1 ? 1 : p1 * Math.pow(2, -10 * p) * _sin$1((p - p3) * p2) + 1; + }, ease = type === "out" ? easeOut : type === "in" ? function(p) { + return 1 - easeOut(1 - p); + } : _easeInOutFromOut(easeOut); + p2 = _2PI / p2; + ease.config = function(amplitude2, period2) { + return _configElastic2(type, amplitude2, period2); + }; + return ease; +}, _configBack = function _configBack2(type, overshoot) { + if (overshoot === void 0) { + overshoot = 1.70158; + } + var easeOut = function easeOut2(p) { + return p ? --p * p * ((overshoot + 1) * p + overshoot) + 1 : 0; + }, ease = type === "out" ? easeOut : type === "in" ? function(p) { + return 1 - easeOut(1 - p); + } : _easeInOutFromOut(easeOut); + ease.config = function(overshoot2) { + return _configBack2(type, overshoot2); + }; + return ease; }; -const shuffle = (array) => { - let currentIndex = array.length; - let randomIndex; - while (currentIndex !== 0) { - randomIndex = Math.floor(Math.random() * currentIndex); - currentIndex--; - [array[currentIndex], array[randomIndex]] = [ - array[randomIndex], - array[currentIndex] - ]; +_forEachName("Linear,Quad,Cubic,Quart,Quint,Strong", function(name, i) { + var power = i < 5 ? i + 1 : i; + _insertEase(name + ",Power" + (power - 1), i ? function(p) { + return Math.pow(p, power); + } : function(p) { + return p; + }, function(p) { + return 1 - Math.pow(1 - p, power); + }, function(p) { + return p < 0.5 ? Math.pow(p * 2, power) / 2 : 1 - Math.pow((1 - p) * 2, power) / 2; + }); +}); +_easeMap.Linear.easeNone = _easeMap.none = _easeMap.Linear.easeIn; +_insertEase("Elastic", _configElastic("in"), _configElastic("out"), _configElastic()); +(function(n, c) { + var n1 = 1 / c, n2 = 2 * n1, n3 = 2.5 * n1, easeOut = function easeOut2(p) { + return p < n1 ? n * p * p : p < n2 ? n * Math.pow(p - 1.5 / c, 2) + 0.75 : p < n3 ? n * (p -= 2.25 / c) * p + 0.9375 : n * Math.pow(p - 2.625 / c, 2) + 0.984375; + }; + _insertEase("Bounce", function(p) { + return 1 - easeOut(1 - p); + }, easeOut); +})(7.5625, 2.75); +_insertEase("Expo", function(p) { + return p ? Math.pow(2, 10 * (p - 1)) : 0; +}); +_insertEase("Circ", function(p) { + return -(_sqrt$1(1 - p * p) - 1); +}); +_insertEase("Sine", function(p) { + return p === 1 ? 1 : -_cos$1(p * _HALF_PI) + 1; +}); +_insertEase("Back", _configBack("in"), _configBack("out"), _configBack()); +_easeMap.SteppedEase = _easeMap.steps = _globals.SteppedEase = { + config: function config(steps, immediateStart) { + if (steps === void 0) { + steps = 1; + } + var p1 = 1 / steps, p2 = steps + (immediateStart ? 0 : 1), p3 = immediateStart ? 1 : 0, max = 1 - _tinyNum; + return function(p) { + return ((p2 * _clamp(0, max, p) | 0) + p3) * p1; + }; } - return array; }; -const toArray = (target) => { - return gsap.utils.toArray(target); +_defaults.ease = _easeMap["quad.out"]; +_forEachName("onComplete,onUpdate,onStart,onRepeat,onReverseComplete,onInterrupt", function(name) { + return _callbackNames += name + "," + name + "Params,"; +}); +var GSCache = function GSCache2(target, harness) { + this.id = _gsID++; + target._gsap = this; + this.target = target; + this.harness = harness; + this.get = harness ? harness.get : _getProperty; + this.set = harness ? harness.getSetter : _getSetter; }; -const checkVal = ({ k, v }, checkTest) => { - if (typeof checkTest === "function") { - if (isDefined(v)) { - return checkTest(v, k); +var Animation = /* @__PURE__ */ function() { + function Animation2(vars) { + this.vars = vars; + this._delay = +vars.delay || 0; + if (this._repeat = vars.repeat === Infinity ? -2 : vars.repeat || 0) { + this._rDelay = vars.repeatDelay || 0; + this._yoyo = !!vars.yoyo || !!vars.yoyoEase; + } + this._ts = 1; + _setDuration(this, +vars.duration, 1, 1); + this.data = vars.data; + if (_context$2) { + this._ctx = _context$2; + _context$2.data.push(this); + } + _tickerActive || _ticker.wake(); + } + var _proto = Animation2.prototype; + _proto.delay = function delay(value) { + if (value || value === 0) { + this.parent && this.parent.smoothChildTiming && this.startTime(this._start + value - this._delay); + this._delay = value; + return this; } - return checkTest(k); - } - if (typeof checkTest === "number") { - checkTest = `${checkTest}`; - } - return new RegExp(checkTest).test(`${v}`); -}; -const remove = (obj, checkTest) => { - if (isArray(obj)) { - const index = obj.findIndex((v) => checkVal({ v }, checkTest)); - if (index >= 0) { - return removeElementFromArray(obj, index); + return this._delay; + }; + _proto.duration = function duration(value) { + return arguments.length ? this.totalDuration(this._repeat > 0 ? value + (value + this._rDelay) * this._repeat : value) : this.totalDuration() && this._dur; + }; + _proto.totalDuration = function totalDuration(value) { + if (!arguments.length) { + return this._tDur; } - } else if (isList(obj)) { - const [remKey] = Object.entries(obj).find(([k, v]) => checkVal({ k, v }, checkTest)) ?? []; - if (remKey) { - return removeElementFromList(obj, remKey); + this._dirty = 0; + return _setDuration(this, this._repeat < 0 ? value : (value - this._repeat * this._rDelay) / (this._repeat + 1)); + }; + _proto.totalTime = function totalTime(_totalTime, suppressEvents) { + _wake(); + if (!arguments.length) { + return this._tTime; + } + var parent = this._dp; + if (parent && parent.smoothChildTiming && this._ts) { + _alignPlayhead(this, _totalTime); + !parent._dp || parent.parent || _postAddChecks(parent, this); + while (parent && parent.parent) { + if (parent.parent._time !== parent._start + (parent._ts >= 0 ? parent._tTime / parent._ts : (parent.totalDuration() - parent._tTime) / -parent._ts)) { + parent.totalTime(parent._tTime, true); + } + parent = parent.parent; + } + if (!this.parent && this._dp.autoRemoveChildren && (this._ts > 0 && _totalTime < this._tDur || this._ts < 0 && _totalTime > 0 || !this._tDur && !_totalTime)) { + _addToTimeline(this._dp, this, this._start - this._delay); + } } - } - return false; -}; -const removeElementFromArray = (array, index) => { - let remVal; - for (let i = 0; i <= array.length; i++) { - if (i === index) { - remVal = array.shift(); - } else { - array.push(array.shift()); + if (this._tTime !== _totalTime || !this._dur && !suppressEvents || this._initted && Math.abs(this._zTime) === _tinyNum || !_totalTime && !this._initted && (this.add || this._ptLookup)) { + this._ts || (this._pTime = _totalTime); + _lazySafeRender(this, _totalTime, suppressEvents); } - } - return remVal; -}; -const removeElementFromList = (list, key) => { - const remVal = list[key]; - delete list[key]; - return remVal; -}; -const replace = (obj, checkTest, repVal) => { - let repKey; - if (isList(obj)) { - [repKey] = Object.entries(obj).find((v) => checkVal({ v }, checkTest)) || [false]; - if (repKey === false) { - return false; + return this; + }; + _proto.time = function time(value, suppressEvents) { + return arguments.length ? this.totalTime(Math.min(this.totalDuration(), value + _elapsedCycleDuration(this)) % (this._dur + this._rDelay) || (value ? this._dur : 0), suppressEvents) : this._time; + }; + _proto.totalProgress = function totalProgress(value, suppressEvents) { + return arguments.length ? this.totalTime(this.totalDuration() * value, suppressEvents) : this.totalDuration() ? Math.min(1, this._tTime / this._tDur) : this.rawTime() > 0 ? 1 : 0; + }; + _proto.progress = function progress(value, suppressEvents) { + return arguments.length ? this.totalTime(this.duration() * (this._yoyo && !(this.iteration() & 1) ? 1 - value : value) + _elapsedCycleDuration(this), suppressEvents) : this.duration() ? Math.min(1, this._time / this._dur) : this.rawTime() > 0 ? 1 : 0; + }; + _proto.iteration = function iteration(value, suppressEvents) { + var cycleDuration = this.duration() + this._rDelay; + return arguments.length ? this.totalTime(this._time + (value - 1) * cycleDuration, suppressEvents) : this._repeat ? _animationCycle(this._tTime, cycleDuration) + 1 : 1; + }; + _proto.timeScale = function timeScale(value, suppressEvents) { + if (!arguments.length) { + return this._rts === -_tinyNum ? 0 : this._rts; } - } else if (isArray(obj)) { - repKey = obj.findIndex((v) => checkVal({ v }, checkTest)); - if (repKey === -1) { - return false; + if (this._rts === value) { + return this; } - } - if (typeof repKey !== "number") { - repKey = `${repKey}`; - } - if (typeof repVal === "function") { - obj[repKey] = repVal(obj[repKey], repKey); - } else { - obj[repKey] = repVal; - } - return true; -}; -const objClean = (data, remVals = [void 0, null, "", {}, []]) => { - const remStrings = remVals.map((rVal) => JSON.stringify(rVal)); - if (remStrings.includes(JSON.stringify(data)) || remVals.includes(data)) { - return "KILL"; - } - if (Array.isArray(data)) { - const newData = data.map((elem) => objClean(elem, remVals)).filter((elem) => elem !== "KILL"); - return Array.isArray(newData) && newData.length ? newData : "KILL"; - } - if (data && typeof data === "object" && JSON.stringify(data).startsWith("{")) { - const newData = Object.entries(data).map(([key, val]) => [key, objClean(val, remVals)]).filter(([, val]) => val !== "KILL"); - return newData.length ? Object.fromEntries(newData) : "KILL"; - } - return data; -}; -const partition = (obj, predicate = () => true) => [ - objFilter(obj, predicate), - objFilter(obj, (v, k) => !predicate(v, k)) -]; -const zip = (keys, values) => { - if (keys.length !== values.length) { - throw new Error("The arrays must be of equal length."); - } - if (new Set(keys).size !== keys.length) { - throw new Error("The keys must be unique."); - } - const result = {}; - keys.forEach((key, i) => { - result[key] = values[i]; - }); - return result; -}; -function objMap(obj, keyFunc, valFunc) { - let valFuncTyped = valFunc; - let keyFuncTyped = keyFunc; - if (!valFuncTyped) { - valFuncTyped = keyFunc; - keyFuncTyped = false; - } - if (!keyFuncTyped) { - keyFuncTyped = (k) => k; - } - if (Array.isArray(obj)) { - return obj.map(valFuncTyped); - } - return Object.fromEntries(Object.entries(obj).map(([key, val]) => { - assertNonNullType(valFuncTyped, "function"); - return [keyFuncTyped(key, val), valFuncTyped(val, key)]; - })); -} -const objSize = (obj) => { - if (isSimpleObj(obj)) { - return Object.keys(obj).length; - } - if (isArray(obj)) { - return obj.length; - } - if (obj === false || obj === null || obj === void 0) { - return 0; - } - return 1; -}; -function objFindKey(obj, keyFunc, valFunc) { - if (!valFunc) { - valFunc = keyFunc; - keyFunc = false; - } - if (!keyFunc) { - keyFunc = (k) => k; - } - if (isArray(obj)) { - return obj.findIndex(valFunc); - } - const kFunc = keyFunc || (() => true); - const vFunc = valFunc || (() => true); - const validEntry = Object.entries(obj).find(([k, v]) => kFunc(k, v) && vFunc(v, k)); - if (validEntry) { - return validEntry[0]; - } - return false; -} -const objFilter = (obj, keyFunc, valFunc, isMutating = false) => { - if (!valFunc) { - valFunc = keyFunc; - keyFunc = false; - } - if (!keyFunc) { - keyFunc = (k) => k; - } - if (isArray(obj)) { - const keptValues = obj.filter(valFunc); - if (isMutating) { - obj.splice(0, obj.length, ...keptValues); - return obj; - } - return keptValues; - } - const kFunc = keyFunc || (() => true); - const vFunc = valFunc || (() => true); - if (isMutating) { - const entriesToRemove = Object.entries(obj).filter(([key, val]) => !(kFunc(key, val) && vFunc(val, key))); - for (const [key] of entriesToRemove) { - delete obj[key]; - } - return obj; - } - return Object.fromEntries( - Object.entries(obj).filter(([key, val]) => kFunc(key, val) && vFunc(val, key)) - ); -}; -const objForEach = (obj, func) => { - if (isArray(obj)) { - obj.forEach(func); - } else { - Object.entries(obj).forEach(([key, val]) => func(val, key)); - } -}; -const objCompact = (obj, removeWhiteList = [void 0, null], isMutating = false) => objFilter(obj, (val) => !removeWhiteList.includes(val), void 0, isMutating); -const objClone = (obj, isStrictlySafe = false) => { - const cloneArray = (arr) => [...arr]; - const cloneObject = (o) => ({ ...o }); - try { - return JSON.parse(JSON.stringify(obj)); - } catch (err) { - if (isStrictlySafe) { - throw err; + var tTime = this.parent && this._ts ? _parentToChildTotalTime(this.parent._time, this) : this._tTime; + this._rts = +value || 0; + this._ts = this._ps || value === -_tinyNum ? 0 : this._rts; + this.totalTime(_clamp(-Math.abs(this._delay), this._tDur, tTime), suppressEvents !== false); + _setEnd(this); + return _recacheAncestors(this); + }; + _proto.paused = function paused(value) { + if (!arguments.length) { + return this._ps; + } + if (this._ps !== value) { + this._ps = value; + if (value) { + this._pTime = this._tTime || Math.max(-this._delay, this.rawTime()); + this._ts = this._act = 0; + } else { + _wake(); + this._ts = this._rts; + this.totalTime(this.parent && !this.parent.smoothChildTiming ? this.rawTime() : this._tTime || this._pTime, this.progress() === 1 && Math.abs(this._zTime) !== _tinyNum && (this._tTime -= _tinyNum)); + } } - if (Array.isArray(obj)) { - return cloneArray(obj); + return this; + }; + _proto.startTime = function startTime(value) { + if (arguments.length) { + this._start = value; + var parent = this.parent || this._dp; + parent && (parent._sort || !this.parent) && _addToTimeline(parent, this, value - this._delay); + return this; } - if (typeof obj === "object") { - return cloneObject(obj); + return this._start; + }; + _proto.endTime = function endTime(includeRepeats) { + return this._start + (_isNotFalse(includeRepeats) ? this.totalDuration() : this.duration()) / Math.abs(this._ts || 1); + }; + _proto.rawTime = function rawTime(wrapRepeats) { + var parent = this.parent || this._dp; + return !parent ? this._tTime : wrapRepeats && (!this._ts || this._repeat && this._time && this.totalProgress() < 1) ? this._tTime % (this._dur + this._rDelay) : !this._ts ? this._tTime : _parentToChildTotalTime(parent.rawTime(wrapRepeats), this); + }; + _proto.revert = function revert(config3) { + if (config3 === void 0) { + config3 = _revertConfig; + } + var prevIsReverting = _reverting$2; + _reverting$2 = config3; + if (this._initted || this._startAt) { + this.timeline && this.timeline.revert(config3); + this.totalTime(-0.01, config3.suppressEvents); + } + this.data !== "nested" && config3.kill !== false && this.kill(); + _reverting$2 = prevIsReverting; + return this; + }; + _proto.globalTime = function globalTime(rawTime) { + var animation = this, time = arguments.length ? rawTime : animation.rawTime(); + while (animation) { + time = animation._start + time / (Math.abs(animation._ts) || 1); + animation = animation._dp; } - } - return obj; -}; -function objMerge(target, source, { - isMutatingOk = false, - isStrictlySafe = false, - isConcatenatingArrays = true, - isReplacingArrays = false -} = {}) { - target = isMutatingOk ? target : objClone(target, isStrictlySafe); - if (source && typeof source === "object" && "id" in source && isDocID(source.id) || isUndefined(target)) { - return source; - } - if (isUndefined(source)) { - return target; - } - if (!isIndex(source)) { - return target; - } - for (const [key, val] of Object.entries(source)) { - const targetVal = target[key]; - if (isReplacingArrays && isArray(targetVal) && isArray(val)) { - target[key] = val; - } else if (isConcatenatingArrays && isArray(targetVal) && isArray(val)) { - target[key].push(...val); - } else if (val !== null && typeof val === "object") { - if (isUndefined(targetVal) && !(val instanceof Application)) { - target[key] = new (Object.getPrototypeOf(val)).constructor(); - } - target[key] = objMerge( - target[key], - val, - { isMutatingOk: true, isStrictlySafe } - ); - } else { - target[key] = val; + return !this.parent && this._sat ? this._sat.globalTime(rawTime) : time; + }; + _proto.repeat = function repeat(value) { + if (arguments.length) { + this._repeat = value === Infinity ? -2 : value; + return _onUpdateTotalDuration(this); } - } - return target; -} -function objDiff(obj1, obj2) { - const diff = {}; - const bothObj1AndObj2Keys = Object.keys(obj2).filter((key) => Object.hasOwn(obj2, key) && Object.hasOwn(obj1, key)); - const onlyObj2Keys = Object.keys(obj2).filter((key) => Object.hasOwn(obj2, key) && !Object.hasOwn(obj1, key)); - for (const key of bothObj1AndObj2Keys) { - if (typeof obj1[key] === "object" && typeof obj2[key] === "object" && !Array.isArray(obj1[key]) && !Array.isArray(obj2[key])) { - const nestedDiff = objDiff(obj1[key], obj2[key]); - if (Object.keys(nestedDiff).length > 0) { - diff[key] = nestedDiff; - } - } else if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) { - const array1 = obj1[key]; - const array2 = obj2[key]; - if (array1.toString() !== array2.toString()) { - diff[key] = obj2[key]; - } - } else if (obj1[key] !== obj2[key]) { - diff[key] = obj2[key]; + return this._repeat === -2 ? Infinity : this._repeat; + }; + _proto.repeatDelay = function repeatDelay(value) { + if (arguments.length) { + var time = this._time; + this._rDelay = value; + _onUpdateTotalDuration(this); + return time ? this.time(time) : this; + } + return this._rDelay; + }; + _proto.yoyo = function yoyo(value) { + if (arguments.length) { + this._yoyo = value; + return this; } - } - for (const key of onlyObj2Keys) { - diff[`-=${key}`] = obj2[key]; - } - return diff; -} -const objExpand = (obj) => { - const expObj = {}; - for (const [key, val] of Object.entries(obj)) { - if (isList(val)) { - const expandedVal = objExpand(val); - setProperty(expObj, key, expandedVal); - } else { - setProperty(expObj, key, val); + return this._yoyo; + }; + _proto.seek = function seek(position, suppressEvents) { + return this.totalTime(_parsePosition(this, position), _isNotFalse(suppressEvents)); + }; + _proto.restart = function restart(includeDelay, suppressEvents) { + return this.play().totalTime(includeDelay ? -this._delay : 0, _isNotFalse(suppressEvents)); + }; + _proto.play = function play(from, suppressEvents) { + from != null && this.seek(from, suppressEvents); + return this.reversed(false).paused(false); + }; + _proto.reverse = function reverse(from, suppressEvents) { + from != null && this.seek(from || this.totalDuration(), suppressEvents); + return this.reversed(true).paused(false); + }; + _proto.pause = function pause(atTime, suppressEvents) { + atTime != null && this.seek(atTime, suppressEvents); + return this.paused(true); + }; + _proto.resume = function resume() { + return this.paused(false); + }; + _proto.reversed = function reversed(value) { + if (arguments.length) { + !!value !== this.reversed() && this.timeScale(-this._rts || (value ? -_tinyNum : 0)); + return this; } - } - function arrayify(o) { - if (isList(o)) { - if (/^\d+$/.test(Object.keys(o).join(""))) { - return Object.values(o).map(arrayify); + return this._rts < 0; + }; + _proto.invalidate = function invalidate() { + this._initted = this._act = 0; + this._zTime = -_tinyNum; + return this; + }; + _proto.isActive = function isActive() { + var parent = this.parent || this._dp, start = this._start, rawTime; + return !!(!parent || this._ts && this._initted && parent.isActive() && (rawTime = parent.rawTime(true)) >= start && rawTime < this.endTime(true) - _tinyNum); + }; + _proto.eventCallback = function eventCallback(type, callback, params) { + var vars = this.vars; + if (arguments.length > 1) { + if (!callback) { + delete vars[type]; + } else { + vars[type] = callback; + params && (vars[type + "Params"] = params); + type === "onUpdate" && (this._onUpdate = callback); } - return objMap(o, (v) => arrayify(v)); - } - if (isArray(o)) { - return o.map(arrayify); + return this; } - return o; - } - return arrayify(expObj); -}; -const objFlatten = (obj) => { - const flatObj = {}; - for (const [key, val] of Object.entries(obj)) { - if ((isArray(val) || isList(val)) && hasItems(val)) { - for (const [subKey, subVal] of Object.entries(objFlatten(val))) { - flatObj[`${key}.${subKey}`] = subVal; + return vars[type]; + }; + _proto.then = function then(onFulfilled) { + var self2 = this; + return new Promise(function(resolve) { + var f = _isFunction$1(onFulfilled) ? onFulfilled : _passThrough, _resolve = function _resolve2() { + var _then = self2.then; + self2.then = null; + _isFunction$1(f) && (f = f(self2)) && (f.then || f === self2) && (self2.then = _then); + resolve(f); + self2.then = _then; + }; + if (self2._initted && self2.totalProgress() === 1 && self2._ts >= 0 || !self2._tTime && self2._ts < 0) { + _resolve(); + } else { + self2._prom = _resolve; } - } else { - flatObj[key] = val; - } - } - return flatObj; -}; -function objNullify(obj) { - if (!isIndex(obj)) { - return obj; - } - if (Array.isArray(obj)) { - obj.forEach((_, i) => { - obj[i] = null; }); - return obj; - } - Object.keys(obj).forEach((objKey) => { - obj[objKey] = null; - }); - return obj; -} -function objFreezeProps(data, ...keysOrSchema) { - const firstArg = keysOrSchema[0]; - if (firstArg instanceof Object && !Array.isArray(firstArg)) { - const schema = firstArg; - for (const key in schema) { - if (data[key] === void 0) { - throw new Error(`Missing value for ${key}`); + }; + _proto.kill = function kill() { + _interrupt$1(this); + }; + return Animation2; +}(); +_setDefaults$1(Animation.prototype, { + _time: 0, + _start: 0, + _end: 0, + _tTime: 0, + _tDur: 0, + _dirty: 0, + _repeat: 0, + _yoyo: false, + parent: null, + _initted: false, + _rDelay: 0, + _ts: 1, + _dp: 0, + ratio: 0, + _zTime: -_tinyNum, + _prom: 0, + _ps: false, + _rts: 1 +}); +var Timeline = /* @__PURE__ */ function(_Animation) { + _inheritsLoose$1(Timeline2, _Animation); + function Timeline2(vars, position) { + var _this; + if (vars === void 0) { + vars = {}; + } + _this = _Animation.call(this, vars) || this; + _this.labels = {}; + _this.smoothChildTiming = !!vars.smoothChildTiming; + _this.autoRemoveChildren = !!vars.autoRemoveChildren; + _this._sort = _isNotFalse(vars.sortChildren); + _globalTimeline && _addToTimeline(vars.parent || _globalTimeline, _assertThisInitialized$1(_this), position); + vars.reversed && _this.reverse(); + vars.paused && _this.paused(true); + vars.scrollTrigger && _scrollTrigger(_assertThisInitialized$1(_this), vars.scrollTrigger); + return _this; + } + var _proto2 = Timeline2.prototype; + _proto2.to = function to(targets, vars, position) { + _createTweenType(0, arguments, this); + return this; + }; + _proto2.from = function from(targets, vars, position) { + _createTweenType(1, arguments, this); + return this; + }; + _proto2.fromTo = function fromTo(targets, fromVars, toVars, position) { + _createTweenType(2, arguments, this); + return this; + }; + _proto2.set = function set2(targets, vars, position) { + vars.duration = 0; + vars.parent = this; + _inheritDefaults(vars).repeatDelay || (vars.repeat = 0); + vars.immediateRender = !!vars.immediateRender; + new Tween(targets, vars, _parsePosition(this, position), 1); + return this; + }; + _proto2.call = function call(callback, params, position) { + return _addToTimeline(this, Tween.delayedCall(0, callback, params), position); + }; + _proto2.staggerTo = function staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams) { + vars.duration = duration; + vars.stagger = vars.stagger || stagger; + vars.onComplete = onCompleteAll; + vars.onCompleteParams = onCompleteAllParams; + vars.parent = this; + new Tween(targets, vars, _parsePosition(this, position)); + return this; + }; + _proto2.staggerFrom = function staggerFrom(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams) { + vars.runBackwards = 1; + _inheritDefaults(vars).immediateRender = _isNotFalse(vars.immediateRender); + return this.staggerTo(targets, duration, vars, stagger, position, onCompleteAll, onCompleteAllParams); + }; + _proto2.staggerFromTo = function staggerFromTo(targets, duration, fromVars, toVars, stagger, position, onCompleteAll, onCompleteAllParams) { + toVars.startAt = fromVars; + _inheritDefaults(toVars).immediateRender = _isNotFalse(toVars.immediateRender); + return this.staggerTo(targets, duration, toVars, stagger, position, onCompleteAll, onCompleteAllParams); + }; + _proto2.render = function render5(totalTime, suppressEvents, force) { + var prevTime = this._time, tDur = this._dirty ? this.totalDuration() : this._tDur, dur = this._dur, tTime = totalTime <= 0 ? 0 : _roundPrecise$1(totalTime), crossingStart = this._zTime < 0 !== totalTime < 0 && (this._initted || !dur), time, child, next, iteration, cycleDuration, prevPaused, pauseTween, timeScale, prevStart, prevIteration, yoyo, isYoyo; + this !== _globalTimeline && tTime > tDur && totalTime >= 0 && (tTime = tDur); + if (tTime !== this._tTime || force || crossingStart) { + if (prevTime !== this._time && dur) { + tTime += this._time - prevTime; + totalTime += this._time - prevTime; + } + time = tTime; + prevStart = this._start; + timeScale = this._ts; + prevPaused = !timeScale; + if (crossingStart) { + dur || (prevTime = this._zTime); + (totalTime || !suppressEvents) && (this._zTime = totalTime); + } + if (this._repeat) { + yoyo = this._yoyo; + cycleDuration = dur + this._rDelay; + if (this._repeat < -1 && totalTime < 0) { + return this.totalTime(cycleDuration * 100 + totalTime, suppressEvents, force); + } + time = _roundPrecise$1(tTime % cycleDuration); + if (tTime === tDur) { + iteration = this._repeat; + time = dur; + } else { + iteration = ~~(tTime / cycleDuration); + if (iteration && iteration === tTime / cycleDuration) { + time = dur; + iteration--; + } + time > dur && (time = dur); + } + prevIteration = _animationCycle(this._tTime, cycleDuration); + !prevTime && this._tTime && prevIteration !== iteration && this._tTime - prevIteration * cycleDuration - this._dur <= 0 && (prevIteration = iteration); + if (yoyo && iteration & 1) { + time = dur - time; + isYoyo = 1; + } + if (iteration !== prevIteration && !this._lock) { + var rewinding = yoyo && prevIteration & 1, doesWrap = rewinding === (yoyo && iteration & 1); + iteration < prevIteration && (rewinding = !rewinding); + prevTime = rewinding ? 0 : tTime % dur ? dur : tTime; + this._lock = 1; + this.render(prevTime || (isYoyo ? 0 : _roundPrecise$1(iteration * cycleDuration)), suppressEvents, !dur)._lock = 0; + this._tTime = tTime; + !suppressEvents && this.parent && _callback(this, "onRepeat"); + this.vars.repeatRefresh && !isYoyo && (this.invalidate()._lock = 1); + if (prevTime && prevTime !== this._time || prevPaused !== !this._ts || this.vars.onRepeat && !this.parent && !this._act) { + return this; + } + dur = this._dur; + tDur = this._tDur; + if (doesWrap) { + this._lock = 2; + prevTime = rewinding ? dur : -1e-4; + this.render(prevTime, true); + this.vars.repeatRefresh && !isYoyo && this.invalidate(); + } + this._lock = 0; + if (!this._ts && !prevPaused) { + return this; + } + _propagateYoyoEase(this, isYoyo); + } } - } - } else { - for (const key of keysOrSchema) { - if (data[key] === void 0) { - throw new Error(`Missing value for ${String(key)}`); + if (this._hasPause && !this._forcing && this._lock < 2) { + pauseTween = _findNextPauseTween(this, _roundPrecise$1(prevTime), _roundPrecise$1(time)); + if (pauseTween) { + tTime -= time - (time = pauseTween._start); + } + } + this._tTime = tTime; + this._time = time; + this._act = !timeScale; + if (!this._initted) { + this._onUpdate = this.vars.onUpdate; + this._initted = 1; + this._zTime = totalTime; + prevTime = 0; + } + if (!prevTime && time && !suppressEvents && !iteration) { + _callback(this, "onStart"); + if (this._tTime !== tTime) { + return this; + } + } + if (time >= prevTime && totalTime >= 0) { + child = this._first; + while (child) { + next = child._next; + if ((child._act || time >= child._start) && child._ts && pauseTween !== child) { + if (child.parent !== this) { + return this.render(totalTime, suppressEvents, force); + } + child.render(child._ts > 0 ? (time - child._start) * child._ts : (child._dirty ? child.totalDuration() : child._tDur) + (time - child._start) * child._ts, suppressEvents, force); + if (time !== this._time || !this._ts && !prevPaused) { + pauseTween = 0; + next && (tTime += this._zTime = -_tinyNum); + break; + } + } + child = next; + } + } else { + child = this._last; + var adjustedTime = totalTime < 0 ? totalTime : time; + while (child) { + next = child._prev; + if ((child._act || adjustedTime <= child._end) && child._ts && pauseTween !== child) { + if (child.parent !== this) { + return this.render(totalTime, suppressEvents, force); + } + child.render(child._ts > 0 ? (adjustedTime - child._start) * child._ts : (child._dirty ? child.totalDuration() : child._tDur) + (adjustedTime - child._start) * child._ts, suppressEvents, force || _reverting$2 && (child._initted || child._startAt)); + if (time !== this._time || !this._ts && !prevPaused) { + pauseTween = 0; + next && (tTime += this._zTime = adjustedTime ? -_tinyNum : _tinyNum); + break; + } + } + child = next; + } + } + if (pauseTween && !suppressEvents) { + this.pause(); + pauseTween.render(time >= prevTime ? 0 : -_tinyNum)._zTime = time >= prevTime ? 1 : -1; + if (this._ts) { + this._start = prevStart; + _setEnd(this); + return this.render(totalTime, suppressEvents, force); + } + } + this._onUpdate && !suppressEvents && _callback(this, "onUpdate", true); + if (tTime === tDur && this._tTime >= this.totalDuration() || !tTime && prevTime) { + if (prevStart === this._start || Math.abs(timeScale) !== Math.abs(this._ts)) { + if (!this._lock) { + (totalTime || !dur) && (tTime === tDur && this._ts > 0 || !tTime && this._ts < 0) && _removeFromParent(this, 1); + if (!suppressEvents && !(totalTime < 0 && !prevTime) && (tTime || prevTime || !tDur)) { + _callback(this, tTime === tDur && totalTime >= 0 ? "onComplete" : "onReverseComplete", true); + this._prom && !(tTime < tDur && this.timeScale() > 0) && this._prom(); + } + } + } } } - } - return data; -} -const getDynamicFunc = (funcName, func, context) => { - if (typeof func === "function") { - const dFunc = { [funcName](...args) { - return func(...args); - } }[funcName]; - return context ? dFunc.bind(context) : dFunc; - } - return false; -}; -const withLog = (fn) => { - return (...args) => { - console.log(`calling ${fn.name}`); - return fn(...args); + return this; }; -}; -const changeContainer = (elem, container, isCloning = false) => { - elem = $(elem)[0]; - container = $(container)[0]; - const curContainer = $(elem).parent()[0]; - const curPosition = { - x: gsap.getProperty(elem, "x"), - y: gsap.getProperty(elem, "y") + _proto2.add = function add(child, position) { + var _this2 = this; + _isNumber$1(position) || (position = _parsePosition(this, position, child)); + if (!(child instanceof Animation)) { + if (_isArray$1(child)) { + child.forEach(function(obj) { + return _this2.add(obj, position); + }); + return this; + } + if (_isString$1(child)) { + return this.addLabel(child, position); + } + if (_isFunction$1(child)) { + child = Tween.delayedCall(0, child); + } else { + return this; + } + } + return this !== child ? _addToTimeline(this, child, position) : this; }; - const relPos = MotionPathPlugin.convertCoordinates( - curContainer, - container, - curPosition - ); - eLog.checkLog3("changeContainer", "Target Element", { elem, container, curContainer, curPosition, relPos }); - if (isCloning) { - elem = $(elem).clone()[0]; - } - $(elem).appendTo($(container)); - gsap.set(elem, relPos); - return elem; -}; -const adjustTextContainerAspectRatio = (textContainer, targetRatio, maxHeight, maxWidth, minFontSize = 8) => { - textContainer = $(textContainer)[0]; - if (!maxWidth) { - textContainer.style.setProperty("width", "max-content", "important"); - } else { - textContainer.style.setProperty("width", `${maxWidth}px`, "important"); - } - function recurAdjustment() { - textContainer = $(textContainer)[0]; - const newFontSize = parseFloat(style.fontSize) * 0.8; - const newLineHeight = parseFloat(style.lineHeight) * 0.8; - if (newFontSize < minFontSize) { - return false; + _proto2.getChildren = function getChildren(nested, tweens, timelines, ignoreBeforeTime) { + if (nested === void 0) { + nested = true; } - textContainer.style.fontSize = `${newFontSize}px`; - textContainer.style.lineHeight = `${newLineHeight}px`; - return adjustTextContainerAspectRatio(textContainer, targetRatio, lineCount ?? maxHeight, maxWidth, minFontSize); - } - const style = window.getComputedStyle(textContainer); - const lineHeight = parseFloat(style.lineHeight); - let lineCount = void 0; - if (isInt(maxHeight) && maxHeight < lineHeight) { - lineCount = maxHeight; - } - const initialWidth = parseFloat(style.width); - let bestWidth = initialWidth; - let isAtMaxLineCount = false; - for (let lines = 1; ; lines++) { - const expectedHeight = lineHeight * lines; - const expectedWidth = initialWidth / lines; - const expectedRatio = expectedWidth / expectedHeight; - if (expectedRatio < targetRatio) { - break; + if (tweens === void 0) { + tweens = true; } - if (isInt(lineCount)) { - if (lines > lineCount) { - if (recurAdjustment()) { - return; + if (timelines === void 0) { + timelines = true; + } + if (ignoreBeforeTime === void 0) { + ignoreBeforeTime = -_bigNum$3; + } + var a = [], child = this._first; + while (child) { + if (child._start >= ignoreBeforeTime) { + if (child instanceof Tween) { + tweens && a.push(child); + } else { + timelines && a.push(child); + nested && a.push.apply(a, child.getChildren(true, tweens, timelines)); } - break; } - } else if (maxHeight && expectedHeight > maxHeight) { - if (recurAdjustment()) { - return; + child = child._next; + } + return a; + }; + _proto2.getById = function getById2(id) { + var animations = this.getChildren(1, 1, 1), i = animations.length; + while (i--) { + if (animations[i].vars.id === id) { + return animations[i]; } - break; } - bestWidth = expectedWidth; - if (isInt(lineCount) && lines === lineCount) { - isAtMaxLineCount = true; - break; + }; + _proto2.remove = function remove2(child) { + if (_isString$1(child)) { + return this.removeLabel(child); } - } - if (!isAtMaxLineCount && maxWidth && bestWidth > maxWidth) { - if (recurAdjustment()) { - return; + if (_isFunction$1(child)) { + return this.killTweensOf(child); } - } - textContainer.style.setProperty("width", `${bestWidth}px`, "important"); -}; -const getSvgCode = (svgDotKey, svgPathKeys) => { - const svgData = getProperty(SVGDATA, svgDotKey); - if (!svgData) { - return ""; - } - const { viewBox, paths, classes } = svgData; - svgPathKeys ?? (svgPathKeys = Object.keys(paths).join("|")); - if (typeof svgPathKeys === "string") { - svgPathKeys = svgPathKeys.split("|"); - } - return [ - ``, - ...svgPathKeys.map((path) => ``), - "" - ].join("\n"); -}; -const getRawCirclePath = (r, { x: xO, y: yO } = { x: 0, y: 0 }) => { - [r, xO, yO] = [r, xO, yO].map((val) => roundNum(val, 2)); - const [b1, b2] = [0.4475 * r, (1 - 0.4475) * r]; - const [xT, yT] = [xO, yO - r]; - return [[ - ...[xT, yT], - ...[b2, 0, r, b1, r, r], - ...[0, b2, -b1, r, -r, r], - ...[-b2, 0, -r, -b1, -r, -r], - ...[0, -b2, b1, -r, r, -r] - ]]; -}; -const drawCirclePath = (radius, origin) => { - const [[xT, yT, ...segments]] = getRawCirclePath(radius, origin); - const path = [`m ${xT} ${yT}`]; - segments.forEach((coord, i) => { - if (i % 6 === 0) { - path.push("c"); + _removeLinkedListItem(this, child); + if (child === this._recent) { + this._recent = this._last; } - path.push(coord); - }); - path.push("z"); - return path.join(" "); -}; -const getColorVals = (red, green, blue, alpha) => { - var _a; - if (isRGBColor(red)) { - [red, green, blue, alpha] = red.replace(/[^\d.,]/g, "").split(/,/).map((color) => isUndefined(color) ? void 0 : parseFloat(color)); - } - if (isHexColor(red)) { - if ([4, 5].includes(red.length)) { - red = red.replace(/([^#])/g, "$1$1"); + return _uncache(this); + }; + _proto2.totalTime = function totalTime(_totalTime2, suppressEvents) { + if (!arguments.length) { + return this._tTime; } - [red, green, blue, alpha] = ((_a = red.match(/[^#]{2}/g)) == null ? void 0 : _a.map((val) => parseInt(val, 16))) ?? []; - } - if ([red, green, blue].every((color) => /^\d+$/.test(`${color}`))) { - return [red, green, blue, alpha].filter((color) => /^[\d.]+$/.test(`${color}`)); - } - return null; -}; -const getRGBString = (red, green, blue, alpha) => { - if (isRGBColor(red) || isHexColor(red)) { - [red, green, blue, alpha] = getColorVals(red) ?? []; - } - if ([red, green, blue].every((color) => /^[.\d]+$/.test(`${color}`))) { - let colorString = "rgb"; - const colors = [red, green, blue]; - if (/^[.\d]+$/.test(`${alpha}`)) { - colors.push(alpha >= 1 ? pInt(alpha) : pFloat(alpha, 2)); - colorString += "a"; + this._forcing = 1; + if (!this._dp && this._ts) { + this._start = _roundPrecise$1(_ticker.time - (this._ts > 0 ? _totalTime2 / this._ts : (this.totalDuration() - _totalTime2) / -this._ts)); } - return `${colorString}(${colors.join(", ")})`; - } - return null; -}; -const getHEXString = (red, green, blue) => { - function componentToHex(c) { - const hex = c.toString(16); - return hex.length === 1 ? `0${hex}` : hex; - } - if (isHexColor(red)) { - return red; - } - if (isRGBColor(red)) { - [red, green, blue] = getColorVals(red) ?? []; - } - if (isDefined(red) && isDefined(green) && isDefined(blue) && [red, green, blue].every((color) => /^[.\d]+$/.test(`${color}`))) { - return `#${componentToHex(red ?? 0)}${componentToHex(green ?? 0)}${componentToHex(blue ?? 0)}`; - } - return null; -}; -const getContrastingColor = (...colorVals) => { - const [red, green, blue] = getColorVals(...colorVals) ?? []; - if ([red, green, blue].every(isNumber)) { - const YIQ = (red * 299 + green * 587 + blue * 114) / 1e3; - return YIQ >= 128 ? "rgba(0, 0, 0, 1)" : "rgba(255, 255, 255, 0.8)"; - } - return null; -}; -const getRandomColor = () => getRGBString( - gsap.utils.random(0, 255, 1), - gsap.utils.random(0, 255, 1), - gsap.utils.random(0, 255, 1) -); -const getSiblings = (elem) => { - const siblings = []; - if (!elem.parentNode) { - return siblings; - } - Array.from(elem.parentNode.children).forEach((sibling) => { - if (sibling !== elem) { - siblings.push(sibling); + _Animation.prototype.totalTime.call(this, _totalTime2, suppressEvents); + this._forcing = 0; + return this; + }; + _proto2.addLabel = function addLabel(label, position) { + this.labels[label] = _parsePosition(this, position); + return this; + }; + _proto2.removeLabel = function removeLabel(label) { + delete this.labels[label]; + return this; + }; + _proto2.addPause = function addPause(position, callback, params) { + var t = Tween.delayedCall(0, callback || _emptyFunc$2, params); + t.data = "isPause"; + this._hasPause = 1; + return _addToTimeline(this, t, _parsePosition(this, position)); + }; + _proto2.removePause = function removePause(position) { + var child = this._first; + position = _parsePosition(this, position); + while (child) { + if (child._start === position && child.data === "isPause") { + _removeFromParent(child); + } + child = child._next; } - }); - return siblings; -}; -const escapeHTML$1 = (str) => typeof str === "string" ? str.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/[`']/g, "'") : str; -const testFuncPerformance = (func, ...params) => { - const start = performance.now(); - let tally = 0; - const handleResult = () => { - if (performance.now() - start < 1e4) { - runFunc(); - tally++; - } else { - const elapsedTime = performance.now() - start; - const timePerCall = roundNum(elapsedTime / tally / 4e3, 4); - eLog.checkLog3("performance", `[TestPerformance] Function Ran ${tally} Times in ${roundNum(elapsedTime / 1e3, 4)}s, Averaging ${timePerCall}s per Call`); + }; + _proto2.killTweensOf = function killTweensOf(targets, props, onlyActive) { + var tweens = this.getTweensOf(targets, onlyActive), i = tweens.length; + while (i--) { + _overwritingTween !== tweens[i] && tweens[i].kill(targets, props); } + return this; }; - const runFunc = () => { - const result = func(...params); - if (result instanceof Promise) { - result.then(handleResult); - } else { - handleResult(); + _proto2.getTweensOf = function getTweensOf2(targets, onlyActive) { + var a = [], parsedTargets = toArray$1(targets), child = this._first, isGlobalTime = _isNumber$1(onlyActive), children; + while (child) { + if (child instanceof Tween) { + if (_arrayContainsAny(child._targets, parsedTargets) && (isGlobalTime ? (!_overwritingTween || child._initted && child._ts) && child.globalTime(0) <= onlyActive && child.globalTime(child.totalDuration()) > onlyActive : !onlyActive || child.isActive())) { + a.push(child); + } + } else if ((children = child.getTweensOf(parsedTargets, onlyActive)).length) { + a.push.apply(a, children); + } + child = child._next; } + return a; }; - runFunc(); -}; -const set = (targets, vars) => gsap.set(targets, vars); -function get(target, property, unit) { - if (unit) { - const propVal = regExtract(gsap.getProperty(target, property, unit), /[\d.]+/); - if (typeof propVal === "string") { - return pFloat(propVal); + _proto2.tweenTo = function tweenTo(position, vars) { + vars = vars || {}; + var tl = this, endTime = _parsePosition(tl, position), _vars = vars, startAt = _vars.startAt, _onStart = _vars.onStart, onStartParams = _vars.onStartParams, immediateRender = _vars.immediateRender, initted, tween = Tween.to(tl, _setDefaults$1({ + ease: vars.ease || "none", + lazy: false, + immediateRender: false, + time: endTime, + overwrite: "auto", + duration: vars.duration || Math.abs((endTime - (startAt && "time" in startAt ? startAt.time : tl._time)) / tl.timeScale()) || _tinyNum, + onStart: function onStart() { + tl.pause(); + if (!initted) { + var duration = vars.duration || Math.abs((endTime - (startAt && "time" in startAt ? startAt.time : tl._time)) / tl.timeScale()); + tween._dur !== duration && _setDuration(tween, duration, 0, 1).render(tween._time, true, true); + initted = 1; + } + _onStart && _onStart.apply(tween, onStartParams || []); + } + }, vars)); + return immediateRender ? tween.render(0) : tween; + }; + _proto2.tweenFromTo = function tweenFromTo(fromPosition, toPosition, vars) { + return this.tweenTo(toPosition, _setDefaults$1({ + startAt: { + time: _parsePosition(this, fromPosition) + } + }, vars)); + }; + _proto2.recent = function recent() { + return this._recent; + }; + _proto2.nextLabel = function nextLabel(afterTime) { + if (afterTime === void 0) { + afterTime = this._time; } - throw new Error(`Unable to extract property '${property}' in '${unit}' units from ${target}`); - } - return gsap.getProperty(target, property); -} -const getGSAngleDelta = (startAngle, endAngle) => signNum(roundNum(getAngleDelta(startAngle, endAngle), 2)).replace(/^(.)/, "$1="); -const getNearestLabel = (tl, matchTest) => { - if (!tl) { - return void 0; - } - if (!objSize(tl.labels)) { - return void 0; - } - if (typeof matchTest === "string") { - matchTest = new RegExp(matchTest); - } - const labelTimes = Object.entries(tl.labels).filter(([label]) => { - return matchTest instanceof RegExp ? matchTest.test(label) : true; - }).sort((a, b) => a[1] - b[1]); - const nearestTime = gsap.utils.snap(labelTimes.map(([_label, time]) => time), tl.time()); - const [nearestLabel] = labelTimes.find(([_label, time]) => time === nearestTime); - return nearestLabel; -}; -const reverseRepeatingTimeline = (tl) => { - if (tl.repeat() === -1) { - tl.totalTime(tl.time()); - } else { - const [tw] = tl.getChildren(false, true, true, tl.time()); - if (tw && tw.repeat() === -1) { - tw.totalTime(tw.time()); + return _getLabelInDirection(this, _parsePosition(this, afterTime)); + }; + _proto2.previousLabel = function previousLabel(beforeTime) { + if (beforeTime === void 0) { + beforeTime = this._time; } - tl.reverse(); - } - return tl; -}; -const sleep = (duration) => new Promise( - (resolve) => { - setTimeout(resolve, duration >= 100 ? duration : duration * 1e3); - } -); -function waitFor(waitForTarget) { - return new Promise( - (resolve, reject) => { - if (waitForTarget instanceof Promise || waitForTarget instanceof gsap.core.Animation) { - waitForTarget.then(() => resolve()).catch(reject); - } else if (Array.isArray(waitForTarget)) { - Promise.all(waitForTarget.map((target) => waitFor(target))).then(() => resolve()).catch(reject); - } else { - resolve(); + return _getLabelInDirection(this, _parsePosition(this, beforeTime), 1); + }; + _proto2.currentLabel = function currentLabel(value) { + return arguments.length ? this.seek(value, true) : this.previousLabel(this._time + _tinyNum); + }; + _proto2.shiftChildren = function shiftChildren(amount, adjustLabels, ignoreBeforeTime) { + if (ignoreBeforeTime === void 0) { + ignoreBeforeTime = 0; + } + var child = this._first, labels = this.labels, p; + while (child) { + if (child._start >= ignoreBeforeTime) { + child._start += amount; + child._end += amount; + } + child = child._next; + } + if (adjustLabels) { + for (p in labels) { + if (labels[p] >= ignoreBeforeTime) { + labels[p] += amount; + } } } - ); -} -const EventHandlers = { - onTextInputBlur: async (inst, event) => { - const elem = event.target; - const { action, target, flagTarget } = elem.dataset; - if (!action) { - throw new Error("Input text elements require a data-action attribute."); - } - if (!target && !flagTarget) { - throw new Error("Input text elements require a 'data-target' or 'data-flag-target' attribute."); + return _uncache(this); + }; + _proto2.invalidate = function invalidate(soft) { + var child = this._first; + this._lock = 0; + while (child) { + child.invalidate(soft); + child = child._next; + } + return _Animation.prototype.invalidate.call(this, soft); + }; + _proto2.clear = function clear(includeLabels) { + if (includeLabels === void 0) { + includeLabels = true; + } + var child = this._first, next; + while (child) { + next = child._next; + this.remove(child); + child = next; + } + this._dp && (this._time = this._tTime = this._pTime = 0); + includeLabels && (this.labels = {}); + return _uncache(this); + }; + _proto2.totalDuration = function totalDuration(value) { + var max = 0, self2 = this, child = self2._last, prevStart = _bigNum$3, prev, start, parent; + if (arguments.length) { + return self2.timeScale((self2._repeat < 0 ? self2.duration() : self2.totalDuration()) / (self2.reversed() ? -value : value)); + } + if (self2._dirty) { + parent = self2.parent; + while (child) { + prev = child._prev; + child._dirty && child.totalDuration(); + start = child._start; + if (start > prevStart && self2._sort && child._ts && !self2._lock) { + self2._lock = 1; + _addToTimeline(self2, child, start - child._delay, 1)._lock = 0; + } else { + prevStart = start; + } + if (start < 0 && child._ts) { + max -= start; + if (!parent && !self2._dp || parent && parent.smoothChildTiming) { + self2._start += start / self2._ts; + self2._time -= start; + self2._tTime -= start; + } + self2.shiftChildren(-start, false, -Infinity); + prevStart = 0; + } + child._end > max && child._ts && (max = child._end); + child = prev; + } + _setDuration(self2, self2 === _globalTimeline && self2._time > max ? self2._time : max, 1, 1); + self2._dirty = 0; } - if (target) { - await inst.document.update({ [target]: elem.value }); - } else if (flagTarget) { - if (elem.value === "") { - await inst.document.unsetFlag(C.SYSTEM_ID, flagTarget); - } else { - await inst.document.setFlag(C.SYSTEM_ID, flagTarget, elem.value); + return self2._tDur; + }; + Timeline2.updateRoot = function updateRoot(time) { + if (_globalTimeline._ts) { + _lazySafeRender(_globalTimeline, _parentToChildTotalTime(time, _globalTimeline)); + _lastRenderedFrame = _ticker.frame; + } + if (_ticker.frame >= _nextGCFrame) { + _nextGCFrame += _config.autoSleep || 120; + var child = _globalTimeline._first; + if (!child || !child._ts) { + if (_config.autoSleep && _ticker._listeners.length < 2) { + while (child && !child._ts) { + child = child._next; + } + child || _ticker.sleep(); + } } } - }, - onSelectChange: async (inst, event) => { - const elem = event.currentTarget; - const { action, dtype, target, flagTarget } = elem.dataset; - if (!action) { - throw new Error("Select elements require a data-action attribute."); + }; + return Timeline2; +}(Animation); +_setDefaults$1(Timeline.prototype, { + _lock: 0, + _hasPause: 0, + _forcing: 0 +}); +var _addComplexStringPropTween = function _addComplexStringPropTween2(target, prop, start, end, setter, stringFilter, funcParam) { + var pt = new PropTween$1(this._pt, target, prop, 0, 1, _renderComplexString, null, setter), index = 0, matchIndex = 0, result, startNums, color, endNum, chunk, startNum, hasRandom, a; + pt.b = start; + pt.e = end; + start += ""; + end += ""; + if (hasRandom = ~end.indexOf("random(")) { + end = _replaceRandom(end); + } + if (stringFilter) { + a = [start, end]; + stringFilter(a, target, prop); + start = a[0]; + end = a[1]; + } + startNums = start.match(_complexStringNumExp) || []; + while (result = _complexStringNumExp.exec(end)) { + endNum = result[0]; + chunk = end.substring(index, result.index); + if (color) { + color = (color + 1) % 5; + } else if (chunk.substr(-5) === "rgba(") { + color = 1; + } + if (endNum !== startNums[matchIndex++]) { + startNum = parseFloat(startNums[matchIndex - 1]) || 0; + pt._pt = { + _next: pt._pt, + p: chunk || matchIndex === 1 ? chunk : ",", + //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case. + s: startNum, + c: endNum.charAt(1) === "=" ? _parseRelative(startNum, endNum) - startNum : parseFloat(endNum) - startNum, + m: color && color < 4 ? Math.round : 0 + }; + index = _complexStringNumExp.lastIndex; + } + } + pt.c = index < end.length ? end.substring(index, end.length) : ""; + pt.fp = funcParam; + if (_relExp.test(end) || hasRandom) { + pt.e = 0; + } + this._pt = pt; + return pt; +}, _addPropTween = function _addPropTween2(target, prop, start, end, index, targets, modifier, stringFilter, funcParam, optional) { + _isFunction$1(end) && (end = end(index || 0, target, targets)); + var currentValue = target[prop], parsedStart = start !== "get" ? start : !_isFunction$1(currentValue) ? currentValue : funcParam ? target[prop.indexOf("set") || !_isFunction$1(target["get" + prop.substr(3)]) ? prop : "get" + prop.substr(3)](funcParam) : target[prop](), setter = !_isFunction$1(currentValue) ? _setterPlain : funcParam ? _setterFuncWithParam : _setterFunc, pt; + if (_isString$1(end)) { + if (~end.indexOf("random(")) { + end = _replaceRandom(end); + } + if (end.charAt(1) === "=") { + pt = _parseRelative(parsedStart, end) + (getUnit(parsedStart) || 0); + if (pt || pt === 0) { + end = pt; + } + } + } + if (!optional || parsedStart !== end || _forceAllPropTweens) { + if (!isNaN(parsedStart * end) && end !== "") { + pt = new PropTween$1(this._pt, target, prop, +parsedStart || 0, end - (parsedStart || 0), typeof currentValue === "boolean" ? _renderBoolean : _renderPlain, 0, setter); + funcParam && (pt.fp = funcParam); + modifier && pt.modifier(modifier, this, target); + return this._pt = pt; + } + !currentValue && !(prop in target) && _missingPlugin(prop, end); + return _addComplexStringPropTween.call(this, target, prop, parsedStart, end, setter, stringFilter || _config.stringFilter, funcParam); + } +}, _processVars = function _processVars2(vars, index, target, targets, tween) { + _isFunction$1(vars) && (vars = _parseFuncOrString(vars, tween, index, target, targets)); + if (!_isObject$1(vars) || vars.style && vars.nodeType || _isArray$1(vars) || _isTypedArray(vars)) { + return _isString$1(vars) ? _parseFuncOrString(vars, tween, index, target, targets) : vars; + } + var copy = {}, p; + for (p in vars) { + copy[p] = _parseFuncOrString(vars[p], tween, index, target, targets); + } + return copy; +}, _checkPlugin = function _checkPlugin2(property, vars, tween, index, target, targets) { + var plugin, pt, ptLookup, i; + if (_plugins[property] && (plugin = new _plugins[property]()).init(target, plugin.rawVars ? vars[property] : _processVars(vars[property], index, target, targets, tween), tween, index, targets) !== false) { + tween._pt = pt = new PropTween$1(tween._pt, target, property, 0, 1, plugin.render, plugin, 0, plugin.priority); + if (tween !== _quickTween) { + ptLookup = tween._ptLookup[tween._targets.indexOf(target)]; + i = plugin._props.length; + while (i--) { + ptLookup[plugin._props[i]] = pt; + } + } + } + return plugin; +}, _overwritingTween, _forceAllPropTweens, _initTween = function _initTween2(tween, time, tTime) { + var vars = tween.vars, ease = vars.ease, startAt = vars.startAt, immediateRender = vars.immediateRender, lazy = vars.lazy, onUpdate = vars.onUpdate, runBackwards = vars.runBackwards, yoyoEase = vars.yoyoEase, keyframes = vars.keyframes, autoRevert = vars.autoRevert, dur = tween._dur, prevStartAt = tween._startAt, targets = tween._targets, parent = tween.parent, fullTargets = parent && parent.data === "nested" ? parent.vars.targets : targets, autoOverwrite = tween._overwrite === "auto" && !_suppressOverwrites, tl = tween.timeline, cleanVars, i, p, pt, target, hasPriority, gsData, harness, plugin, ptLookup, index, harnessVars, overwritten; + tl && (!keyframes || !ease) && (ease = "none"); + tween._ease = _parseEase(ease, _defaults.ease); + tween._yEase = yoyoEase ? _invertEase(_parseEase(yoyoEase === true ? ease : yoyoEase, _defaults.ease)) : 0; + if (yoyoEase && tween._yoyo && !tween._repeat) { + yoyoEase = tween._yEase; + tween._yEase = tween._ease; + tween._ease = yoyoEase; + } + tween._from = !tl && !!vars.runBackwards; + if (!tl || keyframes && !vars.stagger) { + harness = targets[0] ? _getCache(targets[0]).harness : 0; + harnessVars = harness && vars[harness.prop]; + cleanVars = _copyExcluding(vars, _reservedProps); + if (prevStartAt) { + prevStartAt._zTime < 0 && prevStartAt.progress(1); + time < 0 && runBackwards && immediateRender && !autoRevert ? prevStartAt.render(-1, true) : prevStartAt.revert(runBackwards && dur ? _revertConfigNoKill : _startAtRevertConfig); + prevStartAt._lazy = 0; + } + if (startAt) { + _removeFromParent(tween._startAt = Tween.set(targets, _setDefaults$1({ + data: "isStart", + overwrite: false, + parent, + immediateRender: true, + lazy: !prevStartAt && _isNotFalse(lazy), + startAt: null, + delay: 0, + onUpdate: onUpdate && function() { + return _callback(tween, "onUpdate"); + }, + stagger: 0 + }, startAt))); + tween._startAt._dp = 0; + tween._startAt._sat = tween; + time < 0 && (_reverting$2 || !immediateRender && !autoRevert) && tween._startAt.revert(_revertConfigNoKill); + if (immediateRender) { + if (dur && time <= 0 && tTime <= 0) { + time && (tween._zTime = time); + return; + } + } + } else if (runBackwards && dur) { + if (!prevStartAt) { + time && (immediateRender = false); + p = _setDefaults$1({ + overwrite: false, + data: "isFromStart", + //we tag the tween with as "isFromStart" so that if [inside a plugin] we need to only do something at the very END of a tween, we have a way of identifying this tween as merely the one that's setting the beginning values for a "from()" tween. For example, clearProps in CSSPlugin should only get applied at the very END of a tween and without this tag, from(...{height:100, clearProps:"height", delay:1}) would wipe the height at the beginning of the tween and after 1 second, it'd kick back in. + lazy: immediateRender && !prevStartAt && _isNotFalse(lazy), + immediateRender, + //zero-duration tweens render immediately by default, but if we're not specifically instructed to render this tween immediately, we should skip this and merely _init() to record the starting values (rendering them immediately would push them to completion which is wasteful in that case - we'd have to render(-1) immediately after) + stagger: 0, + parent + //ensures that nested tweens that had a stagger are handled properly, like gsap.from(".class", {y: gsap.utils.wrap([-100,100]), stagger: 0.5}) + }, cleanVars); + harnessVars && (p[harness.prop] = harnessVars); + _removeFromParent(tween._startAt = Tween.set(targets, p)); + tween._startAt._dp = 0; + tween._startAt._sat = tween; + time < 0 && (_reverting$2 ? tween._startAt.revert(_revertConfigNoKill) : tween._startAt.render(-1, true)); + tween._zTime = time; + if (!immediateRender) { + _initTween2(tween._startAt, _tinyNum, _tinyNum); + } else if (!time) { + return; + } + } } - if (!target && !flagTarget) { - throw new Error("Select elements require a 'data-target' or 'data-flag-target' attribute."); + tween._pt = tween._ptCache = 0; + lazy = dur && _isNotFalse(lazy) || lazy && !dur; + for (i = 0; i < targets.length; i++) { + target = targets[i]; + gsData = target._gsap || _harness(targets)[i]._gsap; + tween._ptLookup[i] = ptLookup = {}; + _lazyLookup[gsData.id] && _lazyTweens.length && _lazyRender(); + index = fullTargets === targets ? i : fullTargets.indexOf(target); + if (harness && (plugin = new harness()).init(target, harnessVars || cleanVars, tween, index, fullTargets) !== false) { + tween._pt = pt = new PropTween$1(tween._pt, target, plugin.name, 0, 1, plugin.render, plugin, 0, plugin.priority); + plugin._props.forEach(function(name) { + ptLookup[name] = pt; + }); + plugin.priority && (hasPriority = 1); + } + if (!harness || harnessVars) { + for (p in cleanVars) { + if (_plugins[p] && (plugin = _checkPlugin(p, cleanVars, tween, index, target, fullTargets))) { + plugin.priority && (hasPriority = 1); + } else { + ptLookup[p] = pt = _addPropTween.call(tween, target, p, "get", cleanVars[p], index, fullTargets, 0, vars.stringFilter); + } + } + } + tween._op && tween._op[i] && tween.kill(target, tween._op[i]); + if (autoOverwrite && tween._pt) { + _overwritingTween = tween; + _globalTimeline.killTweensOf(target, ptLookup, tween.globalTime(time)); + overwritten = !tween.parent; + _overwritingTween = 0; + } + tween._pt && lazy && (_lazyLookup[gsData.id] = 1); + } + hasPriority && _sortPropTweensByPriority(tween); + tween._onInit && tween._onInit(tween); + } + tween._onUpdate = onUpdate; + tween._initted = (!tween._op || tween._pt) && !overwritten; + keyframes && time <= 0 && tl.render(_bigNum$3, true, true); +}, _updatePropTweens = function _updatePropTweens2(tween, property, value, start, startIsRelative, ratio, time, skipRecursion) { + var ptCache = (tween._pt && tween._ptCache || (tween._ptCache = {}))[property], pt, rootPT, lookup, i; + if (!ptCache) { + ptCache = tween._ptCache[property] = []; + lookup = tween._ptLookup; + i = tween._targets.length; + while (i--) { + pt = lookup[i][property]; + if (pt && pt.d && pt.d._pt) { + pt = pt.d._pt; + while (pt && pt.p !== property && pt.fp !== property) { + pt = pt._next; + } + } + if (!pt) { + _forceAllPropTweens = 1; + tween.vars[property] = "+=0"; + _initTween(tween, time); + _forceAllPropTweens = 0; + return skipRecursion ? _warn(property + " not eligible for reset") : 1; + } + ptCache.push(pt); + } + } + i = ptCache.length; + while (i--) { + rootPT = ptCache[i]; + pt = rootPT._pt || rootPT; + pt.s = (start || start === 0) && !startIsRelative ? start : pt.s + (start || 0) + ratio * pt.c; + pt.c = value - pt.s; + rootPT.e && (rootPT.e = _round$4(value) + getUnit(rootPT.e)); + rootPT.b && (rootPT.b = pt.s + getUnit(rootPT.b)); + } +}, _addAliasesToVars = function _addAliasesToVars2(targets, vars) { + var harness = targets[0] ? _getCache(targets[0]).harness : 0, propertyAliases = harness && harness.aliases, copy, p, i, aliases; + if (!propertyAliases) { + return vars; + } + copy = _merge({}, vars); + for (p in propertyAliases) { + if (p in copy) { + aliases = propertyAliases[p].split(","); + i = aliases.length; + while (i--) { + copy[aliases[i]] = copy[p]; + } + } + } + return copy; +}, _parseKeyframe = function _parseKeyframe2(prop, obj, allProps, easeEach) { + var ease = obj.ease || easeEach || "power1.inOut", p, a; + if (_isArray$1(obj)) { + a = allProps[prop] || (allProps[prop] = []); + obj.forEach(function(value, i) { + return a.push({ + t: i / (obj.length - 1) * 100, + v: value, + e: ease + }); + }); + } else { + for (p in obj) { + a = allProps[p] || (allProps[p] = []); + p === "ease" || a.push({ + t: parseFloat(prop), + v: obj[p], + e: ease + }); } - const dataType = lCase(dtype); - let value; - switch (dataType) { - case "number": - value = pFloat(elem.value); - break; - case "boolean": - value = lCase(`${elem.value}`) === "true"; - break; - case "string": - value = `${elem.value}`; - break; - default: { - if (isNumString(value)) { - throw new Error(`You must set 'data-dtype="Number"' for elements with boolean values.`); + for (i = 0; i < l; i++) { + copy = _copyExcluding(vars, _staggerPropsToSkip); + copy.stagger = 0; + yoyoEase && (copy.yoyoEase = yoyoEase); + staggerVarsToMerge && _merge(copy, staggerVarsToMerge); + curTarget = parsedTargets[i]; + copy.duration = +_parseFuncOrString(duration, _assertThisInitialized$1(_this3), i, curTarget, parsedTargets); + copy.delay = (+_parseFuncOrString(delay, _assertThisInitialized$1(_this3), i, curTarget, parsedTargets) || 0) - _this3._delay; + if (!stagger && l === 1 && copy.delay) { + _this3._delay = delay = copy.delay; + _this3._start += delay; + copy.delay = 0; + } + tl.to(curTarget, copy, staggerFunc ? staggerFunc(i, curTarget, parsedTargets) : 0); + tl._ease = _easeMap.none; + } + tl.duration() ? duration = delay = 0 : _this3.timeline = 0; + } else if (keyframes) { + _inheritDefaults(_setDefaults$1(tl.vars.defaults, { + ease: "none" + })); + tl._ease = _parseEase(keyframes.ease || vars.ease || "none"); + var time = 0, a, kf, v; + if (_isArray$1(keyframes)) { + keyframes.forEach(function(frame) { + return tl.to(parsedTargets, frame, ">"); + }); + tl.duration(); + } else { + copy = {}; + for (p in keyframes) { + p === "ease" || p === "easeEach" || _parseKeyframe(p, keyframes[p], copy, keyframes.easeEach); + } + for (p in copy) { + a = copy[p].sort(function(a2, b) { + return a2.t - b.t; + }); + time = 0; + for (i = 0; i < a.length; i++) { + kf = a[i]; + v = { + ease: kf.e, + duration: (kf.t - (i ? a[i - 1].t : 0)) / 100 * duration + }; + v[p] = kf.v; + tl.to(parsedTargets, v, time); + time += v.duration; + } + } + tl.duration() < duration && tl.to({}, { + duration: duration - tl.duration() + }); + } + } + duration || _this3.duration(duration = tl.duration()); + } else { + _this3.timeline = 0; + } + if (overwrite === true && !_suppressOverwrites) { + _overwritingTween = _assertThisInitialized$1(_this3); + _globalTimeline.killTweensOf(parsedTargets); + _overwritingTween = 0; + } + _addToTimeline(parent, _assertThisInitialized$1(_this3), position); + vars.reversed && _this3.reverse(); + vars.paused && _this3.paused(true); + if (immediateRender || !duration && !keyframes && _this3._start === _roundPrecise$1(parent._time) && _isNotFalse(immediateRender) && _hasNoPausedAncestors(_assertThisInitialized$1(_this3)) && parent.data !== "nested") { + _this3._tTime = -_tinyNum; + _this3.render(Math.max(0, -delay) || 0); + } + scrollTrigger && _scrollTrigger(_assertThisInitialized$1(_this3), scrollTrigger); + return _this3; + } + var _proto3 = Tween2.prototype; + _proto3.render = function render5(totalTime, suppressEvents, force) { + var prevTime = this._time, tDur = this._tDur, dur = this._dur, isNegative = totalTime < 0, tTime = totalTime > tDur - _tinyNum && !isNegative ? tDur : totalTime < _tinyNum ? 0 : totalTime, time, pt, iteration, cycleDuration, prevIteration, isYoyo, ratio, timeline2, yoyoEase; + if (!dur) { + _renderZeroDurationTween(this, totalTime, suppressEvents, force); + } else if (tTime !== this._tTime || !totalTime || force || !this._initted && this._tTime || this._startAt && this._zTime < 0 !== isNegative) { + time = tTime; + timeline2 = this.timeline; + if (this._repeat) { + cycleDuration = dur + this._rDelay; + if (this._repeat < -1 && isNegative) { + return this.totalTime(cycleDuration * 100 + totalTime, suppressEvents, force); + } + time = _roundPrecise$1(tTime % cycleDuration); + if (tTime === tDur) { + iteration = this._repeat; + time = dur; + } else { + iteration = ~~(tTime / cycleDuration); + if (iteration && iteration === _roundPrecise$1(tTime / cycleDuration)) { + time = dur; + iteration--; + } + time > dur && (time = dur); + } + isYoyo = this._yoyo && iteration & 1; + if (isYoyo) { + yoyoEase = this._yEase; + time = dur - time; + } + prevIteration = _animationCycle(this._tTime, cycleDuration); + if (time === prevTime && !force && this._initted && iteration === prevIteration) { + this._tTime = tTime; + return this; + } + if (iteration !== prevIteration) { + timeline2 && this._yEase && _propagateYoyoEase(timeline2, isYoyo); + if (this.vars.repeatRefresh && !isYoyo && !this._lock && this._time !== cycleDuration && this._initted) { + this._lock = force = 1; + this.render(_roundPrecise$1(cycleDuration * iteration), true).invalidate()._lock = 0; + } + } + } + if (!this._initted) { + if (_attemptInitTween(this, isNegative ? totalTime : time, force, suppressEvents, tTime)) { + this._tTime = 0; + return this; + } + if (prevTime !== this._time && !(force && this.vars.repeatRefresh && iteration !== prevIteration)) { + return this; + } + if (dur !== this._dur) { + return this.render(totalTime, suppressEvents, force); + } + } + this._tTime = tTime; + this._time = time; + if (!this._act && this._ts) { + this._act = 1; + this._lazy = 0; + } + this.ratio = ratio = (yoyoEase || this._ease)(time / dur); + if (this._from) { + this.ratio = ratio = 1 - ratio; + } + if (time && !prevTime && !suppressEvents && !iteration) { + _callback(this, "onStart"); + if (this._tTime !== tTime) { + return this; + } + } + pt = this._pt; + while (pt) { + pt.r(ratio, pt.d); + pt = pt._next; + } + timeline2 && timeline2.render(totalTime < 0 ? totalTime : timeline2._dur * timeline2._ease(time / this._dur), suppressEvents, force) || this._startAt && (this._zTime = totalTime); + if (this._onUpdate && !suppressEvents) { + isNegative && _rewindStartAt(this, totalTime, suppressEvents, force); + _callback(this, "onUpdate"); + } + this._repeat && iteration !== prevIteration && this.vars.onRepeat && !suppressEvents && this.parent && _callback(this, "onRepeat"); + if ((tTime === this._tDur || !tTime) && this._tTime === tTime) { + isNegative && !this._onUpdate && _rewindStartAt(this, totalTime, true, true); + (totalTime || !dur) && (tTime === this._tDur && this._ts > 0 || !tTime && this._ts < 0) && _removeFromParent(this, 1); + if (!suppressEvents && !(isNegative && !prevTime) && (tTime || prevTime || isYoyo)) { + _callback(this, tTime === tDur ? "onComplete" : "onReverseComplete", true); + this._prom && !(tTime < tDur && this.timeScale() > 0) && this._prom(); } - value = `${elem.value}`; - break; } } - if (target) { - await inst.document.update({ [target]: value }); - } else if (flagTarget) { - if (elem.value === "") { - await inst.document.unsetFlag(C.SYSTEM_ID, flagTarget); - } else { - await inst.document.setFlag(C.SYSTEM_ID, flagTarget, value); + return this; + }; + _proto3.targets = function targets() { + return this._targets; + }; + _proto3.invalidate = function invalidate(soft) { + (!soft || !this.vars.runBackwards) && (this._startAt = 0); + this._pt = this._op = this._onUpdate = this._lazy = this.ratio = 0; + this._ptLookup = []; + this.timeline && this.timeline.invalidate(soft); + return _Animation2.prototype.invalidate.call(this, soft); + }; + _proto3.resetTo = function resetTo(property, value, start, startIsRelative, skipRecursion) { + _tickerActive || _ticker.wake(); + this._ts || this.play(); + var time = Math.min(this._dur, (this._dp._time - this._start) * this._ts), ratio; + this._initted || _initTween(this, time); + ratio = this._ease(time / this._dur); + if (_updatePropTweens(this, property, value, start, startIsRelative, ratio, time, skipRecursion)) { + return this.resetTo(property, value, start, startIsRelative, 1); + } + _alignPlayhead(this, 0); + this.parent || _addLinkedListItem(this._dp, this, "_first", "_last", this._dp._sort ? "_start" : 0); + return this.render(0); + }; + _proto3.kill = function kill(targets, vars) { + if (vars === void 0) { + vars = "all"; + } + if (!targets && (!vars || vars === "all")) { + this._lazy = this._pt = 0; + return this.parent ? _interrupt$1(this) : this; + } + if (this.timeline) { + var tDur = this.timeline.totalDuration(); + this.timeline.killTweensOf(targets, vars, _overwritingTween && _overwritingTween.vars.overwrite !== true)._first || _interrupt$1(this); + this.parent && tDur !== this.timeline.totalDuration() && _setDuration(this, this._dur * this.timeline._tDur / tDur, 0, 1); + return this; + } + var parsedTargets = this._targets, killingTargets = targets ? toArray$1(targets) : parsedTargets, propTweenLookup = this._ptLookup, firstPT = this._pt, overwrittenProps, curLookup, curOverwriteProps, props, p, pt, i; + if ((!vars || vars === "all") && _arraysMatch(parsedTargets, killingTargets)) { + vars === "all" && (this._pt = 0); + return _interrupt$1(this); + } + overwrittenProps = this._op = this._op || []; + if (vars !== "all") { + if (_isString$1(vars)) { + p = {}; + _forEachName(vars, function(name) { + return p[name] = 1; + }); + vars = p; + } + vars = _addAliasesToVars(parsedTargets, vars); + } + i = parsedTargets.length; + while (i--) { + if (~killingTargets.indexOf(parsedTargets[i])) { + curLookup = propTweenLookup[i]; + if (vars === "all") { + overwrittenProps[i] = vars; + props = curLookup; + curOverwriteProps = {}; + } else { + curOverwriteProps = overwrittenProps[i] = overwrittenProps[i] || {}; + props = vars; + } + for (p in props) { + pt = curLookup && curLookup[p]; + if (pt) { + if (!("kill" in pt.d) || pt.d.kill(p) === true) { + _removeLinkedListItem(this, pt, "_pt"); + } + delete curLookup[p]; + } + if (curOverwriteProps !== "all") { + curOverwriteProps[p] = 1; + } + } } } + this._initted && !this._pt && firstPT && _interrupt$1(this); + return this; + }; + Tween2.to = function to(targets, vars) { + return new Tween2(targets, vars, arguments[2]); + }; + Tween2.from = function from(targets, vars) { + return _createTweenType(1, arguments); + }; + Tween2.delayedCall = function delayedCall(delay, callback, params, scope) { + return new Tween2(callback, 0, { + immediateRender: false, + lazy: false, + overwrite: false, + delay, + onComplete: callback, + onReverseComplete: callback, + onCompleteParams: params, + onReverseCompleteParams: params, + callbackScope: scope + }); + }; + Tween2.fromTo = function fromTo(targets, fromVars, toVars) { + return _createTweenType(2, arguments); + }; + Tween2.set = function set2(targets, vars) { + vars.duration = 0; + vars.repeatDelay || (vars.repeat = 0); + return new Tween2(targets, vars); + }; + Tween2.killTweensOf = function killTweensOf(targets, props, onlyActive) { + return _globalTimeline.killTweensOf(targets, props, onlyActive); + }; + return Tween2; +}(Animation); +_setDefaults$1(Tween.prototype, { + _targets: [], + _lazy: 0, + _startAt: 0, + _op: 0, + _onInit: 0 +}); +_forEachName("staggerTo,staggerFrom,staggerFromTo", function(name) { + Tween[name] = function() { + var tl = new Timeline(), params = _slice.call(arguments, 0); + params.splice(name === "staggerFromTo" ? 5 : 4, 0, 0); + return tl[name].apply(tl, params); + }; +}); +var _setterPlain = function _setterPlain2(target, property, value) { + return target[property] = value; +}, _setterFunc = function _setterFunc2(target, property, value) { + return target[property](value); +}, _setterFuncWithParam = function _setterFuncWithParam2(target, property, value, data) { + return target[property](data.fp, value); +}, _setterAttribute = function _setterAttribute2(target, property, value) { + return target.setAttribute(property, value); +}, _getSetter = function _getSetter2(target, property) { + return _isFunction$1(target[property]) ? _setterFunc : _isUndefined$2(target[property]) && target.setAttribute ? _setterAttribute : _setterPlain; +}, _renderPlain = function _renderPlain2(ratio, data) { + return data.set(data.t, data.p, Math.round((data.s + data.c * ratio) * 1e6) / 1e6, data); +}, _renderBoolean = function _renderBoolean2(ratio, data) { + return data.set(data.t, data.p, !!(data.s + data.c * ratio), data); +}, _renderComplexString = function _renderComplexString2(ratio, data) { + var pt = data._pt, s = ""; + if (!ratio && data.b) { + s = data.b; + } else if (ratio === 1 && data.e) { + s = data.e; + } else { + while (pt) { + s = pt.p + (pt.m ? pt.m(pt.s + pt.c * ratio) : Math.round((pt.s + pt.c * ratio) * 1e4) / 1e4) + s; + pt = pt._next; + } + s += data.c; + } + data.set(data.t, data.p, s, data); +}, _renderPropTweens = function _renderPropTweens2(ratio, data) { + var pt = data._pt; + while (pt) { + pt.r(ratio, pt.d); + pt = pt._next; + } +}, _addPluginModifier = function _addPluginModifier2(modifier, tween, target, property) { + var pt = this._pt, next; + while (pt) { + next = pt._next; + pt.p === property && pt.modifier(modifier, tween, target); + pt = next; + } +}, _killPropTweensOf = function _killPropTweensOf2(property) { + var pt = this._pt, hasNonDependentRemaining, next; + while (pt) { + next = pt._next; + if (pt.p === property && !pt.op || pt.op === property) { + _removeLinkedListItem(this, pt, "_pt"); + } else if (!pt.dep) { + hasNonDependentRemaining = 1; + } + pt = next; + } + return !hasNonDependentRemaining; +}, _setterWithModifier = function _setterWithModifier2(target, property, value, data) { + data.mSet(target, property, data.m.call(data.tween, value, data.mt), data); +}, _sortPropTweensByPriority = function _sortPropTweensByPriority2(parent) { + var pt = parent._pt, next, pt2, first, last; + while (pt) { + next = pt._next; + pt2 = first; + while (pt2 && pt2.pr > pt.pr) { + pt2 = pt2._next; + } + if (pt._prev = pt2 ? pt2._prev : last) { + pt._prev._next = pt; + } else { + first = pt; + } + if (pt._next = pt2) { + pt2._prev = pt; + } else { + last = pt; + } + pt = next; } + parent._pt = first; }; -const isDocID = (ref) => { - return typeof ref === "string" && /^[A-Za-z0-9]{16}$/.test(ref); -}; -const isDocUUID = (ref) => { - if (typeof ref !== "string") { - return false; - } - const [docName, docID] = ref.split(/\./); - if (!isDocID(docID)) { - return false; +var PropTween$1 = /* @__PURE__ */ function() { + function PropTween2(next, target, prop, start, change, renderer, data, setter, priority) { + this.t = target; + this.s = start; + this.c = change; + this.p = prop; + this.r = renderer || _renderPlain; + this.d = data || this; + this.set = setter || _setterPlain; + this.pr = priority || 0; + this._next = next; + if (next) { + next._prev = this; + } + } + var _proto4 = PropTween2.prototype; + _proto4.modifier = function modifier(func, tween, target) { + this.mSet = this.mSet || this.set; + this.set = _setterWithModifier; + this.m = func; + this.mt = target; + this.tween = tween; + }; + return PropTween2; +}(); +_forEachName(_callbackNames + "parent,duration,ease,delay,overwrite,runBackwards,startAt,yoyo,immediateRender,repeat,repeatDelay,data,paused,reversed,lazy,callbackScope,stringFilter,id,yoyoEase,stagger,inherit,repeatRefresh,keyframes,autoRevert,scrollTrigger", function(name) { + return _reservedProps[name] = 1; +}); +_globals.TweenMax = _globals.TweenLite = Tween; +_globals.TimelineLite = _globals.TimelineMax = Timeline; +_globalTimeline = new Timeline({ + sortChildren: false, + defaults: _defaults, + autoRemoveChildren: true, + id: "root", + smoothChildTiming: true +}); +_config.stringFilter = _colorStringFilter; +var _media = [], _listeners = {}, _emptyArray = [], _lastMediaTime = 0, _contextID = 0, _dispatch = function _dispatch2(type) { + return (_listeners[type] || _emptyArray).map(function(f) { + return f(); + }); +}, _onMediaChange = function _onMediaChange2() { + var time = Date.now(), matches = []; + if (time - _lastMediaTime > 2) { + _dispatch("matchMediaInit"); + _media.forEach(function(c) { + var queries = c.queries, conditions = c.conditions, match, p, anyMatch, toggled; + for (p in queries) { + match = _win$4.matchMedia(queries[p]).matches; + match && (anyMatch = 1); + if (match !== conditions[p]) { + conditions[p] = match; + toggled = 1; + } + } + if (toggled) { + c.revert(); + anyMatch && matches.push(c); + } + }); + _dispatch("matchMediaRevert"); + matches.forEach(function(c) { + return c.onMatch(c, function(func) { + return c.add(null, func); + }); + }); + _lastMediaTime = time; + _dispatch("matchMedia"); } - return game.collections.has(docName); }; -const isDotKey = (ref) => { - return typeof ref === "string"; +var Context = /* @__PURE__ */ function() { + function Context2(func, scope) { + this.selector = scope && selector(scope); + this.data = []; + this._r = []; + this.isReverted = false; + this.id = _contextID++; + func && this.add(func); + } + var _proto5 = Context2.prototype; + _proto5.add = function add(name, func, scope) { + if (_isFunction$1(name)) { + scope = func; + func = name; + name = _isFunction$1; + } + var self2 = this, f = function f2() { + var prev = _context$2, prevSelector = self2.selector, result; + prev && prev !== self2 && prev.data.push(self2); + scope && (self2.selector = selector(scope)); + _context$2 = self2; + result = func.apply(self2, arguments); + _isFunction$1(result) && self2._r.push(result); + _context$2 = prev; + self2.selector = prevSelector; + self2.isReverted = false; + return result; + }; + self2.last = f; + return name === _isFunction$1 ? f(self2, function(func2) { + return self2.add(null, func2); + }) : name ? self2[name] = f : f; + }; + _proto5.ignore = function ignore(func) { + var prev = _context$2; + _context$2 = null; + func(this); + _context$2 = prev; + }; + _proto5.getTweens = function getTweens() { + var a = []; + this.data.forEach(function(e) { + return e instanceof Context2 ? a.push.apply(a, e.getTweens()) : e instanceof Tween && !(e.parent && e.parent.data === "nested") && a.push(e); + }); + return a; + }; + _proto5.clear = function clear() { + this._r.length = this.data.length = 0; + }; + _proto5.kill = function kill(revert, matchMedia2) { + var _this4 = this; + if (revert) { + (function() { + var tweens = _this4.getTweens(), i2 = _this4.data.length, t; + while (i2--) { + t = _this4.data[i2]; + if (t.data === "isFlip") { + t.revert(); + t.getChildren(true, true, false).forEach(function(tween) { + return tweens.splice(tweens.indexOf(tween), 1); + }); + } + } + tweens.map(function(t2) { + return { + g: t2._dur || t2._delay || t2._sat && !t2._sat.vars.immediateRender ? t2.globalTime(0) : -Infinity, + t: t2 + }; + }).sort(function(a, b) { + return b.g - a.g || -Infinity; + }).forEach(function(o) { + return o.t.revert(revert); + }); + i2 = _this4.data.length; + while (i2--) { + t = _this4.data[i2]; + if (t instanceof Timeline) { + if (t.data !== "nested") { + t.scrollTrigger && t.scrollTrigger.revert(); + t.kill(); + } + } else { + !(t instanceof Tween) && t.revert && t.revert(revert); + } + } + _this4._r.forEach(function(f) { + return f(revert, _this4); + }); + _this4.isReverted = true; + })(); + } else { + this.data.forEach(function(e) { + return e.kill && e.kill(); + }); + } + this.clear(); + if (matchMedia2) { + var i = _media.length; + while (i--) { + _media[i].id === this.id && _media.splice(i, 1); + } + } + }; + _proto5.revert = function revert(config3) { + this.kill(config3 || {}); + }; + return Context2; +}(); +var MatchMedia = /* @__PURE__ */ function() { + function MatchMedia2(scope) { + this.contexts = []; + this.scope = scope; + _context$2 && _context$2.data.push(this); + } + var _proto6 = MatchMedia2.prototype; + _proto6.add = function add(conditions, func, scope) { + _isObject$1(conditions) || (conditions = { + matches: conditions + }); + var context3 = new Context(0, scope || this.scope), cond = context3.conditions = {}, mq, p, active; + _context$2 && !context3.selector && (context3.selector = _context$2.selector); + this.contexts.push(context3); + func = context3.add("onMatch", func); + context3.queries = conditions; + for (p in conditions) { + if (p === "all") { + active = 1; + } else { + mq = _win$4.matchMedia(conditions[p]); + if (mq) { + _media.indexOf(context3) < 0 && _media.push(context3); + (cond[p] = mq.matches) && (active = 1); + mq.addListener ? mq.addListener(_onMediaChange) : mq.addEventListener("change", _onMediaChange); + } + } + } + active && func(context3, function(f) { + return context3.add(null, f); + }); + return this; + }; + _proto6.revert = function revert(config3) { + this.kill(config3 || {}); + }; + _proto6.kill = function kill(revert) { + this.contexts.forEach(function(c) { + return c.kill(revert, true); + }); + }; + return MatchMedia2; +}(); +var _gsap = { + registerPlugin: function registerPlugin() { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + args.forEach(function(config3) { + return _createPlugin(config3); + }); + }, + timeline: function timeline(vars) { + return new Timeline(vars); + }, + getTweensOf: function getTweensOf(targets, onlyActive) { + return _globalTimeline.getTweensOf(targets, onlyActive); + }, + getProperty: function getProperty2(target, property, unit, uncache) { + _isString$1(target) && (target = toArray$1(target)[0]); + var getter = _getCache(target || {}).get, format = unit ? _passThrough : _numericIfPossible; + unit === "native" && (unit = ""); + return !target ? target : !property ? function(property2, unit2, uncache2) { + return format((_plugins[property2] && _plugins[property2].get || getter)(target, property2, unit2, uncache2)); + } : format((_plugins[property] && _plugins[property].get || getter)(target, property, unit, uncache)); + }, + quickSetter: function quickSetter(target, property, unit) { + target = toArray$1(target); + if (target.length > 1) { + var setters = target.map(function(t) { + return gsap$6.quickSetter(t, property, unit); + }), l = setters.length; + return function(value) { + var i = l; + while (i--) { + setters[i](value); + } + }; + } + target = target[0] || {}; + var Plugin = _plugins[property], cache = _getCache(target), p = cache.harness && (cache.harness.aliases || {})[property] || property, setter = Plugin ? function(value) { + var p2 = new Plugin(); + _quickTween._pt = 0; + p2.init(target, unit ? value + unit : value, _quickTween, 0, [target]); + p2.render(1, p2); + _quickTween._pt && _renderPropTweens(1, _quickTween); + } : cache.set(target, p); + return Plugin ? setter : function(value) { + return setter(target, p, unit ? value + unit : value, cache, 1); + }; + }, + quickTo: function quickTo(target, property, vars) { + var _merge22; + var tween = gsap$6.to(target, _merge((_merge22 = {}, _merge22[property] = "+=0.1", _merge22.paused = true, _merge22), vars || {})), func = function func2(value, start, startIsRelative) { + return tween.resetTo(property, value, start, startIsRelative); + }; + func.tween = tween; + return func; + }, + isTweening: function isTweening(targets) { + return _globalTimeline.getTweensOf(targets, true).length > 0; + }, + defaults: function defaults(value) { + value && value.ease && (value.ease = _parseEase(value.ease, _defaults.ease)); + return _mergeDeep(_defaults, value || {}); + }, + config: function config2(value) { + return _mergeDeep(_config, value || {}); + }, + registerEffect: function registerEffect(_ref3) { + var name = _ref3.name, effect = _ref3.effect, plugins = _ref3.plugins, defaults2 = _ref3.defaults, extendTimeline = _ref3.extendTimeline; + (plugins || "").split(",").forEach(function(pluginName) { + return pluginName && !_plugins[pluginName] && !_globals[pluginName] && _warn(name + " effect requires " + pluginName + " plugin."); + }); + _effects[name] = function(targets, vars, tl) { + return effect(toArray$1(targets), _setDefaults$1(vars || {}, defaults2), tl); + }; + if (extendTimeline) { + Timeline.prototype[name] = function(targets, vars, position) { + return this.add(_effects[name](targets, _isObject$1(vars) ? vars : (position = vars) && {}, this), position); + }; + } + }, + registerEase: function registerEase(name, ease) { + _easeMap[name] = _parseEase(ease); + }, + parseEase: function parseEase(ease, defaultEase) { + return arguments.length ? _parseEase(ease, defaultEase) : _easeMap; + }, + getById: function getById(id) { + return _globalTimeline.getById(id); + }, + exportRoot: function exportRoot(vars, includeDelayedCalls) { + if (vars === void 0) { + vars = {}; + } + var tl = new Timeline(vars), child, next; + tl.smoothChildTiming = _isNotFalse(vars.smoothChildTiming); + _globalTimeline.remove(tl); + tl._dp = 0; + tl._time = tl._tTime = _globalTimeline._time; + child = _globalTimeline._first; + while (child) { + next = child._next; + if (includeDelayedCalls || !(!child._dur && child instanceof Tween && child.vars.onComplete === child._targets[0])) { + _addToTimeline(tl, child, child._start - child._delay); + } + child = next; + } + _addToTimeline(_globalTimeline, tl, 0); + return tl; + }, + context: function context(func, scope) { + return func ? new Context(func, scope) : _context$2; + }, + matchMedia: function matchMedia(scope) { + return new MatchMedia(scope); + }, + matchMediaRefresh: function matchMediaRefresh() { + return _media.forEach(function(c) { + var cond = c.conditions, found, p; + for (p in cond) { + if (cond[p]) { + cond[p] = false; + found = 1; + } + } + found && c.revert(); + }) || _onMediaChange(); + }, + addEventListener: function addEventListener(type, callback) { + var a = _listeners[type] || (_listeners[type] = []); + ~a.indexOf(callback) || a.push(callback); + }, + removeEventListener: function removeEventListener(type, callback) { + var a = _listeners[type], i = a && a.indexOf(callback); + i >= 0 && a.splice(i, 1); + }, + utils: { + wrap, + wrapYoyo, + distribute, + random, + snap, + normalize, + getUnit, + clamp, + splitColor, + toArray: toArray$1, + selector, + mapRange, + pipe, + unitize, + interpolate, + shuffle: shuffle$1 + }, + install: _install, + effects: _effects, + ticker: _ticker, + updateRoot: Timeline.updateRoot, + plugins: _plugins, + globalTimeline: _globalTimeline, + core: { + PropTween: PropTween$1, + globals: _addGlobal, + Tween, + Timeline, + Animation, + getCache: _getCache, + _removeLinkedListItem, + reverting: function reverting() { + return _reverting$2; + }, + context: function context2(toAdd) { + if (toAdd && _context$2) { + _context$2.data.push(toAdd); + toAdd._ctx = _context$2; + } + return _context$2; + }, + suppressOverwrites: function suppressOverwrites(value) { + return _suppressOverwrites = value; + } + } }; -const isTargetKey = (ref) => { - if (!isDotKey(ref)) { - return false; +_forEachName("to,from,fromTo,delayedCall,set,killTweensOf", function(name) { + return _gsap[name] = Tween[name]; +}); +_ticker.add(Timeline.updateRoot); +_quickTween = _gsap.to({}, { + duration: 0 +}); +var _getPluginPropTween = function _getPluginPropTween2(plugin, prop) { + var pt = plugin._pt; + while (pt && pt.p !== prop && pt.op !== prop && pt.fp !== prop) { + pt = pt._next; + } + return pt; +}, _addModifiers = function _addModifiers2(tween, modifiers) { + var targets = tween._targets, p, i, pt; + for (p in modifiers) { + i = targets.length; + while (i--) { + pt = tween._ptLookup[i][p]; + if (pt && (pt = pt.d)) { + if (pt._pt) { + pt = _getPluginPropTween(pt, p); + } + pt && pt.modifier && pt.modifier(modifiers[p], tween, targets[i], p); + } + } } - if (["name", "img", "id", "_id"].includes(ref)) { - return true; +}, _buildModifierPlugin = function _buildModifierPlugin2(name, modifier) { + return { + name, + rawVars: 1, + //don't pre-process function-based values or "random()" strings. + init: function init6(target, vars, tween) { + tween._onInit = function(tween2) { + var temp, p; + if (_isString$1(vars)) { + temp = {}; + _forEachName(vars, function(name2) { + return temp[name2] = 1; + }); + vars = temp; + } + if (modifier) { + temp = {}; + for (p in vars) { + temp[p] = modifier(vars[p]); + } + vars = temp; + } + _addModifiers(tween2, vars); + }; + } + }; +}; +var gsap$6 = _gsap.registerPlugin({ + name: "attr", + init: function init(target, vars, tween, index, targets) { + var p, pt, v; + this.tween = tween; + for (p in vars) { + v = target.getAttribute(p) || ""; + pt = this.add(target, "setAttribute", (v || 0) + "", vars[p], index, targets, 0, 0, p); + pt.op = p; + pt.b = v; + this._props.push(p); + } + }, + render: function render(ratio, data) { + var pt = data._pt; + while (pt) { + _reverting$2 ? pt.set(pt.t, pt.p, pt.b, pt) : pt.r(ratio, pt.d); + pt = pt._next; + } } - if (ref.startsWith("system")) { - return true; +}, { + name: "endArray", + init: function init2(target, value) { + var i = value.length; + while (i--) { + this.add(target, i, target[i] || 0, value[i], 0, 0, 0, 0, 0, 1); + } + } +}, _buildModifierPlugin("roundProps", _roundModifier), _buildModifierPlugin("modifiers"), _buildModifierPlugin("snap", snap)) || _gsap; +Tween.version = Timeline.version = gsap$6.version = "3.12.5"; +_coreReady = 1; +_windowExists$2() && _wake(); +_easeMap.Power0; +_easeMap.Power1; +_easeMap.Power2; +_easeMap.Power3; +_easeMap.Power4; +_easeMap.Linear; +_easeMap.Quad; +_easeMap.Cubic; +_easeMap.Quart; +_easeMap.Quint; +_easeMap.Strong; +_easeMap.Elastic; +_easeMap.Back; +_easeMap.SteppedEase; +_easeMap.Bounce; +_easeMap.Sine; +_easeMap.Expo; +_easeMap.Circ; +/*! + * CSSPlugin 3.12.5 + * https://gsap.com + * + * Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _win$3, _doc$3, _docElement$2, _pluginInitted, _tempDiv$2, _recentSetterPlugin, _reverting$1, _windowExists$1 = function _windowExists2() { + return typeof window !== "undefined"; +}, _transformProps = {}, _RAD2DEG$3 = 180 / Math.PI, _DEG2RAD$3 = Math.PI / 180, _atan2$1 = Math.atan2, _bigNum$2 = 1e8, _capsExp = /([A-Z])/g, _horizontalExp = /(left|right|width|margin|padding|x)/i, _complexExp = /[\s,\(]\S/, _propertyAliases = { + autoAlpha: "opacity,visibility", + scale: "scaleX,scaleY", + alpha: "opacity" +}, _renderCSSProp = function _renderCSSProp2(ratio, data) { + return data.set(data.t, data.p, Math.round((data.s + data.c * ratio) * 1e4) / 1e4 + data.u, data); +}, _renderPropWithEnd = function _renderPropWithEnd2(ratio, data) { + return data.set(data.t, data.p, ratio === 1 ? data.e : Math.round((data.s + data.c * ratio) * 1e4) / 1e4 + data.u, data); +}, _renderCSSPropWithBeginning = function _renderCSSPropWithBeginning2(ratio, data) { + return data.set(data.t, data.p, ratio ? Math.round((data.s + data.c * ratio) * 1e4) / 1e4 + data.u : data.b, data); +}, _renderRoundedCSSProp = function _renderRoundedCSSProp2(ratio, data) { + var value = data.s + data.c * ratio; + data.set(data.t, data.p, ~~(value + (value < 0 ? -0.5 : 0.5)) + data.u, data); +}, _renderNonTweeningValue = function _renderNonTweeningValue2(ratio, data) { + return data.set(data.t, data.p, ratio ? data.e : data.b, data); +}, _renderNonTweeningValueOnlyAtEnd = function _renderNonTweeningValueOnlyAtEnd2(ratio, data) { + return data.set(data.t, data.p, ratio !== 1 ? data.b : data.e, data); +}, _setterCSSStyle = function _setterCSSStyle2(target, property, value) { + return target.style[property] = value; +}, _setterCSSProp = function _setterCSSProp2(target, property, value) { + return target.style.setProperty(property, value); +}, _setterTransform = function _setterTransform2(target, property, value) { + return target._gsap[property] = value; +}, _setterScale = function _setterScale2(target, property, value) { + return target._gsap.scaleX = target._gsap.scaleY = value; +}, _setterScaleWithRender = function _setterScaleWithRender2(target, property, value, data, ratio) { + var cache = target._gsap; + cache.scaleX = cache.scaleY = value; + cache.renderTransform(ratio, cache); +}, _setterTransformWithRender = function _setterTransformWithRender2(target, property, value, data, ratio) { + var cache = target._gsap; + cache[property] = value; + cache.renderTransform(ratio, cache); +}, _transformProp$2 = "transform", _transformOriginProp$2 = _transformProp$2 + "Origin", _saveStyle = function _saveStyle2(property, isNotCSS) { + var _this = this; + var target = this.target, style = target.style, cache = target._gsap; + if (property in _transformProps && style) { + this.tfm = this.tfm || {}; + if (property !== "transform") { + property = _propertyAliases[property] || property; + ~property.indexOf(",") ? property.split(",").forEach(function(a) { + return _this.tfm[a] = _get(target, a); + }) : this.tfm[property] = cache.x ? cache[property] : _get(target, property); + property === _transformOriginProp$2 && (this.tfm.zOrigin = cache.zOrigin); + } else { + return _propertyAliases.transform.split(",").forEach(function(p) { + return _saveStyle2.call(_this, p, isNotCSS); + }); + } + if (this.props.indexOf(_transformProp$2) >= 0) { + return; + } + if (cache.svg) { + this.svgo = target.getAttribute("data-svg-origin"); + this.props.push(_transformOriginProp$2, isNotCSS, ""); + } + property = _transformProp$2; + } + (style || isNotCSS) && this.props.push(property, isNotCSS, style[property]); +}, _removeIndependentTransforms = function _removeIndependentTransforms2(style) { + if (style.translate) { + style.removeProperty("translate"); + style.removeProperty("scale"); + style.removeProperty("rotate"); + } +}, _revertStyle = function _revertStyle2() { + var props = this.props, target = this.target, style = target.style, cache = target._gsap, i, p; + for (i = 0; i < props.length; i += 3) { + props[i + 1] ? target[props[i]] = props[i + 2] : props[i + 2] ? style[props[i]] = props[i + 2] : style.removeProperty(props[i].substr(0, 2) === "--" ? props[i] : props[i].replace(_capsExp, "-$1").toLowerCase()); + } + if (this.tfm) { + for (p in this.tfm) { + cache[p] = this.tfm[p]; + } + if (cache.svg) { + cache.renderTransform(); + target.setAttribute("data-svg-origin", this.svgo || ""); + } + i = _reverting$1(); + if ((!i || !i.isStart) && !style[_transformProp$2]) { + _removeIndependentTransforms(style); + if (cache.zOrigin && style[_transformOriginProp$2]) { + style[_transformOriginProp$2] += " " + cache.zOrigin + "px"; + cache.zOrigin = 0; + cache.renderTransform(); + } + cache.uncache = 1; + } + } +}, _getStyleSaver$3 = function _getStyleSaver(target, properties) { + var saver = { + target, + props: [], + revert: _revertStyle, + save: _saveStyle + }; + target._gsap || gsap$6.core.getCache(target); + properties && properties.split(",").forEach(function(p) { + return saver.save(p); + }); + return saver; +}, _supports3D$1, _createElement$1 = function _createElement(type, ns) { + var e = _doc$3.createElementNS ? _doc$3.createElementNS((ns || "http://www.w3.org/1999/xhtml").replace(/^https/, "http"), type) : _doc$3.createElement(type); + return e && e.style ? e : _doc$3.createElement(type); +}, _getComputedProperty = function _getComputedProperty2(target, property, skipPrefixFallback) { + var cs = getComputedStyle(target); + return cs[property] || cs.getPropertyValue(property.replace(_capsExp, "-$1").toLowerCase()) || cs.getPropertyValue(property) || !skipPrefixFallback && _getComputedProperty2(target, _checkPropPrefix(property) || property, 1) || ""; +}, _prefixes = "O,Moz,ms,Ms,Webkit".split(","), _checkPropPrefix = function _checkPropPrefix2(property, element, preferPrefix) { + var e = element || _tempDiv$2, s = e.style, i = 5; + if (property in s && !preferPrefix) { + return property; + } + property = property.charAt(0).toUpperCase() + property.substr(1); + while (i-- && !(_prefixes[i] + property in s)) { + } + return i < 0 ? null : (i === 3 ? "ms" : i >= 0 ? _prefixes[i] : "") + property; +}, _initCore$3 = function _initCore() { + if (_windowExists$1() && window.document) { + _win$3 = window; + _doc$3 = _win$3.document; + _docElement$2 = _doc$3.documentElement; + _tempDiv$2 = _createElement$1("div") || { + style: {} + }; + _createElement$1("div"); + _transformProp$2 = _checkPropPrefix(_transformProp$2); + _transformOriginProp$2 = _transformProp$2 + "Origin"; + _tempDiv$2.style.cssText = "border-width:0;line-height:0;position:absolute;padding:0"; + _supports3D$1 = !!_checkPropPrefix("perspective"); + _reverting$1 = gsap$6.core.reverting; + _pluginInitted = 1; + } +}, _getBBoxHack = function _getBBoxHack2(swapIfPossible) { + var svg = _createElement$1("svg", this.ownerSVGElement && this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"), oldParent = this.parentNode, oldSibling = this.nextSibling, oldCSS = this.style.cssText, bbox; + _docElement$2.appendChild(svg); + svg.appendChild(this); + this.style.display = "block"; + if (swapIfPossible) { + try { + bbox = this.getBBox(); + this._gsapBBox = this.getBBox; + this.getBBox = _getBBoxHack2; + } catch (e) { + } + } else if (this._gsapBBox) { + bbox = this._gsapBBox(); } - if (ref.startsWith("flag")) { - return true; + if (oldParent) { + if (oldSibling) { + oldParent.insertBefore(this, oldSibling); + } else { + oldParent.appendChild(this); + } } - return false; -}; -const isTargetFlagKey = (ref) => { - if (!isDotKey(ref)) { - return false; + _docElement$2.removeChild(svg); + this.style.cssText = oldCSS; + return bbox; +}, _getAttributeFallbacks = function _getAttributeFallbacks2(target, attributesArray) { + var i = attributesArray.length; + while (i--) { + if (target.hasAttribute(attributesArray[i])) { + return target.getAttribute(attributesArray[i]); + } } - if (isTargetKey(ref)) { - return false; +}, _getBBox = function _getBBox2(target) { + var bounds; + try { + bounds = target.getBBox(); + } catch (error) { + bounds = _getBBoxHack.call(target, true); + } + bounds && (bounds.width || bounds.height) || target.getBBox === _getBBoxHack || (bounds = _getBBoxHack.call(target, true)); + return bounds && !bounds.width && !bounds.x && !bounds.y ? { + x: +_getAttributeFallbacks(target, ["x", "cx", "x1"]) || 0, + y: +_getAttributeFallbacks(target, ["y", "cy", "y1"]) || 0, + width: 0, + height: 0 + } : bounds; +}, _isSVG = function _isSVG2(e) { + return !!(e.getCTM && (!e.parentNode || e.ownerSVGElement) && _getBBox(e)); +}, _removeProperty = function _removeProperty2(target, property) { + if (property) { + var style = target.style, first2Chars; + if (property in _transformProps && property !== _transformOriginProp$2) { + property = _transformProp$2; + } + if (style.removeProperty) { + first2Chars = property.substr(0, 2); + if (first2Chars === "ms" || property.substr(0, 6) === "webkit") { + property = "-" + property; + } + style.removeProperty(first2Chars === "--" ? property : property.replace(_capsExp, "-$1").toLowerCase()); + } else { + style.removeAttribute(property); + } + } +}, _addNonTweeningPT = function _addNonTweeningPT2(plugin, target, property, beginning, end, onlySetAtEnd) { + var pt = new PropTween$1(plugin._pt, target, property, 0, 1, onlySetAtEnd ? _renderNonTweeningValueOnlyAtEnd : _renderNonTweeningValue); + plugin._pt = pt; + pt.b = beginning; + pt.e = end; + plugin._props.push(property); + return pt; +}, _nonConvertibleUnits = { + deg: 1, + rad: 1, + turn: 1 +}, _nonStandardLayouts = { + grid: 1, + flex: 1 +}, _convertToUnit = function _convertToUnit2(target, property, value, unit) { + var curValue = parseFloat(value) || 0, curUnit = (value + "").trim().substr((curValue + "").length) || "px", style = _tempDiv$2.style, horizontal = _horizontalExp.test(property), isRootSVG = target.tagName.toLowerCase() === "svg", measureProperty = (isRootSVG ? "client" : "offset") + (horizontal ? "Width" : "Height"), amount = 100, toPixels = unit === "px", toPercent = unit === "%", px, parent, cache, isSVG; + if (unit === curUnit || !curValue || _nonConvertibleUnits[unit] || _nonConvertibleUnits[curUnit]) { + return curValue; + } + curUnit !== "px" && !toPixels && (curValue = _convertToUnit2(target, property, value, "px")); + isSVG = target.getCTM && _isSVG(target); + if ((toPercent || curUnit === "%") && (_transformProps[property] || ~property.indexOf("adius"))) { + px = isSVG ? target.getBBox()[horizontal ? "width" : "height"] : target[measureProperty]; + return _round$4(toPercent ? curValue / px * amount : curValue / 100 * px); + } + style[horizontal ? "width" : "height"] = amount + (toPixels ? curUnit : unit); + parent = ~property.indexOf("adius") || unit === "em" && target.appendChild && !isRootSVG ? target : target.parentNode; + if (isSVG) { + parent = (target.ownerSVGElement || {}).parentNode; + } + if (!parent || parent === _doc$3 || !parent.appendChild) { + parent = _doc$3.body; + } + cache = parent._gsap; + if (cache && toPercent && cache.width && horizontal && cache.time === _ticker.time && !cache.uncache) { + return _round$4(curValue / cache.width * amount); + } else { + if (toPercent && (property === "height" || property === "width")) { + var v = target.style[property]; + target.style[property] = amount + unit; + px = target[measureProperty]; + v ? target.style[property] = v : _removeProperty(target, property); + } else { + (toPercent || curUnit === "%") && !_nonStandardLayouts[_getComputedProperty(parent, "display")] && (style.position = _getComputedProperty(target, "position")); + parent === target && (style.position = "static"); + parent.appendChild(_tempDiv$2); + px = _tempDiv$2[measureProperty]; + parent.removeChild(_tempDiv$2); + style.position = "absolute"; + } + if (horizontal && toPercent) { + cache = _getCache(parent); + cache.time = _ticker.time; + cache.width = parent[measureProperty]; + } + } + return _round$4(toPixels ? px * curValue / amount : px && curValue ? amount / px * curValue : 0); +}, _get = function _get2(target, property, unit, uncache) { + var value; + _pluginInitted || _initCore$3(); + if (property in _propertyAliases && property !== "transform") { + property = _propertyAliases[property]; + if (~property.indexOf(",")) { + property = property.split(",")[0]; + } + } + if (_transformProps[property] && property !== "transform") { + value = _parseTransform(target, uncache); + value = property !== "transformOrigin" ? value[property] : value.svg ? value.origin : _firstTwoOnly(_getComputedProperty(target, _transformOriginProp$2)) + " " + value.zOrigin + "px"; + } else { + value = target.style[property]; + if (!value || value === "auto" || uncache || ~(value + "").indexOf("calc(")) { + value = _specialProps[property] && _specialProps[property](target, property, unit) || _getComputedProperty(target, property) || _getProperty(target, property) || (property === "opacity" ? 1 : 0); + } + } + return unit && !~(value + "").trim().indexOf(" ") ? _convertToUnit(target, property, value, unit) + unit : value; +}, _tweenComplexCSSString = function _tweenComplexCSSString2(target, prop, start, end) { + if (!start || start === "none") { + var p = _checkPropPrefix(prop, target, 1), s = p && _getComputedProperty(target, p, 1); + if (s && s !== start) { + prop = p; + start = s; + } else if (prop === "borderColor") { + start = _getComputedProperty(target, "borderTopColor"); + } + } + var pt = new PropTween$1(this._pt, target.style, prop, 0, 1, _renderComplexString), index = 0, matchIndex = 0, a, result, startValues, startNum, color, startValue, endValue, endNum, chunk, endUnit, startUnit, endValues; + pt.b = start; + pt.e = end; + start += ""; + end += ""; + if (end === "auto") { + startValue = target.style[prop]; + target.style[prop] = end; + end = _getComputedProperty(target, prop) || end; + startValue ? target.style[prop] = startValue : _removeProperty(target, prop); + } + a = [start, end]; + _colorStringFilter(a); + start = a[0]; + end = a[1]; + startValues = start.match(_numWithUnitExp) || []; + endValues = end.match(_numWithUnitExp) || []; + if (endValues.length) { + while (result = _numWithUnitExp.exec(end)) { + endValue = result[0]; + chunk = end.substring(index, result.index); + if (color) { + color = (color + 1) % 5; + } else if (chunk.substr(-5) === "rgba(" || chunk.substr(-5) === "hsla(") { + color = 1; + } + if (endValue !== (startValue = startValues[matchIndex++] || "")) { + startNum = parseFloat(startValue) || 0; + startUnit = startValue.substr((startNum + "").length); + endValue.charAt(1) === "=" && (endValue = _parseRelative(startNum, endValue) + startUnit); + endNum = parseFloat(endValue); + endUnit = endValue.substr((endNum + "").length); + index = _numWithUnitExp.lastIndex - endUnit.length; + if (!endUnit) { + endUnit = endUnit || _config.units[prop] || startUnit; + if (index === end.length) { + end += endUnit; + pt.e += endUnit; + } + } + if (startUnit !== endUnit) { + startNum = _convertToUnit(target, prop, startValue, endUnit) || 0; + } + pt._pt = { + _next: pt._pt, + p: chunk || matchIndex === 1 ? chunk : ",", + //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case. + s: startNum, + c: endNum - startNum, + m: color && color < 4 || prop === "zIndex" ? Math.round : 0 + }; + } + } + pt.c = index < end.length ? end.substring(index, end.length) : ""; + } else { + pt.r = prop === "display" && end === "none" ? _renderNonTweeningValueOnlyAtEnd : _renderNonTweeningValue; + } + _relExp.test(end) && (pt.e = 0); + this._pt = pt; + return pt; +}, _keywordToPercent = { + top: "0%", + bottom: "100%", + left: "0%", + right: "100%", + center: "50%" +}, _convertKeywordsToPercentages = function _convertKeywordsToPercentages2(value) { + var split = value.split(" "), x = split[0], y = split[1] || "50%"; + if (x === "top" || x === "bottom" || y === "left" || y === "right") { + value = x; + x = y; + y = value; + } + split[0] = _keywordToPercent[x] || x; + split[1] = _keywordToPercent[y] || y; + return split.join(" "); +}, _renderClearProps = function _renderClearProps2(ratio, data) { + if (data.tween && data.tween._time === data.tween._dur) { + var target = data.t, style = target.style, props = data.u, cache = target._gsap, prop, clearTransforms, i; + if (props === "all" || props === true) { + style.cssText = ""; + clearTransforms = 1; + } else { + props = props.split(","); + i = props.length; + while (--i > -1) { + prop = props[i]; + if (_transformProps[prop]) { + clearTransforms = 1; + prop = prop === "transformOrigin" ? _transformOriginProp$2 : _transformProp$2; + } + _removeProperty(target, prop); + } + } + if (clearTransforms) { + _removeProperty(target, _transformProp$2); + if (cache) { + cache.svg && target.removeAttribute("transform"); + _parseTransform(target, 1); + cache.uncache = 1; + _removeIndependentTransforms(style); + } + } } - return true; -}; -const parseDocRefToUUID = (ref) => { - var _a; - if (isDocUUID(ref)) { - return ref; - } else if (isDocID(ref)) { - const doc = (_a = game.collections.find((collection) => collection.has(ref))) == null ? void 0 : _a.get(ref); - if (doc && "uuid" in doc) { - return doc.uuid; +}, _specialProps = { + clearProps: function clearProps(plugin, target, property, endValue, tween) { + if (tween.data !== "isFromStart") { + var pt = plugin._pt = new PropTween$1(plugin._pt, target, property, 0, 0, _renderClearProps); + pt.u = endValue; + pt.pr = -10; + pt.tween = tween; + plugin._props.push(property); + return 1; } - throw new Error(`[U.parseDocRefToUUID] Unable to find document with id '${ref}'`); - } else if (ref && typeof ref === "object" && "uuid" in ref && typeof ref.uuid === "string") { - return ref.uuid; } - throw new Error(`[U.parseDocRefToUUID] Unrecognized reference: '${ref}'`); -}; -const loc = (locRef, formatDict = {}) => { - if (/[a-z]/.test(locRef)) { - locRef = locRef.replace(new RegExp(`^(${C.SYSTEM_ID}.)*`), `${C.SYSTEM_ID}.`); + /* className feature (about 0.4kb gzipped). + , className(plugin, target, property, endValue, tween) { + let _renderClassName = (ratio, data) => { + data.css.render(ratio, data.css); + if (!ratio || ratio === 1) { + let inline = data.rmv, + target = data.t, + p; + target.setAttribute("class", ratio ? data.e : data.b); + for (p in inline) { + _removeProperty(target, p); + } + } + }, + _getAllStyles = (target) => { + let styles = {}, + computed = getComputedStyle(target), + p; + for (p in computed) { + if (isNaN(p) && p !== "cssText" && p !== "length") { + styles[p] = computed[p]; + } + } + _setDefaults(styles, _parseTransform(target, 1)); + return styles; + }, + startClassList = target.getAttribute("class"), + style = target.style, + cssText = style.cssText, + cache = target._gsap, + classPT = cache.classPT, + inlineToRemoveAtEnd = {}, + data = {t:target, plugin:plugin, rmv:inlineToRemoveAtEnd, b:startClassList, e:(endValue.charAt(1) !== "=") ? endValue : startClassList.replace(new RegExp("(?:\\s|^)" + endValue.substr(2) + "(?![\\w-])"), "") + ((endValue.charAt(0) === "+") ? " " + endValue.substr(2) : "")}, + changingVars = {}, + startVars = _getAllStyles(target), + transformRelated = /(transform|perspective)/i, + endVars, p; + if (classPT) { + classPT.r(1, classPT.d); + _removeLinkedListItem(classPT.d.plugin, classPT, "_pt"); + } + target.setAttribute("class", data.e); + endVars = _getAllStyles(target, true); + target.setAttribute("class", startClassList); + for (p in endVars) { + if (endVars[p] !== startVars[p] && !transformRelated.test(p)) { + changingVars[p] = endVars[p]; + if (!style[p] && style[p] !== "0") { + inlineToRemoveAtEnd[p] = 1; + } + } + } + cache.classPT = plugin._pt = new PropTween(plugin._pt, target, "className", 0, 0, _renderClassName, data, 0, -11); + if (style.cssText !== cssText) { //only apply if things change. Otherwise, in cases like a background-image that's pulled dynamically, it could cause a refresh. See https://gsap.com/forums/topic/20368-possible-gsap-bug-switching-classnames-in-chrome/. + style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity). + } + _parseTransform(target, true); //to clear the caching of transforms + data.css = new gsap.plugins.css(); + data.css.init(target, changingVars, tween); + plugin._props.push(...data.css._props); + return 1; } - if (typeof game.i18n.localize(locRef) === "string") { - for (const [key, val] of Object.entries(formatDict)) { - formatDict[key] = loc(val); - } - return game.i18n.format(locRef, formatDict) || game.i18n.localize(locRef) || locRef; + */ +}, _identity2DMatrix = [1, 0, 0, 1, 0, 0], _rotationalProperties = {}, _isNullTransform = function _isNullTransform2(value) { + return value === "matrix(1, 0, 0, 1, 0, 0)" || value === "none" || !value; +}, _getComputedTransformMatrixAsArray = function _getComputedTransformMatrixAsArray2(target) { + var matrixString = _getComputedProperty(target, _transformProp$2); + return _isNullTransform(matrixString) ? _identity2DMatrix : matrixString.substr(7).match(_numExp$2).map(_round$4); +}, _getMatrix = function _getMatrix2(target, force2D) { + var cache = target._gsap || _getCache(target), style = target.style, matrix = _getComputedTransformMatrixAsArray(target), parent, nextSibling, temp, addedToDOM; + if (cache.svg && target.getAttribute("transform")) { + temp = target.transform.baseVal.consolidate().matrix; + matrix = [temp.a, temp.b, temp.c, temp.d, temp.e, temp.f]; + return matrix.join(",") === "1,0,0,1,0,0" ? _identity2DMatrix : matrix; + } else if (matrix === _identity2DMatrix && !target.offsetParent && target !== _docElement$2 && !cache.svg) { + temp = style.display; + style.display = "block"; + parent = target.parentNode; + if (!parent || !target.offsetParent) { + addedToDOM = 1; + nextSibling = target.nextElementSibling; + _docElement$2.appendChild(target); + } + matrix = _getComputedTransformMatrixAsArray(target); + temp ? style.display = temp : _removeProperty(target, "display"); + if (addedToDOM) { + nextSibling ? parent.insertBefore(target, nextSibling) : parent ? parent.appendChild(target) : _docElement$2.removeChild(target); + } + } + return force2D && matrix.length > 6 ? [matrix[0], matrix[1], matrix[4], matrix[5], matrix[12], matrix[13]] : matrix; +}, _applySVGOrigin = function _applySVGOrigin2(target, origin, originIsAbsolute, smooth, matrixArray, pluginToAddPropTweensTo) { + var cache = target._gsap, matrix = matrixArray || _getMatrix(target, true), xOriginOld = cache.xOrigin || 0, yOriginOld = cache.yOrigin || 0, xOffsetOld = cache.xOffset || 0, yOffsetOld = cache.yOffset || 0, a = matrix[0], b = matrix[1], c = matrix[2], d = matrix[3], tx = matrix[4], ty = matrix[5], originSplit = origin.split(" "), xOrigin = parseFloat(originSplit[0]) || 0, yOrigin = parseFloat(originSplit[1]) || 0, bounds, determinant, x, y; + if (!originIsAbsolute) { + bounds = _getBBox(target); + xOrigin = bounds.x + (~originSplit[0].indexOf("%") ? xOrigin / 100 * bounds.width : xOrigin); + yOrigin = bounds.y + (~(originSplit[1] || originSplit[0]).indexOf("%") ? yOrigin / 100 * bounds.height : yOrigin); + } else if (matrix !== _identity2DMatrix && (determinant = a * d - b * c)) { + x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + (c * ty - d * tx) / determinant; + y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - (a * ty - b * tx) / determinant; + xOrigin = x; + yOrigin = y; + } + if (smooth || smooth !== false && cache.smooth) { + tx = xOrigin - xOriginOld; + ty = yOrigin - yOriginOld; + cache.xOffset = xOffsetOld + (tx * a + ty * c) - tx; + cache.yOffset = yOffsetOld + (tx * b + ty * d) - ty; + } else { + cache.xOffset = cache.yOffset = 0; + } + cache.xOrigin = xOrigin; + cache.yOrigin = yOrigin; + cache.smooth = !!smooth; + cache.origin = origin; + cache.originIsAbsolute = !!originIsAbsolute; + target.style[_transformOriginProp$2] = "0px 0px"; + if (pluginToAddPropTweensTo) { + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "xOrigin", xOriginOld, xOrigin); + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "yOrigin", yOriginOld, yOrigin); + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "xOffset", xOffsetOld, cache.xOffset); + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "yOffset", yOffsetOld, cache.yOffset); + } + target.setAttribute("data-svg-origin", xOrigin + " " + yOrigin); +}, _parseTransform = function _parseTransform2(target, uncache) { + var cache = target._gsap || new GSCache(target); + if ("x" in cache && !uncache && !cache.uncache) { + return cache; + } + var style = target.style, invertedScaleX = cache.scaleX < 0, px = "px", deg = "deg", cs = getComputedStyle(target), origin = _getComputedProperty(target, _transformOriginProp$2) || "0", x, y, z, scaleX, scaleY, rotation, rotationX, rotationY, skewX, skewY, perspective, xOrigin, yOrigin, matrix, angle, cos, sin, a, b, c, d, a12, a22, t1, t2, t3, a13, a23, a33, a42, a43, a32; + x = y = z = rotation = rotationX = rotationY = skewX = skewY = perspective = 0; + scaleX = scaleY = 1; + cache.svg = !!(target.getCTM && _isSVG(target)); + if (cs.translate) { + if (cs.translate !== "none" || cs.scale !== "none" || cs.rotate !== "none") { + style[_transformProp$2] = (cs.translate !== "none" ? "translate3d(" + (cs.translate + " 0 0").split(" ").slice(0, 3).join(", ") + ") " : "") + (cs.rotate !== "none" ? "rotate(" + cs.rotate + ") " : "") + (cs.scale !== "none" ? "scale(" + cs.scale.split(" ").join(",") + ") " : "") + (cs[_transformProp$2] !== "none" ? cs[_transformProp$2] : ""); + } + style.scale = style.rotate = style.translate = "none"; + } + matrix = _getMatrix(target, cache.svg); + if (cache.svg) { + if (cache.uncache) { + t2 = target.getBBox(); + origin = cache.xOrigin - t2.x + "px " + (cache.yOrigin - t2.y) + "px"; + t1 = ""; + } else { + t1 = !uncache && target.getAttribute("data-svg-origin"); + } + _applySVGOrigin(target, t1 || origin, !!t1 || cache.originIsAbsolute, cache.smooth !== false, matrix); + } + xOrigin = cache.xOrigin || 0; + yOrigin = cache.yOrigin || 0; + if (matrix !== _identity2DMatrix) { + a = matrix[0]; + b = matrix[1]; + c = matrix[2]; + d = matrix[3]; + x = a12 = matrix[4]; + y = a22 = matrix[5]; + if (matrix.length === 6) { + scaleX = Math.sqrt(a * a + b * b); + scaleY = Math.sqrt(d * d + c * c); + rotation = a || b ? _atan2$1(b, a) * _RAD2DEG$3 : 0; + skewX = c || d ? _atan2$1(c, d) * _RAD2DEG$3 + rotation : 0; + skewX && (scaleY *= Math.abs(Math.cos(skewX * _DEG2RAD$3))); + if (cache.svg) { + x -= xOrigin - (xOrigin * a + yOrigin * c); + y -= yOrigin - (xOrigin * b + yOrigin * d); + } + } else { + a32 = matrix[6]; + a42 = matrix[7]; + a13 = matrix[8]; + a23 = matrix[9]; + a33 = matrix[10]; + a43 = matrix[11]; + x = matrix[12]; + y = matrix[13]; + z = matrix[14]; + angle = _atan2$1(a32, a33); + rotationX = angle * _RAD2DEG$3; + if (angle) { + cos = Math.cos(-angle); + sin = Math.sin(-angle); + t1 = a12 * cos + a13 * sin; + t2 = a22 * cos + a23 * sin; + t3 = a32 * cos + a33 * sin; + a13 = a12 * -sin + a13 * cos; + a23 = a22 * -sin + a23 * cos; + a33 = a32 * -sin + a33 * cos; + a43 = a42 * -sin + a43 * cos; + a12 = t1; + a22 = t2; + a32 = t3; + } + angle = _atan2$1(-c, a33); + rotationY = angle * _RAD2DEG$3; + if (angle) { + cos = Math.cos(-angle); + sin = Math.sin(-angle); + t1 = a * cos - a13 * sin; + t2 = b * cos - a23 * sin; + t3 = c * cos - a33 * sin; + a43 = d * sin + a43 * cos; + a = t1; + b = t2; + c = t3; + } + angle = _atan2$1(b, a); + rotation = angle * _RAD2DEG$3; + if (angle) { + cos = Math.cos(angle); + sin = Math.sin(angle); + t1 = a * cos + b * sin; + t2 = a12 * cos + a22 * sin; + b = b * cos - a * sin; + a22 = a22 * cos - a12 * sin; + a = t1; + a12 = t2; + } + if (rotationX && Math.abs(rotationX) + Math.abs(rotation) > 359.9) { + rotationX = rotation = 0; + rotationY = 180 - rotationY; + } + scaleX = _round$4(Math.sqrt(a * a + b * b + c * c)); + scaleY = _round$4(Math.sqrt(a22 * a22 + a32 * a32)); + angle = _atan2$1(a12, a22); + skewX = Math.abs(angle) > 2e-4 ? angle * _RAD2DEG$3 : 0; + perspective = a43 ? 1 / (a43 < 0 ? -a43 : a43) : 0; + } + if (cache.svg) { + t1 = target.getAttribute("transform"); + cache.forceCSS = target.setAttribute("transform", "") || !_isNullTransform(_getComputedProperty(target, _transformProp$2)); + t1 && target.setAttribute("transform", t1); + } + } + if (Math.abs(skewX) > 90 && Math.abs(skewX) < 270) { + if (invertedScaleX) { + scaleX *= -1; + skewX += rotation <= 0 ? 180 : -180; + rotation += rotation <= 0 ? 180 : -180; + } else { + scaleY *= -1; + skewX += skewX <= 0 ? 180 : -180; + } + } + uncache = uncache || cache.uncache; + cache.x = x - ((cache.xPercent = x && (!uncache && cache.xPercent || (Math.round(target.offsetWidth / 2) === Math.round(-x) ? -50 : 0))) ? target.offsetWidth * cache.xPercent / 100 : 0) + px; + cache.y = y - ((cache.yPercent = y && (!uncache && cache.yPercent || (Math.round(target.offsetHeight / 2) === Math.round(-y) ? -50 : 0))) ? target.offsetHeight * cache.yPercent / 100 : 0) + px; + cache.z = z + px; + cache.scaleX = _round$4(scaleX); + cache.scaleY = _round$4(scaleY); + cache.rotation = _round$4(rotation) + deg; + cache.rotationX = _round$4(rotationX) + deg; + cache.rotationY = _round$4(rotationY) + deg; + cache.skewX = skewX + deg; + cache.skewY = skewY + deg; + cache.transformPerspective = perspective + px; + if (cache.zOrigin = parseFloat(origin.split(" ")[2]) || !uncache && cache.zOrigin || 0) { + style[_transformOriginProp$2] = _firstTwoOnly(origin); + } + cache.xOffset = cache.yOffset = 0; + cache.force3D = _config.force3D; + cache.renderTransform = cache.svg ? _renderSVGTransforms : _supports3D$1 ? _renderCSSTransforms : _renderNon3DTransforms; + cache.uncache = 0; + return cache; +}, _firstTwoOnly = function _firstTwoOnly2(value) { + return (value = value.split(" "))[0] + " " + value[1]; +}, _addPxTranslate = function _addPxTranslate2(target, start, value) { + var unit = getUnit(start); + return _round$4(parseFloat(start) + parseFloat(_convertToUnit(target, "x", value + "px", unit))) + unit; +}, _renderNon3DTransforms = function _renderNon3DTransforms2(ratio, cache) { + cache.z = "0px"; + cache.rotationY = cache.rotationX = "0deg"; + cache.force3D = 0; + _renderCSSTransforms(ratio, cache); +}, _zeroDeg = "0deg", _zeroPx = "0px", _endParenthesis = ") ", _renderCSSTransforms = function _renderCSSTransforms2(ratio, cache) { + var _ref = cache || this, xPercent = _ref.xPercent, yPercent = _ref.yPercent, x = _ref.x, y = _ref.y, z = _ref.z, rotation = _ref.rotation, rotationY = _ref.rotationY, rotationX = _ref.rotationX, skewX = _ref.skewX, skewY = _ref.skewY, scaleX = _ref.scaleX, scaleY = _ref.scaleY, transformPerspective = _ref.transformPerspective, force3D = _ref.force3D, target = _ref.target, zOrigin = _ref.zOrigin, transforms = "", use3D = force3D === "auto" && ratio && ratio !== 1 || force3D === true; + if (zOrigin && (rotationX !== _zeroDeg || rotationY !== _zeroDeg)) { + var angle = parseFloat(rotationY) * _DEG2RAD$3, a13 = Math.sin(angle), a33 = Math.cos(angle), cos; + angle = parseFloat(rotationX) * _DEG2RAD$3; + cos = Math.cos(angle); + x = _addPxTranslate(target, x, a13 * cos * -zOrigin); + y = _addPxTranslate(target, y, -Math.sin(angle) * -zOrigin); + z = _addPxTranslate(target, z, a33 * cos * -zOrigin + zOrigin); + } + if (transformPerspective !== _zeroPx) { + transforms += "perspective(" + transformPerspective + _endParenthesis; + } + if (xPercent || yPercent) { + transforms += "translate(" + xPercent + "%, " + yPercent + "%) "; + } + if (use3D || x !== _zeroPx || y !== _zeroPx || z !== _zeroPx) { + transforms += z !== _zeroPx || use3D ? "translate3d(" + x + ", " + y + ", " + z + ") " : "translate(" + x + ", " + y + _endParenthesis; + } + if (rotation !== _zeroDeg) { + transforms += "rotate(" + rotation + _endParenthesis; + } + if (rotationY !== _zeroDeg) { + transforms += "rotateY(" + rotationY + _endParenthesis; + } + if (rotationX !== _zeroDeg) { + transforms += "rotateX(" + rotationX + _endParenthesis; + } + if (skewX !== _zeroDeg || skewY !== _zeroDeg) { + transforms += "skew(" + skewX + ", " + skewY + _endParenthesis; + } + if (scaleX !== 1 || scaleY !== 1) { + transforms += "scale(" + scaleX + ", " + scaleY + _endParenthesis; + } + target.style[_transformProp$2] = transforms || "translate(0, 0)"; +}, _renderSVGTransforms = function _renderSVGTransforms2(ratio, cache) { + var _ref2 = cache || this, xPercent = _ref2.xPercent, yPercent = _ref2.yPercent, x = _ref2.x, y = _ref2.y, rotation = _ref2.rotation, skewX = _ref2.skewX, skewY = _ref2.skewY, scaleX = _ref2.scaleX, scaleY = _ref2.scaleY, target = _ref2.target, xOrigin = _ref2.xOrigin, yOrigin = _ref2.yOrigin, xOffset = _ref2.xOffset, yOffset = _ref2.yOffset, forceCSS = _ref2.forceCSS, tx = parseFloat(x), ty = parseFloat(y), a11, a21, a12, a22, temp; + rotation = parseFloat(rotation); + skewX = parseFloat(skewX); + skewY = parseFloat(skewY); + if (skewY) { + skewY = parseFloat(skewY); + skewX += skewY; + rotation += skewY; + } + if (rotation || skewX) { + rotation *= _DEG2RAD$3; + skewX *= _DEG2RAD$3; + a11 = Math.cos(rotation) * scaleX; + a21 = Math.sin(rotation) * scaleX; + a12 = Math.sin(rotation - skewX) * -scaleY; + a22 = Math.cos(rotation - skewX) * scaleY; + if (skewX) { + skewY *= _DEG2RAD$3; + temp = Math.tan(skewX - skewY); + temp = Math.sqrt(1 + temp * temp); + a12 *= temp; + a22 *= temp; + if (skewY) { + temp = Math.tan(skewY); + temp = Math.sqrt(1 + temp * temp); + a11 *= temp; + a21 *= temp; + } + } + a11 = _round$4(a11); + a21 = _round$4(a21); + a12 = _round$4(a12); + a22 = _round$4(a22); + } else { + a11 = scaleX; + a22 = scaleY; + a21 = a12 = 0; + } + if (tx && !~(x + "").indexOf("px") || ty && !~(y + "").indexOf("px")) { + tx = _convertToUnit(target, "x", x, "px"); + ty = _convertToUnit(target, "y", y, "px"); + } + if (xOrigin || yOrigin || xOffset || yOffset) { + tx = _round$4(tx + xOrigin - (xOrigin * a11 + yOrigin * a12) + xOffset); + ty = _round$4(ty + yOrigin - (xOrigin * a21 + yOrigin * a22) + yOffset); + } + if (xPercent || yPercent) { + temp = target.getBBox(); + tx = _round$4(tx + xPercent / 100 * temp.width); + ty = _round$4(ty + yPercent / 100 * temp.height); + } + temp = "matrix(" + a11 + "," + a21 + "," + a12 + "," + a22 + "," + tx + "," + ty + ")"; + target.setAttribute("transform", temp); + forceCSS && (target.style[_transformProp$2] = temp); +}, _addRotationalPropTween = function _addRotationalPropTween2(plugin, target, property, startNum, endValue) { + var cap = 360, isString = _isString$1(endValue), endNum = parseFloat(endValue) * (isString && ~endValue.indexOf("rad") ? _RAD2DEG$3 : 1), change = endNum - startNum, finalValue = startNum + change + "deg", direction, pt; + if (isString) { + direction = endValue.split("_")[1]; + if (direction === "short") { + change %= cap; + if (change !== change % (cap / 2)) { + change += change < 0 ? cap : -cap; + } + } + if (direction === "cw" && change < 0) { + change = (change + cap * _bigNum$2) % cap - ~~(change / cap) * cap; + } else if (direction === "ccw" && change > 0) { + change = (change - cap * _bigNum$2) % cap - ~~(change / cap) * cap; + } + } + plugin._pt = pt = new PropTween$1(plugin._pt, target, property, startNum, change, _renderPropWithEnd); + pt.e = finalValue; + pt.u = "deg"; + plugin._props.push(property); + return pt; +}, _assign = function _assign2(target, source) { + for (var p in source) { + target[p] = source[p]; } - return locRef; + return target; +}, _addRawTransformPTs = function _addRawTransformPTs2(plugin, transforms, target) { + var startCache = _assign({}, target._gsap), exclude = "perspective,force3D,transformOrigin,svgOrigin", style = target.style, endCache, p, startValue, endValue, startNum, endNum, startUnit, endUnit; + if (startCache.svg) { + startValue = target.getAttribute("transform"); + target.setAttribute("transform", ""); + style[_transformProp$2] = transforms; + endCache = _parseTransform(target, 1); + _removeProperty(target, _transformProp$2); + target.setAttribute("transform", startValue); + } else { + startValue = getComputedStyle(target)[_transformProp$2]; + style[_transformProp$2] = transforms; + endCache = _parseTransform(target, 1); + style[_transformProp$2] = startValue; + } + for (p in _transformProps) { + startValue = startCache[p]; + endValue = endCache[p]; + if (startValue !== endValue && exclude.indexOf(p) < 0) { + startUnit = getUnit(startValue); + endUnit = getUnit(endValue); + startNum = startUnit !== endUnit ? _convertToUnit(target, p, startValue, endUnit) : parseFloat(startValue); + endNum = parseFloat(endValue); + plugin._pt = new PropTween$1(plugin._pt, endCache, p, startNum, endNum - startNum, _renderCSSProp); + plugin._pt.u = endUnit || 0; + plugin._props.push(p); + } + } + _assign(endCache, startCache); }; -const getSetting = (setting) => { - if (game.settings.settings.has(`${C.SYSTEM_ID}.${setting}`)) { - return game.settings.get(C.SYSTEM_ID, setting); +_forEachName("padding,margin,Width,Radius", function(name, index) { + var t = "Top", r = "Right", b = "Bottom", l = "Left", props = (index < 3 ? [t, r, b, l] : [t + l, t + r, b + r, b + l]).map(function(side) { + return index < 2 ? name + side : "border" + side + name; + }); + _specialProps[index > 1 ? "border" + name : name] = function(plugin, target, property, endValue, tween) { + var a, vars; + if (arguments.length < 4) { + a = props.map(function(prop) { + return _get(plugin, prop, property); + }); + vars = a.join(" "); + return vars.split(a[0]).length === 5 ? a[0] : vars; + } + a = (endValue + "").split(" "); + vars = {}; + props.forEach(function(prop, i) { + return vars[prop] = a[i] = a[i] || a[(i - 1) / 2 | 0]; + }); + plugin.init(target, vars, tween); + }; +}); +var CSSPlugin = { + name: "css", + register: _initCore$3, + targetTest: function targetTest(target) { + return target.style && target.nodeType; + }, + init: function init3(target, vars, tween, index, targets) { + var props = this._props, style = target.style, startAt = tween.vars.startAt, startValue, endValue, endNum, startNum, type, specialProp, p, startUnit, endUnit, relative, isTransformRelated, transformPropTween, cache, smooth, hasPriority, inlineProps; + _pluginInitted || _initCore$3(); + this.styles = this.styles || _getStyleSaver$3(target); + inlineProps = this.styles.props; + this.tween = tween; + for (p in vars) { + if (p === "autoRound") { + continue; + } + endValue = vars[p]; + if (_plugins[p] && _checkPlugin(p, vars, tween, index, target, targets)) { + continue; + } + type = typeof endValue; + specialProp = _specialProps[p]; + if (type === "function") { + endValue = endValue.call(tween, index, target, targets); + type = typeof endValue; + } + if (type === "string" && ~endValue.indexOf("random(")) { + endValue = _replaceRandom(endValue); + } + if (specialProp) { + specialProp(this, target, p, endValue, tween) && (hasPriority = 1); + } else if (p.substr(0, 2) === "--") { + startValue = (getComputedStyle(target).getPropertyValue(p) + "").trim(); + endValue += ""; + _colorExp.lastIndex = 0; + if (!_colorExp.test(startValue)) { + startUnit = getUnit(startValue); + endUnit = getUnit(endValue); + } + endUnit ? startUnit !== endUnit && (startValue = _convertToUnit(target, p, startValue, endUnit) + endUnit) : startUnit && (endValue += startUnit); + this.add(style, "setProperty", startValue, endValue, index, targets, 0, 0, p); + props.push(p); + inlineProps.push(p, 0, style[p]); + } else if (type !== "undefined") { + if (startAt && p in startAt) { + startValue = typeof startAt[p] === "function" ? startAt[p].call(tween, index, target, targets) : startAt[p]; + _isString$1(startValue) && ~startValue.indexOf("random(") && (startValue = _replaceRandom(startValue)); + getUnit(startValue + "") || startValue === "auto" || (startValue += _config.units[p] || getUnit(_get(target, p)) || ""); + (startValue + "").charAt(1) === "=" && (startValue = _get(target, p)); + } else { + startValue = _get(target, p); + } + startNum = parseFloat(startValue); + relative = type === "string" && endValue.charAt(1) === "=" && endValue.substr(0, 2); + relative && (endValue = endValue.substr(2)); + endNum = parseFloat(endValue); + if (p in _propertyAliases) { + if (p === "autoAlpha") { + if (startNum === 1 && _get(target, "visibility") === "hidden" && endNum) { + startNum = 0; + } + inlineProps.push("visibility", 0, style.visibility); + _addNonTweeningPT(this, style, "visibility", startNum ? "inherit" : "hidden", endNum ? "inherit" : "hidden", !endNum); + } + if (p !== "scale" && p !== "transform") { + p = _propertyAliases[p]; + ~p.indexOf(",") && (p = p.split(",")[0]); + } + } + isTransformRelated = p in _transformProps; + if (isTransformRelated) { + this.styles.save(p); + if (!transformPropTween) { + cache = target._gsap; + cache.renderTransform && !vars.parseTransform || _parseTransform(target, vars.parseTransform); + smooth = vars.smoothOrigin !== false && cache.smooth; + transformPropTween = this._pt = new PropTween$1(this._pt, style, _transformProp$2, 0, 1, cache.renderTransform, cache, 0, -1); + transformPropTween.dep = 1; + } + if (p === "scale") { + this._pt = new PropTween$1(this._pt, cache, "scaleY", cache.scaleY, (relative ? _parseRelative(cache.scaleY, relative + endNum) : endNum) - cache.scaleY || 0, _renderCSSProp); + this._pt.u = 0; + props.push("scaleY", p); + p += "X"; + } else if (p === "transformOrigin") { + inlineProps.push(_transformOriginProp$2, 0, style[_transformOriginProp$2]); + endValue = _convertKeywordsToPercentages(endValue); + if (cache.svg) { + _applySVGOrigin(target, endValue, 0, smooth, 0, this); + } else { + endUnit = parseFloat(endValue.split(" ")[2]) || 0; + endUnit !== cache.zOrigin && _addNonTweeningPT(this, cache, "zOrigin", cache.zOrigin, endUnit); + _addNonTweeningPT(this, style, p, _firstTwoOnly(startValue), _firstTwoOnly(endValue)); + } + continue; + } else if (p === "svgOrigin") { + _applySVGOrigin(target, endValue, 1, smooth, 0, this); + continue; + } else if (p in _rotationalProperties) { + _addRotationalPropTween(this, cache, p, startNum, relative ? _parseRelative(startNum, relative + endValue) : endValue); + continue; + } else if (p === "smoothOrigin") { + _addNonTweeningPT(this, cache, "smooth", cache.smooth, endValue); + continue; + } else if (p === "force3D") { + cache[p] = endValue; + continue; + } else if (p === "transform") { + _addRawTransformPTs(this, endValue, target); + continue; + } + } else if (!(p in style)) { + p = _checkPropPrefix(p) || p; + } + if (isTransformRelated || (endNum || endNum === 0) && (startNum || startNum === 0) && !_complexExp.test(endValue) && p in style) { + startUnit = (startValue + "").substr((startNum + "").length); + endNum || (endNum = 0); + endUnit = getUnit(endValue) || (p in _config.units ? _config.units[p] : startUnit); + startUnit !== endUnit && (startNum = _convertToUnit(target, p, startValue, endUnit)); + this._pt = new PropTween$1(this._pt, isTransformRelated ? cache : style, p, startNum, (relative ? _parseRelative(startNum, relative + endNum) : endNum) - startNum, !isTransformRelated && (endUnit === "px" || p === "zIndex") && vars.autoRound !== false ? _renderRoundedCSSProp : _renderCSSProp); + this._pt.u = endUnit || 0; + if (startUnit !== endUnit && endUnit !== "%") { + this._pt.b = startValue; + this._pt.r = _renderCSSPropWithBeginning; + } + } else if (!(p in style)) { + if (p in target) { + this.add(target, p, startValue || target[p], relative ? relative + endValue : endValue, index, targets); + } else if (p !== "parseTransform") { + _missingPlugin(p, endValue); + continue; + } + } else { + _tweenComplexCSSString.call(this, target, p, startValue, relative ? relative + endValue : endValue); + } + isTransformRelated || (p in style ? inlineProps.push(p, 0, style[p]) : inlineProps.push(p, 1, startValue || target[p])); + props.push(p); + } + } + hasPriority && _sortPropTweensByPriority(this); + }, + render: function render2(ratio, data) { + if (data.tween._time || !_reverting$1()) { + var pt = data._pt; + while (pt) { + pt.r(ratio, pt.d); + pt = pt._next; + } + } else { + data.styles.revert(); + } + }, + get: _get, + aliases: _propertyAliases, + getSetter: function getSetter(target, property, plugin) { + var p = _propertyAliases[property]; + p && p.indexOf(",") < 0 && (property = p); + return property in _transformProps && property !== _transformOriginProp$2 && (target._gsap.x || _get(target, "x")) ? plugin && _recentSetterPlugin === plugin ? property === "scale" ? _setterScale : _setterTransform : (_recentSetterPlugin = plugin || {}) && (property === "scale" ? _setterScaleWithRender : _setterTransformWithRender) : target.style && !_isUndefined$2(target.style[property]) ? _setterCSSStyle : ~property.indexOf("-") ? _setterCSSProp : _getSetter(target, property); + }, + core: { + _removeProperty, + _getMatrix } - return void 0; }; -function getTemplatePath(subFolder, fileName) { - if (typeof fileName === "string") { - return `${C.TEMPLATE_ROOT}/${subFolder}/${fileName.replace(/\..*$/, "")}.hbs`; +gsap$6.utils.checkPrefix = _checkPropPrefix; +gsap$6.core.getStyleSaver = _getStyleSaver$3; +(function(positionAndScale, rotation, others, aliases) { + var all = _forEachName(positionAndScale + "," + rotation + "," + others, function(name) { + _transformProps[name] = 1; + }); + _forEachName(rotation, function(name) { + _config.units[name] = "deg"; + _rotationalProperties[name] = 1; + }); + _propertyAliases[all[13]] = positionAndScale + "," + rotation; + _forEachName(aliases, function(name) { + var split = name.split(":"); + _propertyAliases[split[1]] = all[split[0]]; + }); +})("x,y,z,scale,scaleX,scaleY,xPercent,yPercent", "rotation,rotationX,rotationY,skewX,skewY", "transform,transformOrigin,svgOrigin,force3D,smoothOrigin,transformPerspective", "0:translateX,1:translateY,2:translateZ,8:rotate,8:rotationZ,8:rotateZ,9:rotateX,10:rotateY"); +_forEachName("x,y,z,top,right,bottom,left,width,height,fontSize,padding,margin,perspective", function(name) { + _config.units[name] = "px"; +}); +gsap$6.registerPlugin(CSSPlugin); +var gsapWithCSS = gsap$6.registerPlugin(CSSPlugin) || gsap$6; +gsapWithCSS.core.Tween; +/*! + * paths 3.12.5 + * https://gsap.com + * + * Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _svgPathExp = /[achlmqstvz]|(-?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig, _numbersExp = /(?:(-)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig, _scientific = /[\+\-]?\d*\.?\d+e[\+\-]?\d+/ig, _selectorExp = /(^[#\.][a-z]|[a-y][a-z])/i, _DEG2RAD$2 = Math.PI / 180, _RAD2DEG$2 = 180 / Math.PI, _sin = Math.sin, _cos = Math.cos, _abs = Math.abs, _sqrt = Math.sqrt, _atan2 = Math.atan2, _largeNum = 1e8, _isString2 = function _isString3(value) { + return typeof value === "string"; +}, _isNumber2 = function _isNumber3(value) { + return typeof value === "number"; +}, _isUndefined$1 = function _isUndefined2(value) { + return typeof value === "undefined"; +}, _temp = {}, _temp2 = {}, _roundingNum = 1e5, _wrapProgress = function _wrapProgress2(progress) { + return Math.round((progress + _largeNum) % 1 * _roundingNum) / _roundingNum || (progress < 0 ? 0 : 1); +}, _round$3 = function _round2(value) { + return Math.round(value * _roundingNum) / _roundingNum || 0; +}, _roundPrecise2 = function _roundPrecise3(value) { + return Math.round(value * 1e10) / 1e10 || 0; +}, _splitSegment = function _splitSegment2(rawPath, segIndex, i, t) { + var segment = rawPath[segIndex], shift = t === 1 ? 6 : subdivideSegment(segment, i, t); + if ((shift || !t) && shift + i + 2 < segment.length) { + rawPath.splice(segIndex, 0, segment.slice(0, i + shift + 2)); + segment.splice(0, i + shift); + return 1; + } +}, _getSampleIndex = function _getSampleIndex2(samples, length, progress) { + var l = samples.length, i = ~~(progress * l); + if (samples[i] > length) { + while (--i && samples[i] > length) { + } + i < 0 && (i = 0); + } else { + while (samples[++i] < length && i < l) { + } + } + return i < l ? i : l - 1; +}, _reverseRawPath = function _reverseRawPath2(rawPath, skipOuter) { + var i = rawPath.length; + skipOuter || rawPath.reverse(); + while (i--) { + rawPath[i].reversed || reverseSegment(rawPath[i]); + } +}, _copyMetaData = function _copyMetaData2(source, copy) { + copy.totalLength = source.totalLength; + if (source.samples) { + copy.samples = source.samples.slice(0); + copy.lookup = source.lookup.slice(0); + copy.minLength = source.minLength; + copy.resolution = source.resolution; + } else if (source.totalPoints) { + copy.totalPoints = source.totalPoints; + } + return copy; +}, _appendOrMerge = function _appendOrMerge2(rawPath, segment) { + var index = rawPath.length, prevSeg = rawPath[index - 1] || [], l = prevSeg.length; + if (index && segment[0] === prevSeg[l - 2] && segment[1] === prevSeg[l - 1]) { + segment = prevSeg.concat(segment.slice(2)); + index--; + } + rawPath[index] = segment; +}; +function getRawPath(value) { + value = _isString2(value) && _selectorExp.test(value) ? document.querySelector(value) || value : value; + var e = value.getAttribute ? value : 0, rawPath; + if (e && (value = value.getAttribute("d"))) { + if (!e._gsPath) { + e._gsPath = {}; + } + rawPath = e._gsPath[value]; + return rawPath && !rawPath._dirty ? rawPath : e._gsPath[value] = stringToRawPath(value); } - return fileName.map((fName) => getTemplatePath(subFolder, fName)); + return !value ? console.warn("Expecting a element or an SVG path data string") : _isString2(value) ? stringToRawPath(value) : _isNumber2(value[0]) ? [value] : value; } -function displayImageSelector(callback, pathRoot = `systems/${C.SYSTEM_ID}/assets`, position = { top: 200, left: 200 }) { - const fp = new FilePicker({ - type: "image", - activeSource: "public", - displayMode: "tiles", - callback, - top: position.top ?? 200 + 40, - left: position.left ?? 200 + 10 - }); - return fp.browse(pathRoot); +function copyRawPath(rawPath) { + var a = [], i = 0; + for (; i < rawPath.length; i++) { + a[i] = _copyMetaData(rawPath[i], rawPath[i].slice(0)); + } + return _copyMetaData(rawPath, a); } -const U = { - // ████████ GETTERS: Basic Data Lookup & Retrieval ████████ - GMID, - getUID: getUID$1, - // ████████ TYPES: Type Checking, Validation, Conversion, Casting ████████ - isNumber, - isNumString, - isBooleanString, - isSimpleObj, - isList, - isArray, - isFunc, - isInt, - isFloat, - isPosInt, - isIterable, - isHTMLCode, - isRGBColor, - isHexColor, - isUndefined, - isDefined, - isEmpty, - hasItems, - isInstance, - isNullish, - areEqual, - areFuzzyEqual, - pFloat, - pInt, - pBool, - radToDeg, - degToRad, - getKey, - assertNonNullType, - FILTERS, - // ████████ REGEXP: Regular Expressions, Replacing, Matching ████████ - testRegExp, - regExtract, - // ████████ STRINGS: String Parsing, Manipulation, Conversion ████████ - // ░░░░░░░ Case Conversion ░░░░░░░ - uCase, - lCase, - sCase, - tCase, - // ░░░░░░░ Formatting ░░░░░░░ - /* hyphenate, */ - unhyphenate, - pluralize, - oxfordize, - ellipsize, - pad, - toKey, - parseArticles, - signNum, - padNum, - stringifyNum, - verbalizeNum, - ordinalizeNum, - romanizeNum, - // ░░░░░░░ Content ░░░░░░░ - loremIpsum, - randString, - randWord, - // ████████ SEARCHING: Searching Various Data Types w/ Fuzzy Matching ████████ - fuzzyMatch, - isIn, - isInExact, - // ████████ NUMBERS: Number Casting, Mathematics, Conversion ████████ - randNum, - randInt, - coinFlip, - cycleNum, - cycleAngle, - roundNum, - clampNum, - sum, - average, - // ░░░░░░░ Positioning ░░░░░░░ - getDistance, - getAngle, - getAngleDelta, - getBoundingRectangle, - // ████████ ARRAYS: Array Manipulation ████████ - randElem, - randIndex, - makeIntRange, - makeCycler, - unique, - group, - sample, - getLast, - removeFirst, - pullElement, - pullIndex, - subGroup, - shuffle, - toArray, - // ████████ OBJECTS: Manipulation of Simple Key/Val Objects ████████ - remove, - replace, - partition, - zip, - objClean, - objSize, - objMap, - objFindKey, - objFilter, - objForEach, - objCompact, - objClone, - objMerge, - objDiff, - objExpand, - objFlatten, - objNullify, - objFreezeProps, - // ████████ FUNCTIONS: Function Wrapping, Queuing, Manipulation ████████ - getDynamicFunc, - withLog, - // ████████ HTML: Parsing HTML Code, Manipulating DOM Objects ████████ - getSvgCode, - changeContainer, - adjustTextContainerAspectRatio, - getRawCirclePath, - drawCirclePath, - getColorVals, - getRGBString, - getHEXString, - getContrastingColor, - getRandomColor, - getSiblings, - escapeHTML: escapeHTML$1, - // ████████ PERFORMANCE: Performance Testing & Metrics ████████ - testFuncPerformance, - // ░░░░░░░ GreenSock ░░░░░░░ - gsap, - get, - set, - getGSAngleDelta, - getNearestLabel, - reverseRepeatingTimeline, - /* to, from, fromTo, */ - TextPlugin, - Flip, - MotionPathPlugin, - // ████████ ASYNC: Async Functions, Asynchronous Flow Control ████████ - sleep, - waitFor, - // EVENT HANDLERS - EventHandlers, - // ░░░░░░░ SYSTEM: System-Specific Functions (Requires Configuration of System ID in constants.js) ░░░░░░░ - isDocID, - isDocUUID, - isDotKey, - isTargetKey, - isTargetFlagKey, - parseDocRefToUUID, - loc, - getSetting, - getTemplatePath, - displayImageSelector +function reverseSegment(segment) { + var i = 0, y; + segment.reverse(); + for (; i < segment.length; i += 2) { + y = segment[i]; + segment[i] = segment[i + 1]; + segment[i + 1] = y; + } + segment.reversed = !segment.reversed; +} +var _createPath = function _createPath2(e, ignore) { + var path = document.createElementNS("http://www.w3.org/2000/svg", "path"), attr = [].slice.call(e.attributes), i = attr.length, name; + ignore = "," + ignore + ","; + while (--i > -1) { + name = attr[i].nodeName.toLowerCase(); + if (ignore.indexOf("," + name + ",") < 0) { + path.setAttributeNS(null, name, attr[i].nodeValue); + } + } + return path; +}, _typeAttrs = { + rect: "rx,ry,x,y,width,height", + circle: "r,cx,cy", + ellipse: "rx,ry,cx,cy", + line: "x1,x2,y1,y2" +}, _attrToObj = function _attrToObj2(e, attrs) { + var props = attrs ? attrs.split(",") : [], obj = {}, i = props.length; + while (--i > -1) { + obj[props[i]] = +e.getAttribute(props[i]) || 0; + } + return obj; }; -const registerSettings = function() { - game.settings.register("eunos-blades", "debug", { - name: "Debug Level", - hint: "The verbosity of the debug messages to console.", - scope: "client", - // This specifies a world-level setting - config: true, - // This specifies that the setting appears in the configuration view - type: Number, - range: { - // If range is specified, the resulting setting will be a range slider - min: 0, - max: 5, - step: 1 - }, - default: 3 - // The default value for the setting - }); - game.settings.register("eunos-blades", "debugHooks", { - name: "Debug HOOKS", - hint: "Whether all Hooks are logged to the console.", - scope: "client", - config: true, - type: Boolean, - default: false - }); - game.settings.register("eunos-blades", "openAPIModelLevel", { - name: "AI Base Quality", - hint: "Lower values are cheaper to run, at the cost of quality.", - scope: "client", - // This specifies a world-level setting - config: true, - // This specifies that the setting appears in the configuration view - type: Number, - range: { - // If range is specified, the resulting setting will be a range slider - min: 0, - max: 2, - step: 1 +function convertToPath(element, swap) { + var type = element.tagName.toLowerCase(), circ = 0.552284749831, data, x, y, r, ry, path, rcirc, rycirc, points, w, h, x2, x3, x4, x5, x6, y2, y3, y4, y5, y6, attr; + if (type === "path" || !element.getBBox) { + return element; + } + path = _createPath(element, "x,y,width,height,cx,cy,rx,ry,r,x1,x2,y1,y2,points"); + attr = _attrToObj(element, _typeAttrs[type]); + if (type === "rect") { + r = attr.rx; + ry = attr.ry || r; + x = attr.x; + y = attr.y; + w = attr.width - r * 2; + h = attr.height - ry * 2; + if (r || ry) { + x2 = x + r * (1 - circ); + x3 = x + r; + x4 = x3 + w; + x5 = x4 + r * circ; + x6 = x4 + r; + y2 = y + ry * (1 - circ); + y3 = y + ry; + y4 = y3 + h; + y5 = y4 + ry * circ; + y6 = y4 + ry; + data = "M" + x6 + "," + y3 + " V" + y4 + " C" + [x6, y5, x5, y6, x4, y6, x4 - (x4 - x3) / 3, y6, x3 + (x4 - x3) / 3, y6, x3, y6, x2, y6, x, y5, x, y4, x, y4 - (y4 - y3) / 3, x, y3 + (y4 - y3) / 3, x, y3, x, y2, x2, y, x3, y, x3 + (x4 - x3) / 3, y, x4 - (x4 - x3) / 3, y, x4, y, x5, y, x6, y2, x6, y3].join(",") + "z"; + } else { + data = "M" + (x + w) + "," + y + " v" + h + " h" + -w + " v" + -h + " h" + w + "z"; } - }); - game.settings.register("eunos-blades", "blacklist", { - name: "Debug Blacklist", - hint: "Comma-delimited list of categories of debug messages to silence.", - scope: "client", - // This specifies a world-level setting - config: true, - // This specifies that the setting appears in the configuration view - type: String, - default: "" - // The default value for the setting - }); - game.settings.register("eunos-blades", "openAPIKey", { - name: "OpenAI API Key", - hint: "Your personal OpenAI API Key (necessary to enable AI functionality)", - scope: "client", - // This specifies a world-level setting - config: true, - // This specifies that the setting appears in the configuration view - type: String, - default: "" - // The default value for the setting - }); - game.settings.register("eunos-blades", "whitelist", { - name: "Debug Whitelist", - hint: "Comma-delimited list of categories of debug messages to promote.", - scope: "client", - // This specifies a world-level setting - config: true, - // This specifies that the setting appears in the configuration view - type: String, - default: "" - // The default value for the setting - }); - game.settings.register("eunos-blades", "systemMigrationVersion", { - name: "System Migration Version", - scope: "world", - config: false, - type: Number, - default: 0 - }); -}; -function initTinyMCEStyles() { - CONFIG.TinyMCE = { - ...CONFIG.TinyMCE, - ...{ - skin: "skin", - skin_url: "systems/eunos-blades/tinymce/skin", - content_css: `systems/eunos-blades/tinymce/content.css?${(/* @__PURE__ */ new Date()).getTime()}`, - font_css: "systems/eunos-blades/fonts.css", - max_height: 500, - min_height: 40, - autoresize_overflow_padding: 0, - autoresize_bottom_margin: 0, - // 25, - menubar: false, - statusbar: false, - // True, - elementPath: true, - branding: false, - resize: false, - plugins: "lists image table code save autoresize searchreplace quickbars template", - save_enablewhendirty: false, - // Table_default_styles: {}, - style_formats: [ - { - title: "Headings", - items: [ - { title: "Heading 1", block: "h1", wrapper: false }, - { title: "Heading 2", block: "h2", wrapper: false }, - { title: "Heading 3", block: "h3", wrapper: false }, - { title: "Heading 4", block: "h4", wrapper: false } - ] - }, - { - title: "Blocks", - items: [ - { title: "Paragraph", block: "p", wrapper: false }, - { title: "Block Quote", block: "blockquote", wrapper: true } - // {title: "Secret", block: "span", classes: "text-secret", attributes: {"data-is-secret": "true"}, wrapper: false} - ] - }, - { - title: "Inline", - items: [ - { title: "Bold", inline: "b", wrapper: false }, - { title: "Italics", inline: "i", wrapper: false }, - { title: "Underline", inline: "u", wrapper: false }, - { title: "Secret", inline: "span", classes: "text-secret", attributes: { "data-is-secret": "true" }, wrapper: false } - ] - } - ], - style_formats_merge: false, - toolbar: "styles | searchreplace | formatting alignment lists elements | removeformat | code | save", - toolbar_groups: { - formatting: { - icon: "color-picker", - tooltip: "Formatting", - items: "bold italic underline" - }, - alignment: { - icon: "align-left", - tooltip: "Alignment", - items: "alignleft aligncenter alignright alignjustify | outdent indent" - }, - lists: { - icon: "unordered-list", - tooltip: "Lists", - items: "bullist numlist" - }, - elements: { - icon: "duplicate", - tooltip: "Insert Element", - items: "tableinsertdialog image hr | template" - } - }, - toolbar_mode: "floating", - quickbars_link_toolbar: false, - quickbars_selection_toolbar: "styles | bold italic underline", - quickbars_insert_toolbar: "hr image table", - quickbars_table_toolbar: "tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol" - } - }; -} -function initCanvasStyles() { - CONFIG.canvasTextStyle = new PIXI.TextStyle({ - align: "center", - dropShadow: true, - dropShadowAngle: U.degToRad(45), - dropShadowBlur: 8, - dropShadowColor: C.Colors.BLACK, - dropShadowDistance: 4, - fill: [ - C.Colors.bWHITE, - C.Colors.bGREY - ], - fillGradientType: 1, - fillGradientStops: [ - 0, - 0.3 - ], - fontFamily: "Kirsty", - fontSize: 32, - letterSpacing: 2, - lineHeight: 32, - lineJoin: "round", - padding: 4, - stroke: C.Colors.dBLACK, - strokeThickness: 3, - trim: true, - whiteSpace: "normal", - wordWrap: true, - wordWrapWidth: 0.1 - }); -} -function initDOMStyles() { - $("body.vtt.game.system-eunos-blades").append(`
`); - $("#interface").append(`
-
`); + } else if (type === "circle" || type === "ellipse") { + if (type === "circle") { + r = ry = attr.r; + rycirc = r * circ; + } else { + r = attr.rx; + ry = attr.ry; + rycirc = ry * circ; + } + x = attr.cx; + y = attr.cy; + rcirc = r * circ; + data = "M" + (x + r) + "," + y + " C" + [x + r, y + rycirc, x + rcirc, y + ry, x, y + ry, x - rcirc, y + ry, x - r, y + rycirc, x - r, y, x - r, y - rycirc, x - rcirc, y - ry, x, y - ry, x + rcirc, y - ry, x + r, y - rycirc, x + r, y].join(",") + "z"; + } else if (type === "line") { + data = "M" + attr.x1 + "," + attr.y1 + " L" + attr.x2 + "," + attr.y2; + } else if (type === "polyline" || type === "polygon") { + points = (element.getAttribute("points") + "").match(_numbersExp) || []; + x = points.shift(); + y = points.shift(); + data = "M" + x + "," + y + " L" + points.join(","); + if (type === "polygon") { + data += "," + x + "," + y + "z"; + } + } + path.setAttribute("d", rawPathToString(path._gsRawPath = stringToRawPath(data))); + if (swap && element.parentNode) { + element.parentNode.insertBefore(path, element); + element.parentNode.removeChild(element); + } + return path; } -async function preloadHandlebarsTemplates() { - const templatePaths = [ - // General Components - "systems/eunos-blades/templates/components/toggle-icon.hbs", - "systems/eunos-blades/templates/components/button-icon.hbs", - "systems/eunos-blades/templates/components/dotline.hbs", - "systems/eunos-blades/templates/components/armor.hbs", - "systems/eunos-blades/templates/components/comp.hbs", - "systems/eunos-blades/templates/components/select.hbs", - "systems/eunos-blades/templates/components/portrait.hbs", - "systems/eunos-blades/templates/components/clock.hbs", - "systems/eunos-blades/templates/components/roll-collab-mod.hbs", - "systems/eunos-blades/templates/components/slide-out-controls.hbs", - "systems/eunos-blades/templates/components/consequence.hbs", - "systems/eunos-blades/templates/components/consequence-accepted.hbs", - // Partials - "systems/eunos-blades/templates/parts/tier-block.hbs", - "systems/eunos-blades/templates/parts/turf-list.hbs", - "systems/eunos-blades/templates/parts/cohort-block.hbs", - "systems/eunos-blades/templates/parts/roll-opposition-creator.hbs", - "systems/eunos-blades/templates/parts/active-effects.hbs", - "systems/eunos-blades/templates/parts/gm-pc-summary.hbs", - "systems/eunos-blades/templates/components/clock-key.hbs" - ]; - return loadTemplates(templatePaths); +function getRotationAtBezierT(segment, i, t) { + var a = segment[i], b = segment[i + 2], c = segment[i + 4], x; + a += (b - a) * t; + b += (c - b) * t; + a += (b - a) * t; + x = b + (c + (segment[i + 6] - c) * t - b) * t - a; + a = segment[i + 1]; + b = segment[i + 3]; + c = segment[i + 5]; + a += (b - a) * t; + b += (c - b) * t; + a += (b - a) * t; + return _round$3(_atan2(b + (c + (segment[i + 7] - c) * t - b) * t - a, x) * _RAD2DEG$2); } -const handlebarHelpers = { - randString(param1 = 10) { - return U.randString(param1); - }, - test(param1, operator, param2) { - const stringMap = { - true: true, - false: false, - null: null, - undefined: void 0 - }; - if (["!", "not", "=??"].includes(String(param1))) { - [operator, param1] = [String(param1), operator]; +function sliceRawPath(rawPath, start, end) { + end = _isUndefined$1(end) ? 1 : _roundPrecise2(end) || 0; + start = _roundPrecise2(start) || 0; + var loops = Math.max(0, ~~(_abs(end - start) - 1e-8)), path = copyRawPath(rawPath); + if (start > end) { + start = 1 - start; + end = 1 - end; + _reverseRawPath(path); + path.totalLength = 0; + } + if (start < 0 || end < 0) { + var offset = Math.abs(~~Math.min(start, end)) + 1; + start += offset; + end += offset; + } + path.totalLength || cacheRawPathMeasurements(path); + var wrap3 = end > 1, s = getProgressData(path, start, _temp, true), e = getProgressData(path, end, _temp2), eSeg = e.segment, sSeg = s.segment, eSegIndex = e.segIndex, sSegIndex = s.segIndex, ei = e.i, si = s.i, sameSegment = sSegIndex === eSegIndex, sameBezier = ei === si && sameSegment, wrapsBehind, sShift, eShift, i, copy, totalSegments, l, j; + if (wrap3 || loops) { + wrapsBehind = eSegIndex < sSegIndex || sameSegment && ei < si || sameBezier && e.t < s.t; + if (_splitSegment(path, sSegIndex, si, s.t)) { + sSegIndex++; + if (!wrapsBehind) { + eSegIndex++; + if (sameBezier) { + e.t = (e.t - s.t) / (1 - s.t); + ei = 0; + } else if (sameSegment) { + ei -= si; + } + } } - if (typeof param1 === "string" && param1 in stringMap) { - param1 = stringMap[param1]; + if (Math.abs(1 - (end - start)) < 1e-5) { + eSegIndex = sSegIndex - 1; + } else if (!e.t && eSegIndex) { + eSegIndex--; + } else if (_splitSegment(path, eSegIndex, ei, e.t) && wrapsBehind) { + sSegIndex++; } - if (typeof param2 === "string" && param2 in stringMap) { - param2 = stringMap[param2]; + if (s.t === 1) { + sSegIndex = (sSegIndex + 1) % path.length; } - switch (operator) { - case "!": - case "not": { - return !param1; - } - case "=??": { - return [void 0, null].includes(param1); - } - case "&&": { - return param1 && param2; + copy = []; + totalSegments = path.length; + l = 1 + totalSegments * loops; + j = sSegIndex; + l += (totalSegments - sSegIndex + eSegIndex) % totalSegments; + for (i = 0; i < l; i++) { + _appendOrMerge(copy, path[j++ % totalSegments]); + } + path = copy; + } else { + eShift = e.t === 1 ? 6 : subdivideSegment(eSeg, ei, e.t); + if (start !== end) { + sShift = subdivideSegment(sSeg, si, sameBezier ? s.t / e.t : s.t); + sameSegment && (eShift += sShift); + eSeg.splice(ei + eShift + 2); + (sShift || si) && sSeg.splice(0, si + sShift); + i = path.length; + while (i--) { + (i < sSegIndex || i > eSegIndex) && path.splice(i, 1); } - case "||": { - return param1 || param2; + } else { + eSeg.angle = getRotationAtBezierT(eSeg, ei + eShift, 0); + ei += eShift; + s = eSeg[ei]; + e = eSeg[ei + 1]; + eSeg.length = eSeg.totalLength = 0; + eSeg.totalPoints = path.totalPoints = 8; + eSeg.push(s, e, s, e, s, e, s, e); + } + } + path.totalLength = 0; + return path; +} +function measureSegment(segment, startIndex, bezierQty) { + startIndex = startIndex || 0; + if (!segment.samples) { + segment.samples = []; + segment.lookup = []; + } + var resolution = ~~segment.resolution || 12, inc = 1 / resolution, endIndex = bezierQty ? startIndex + bezierQty * 6 + 1 : segment.length, x1 = segment[startIndex], y1 = segment[startIndex + 1], samplesIndex = startIndex ? startIndex / 6 * resolution : 0, samples = segment.samples, lookup = segment.lookup, min = (startIndex ? segment.minLength : _largeNum) || _largeNum, prevLength = samples[samplesIndex + bezierQty * resolution - 1], length = startIndex ? samples[samplesIndex - 1] : 0, i, j, x4, x3, x2, xd, xd1, y4, y3, y2, yd, yd1, inv, t, lengthIndex, l, segLength; + samples.length = lookup.length = 0; + for (j = startIndex + 2; j < endIndex; j += 6) { + x4 = segment[j + 4] - x1; + x3 = segment[j + 2] - x1; + x2 = segment[j] - x1; + y4 = segment[j + 5] - y1; + y3 = segment[j + 3] - y1; + y2 = segment[j + 1] - y1; + xd = xd1 = yd = yd1 = 0; + if (_abs(x4) < 0.01 && _abs(y4) < 0.01 && _abs(x2) + _abs(y2) < 0.01) { + if (segment.length > 8) { + segment.splice(j, 6); + j -= 6; + endIndex -= 6; } - case "==": { - return U.areFuzzyEqual(param1, param2); + } else { + for (i = 1; i <= resolution; i++) { + t = inc * i; + inv = 1 - t; + xd = xd1 - (xd1 = (t * t * x4 + 3 * inv * (t * x3 + inv * x2)) * t); + yd = yd1 - (yd1 = (t * t * y4 + 3 * inv * (t * y3 + inv * y2)) * t); + l = _sqrt(yd * yd + xd * xd); + if (l < min) { + min = l; + } + length += l; + samples[samplesIndex++] = length; } - case "===": { - return param1 === param2; + } + x1 += x4; + y1 += y4; + } + if (prevLength) { + prevLength -= length; + for (; samplesIndex < samples.length; samplesIndex++) { + samples[samplesIndex] += prevLength; + } + } + if (samples.length && min) { + segment.totalLength = segLength = samples[samples.length - 1] || 0; + segment.minLength = min; + if (segLength / min < 9999) { + l = lengthIndex = 0; + for (i = 0; i < segLength; i += min) { + lookup[l++] = samples[lengthIndex] < i ? ++lengthIndex : lengthIndex; } - case "!=": - case "!==": { - return param1 !== param2; + } + } else { + segment.totalLength = samples[0] = 0; + } + return startIndex ? length - samples[startIndex / 2 - 1] : length; +} +function cacheRawPathMeasurements(rawPath, resolution) { + var pathLength, points, i; + for (i = pathLength = points = 0; i < rawPath.length; i++) { + rawPath[i].resolution = ~~resolution || 12; + points += rawPath[i].length; + pathLength += measureSegment(rawPath[i]); + } + rawPath.totalPoints = points; + rawPath.totalLength = pathLength; + return rawPath; +} +function subdivideSegment(segment, i, t) { + if (t <= 0 || t >= 1) { + return 0; + } + var ax = segment[i], ay = segment[i + 1], cp1x = segment[i + 2], cp1y = segment[i + 3], cp2x = segment[i + 4], cp2y = segment[i + 5], bx = segment[i + 6], by = segment[i + 7], x1a = ax + (cp1x - ax) * t, x2 = cp1x + (cp2x - cp1x) * t, y1a = ay + (cp1y - ay) * t, y2 = cp1y + (cp2y - cp1y) * t, x1 = x1a + (x2 - x1a) * t, y1 = y1a + (y2 - y1a) * t, x2a = cp2x + (bx - cp2x) * t, y2a = cp2y + (by - cp2y) * t; + x2 += (x2a - x2) * t; + y2 += (y2a - y2) * t; + segment.splice( + i + 2, + 4, + _round$3(x1a), + //first control point + _round$3(y1a), + _round$3(x1), + //second control point + _round$3(y1), + _round$3(x1 + (x2 - x1) * t), + //new fabricated anchor on line + _round$3(y1 + (y2 - y1) * t), + _round$3(x2), + //third control point + _round$3(y2), + _round$3(x2a), + //fourth control point + _round$3(y2a) + ); + segment.samples && segment.samples.splice(i / 6 * segment.resolution | 0, 0, 0, 0, 0, 0, 0, 0); + return 6; +} +function getProgressData(rawPath, progress, decoratee, pushToNextIfAtEnd) { + decoratee = decoratee || {}; + rawPath.totalLength || cacheRawPathMeasurements(rawPath); + if (progress < 0 || progress > 1) { + progress = _wrapProgress(progress); + } + var segIndex = 0, segment = rawPath[0], samples, resolution, length, min, max, i, t; + if (!progress) { + t = i = segIndex = 0; + segment = rawPath[0]; + } else if (progress === 1) { + t = 1; + segIndex = rawPath.length - 1; + segment = rawPath[segIndex]; + i = segment.length - 8; + } else { + if (rawPath.length > 1) { + length = rawPath.totalLength * progress; + max = i = 0; + while ((max += rawPath[i++].totalLength) < length) { + segIndex = i; + } + segment = rawPath[segIndex]; + min = max - segment.totalLength; + progress = (length - min) / (max - min) || 0; + } + samples = segment.samples; + resolution = segment.resolution; + length = segment.totalLength * progress; + i = segment.lookup.length ? segment.lookup[~~(length / segment.minLength)] || 0 : _getSampleIndex(samples, length, progress); + min = i ? samples[i - 1] : 0; + max = samples[i]; + if (max < length) { + min = max; + max = samples[++i]; + } + t = 1 / resolution * ((length - min) / (max - min) + i % resolution); + i = ~~(i / resolution) * 6; + if (pushToNextIfAtEnd && t === 1) { + if (i + 6 < segment.length) { + i += 6; + t = 0; + } else if (segIndex + 1 < rawPath.length) { + i = t = 0; + segment = rawPath[++segIndex]; + } + } + } + decoratee.t = t; + decoratee.i = i; + decoratee.path = rawPath; + decoratee.segment = segment; + decoratee.segIndex = segIndex; + return decoratee; +} +function getPositionOnPath(rawPath, progress, includeAngle, point) { + var segment = rawPath[0], result = point || {}, samples, resolution, length, min, max, i, t, a, inv; + if (progress < 0 || progress > 1) { + progress = _wrapProgress(progress); + } + segment.lookup || cacheRawPathMeasurements(rawPath); + if (rawPath.length > 1) { + length = rawPath.totalLength * progress; + max = i = 0; + while ((max += rawPath[i++].totalLength) < length) { + segment = rawPath[i]; + } + min = max - segment.totalLength; + progress = (length - min) / (max - min) || 0; + } + samples = segment.samples; + resolution = segment.resolution; + length = segment.totalLength * progress; + i = segment.lookup.length ? segment.lookup[progress < 1 ? ~~(length / segment.minLength) : segment.lookup.length - 1] || 0 : _getSampleIndex(samples, length, progress); + min = i ? samples[i - 1] : 0; + max = samples[i]; + if (max < length) { + min = max; + max = samples[++i]; + } + t = 1 / resolution * ((length - min) / (max - min) + i % resolution) || 0; + inv = 1 - t; + i = ~~(i / resolution) * 6; + a = segment[i]; + result.x = _round$3((t * t * (segment[i + 6] - a) + 3 * inv * (t * (segment[i + 4] - a) + inv * (segment[i + 2] - a))) * t + a); + result.y = _round$3((t * t * (segment[i + 7] - (a = segment[i + 1])) + 3 * inv * (t * (segment[i + 5] - a) + inv * (segment[i + 3] - a))) * t + a); + if (includeAngle) { + result.angle = segment.totalLength ? getRotationAtBezierT(segment, i, t >= 1 ? 1 - 1e-9 : t ? t : 1e-9) : segment.angle || 0; + } + return result; +} +function transformRawPath(rawPath, a, b, c, d, tx, ty) { + var j = rawPath.length, segment, l, i, x, y; + while (--j > -1) { + segment = rawPath[j]; + l = segment.length; + for (i = 0; i < l; i += 2) { + x = segment[i]; + y = segment[i + 1]; + segment[i] = x * a + y * c + tx; + segment[i + 1] = x * b + y * d + ty; + } + } + rawPath._dirty = 1; + return rawPath; +} +function arcToSegment(lastX, lastY, rx, ry, angle, largeArcFlag, sweepFlag, x, y) { + if (lastX === x && lastY === y) { + return; + } + rx = _abs(rx); + ry = _abs(ry); + var angleRad = angle % 360 * _DEG2RAD$2, cosAngle = _cos(angleRad), sinAngle = _sin(angleRad), PI = Math.PI, TWOPI = PI * 2, dx2 = (lastX - x) / 2, dy2 = (lastY - y) / 2, x1 = cosAngle * dx2 + sinAngle * dy2, y1 = -sinAngle * dx2 + cosAngle * dy2, x1_sq = x1 * x1, y1_sq = y1 * y1, radiiCheck = x1_sq / (rx * rx) + y1_sq / (ry * ry); + if (radiiCheck > 1) { + rx = _sqrt(radiiCheck) * rx; + ry = _sqrt(radiiCheck) * ry; + } + var rx_sq = rx * rx, ry_sq = ry * ry, sq = (rx_sq * ry_sq - rx_sq * y1_sq - ry_sq * x1_sq) / (rx_sq * y1_sq + ry_sq * x1_sq); + if (sq < 0) { + sq = 0; + } + var coef = (largeArcFlag === sweepFlag ? -1 : 1) * _sqrt(sq), cx1 = coef * (rx * y1 / ry), cy1 = coef * -(ry * x1 / rx), sx2 = (lastX + x) / 2, sy2 = (lastY + y) / 2, cx = sx2 + (cosAngle * cx1 - sinAngle * cy1), cy = sy2 + (sinAngle * cx1 + cosAngle * cy1), ux = (x1 - cx1) / rx, uy = (y1 - cy1) / ry, vx = (-x1 - cx1) / rx, vy = (-y1 - cy1) / ry, temp = ux * ux + uy * uy, angleStart = (uy < 0 ? -1 : 1) * Math.acos(ux / _sqrt(temp)), angleExtent = (ux * vy - uy * vx < 0 ? -1 : 1) * Math.acos((ux * vx + uy * vy) / _sqrt(temp * (vx * vx + vy * vy))); + isNaN(angleExtent) && (angleExtent = PI); + if (!sweepFlag && angleExtent > 0) { + angleExtent -= TWOPI; + } else if (sweepFlag && angleExtent < 0) { + angleExtent += TWOPI; + } + angleStart %= TWOPI; + angleExtent %= TWOPI; + var segments = Math.ceil(_abs(angleExtent) / (TWOPI / 4)), rawPath = [], angleIncrement = angleExtent / segments, controlLength = 4 / 3 * _sin(angleIncrement / 2) / (1 + _cos(angleIncrement / 2)), ma = cosAngle * rx, mb = sinAngle * rx, mc = sinAngle * -ry, md = cosAngle * ry, i; + for (i = 0; i < segments; i++) { + angle = angleStart + i * angleIncrement; + x1 = _cos(angle); + y1 = _sin(angle); + ux = _cos(angle += angleIncrement); + uy = _sin(angle); + rawPath.push(x1 - controlLength * y1, y1 + controlLength * x1, ux + controlLength * uy, uy - controlLength * ux, ux, uy); + } + for (i = 0; i < rawPath.length; i += 2) { + x1 = rawPath[i]; + y1 = rawPath[i + 1]; + rawPath[i] = x1 * ma + y1 * mc + cx; + rawPath[i + 1] = x1 * mb + y1 * md + cy; + } + rawPath[i - 2] = x; + rawPath[i - 1] = y; + return rawPath; +} +function stringToRawPath(d) { + var a = (d + "").replace(_scientific, function(m) { + var n = +m; + return n < 1e-4 && n > -1e-4 ? 0 : n; + }).match(_svgPathExp) || [], path = [], relativeX = 0, relativeY = 0, twoThirds = 2 / 3, elements = a.length, points = 0, errorMessage = "ERROR: malformed path: " + d, i, j, x, y, command, isRelative, segment, startX, startY, difX, difY, beziers, prevCommand, flag1, flag2, line = function line2(sx, sy, ex, ey) { + difX = (ex - sx) / 3; + difY = (ey - sy) / 3; + segment.push(sx + difX, sy + difY, ex - difX, ey - difY, ex, ey); + }; + if (!d || !isNaN(a[0]) || isNaN(a[1])) { + console.log(errorMessage); + return path; + } + for (i = 0; i < elements; i++) { + prevCommand = command; + if (isNaN(a[i])) { + command = a[i].toUpperCase(); + isRelative = command !== a[i]; + } else { + i--; + } + x = +a[i + 1]; + y = +a[i + 2]; + if (isRelative) { + x += relativeX; + y += relativeY; + } + if (!i) { + startX = x; + startY = y; + } + if (command === "M") { + if (segment) { + if (segment.length < 8) { + path.length -= 1; + } else { + points += segment.length; + } } - case ">": { - return typeof param1 === "number" && typeof param2 === "number" && param1 > param2; + relativeX = startX = x; + relativeY = startY = y; + segment = [x, y]; + path.push(segment); + i += 2; + command = "L"; + } else if (command === "C") { + if (!segment) { + segment = [0, 0]; + } + if (!isRelative) { + relativeX = relativeY = 0; + } + segment.push(x, y, relativeX + a[i + 3] * 1, relativeY + a[i + 4] * 1, relativeX += a[i + 5] * 1, relativeY += a[i + 6] * 1); + i += 6; + } else if (command === "S") { + difX = relativeX; + difY = relativeY; + if (prevCommand === "C" || prevCommand === "S") { + difX += relativeX - segment[segment.length - 4]; + difY += relativeY - segment[segment.length - 3]; + } + if (!isRelative) { + relativeX = relativeY = 0; + } + segment.push(difX, difY, x, y, relativeX += a[i + 3] * 1, relativeY += a[i + 4] * 1); + i += 4; + } else if (command === "Q") { + difX = relativeX + (x - relativeX) * twoThirds; + difY = relativeY + (y - relativeY) * twoThirds; + if (!isRelative) { + relativeX = relativeY = 0; + } + relativeX += a[i + 3] * 1; + relativeY += a[i + 4] * 1; + segment.push(difX, difY, relativeX + (x - relativeX) * twoThirds, relativeY + (y - relativeY) * twoThirds, relativeX, relativeY); + i += 4; + } else if (command === "T") { + difX = relativeX - segment[segment.length - 4]; + difY = relativeY - segment[segment.length - 3]; + segment.push(relativeX + difX, relativeY + difY, x + (relativeX + difX * 1.5 - x) * twoThirds, y + (relativeY + difY * 1.5 - y) * twoThirds, relativeX = x, relativeY = y); + i += 2; + } else if (command === "H") { + line(relativeX, relativeY, relativeX = x, relativeY); + i += 1; + } else if (command === "V") { + line(relativeX, relativeY, relativeX, relativeY = x + (isRelative ? relativeY - relativeX : 0)); + i += 1; + } else if (command === "L" || command === "Z") { + if (command === "Z") { + x = startX; + y = startY; + segment.closed = true; + } + if (command === "L" || _abs(relativeX - x) > 0.5 || _abs(relativeY - y) > 0.5) { + line(relativeX, relativeY, x, y); + if (command === "L") { + i += 2; + } } - case "<": { - return typeof param1 === "number" && typeof param2 === "number" && param1 < param2; + relativeX = x; + relativeY = y; + } else if (command === "A") { + flag1 = a[i + 4]; + flag2 = a[i + 5]; + difX = a[i + 6]; + difY = a[i + 7]; + j = 7; + if (flag1.length > 1) { + if (flag1.length < 3) { + difY = difX; + difX = flag2; + j--; + } else { + difY = flag2; + difX = flag1.substr(2); + j -= 2; + } + flag2 = flag1.charAt(1); + flag1 = flag1.charAt(0); + } + beziers = arcToSegment(relativeX, relativeY, +a[i + 1], +a[i + 2], +a[i + 3], +flag1, +flag2, (isRelative ? relativeX : 0) + difX * 1, (isRelative ? relativeY : 0) + difY * 1); + i += j; + if (beziers) { + for (j = 0; j < beziers.length; j++) { + segment.push(beziers[j]); + } } - case ">=": { - return typeof param1 === "number" && typeof param2 === "number" && param1 >= param2; + relativeX = segment[segment.length - 2]; + relativeY = segment[segment.length - 1]; + } else { + console.log(errorMessage); + } + } + i = segment.length; + if (i < 6) { + path.pop(); + i = 0; + } else if (segment[0] === segment[i - 2] && segment[1] === segment[i - 1]) { + segment.closed = true; + } + path.totalPoints = points + i; + return path; +} +function flatPointsToSegment(points, curviness) { + if (curviness === void 0) { + curviness = 1; + } + var x = points[0], y = 0, segment = [x, y], i = 2; + for (; i < points.length; i += 2) { + segment.push(x, y, points[i], y = (points[i] - x) * curviness / 2, x = points[i], -y); + } + return segment; +} +function pointsToSegment(points, curviness) { + _abs(points[0] - points[2]) < 1e-4 && _abs(points[1] - points[3]) < 1e-4 && (points = points.slice(2)); + var l = points.length - 2, x = +points[0], y = +points[1], nextX = +points[2], nextY = +points[3], segment = [x, y, x, y], dx2 = nextX - x, dy2 = nextY - y, closed = Math.abs(points[l] - x) < 1e-3 && Math.abs(points[l + 1] - y) < 1e-3, prevX, prevY, i, dx1, dy1, r1, r2, r3, tl, mx1, mx2, mxm, my1, my2, mym; + if (closed) { + points.push(nextX, nextY); + nextX = x; + nextY = y; + x = points[l - 2]; + y = points[l - 1]; + points.unshift(x, y); + l += 4; + } + curviness = curviness || curviness === 0 ? +curviness : 1; + for (i = 2; i < l; i += 2) { + prevX = x; + prevY = y; + x = nextX; + y = nextY; + nextX = +points[i + 2]; + nextY = +points[i + 3]; + if (x === nextX && y === nextY) { + continue; + } + dx1 = dx2; + dy1 = dy2; + dx2 = nextX - x; + dy2 = nextY - y; + r1 = _sqrt(dx1 * dx1 + dy1 * dy1); + r2 = _sqrt(dx2 * dx2 + dy2 * dy2); + r3 = _sqrt(Math.pow(dx2 / r2 + dx1 / r1, 2) + Math.pow(dy2 / r2 + dy1 / r1, 2)); + tl = (r1 + r2) * curviness * 0.25 / r3; + mx1 = x - (x - prevX) * (r1 ? tl / r1 : 0); + mx2 = x + (nextX - x) * (r2 ? tl / r2 : 0); + mxm = x - (mx1 + ((mx2 - mx1) * (r1 * 3 / (r1 + r2) + 0.5) / 4 || 0)); + my1 = y - (y - prevY) * (r1 ? tl / r1 : 0); + my2 = y + (nextY - y) * (r2 ? tl / r2 : 0); + mym = y - (my1 + ((my2 - my1) * (r1 * 3 / (r1 + r2) + 0.5) / 4 || 0)); + if (x !== prevX || y !== prevY) { + segment.push( + _round$3(mx1 + mxm), + // first control point + _round$3(my1 + mym), + _round$3(x), + // anchor + _round$3(y), + _round$3(mx2 + mxm), + // second control point + _round$3(my2 + mym) + ); + } + } + x !== nextX || y !== nextY || segment.length < 4 ? segment.push(_round$3(nextX), _round$3(nextY), _round$3(nextX), _round$3(nextY)) : segment.length -= 2; + if (segment.length === 2) { + segment.push(x, y, x, y, x, y); + } else if (closed) { + segment.splice(0, 6); + segment.length = segment.length - 6; + } + return segment; +} +function rawPathToString(rawPath) { + if (_isNumber2(rawPath[0])) { + rawPath = [rawPath]; + } + var result = "", l = rawPath.length, sl, s, i, segment; + for (s = 0; s < l; s++) { + segment = rawPath[s]; + result += "M" + _round$3(segment[0]) + "," + _round$3(segment[1]) + " C"; + sl = segment.length; + for (i = 2; i < sl; i++) { + result += _round$3(segment[i++]) + "," + _round$3(segment[i++]) + " " + _round$3(segment[i++]) + "," + _round$3(segment[i++]) + " " + _round$3(segment[i++]) + "," + _round$3(segment[i]) + " "; + } + if (segment.closed) { + result += "z"; + } + } + return result; +} +/*! + * CustomEase 3.12.5 + * https://gsap.com + * + * @license Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var gsap$5, _coreInitted$2, _getGSAP$4 = function _getGSAP() { + return gsap$5 || typeof window !== "undefined" && (gsap$5 = window.gsap) && gsap$5.registerPlugin && gsap$5; +}, _initCore$2 = function _initCore2() { + gsap$5 = _getGSAP$4(); + if (gsap$5) { + gsap$5.registerEase("_CE", CustomEase.create); + _coreInitted$2 = 1; + } else { + console.warn("Please gsap.registerPlugin(CustomEase)"); + } +}, _bigNum$1 = 1e20, _round$2 = function _round3(value) { + return ~~(value * 1e3 + (value < 0 ? -0.5 : 0.5)) / 1e3; +}, _numExp$1 = /[-+=.]*\d+[.e\-+]*\d*[e\-+]*\d*/gi, _needsParsingExp = /[cLlsSaAhHvVtTqQ]/g, _findMinimum = function _findMinimum2(values) { + var l = values.length, min = _bigNum$1, i; + for (i = 1; i < l; i += 6) { + +values[i] < min && (min = +values[i]); + } + return min; +}, _normalize = function _normalize2(values, height, originY) { + if (!originY && originY !== 0) { + originY = Math.max(+values[values.length - 1], +values[1]); + } + var tx = +values[0] * -1, ty = -originY, l = values.length, sx = 1 / (+values[l - 2] + tx), sy = -height || (Math.abs(+values[l - 1] - +values[1]) < 0.01 * (+values[l - 2] - +values[0]) ? _findMinimum(values) + ty : +values[l - 1] + ty), i; + if (sy) { + sy = 1 / sy; + } else { + sy = -sx; + } + for (i = 0; i < l; i += 2) { + values[i] = (+values[i] + tx) * sx; + values[i + 1] = (+values[i + 1] + ty) * sy; + } +}, _bezierToPoints = function _bezierToPoints2(x1, y1, x2, y2, x3, y3, x4, y4, threshold, points, index) { + var x12 = (x1 + x2) / 2, y12 = (y1 + y2) / 2, x23 = (x2 + x3) / 2, y23 = (y2 + y3) / 2, x34 = (x3 + x4) / 2, y34 = (y3 + y4) / 2, x123 = (x12 + x23) / 2, y123 = (y12 + y23) / 2, x234 = (x23 + x34) / 2, y234 = (y23 + y34) / 2, x1234 = (x123 + x234) / 2, y1234 = (y123 + y234) / 2, dx = x4 - x1, dy = y4 - y1, d2 = Math.abs((x2 - x4) * dy - (y2 - y4) * dx), d3 = Math.abs((x3 - x4) * dy - (y3 - y4) * dx), length; + if (!points) { + points = [{ + x: x1, + y: y1 + }, { + x: x4, + y: y4 + }]; + index = 1; + } + points.splice(index || points.length - 1, 0, { + x: x1234, + y: y1234 + }); + if ((d2 + d3) * (d2 + d3) > threshold * (dx * dx + dy * dy)) { + length = points.length; + _bezierToPoints2(x1, y1, x12, y12, x123, y123, x1234, y1234, threshold, points, index); + _bezierToPoints2(x1234, y1234, x234, y234, x34, y34, x4, y4, threshold, points, index + 1 + (points.length - length)); + } + return points; +}; +var CustomEase = /* @__PURE__ */ function() { + function CustomEase2(id, data, config3) { + _coreInitted$2 || _initCore$2(); + this.id = id; + this.setData(data, config3); + } + var _proto = CustomEase2.prototype; + _proto.setData = function setData(data, config3) { + config3 = config3 || {}; + data = data || "0,0,1,1"; + var values = data.match(_numExp$1), closest = 1, points = [], lookup = [], precision = config3.precision || 1, fast = precision <= 1, l, a1, a2, i, inc, j, point, prevPoint, p; + this.data = data; + if (_needsParsingExp.test(data) || ~data.indexOf("M") && data.indexOf("C") < 0) { + values = stringToRawPath(data)[0]; + } + l = values.length; + if (l === 4) { + values.unshift(0, 0); + values.push(1, 1); + l = 8; + } else if ((l - 2) % 6) { + throw "Invalid CustomEase"; + } + if (+values[0] !== 0 || +values[l - 2] !== 1) { + _normalize(values, config3.height, config3.originY); + } + this.segment = values; + for (i = 2; i < l; i += 6) { + a1 = { + x: +values[i - 2], + y: +values[i - 1] + }; + a2 = { + x: +values[i + 4], + y: +values[i + 5] + }; + points.push(a1, a2); + _bezierToPoints(a1.x, a1.y, +values[i], +values[i + 1], +values[i + 2], +values[i + 3], a2.x, a2.y, 1 / (precision * 2e5), points, points.length - 1); + } + l = points.length; + for (i = 0; i < l; i++) { + point = points[i]; + prevPoint = points[i - 1] || point; + if ((point.x > prevPoint.x || prevPoint.y !== point.y && prevPoint.x === point.x || point === prevPoint) && point.x <= 1) { + prevPoint.cx = point.x - prevPoint.x; + prevPoint.cy = point.y - prevPoint.y; + prevPoint.n = point; + prevPoint.nx = point.x; + if (fast && i > 1 && Math.abs(prevPoint.cy / prevPoint.cx - points[i - 2].cy / points[i - 2].cx) > 2) { + fast = 0; + } + if (prevPoint.cx < closest) { + if (!prevPoint.cx) { + prevPoint.cx = 1e-3; + if (i === l - 1) { + prevPoint.x -= 1e-3; + closest = Math.min(closest, 1e-3); + fast = 0; + } + } else { + closest = prevPoint.cx; + } + } + } else { + points.splice(i--, 1); + l--; + } + } + l = 1 / closest + 1 | 0; + inc = 1 / l; + j = 0; + point = points[0]; + if (fast) { + for (i = 0; i < l; i++) { + p = i * inc; + if (point.nx < p) { + point = points[++j]; + } + a1 = point.y + (p - point.x) / point.cx * point.cy; + lookup[i] = { + x: p, + cx: inc, + y: a1, + cy: 0, + nx: 9 + }; + if (i) { + lookup[i - 1].cy = a1 - lookup[i - 1].y; + } } - case "<=": { - return typeof param1 === "number" && typeof param2 === "number" && param1 <= param2; + lookup[l - 1].cy = points[points.length - 1].y - a1; + } else { + for (i = 0; i < l; i++) { + if (point.nx < i * inc) { + point = points[++j]; + } + lookup[i] = point; } - case "??": { - return param1 ?? param2; + if (j < points.length - 1) { + lookup[i - 1] = points[points.length - 2]; } - case "includes": { - return Array.isArray(param1) && param1.includes(param2); + } + this.ease = function(p2) { + var point2 = lookup[p2 * l | 0] || lookup[l - 1]; + if (point2.nx < p2) { + point2 = point2.n; } - case "in": { - if (Array.isArray(param2)) { - return param2.includes(param1); - } - if (U.isList(param2) && (typeof param1 === "number" || typeof param1 === "string")) { - return param1 in param2; - } - if (typeof param2 === "string") { - return new RegExp(String(param1), "gu").test(String(param2)); + return point2.y + (p2 - point2.x) / point2.cx * point2.cy; + }; + this.ease.custom = this; + this.id && gsap$5 && gsap$5.registerEase(this.id, this.ease); + return this; + }; + _proto.getSVGData = function getSVGData(config3) { + return CustomEase2.getSVGData(this, config3); + }; + CustomEase2.create = function create(id, data, config3) { + return new CustomEase2(id, data, config3).ease; + }; + CustomEase2.register = function register2(core) { + gsap$5 = core; + _initCore$2(); + }; + CustomEase2.get = function get2(id) { + return gsap$5.parseEase(id); + }; + CustomEase2.getSVGData = function getSVGData(ease, config3) { + config3 = config3 || {}; + var width = config3.width || 100, height = config3.height || 100, x = config3.x || 0, y = (config3.y || 0) + height, e = gsap$5.utils.toArray(config3.path)[0], a, slope, i, inc, tx, ty, precision, threshold, prevX, prevY; + if (config3.invert) { + height = -height; + y = 0; + } + if (typeof ease === "string") { + ease = gsap$5.parseEase(ease); + } + if (ease.custom) { + ease = ease.custom; + } + if (ease instanceof CustomEase2) { + a = rawPathToString(transformRawPath([ease.segment], width, 0, 0, -height, x, y)); + } else { + a = [x, y]; + precision = Math.max(5, (config3.precision || 1) * 200); + inc = 1 / precision; + precision += 2; + threshold = 5 / precision; + prevX = _round$2(x + inc * width); + prevY = _round$2(y + ease(inc) * -height); + slope = (prevY - y) / (prevX - x); + for (i = 2; i < precision; i++) { + tx = _round$2(x + i * inc * width); + ty = _round$2(y + ease(i * inc) * -height); + if (Math.abs((ty - prevY) / (tx - prevX) - slope) > threshold || i === precision - 1) { + a.push(prevX, prevY); + slope = (ty - prevY) / (tx - prevX); } - return false; - } - default: { - return false; + prevX = tx; + prevY = ty; } + a = "M" + a.join(","); } - }, - calc(...params) { - const calcs = { - "+": (p1, p2) => U.pInt(p1) + U.pInt(p2), - "-": (p1, p2) => U.pInt(p1) - U.pInt(p2), - "*": (p1, p2) => U.pInt(p1) * U.pInt(p2), - "/": (p1, p2) => U.pInt(p1) / U.pInt(p2), - "%": (p1, p2) => U.pInt(p1) % U.pInt(p2), - max: (p1, p2) => Math.max(U.pInt(p1), U.pInt(p2)), - min: (p1, p2) => Math.min(U.pInt(p1), U.pInt(p2)), - ceil: (p1) => Math.ceil(U.pFloat(p1)), - floor: (p1) => Math.floor(U.pFloat(p1)) - }; - const [param1, operator, param2] = typeof params[0] === "string" && params[0] in calcs ? [params[1], params[0]] : params; - return calcs[operator](param1, param2); - }, - isIn(...args) { - const [testStr, ...contents] = args; - return contents.includes(testStr); - }, - case(mode, str) { - switch (mode) { - case "upper": - return U.uCase(str); - case "lower": - return U.lCase(str); - case "sentence": - return U.sCase(str); - case "title": - return U.tCase(str); - default: - return str; + e && e.setAttribute("d", a); + return a; + }; + return CustomEase2; +}(); +_getGSAP$4() && gsap$5.registerPlugin(CustomEase); +CustomEase.version = "3.12.5"; +/*! + * matrix 3.12.5 + * https://gsap.com + * + * Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _doc$2, _win$2, _docElement$1, _body$3, _divContainer, _svgContainer, _identityMatrix$1, _gEl, _transformProp$1 = "transform", _transformOriginProp$1 = _transformProp$1 + "Origin", _hasOffsetBug, _setDoc = function _setDoc2(element) { + var doc = element.ownerDocument || element; + if (!(_transformProp$1 in element.style) && "msTransform" in element.style) { + _transformProp$1 = "msTransform"; + _transformOriginProp$1 = _transformProp$1 + "Origin"; + } + while (doc.parentNode && (doc = doc.parentNode)) { + } + _win$2 = window; + _identityMatrix$1 = new Matrix2D(); + if (doc) { + _doc$2 = doc; + _docElement$1 = doc.documentElement; + _body$3 = doc.body; + _gEl = _doc$2.createElementNS("http://www.w3.org/2000/svg", "g"); + _gEl.style.transform = "none"; + var d1 = doc.createElement("div"), d2 = doc.createElement("div"), root = doc && (doc.body || doc.firstElementChild); + if (root && root.appendChild) { + root.appendChild(d1); + d1.appendChild(d2); + d1.setAttribute("style", "position:static;transform:translate3d(0,0,1px)"); + _hasOffsetBug = d2.offsetParent !== d1; + root.removeChild(d1); + } + } + return doc; +}, _forceNonZeroScale = function _forceNonZeroScale2(e) { + var a, cache; + while (e && e !== _body$3) { + cache = e._gsap; + cache && cache.uncache && cache.get(e, "x"); + if (cache && !cache.scaleX && !cache.scaleY && cache.renderTransform) { + cache.scaleX = cache.scaleY = 1e-4; + cache.renderTransform(1, cache); + a ? a.push(cache) : a = [cache]; + } + e = e.parentNode; + } + return a; +}, _svgTemps = [], _divTemps = [], _getDocScrollTop$1 = function _getDocScrollTop() { + return _win$2.pageYOffset || _doc$2.scrollTop || _docElement$1.scrollTop || _body$3.scrollTop || 0; +}, _getDocScrollLeft$1 = function _getDocScrollLeft() { + return _win$2.pageXOffset || _doc$2.scrollLeft || _docElement$1.scrollLeft || _body$3.scrollLeft || 0; +}, _svgOwner = function _svgOwner2(element) { + return element.ownerSVGElement || ((element.tagName + "").toLowerCase() === "svg" ? element : null); +}, _isFixed$1 = function _isFixed(element) { + if (_win$2.getComputedStyle(element).position === "fixed") { + return true; + } + element = element.parentNode; + if (element && element.nodeType === 1) { + return _isFixed(element); + } +}, _createSibling = function _createSibling2(element, i) { + if (element.parentNode && (_doc$2 || _setDoc(element))) { + var svg = _svgOwner(element), ns = svg ? svg.getAttribute("xmlns") || "http://www.w3.org/2000/svg" : "http://www.w3.org/1999/xhtml", type = svg ? i ? "rect" : "g" : "div", x = i !== 2 ? 0 : 100, y = i === 3 ? 100 : 0, css = "position:absolute;display:block;pointer-events:none;margin:0;padding:0;", e = _doc$2.createElementNS ? _doc$2.createElementNS(ns.replace(/^https/, "http"), type) : _doc$2.createElement(type); + if (i) { + if (!svg) { + if (!_divContainer) { + _divContainer = _createSibling2(element); + _divContainer.style.cssText = css; + } + e.style.cssText = css + "width:0.1px;height:0.1px;top:" + y + "px;left:" + x + "px"; + _divContainer.appendChild(e); + } else { + _svgContainer || (_svgContainer = _createSibling2(element)); + e.setAttribute("width", 0.01); + e.setAttribute("height", 0.01); + e.setAttribute("transform", "translate(" + x + "," + y + ")"); + _svgContainer.appendChild(e); + } + } + return e; + } + throw "Need document and parent."; +}, _consolidate = function _consolidate2(m) { + var c = new Matrix2D(), i = 0; + for (; i < m.numberOfItems; i++) { + c.multiply(m.getItem(i).matrix); + } + return c; +}, _getCTM = function _getCTM2(svg) { + var m = svg.getCTM(), transform; + if (!m) { + transform = svg.style[_transformProp$1]; + svg.style[_transformProp$1] = "none"; + svg.appendChild(_gEl); + m = _gEl.getCTM(); + svg.removeChild(_gEl); + transform ? svg.style[_transformProp$1] = transform : svg.style.removeProperty(_transformProp$1.replace(/([A-Z])/g, "-$1").toLowerCase()); + } + return m || _identityMatrix$1.clone(); +}, _placeSiblings = function _placeSiblings2(element, adjustGOffset) { + var svg = _svgOwner(element), isRootSVG = element === svg, siblings = svg ? _svgTemps : _divTemps, parent = element.parentNode, container, m, b, x, y, cs; + if (element === _win$2) { + return element; + } + siblings.length || siblings.push(_createSibling(element, 1), _createSibling(element, 2), _createSibling(element, 3)); + container = svg ? _svgContainer : _divContainer; + if (svg) { + if (isRootSVG) { + b = _getCTM(element); + x = -b.e / b.a; + y = -b.f / b.d; + m = _identityMatrix$1; + } else if (element.getBBox) { + b = element.getBBox(); + m = element.transform ? element.transform.baseVal : {}; + m = !m.numberOfItems ? _identityMatrix$1 : m.numberOfItems > 1 ? _consolidate(m) : m.getItem(0).matrix; + x = m.a * b.x + m.c * b.y; + y = m.b * b.x + m.d * b.y; + } else { + m = new Matrix2D(); + x = y = 0; } - }, - romanize(val) { - return U.romanizeNum(U.pInt(val)); - }, - count(param) { - if (Array.isArray(param) || U.isList(param)) { - return Object.values(param).filter((val) => val !== null && val !== void 0).length; - } else if (typeof param === "string") { - return param.length; + if (adjustGOffset && element.tagName.toLowerCase() === "g") { + x = y = 0; } - return param ? 1 : 0; - }, - // Concat helper - // Usage: (concat 'first 'second') - concat(...args) { - let outStr = ""; - for (const arg of args) { - if (typeof arg === "string" || typeof arg === "number") { - outStr += arg; + (isRootSVG ? svg : parent).appendChild(container); + container.setAttribute("transform", "matrix(" + m.a + "," + m.b + "," + m.c + "," + m.d + "," + (m.e + x) + "," + (m.f + y) + ")"); + } else { + x = y = 0; + if (_hasOffsetBug) { + m = element.offsetParent; + b = element; + while (b && (b = b.parentNode) && b !== m && b.parentNode) { + if ((_win$2.getComputedStyle(b)[_transformProp$1] + "").length > 4) { + x = b.offsetLeft; + y = b.offsetTop; + b = 0; + } } } - return outStr; - }, - // Merge helper - To merge additional properties into a template's context - merge(context, ...args) { - args.pop(); - return args.reduce((acc, val) => Object.assign(acc, val), context); - }, - // For loop: {{#for [from = 0, to, stepSize = 1]}}{{/for}} - for: (...args) => { - const options = args.pop(); - let [from, to, stepSize] = args; - from = U.pInt(from); - to = U.pInt(to); - stepSize = U.pInt(stepSize) || 1; - if (from > to) { - return ""; + cs = _win$2.getComputedStyle(element); + if (cs.position !== "absolute" && cs.position !== "fixed") { + m = element.offsetParent; + while (parent && parent !== m) { + x += parent.scrollLeft || 0; + y += parent.scrollTop || 0; + parent = parent.parentNode; + } + } + b = container.style; + b.top = element.offsetTop - y + "px"; + b.left = element.offsetLeft - x + "px"; + b[_transformProp$1] = cs[_transformProp$1]; + b[_transformOriginProp$1] = cs[_transformOriginProp$1]; + b.position = cs.position === "fixed" ? "fixed" : "absolute"; + element.parentNode.appendChild(container); + } + return container; +}, _setMatrix = function _setMatrix2(m, a, b, c, d, e, f) { + m.a = a; + m.b = b; + m.c = c; + m.d = d; + m.e = e; + m.f = f; + return m; +}; +var Matrix2D = /* @__PURE__ */ function() { + function Matrix2D2(a, b, c, d, e, f) { + if (a === void 0) { + a = 1; } - let html = ""; - for (let i = parseInt(from || 0, 10); i <= parseInt(to || 0, 10); i += stepSize) { - html += options.fn(i); + if (b === void 0) { + b = 0; } - return html; - }, - signNum(num) { - return U.signNum(num); - }, - compileSvg(...args) { - const [svgDotKey, svgPaths] = args; - return U.getSvgCode(svgDotKey, svgPaths); - }, - eLog(...args) { - args.pop(); - let dbLevel = 3; - if ([0, 1, 2, 3, 4, 5].includes(args[0])) { - dbLevel = args.shift(); + if (c === void 0) { + c = 0; } - eLog.hbsLog(...args, dbLevel); - }, - // Does the name of this turf block represent a standard 'Turf' claim? - isTurfBlock: (name) => U.fuzzyMatch(name, "Turf"), - // Which other connection does this connector overlap with? - getConnectorPartner: (index, direction) => { - index = parseInt(`${index}`, 10); - const partners = { - 1: { right: 2, bottom: 6 }, - 2: { left: 1, right: 3, bottom: 7 }, - 3: { left: 2, right: 4, bottom: 8 }, - 4: { left: 3, right: 5, bottom: 9 }, - 5: { left: 4, bottom: 10 }, - 6: { top: 1, right: 7, bottom: 11 }, - 7: { top: 2, left: 6, right: 8, bottom: 12 }, - 8: { top: 3, left: 7, right: 9, bottom: 13 }, - 9: { top: 4, left: 8, right: 10, bottom: 14 }, - 10: { top: 5, left: 9, bottom: 15 }, - 11: { top: 6, right: 12 }, - 12: { top: 7, left: 11, right: 13 }, - 13: { top: 8, left: 12, right: 14 }, - 14: { top: 9, left: 13, right: 15 }, - 15: { top: 10, left: 14 } - }; - const partnerDir = { left: "right", right: "left", top: "bottom", bottom: "top" }[direction]; - const partnerNum = partners[index][direction] ?? 0; - if (partnerNum) { - return `${partnerNum}-${partnerDir}`; + if (d === void 0) { + d = 1; } - return null; - }, - // Is the value Turf side. - isTurfOnEdge: (index, direction) => { - index = parseInt(`${index}`, 10); - const edges = { - 1: ["top", "left"], - 2: ["top"], - 3: ["top"], - 4: ["top"], - 5: ["top", "right"], - 6: ["left"], - 7: [], - 8: [], - 9: [], - 10: ["right"], - 11: ["left", "bottom"], - 12: ["bottom"], - 13: ["bottom"], - 14: ["bottom"], - 15: ["right", "bottom"] - }; - if (!(index in edges)) { - return true; + if (e === void 0) { + e = 0; } - return edges[index].includes(direction); - }, - // Multiboxes - multiboxes(selected, options) { - let html = options.fn(this); - selected = [selected].flat(1); - selected.forEach((selectedVal) => { - if (selectedVal !== false) { - const escapedValue = RegExp.escape(Handlebars.escapeExpression(String(selectedVal))); - const rgx = new RegExp(` value="${escapedValue}"`); - html = html.replace(rgx, '$& checked="checked"'); + if (f === void 0) { + f = 0; + } + _setMatrix(this, a, b, c, d, e, f); + } + var _proto = Matrix2D2.prototype; + _proto.inverse = function inverse() { + var a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f, determinant = a * d - b * c || 1e-10; + return _setMatrix(this, d / determinant, -b / determinant, -c / determinant, a / determinant, (c * f - d * e) / determinant, -(a * f - b * e) / determinant); + }; + _proto.multiply = function multiply(matrix) { + var a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f, a2 = matrix.a, b2 = matrix.c, c2 = matrix.b, d2 = matrix.d, e2 = matrix.e, f2 = matrix.f; + return _setMatrix(this, a2 * a + c2 * c, a2 * b + c2 * d, b2 * a + d2 * c, b2 * b + d2 * d, e + e2 * a + f2 * c, f + e2 * b + f2 * d); + }; + _proto.clone = function clone() { + return new Matrix2D2(this.a, this.b, this.c, this.d, this.e, this.f); + }; + _proto.equals = function equals(matrix) { + var a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f; + return a === matrix.a && b === matrix.b && c === matrix.c && d === matrix.d && e === matrix.e && f === matrix.f; + }; + _proto.apply = function apply(point, decoratee) { + if (decoratee === void 0) { + decoratee = {}; + } + var x = point.x, y = point.y, a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f; + decoratee.x = x * a + y * c + e || 0; + decoratee.y = x * b + y * d + f || 0; + return decoratee; + }; + return Matrix2D2; +}(); +function getGlobalMatrix(element, inverse, adjustGOffset, includeScrollInFixed) { + if (!element || !element.parentNode || (_doc$2 || _setDoc(element)).documentElement === element) { + return new Matrix2D(); + } + var zeroScales = _forceNonZeroScale(element), svg = _svgOwner(element), temps = svg ? _svgTemps : _divTemps, container = _placeSiblings(element, adjustGOffset), b1 = temps[0].getBoundingClientRect(), b2 = temps[1].getBoundingClientRect(), b3 = temps[2].getBoundingClientRect(), parent = container.parentNode, isFixed = !includeScrollInFixed && _isFixed$1(element), m = new Matrix2D((b2.left - b1.left) / 100, (b2.top - b1.top) / 100, (b3.left - b1.left) / 100, (b3.top - b1.top) / 100, b1.left + (isFixed ? 0 : _getDocScrollLeft$1()), b1.top + (isFixed ? 0 : _getDocScrollTop$1())); + parent.removeChild(container); + if (zeroScales) { + b1 = zeroScales.length; + while (b1--) { + b2 = zeroScales[b1]; + b2.scaleX = b2.scaleY = 0; + b2.renderTransform(1, b2); + } + } + return inverse ? m.inverse() : m; +} +/*! + * Flip 3.12.5 + * https://gsap.com + * + * @license Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _id = 1, _toArray$2, gsap$4, _batch, _batchAction, _body$2, _closestTenth, _getStyleSaver$2, _forEachBatch = function _forEachBatch2(batch, name) { + return batch.actions.forEach(function(a) { + return a.vars[name] && a.vars[name](a); + }); +}, _batchLookup = {}, _RAD2DEG$1 = 180 / Math.PI, _DEG2RAD$1 = Math.PI / 180, _emptyObj = {}, _dashedNameLookup = {}, _memoizedRemoveProps = {}, _listToArray = function _listToArray2(list) { + return typeof list === "string" ? list.split(" ").join("").split(",") : list; +}, _callbacks = _listToArray("onStart,onUpdate,onComplete,onReverseComplete,onInterrupt"), _removeProps = _listToArray("transform,transformOrigin,width,height,position,top,left,opacity,zIndex,maxWidth,maxHeight,minWidth,minHeight"), _getEl = function _getEl2(target) { + return _toArray$2(target)[0] || console.warn("Element not found:", target); +}, _round$1 = function _round4(value) { + return Math.round(value * 1e4) / 1e4 || 0; +}, _toggleClass = function _toggleClass2(targets, className, action) { + return targets.forEach(function(el) { + return el.classList[action](className); + }); +}, _reserved = { + zIndex: 1, + kill: 1, + simple: 1, + spin: 1, + clearProps: 1, + targets: 1, + toggleClass: 1, + onComplete: 1, + onUpdate: 1, + onInterrupt: 1, + onStart: 1, + delay: 1, + repeat: 1, + repeatDelay: 1, + yoyo: 1, + scale: 1, + fade: 1, + absolute: 1, + props: 1, + onEnter: 1, + onLeave: 1, + custom: 1, + paused: 1, + nested: 1, + prune: 1, + absoluteOnLeave: 1 +}, _fitReserved = { + zIndex: 1, + simple: 1, + clearProps: 1, + scale: 1, + absolute: 1, + fitChild: 1, + getVars: 1, + props: 1 +}, _camelToDashed = function _camelToDashed2(p) { + return p.replace(/([A-Z])/g, "-$1").toLowerCase(); +}, _copy$1 = function _copy(obj, exclude) { + var result = {}, p; + for (p in obj) { + exclude[p] || (result[p] = obj[p]); + } + return result; +}, _memoizedProps = {}, _memoizeProps = function _memoizeProps2(props) { + var p = _memoizedProps[props] = _listToArray(props); + _memoizedRemoveProps[props] = p.concat(_removeProps); + return p; +}, _getInverseGlobalMatrix = function _getInverseGlobalMatrix2(el) { + var cache = el._gsap || gsap$4.core.getCache(el); + if (cache.gmCache === gsap$4.ticker.frame) { + return cache.gMatrix; + } + cache.gmCache = gsap$4.ticker.frame; + return cache.gMatrix = getGlobalMatrix(el, true, false, true); +}, _getDOMDepth = function _getDOMDepth2(el, invert, level) { + if (level === void 0) { + level = 0; + } + var parent = el.parentNode, inc = 1e3 * Math.pow(10, level) * (invert ? -1 : 1), l = invert ? -inc * 900 : 0; + while (el) { + l += inc; + el = el.previousSibling; + } + return parent ? l + _getDOMDepth2(parent, invert, level + 1) : l; +}, _orderByDOMDepth = function _orderByDOMDepth2(comps, invert, isElStates) { + comps.forEach(function(comp) { + return comp.d = _getDOMDepth(isElStates ? comp.element : comp.t, invert); + }); + comps.sort(function(c1, c2) { + return c1.d - c2.d; + }); + return comps; +}, _recordInlineStyles = function _recordInlineStyles2(elState, props) { + var style = elState.element.style, a = elState.css = elState.css || [], i = props.length, p, v; + while (i--) { + p = props[i]; + v = style[p] || style.getPropertyValue(p); + a.push(v ? p : _dashedNameLookup[p] || (_dashedNameLookup[p] = _camelToDashed(p)), v); + } + return style; +}, _applyInlineStyles = function _applyInlineStyles2(state) { + var css = state.css, style = state.element.style, i = 0; + state.cache.uncache = 1; + for (; i < css.length; i += 2) { + css[i + 1] ? style[css[i]] = css[i + 1] : style.removeProperty(css[i]); + } + if (!css[css.indexOf("transform") + 1] && style.translate) { + style.removeProperty("translate"); + style.removeProperty("scale"); + style.removeProperty("rotate"); + } +}, _setFinalStates = function _setFinalStates2(comps, onlyTransforms) { + comps.forEach(function(c) { + return c.a.cache.uncache = 1; + }); + onlyTransforms || comps.finalStates.forEach(_applyInlineStyles); +}, _absoluteProps = "paddingTop,paddingRight,paddingBottom,paddingLeft,gridArea,transition".split(","), _makeAbsolute = function _makeAbsolute2(elState, fallbackNode, ignoreBatch) { + var element = elState.element, width = elState.width, height = elState.height, uncache = elState.uncache, getProp = elState.getProp, style = element.style, i = 4, result, displayIsNone, cs; + typeof fallbackNode !== "object" && (fallbackNode = elState); + if (_batch && ignoreBatch !== 1) { + _batch._abs.push({ + t: element, + b: elState, + a: elState, + sd: 0 + }); + _batch._final.push(function() { + return (elState.cache.uncache = 1) && _applyInlineStyles(elState); + }); + return element; + } + displayIsNone = getProp("display") === "none"; + if (!elState.isVisible || displayIsNone) { + displayIsNone && (_recordInlineStyles(elState, ["display"]).display = fallbackNode.display); + elState.matrix = fallbackNode.matrix; + elState.width = width = elState.width || fallbackNode.width; + elState.height = height = elState.height || fallbackNode.height; + } + _recordInlineStyles(elState, _absoluteProps); + cs = window.getComputedStyle(element); + while (i--) { + style[_absoluteProps[i]] = cs[_absoluteProps[i]]; + } + style.gridArea = "1 / 1 / 1 / 1"; + style.transition = "none"; + style.position = "absolute"; + style.width = width + "px"; + style.height = height + "px"; + style.top || (style.top = "0px"); + style.left || (style.left = "0px"); + if (uncache) { + result = new ElementState(element); + } else { + result = _copy$1(elState, _emptyObj); + result.position = "absolute"; + if (elState.simple) { + var bounds = element.getBoundingClientRect(); + result.matrix = new Matrix2D(1, 0, 0, 1, bounds.left + _getDocScrollLeft$1(), bounds.top + _getDocScrollTop$1()); + } else { + result.matrix = getGlobalMatrix(element, false, false, true); + } + } + result = _fit(result, elState, true); + elState.x = _closestTenth(result.x, 0.01); + elState.y = _closestTenth(result.y, 0.01); + return element; +}, _filterComps = function _filterComps2(comps, targets) { + if (targets !== true) { + targets = _toArray$2(targets); + comps = comps.filter(function(c) { + if (targets.indexOf((c.sd < 0 ? c.b : c.a).element) !== -1) { + return true; + } else { + c.t._gsap.renderTransform(1); + if (c.b.isVisible) { + c.t.style.width = c.b.width + "px"; + c.t.style.height = c.b.height + "px"; + } } }); - return html; - }, - repturf: (turfsAmount, options) => { - let html = options.fn(void 0); - let turfsAmountInt = parseInt(turfsAmount, 10); - if (turfsAmountInt > 6) { - turfsAmountInt = 6; + } + return comps; +}, _makeCompsAbsolute = function _makeCompsAbsolute2(comps) { + return _orderByDOMDepth(comps, true).forEach(function(c) { + return (c.a.isVisible || c.b.isVisible) && _makeAbsolute(c.sd < 0 ? c.b : c.a, c.b, 1); + }); +}, _findElStateInState = function _findElStateInState2(state, other) { + return other && state.idLookup[_parseElementState(other).id] || state.elementStates[0]; +}, _parseElementState = function _parseElementState2(elOrNode, props, simple, other) { + return elOrNode instanceof ElementState ? elOrNode : elOrNode instanceof FlipState ? _findElStateInState(elOrNode, other) : new ElementState(typeof elOrNode === "string" ? _getEl(elOrNode) || console.warn(elOrNode + " not found") : elOrNode, props, simple); +}, _recordProps = function _recordProps2(elState, props) { + var getProp = gsap$4.getProperty(elState.element, null, "native"), obj = elState.props = {}, i = props.length; + while (i--) { + obj[props[i]] = (getProp(props[i]) + "").trim(); + } + obj.zIndex && (obj.zIndex = parseFloat(obj.zIndex) || 0); + return elState; +}, _applyProps = function _applyProps2(element, props) { + var style = element.style || element, p; + for (p in props) { + style[p] = props[p]; + } +}, _getID = function _getID2(el) { + var id = el.getAttribute("data-flip-id"); + id || el.setAttribute("data-flip-id", id = "auto-" + _id++); + return id; +}, _elementsFromElementStates = function _elementsFromElementStates2(elStates) { + return elStates.map(function(elState) { + return elState.element; + }); +}, _handleCallback = function _handleCallback2(callback, elStates, tl) { + return callback && elStates.length && tl.add(callback(_elementsFromElementStates(elStates), tl, new FlipState(elStates, 0, true)), 0); +}, _fit = function _fit2(fromState, toState, scale, applyProps, fitChild, vars) { + var element = fromState.element, cache = fromState.cache, parent = fromState.parent, x = fromState.x, y = fromState.y, width = toState.width, height = toState.height, scaleX = toState.scaleX, scaleY = toState.scaleY, rotation = toState.rotation, bounds = toState.bounds, styles = vars && _getStyleSaver$2 && _getStyleSaver$2(element, "transform"), dimensionState = fromState, _toState$matrix = toState.matrix, e = _toState$matrix.e, f = _toState$matrix.f, deep = fromState.bounds.width !== bounds.width || fromState.bounds.height !== bounds.height || fromState.scaleX !== scaleX || fromState.scaleY !== scaleY || fromState.rotation !== rotation, simple = !deep && fromState.simple && toState.simple && !fitChild, skewX, fromPoint, toPoint, getProp, parentMatrix, matrix, bbox; + if (simple || !parent) { + scaleX = scaleY = 1; + rotation = skewX = 0; + } else { + parentMatrix = _getInverseGlobalMatrix(parent); + matrix = parentMatrix.clone().multiply(toState.ctm ? toState.matrix.clone().multiply(toState.ctm) : toState.matrix); + rotation = _round$1(Math.atan2(matrix.b, matrix.a) * _RAD2DEG$1); + skewX = _round$1(Math.atan2(matrix.c, matrix.d) * _RAD2DEG$1 + rotation) % 360; + scaleX = Math.sqrt(Math.pow(matrix.a, 2) + Math.pow(matrix.b, 2)); + scaleY = Math.sqrt(Math.pow(matrix.c, 2) + Math.pow(matrix.d, 2)) * Math.cos(skewX * _DEG2RAD$1); + if (fitChild) { + fitChild = _toArray$2(fitChild)[0]; + getProp = gsap$4.getProperty(fitChild); + bbox = fitChild.getBBox && typeof fitChild.getBBox === "function" && fitChild.getBBox(); + dimensionState = { + scaleX: getProp("scaleX"), + scaleY: getProp("scaleY"), + width: bbox ? bbox.width : Math.ceil(parseFloat(getProp("width", "px"))), + height: bbox ? bbox.height : parseFloat(getProp("height", "px")) + }; } - for (let i = 13 - turfsAmountInt; i <= 12; i++) { - const rgx = new RegExp(` value="${i}"`); - html = html.replace(rgx, '$& disabled="disabled"'); + cache.rotation = rotation + "deg"; + cache.skewX = skewX + "deg"; + } + if (scale) { + scaleX *= width === dimensionState.width || !dimensionState.width ? 1 : width / dimensionState.width; + scaleY *= height === dimensionState.height || !dimensionState.height ? 1 : height / dimensionState.height; + cache.scaleX = scaleX; + cache.scaleY = scaleY; + } else { + width = _closestTenth(width * scaleX / dimensionState.scaleX, 0); + height = _closestTenth(height * scaleY / dimensionState.scaleY, 0); + element.style.width = width + "px"; + element.style.height = height + "px"; + } + applyProps && _applyProps(element, toState.props); + if (simple || !parent) { + x += e - fromState.matrix.e; + y += f - fromState.matrix.f; + } else if (deep || parent !== toState.parent) { + cache.renderTransform(1, cache); + matrix = getGlobalMatrix(fitChild || element, false, false, true); + fromPoint = parentMatrix.apply({ + x: matrix.e, + y: matrix.f + }); + toPoint = parentMatrix.apply({ + x: e, + y: f + }); + x += toPoint.x - fromPoint.x; + y += toPoint.y - fromPoint.y; + } else { + parentMatrix.e = parentMatrix.f = 0; + toPoint = parentMatrix.apply({ + x: e - fromState.matrix.e, + y: f - fromState.matrix.f + }); + x += toPoint.x; + y += toPoint.y; + } + x = _closestTenth(x, 0.02); + y = _closestTenth(y, 0.02); + if (vars && !(vars instanceof ElementState)) { + styles && styles.revert(); + } else { + cache.x = x + "px"; + cache.y = y + "px"; + cache.renderTransform(1, cache); + } + if (vars) { + vars.x = x; + vars.y = y; + vars.rotation = rotation; + vars.skewX = skewX; + if (scale) { + vars.scaleX = scaleX; + vars.scaleY = scaleY; + } else { + vars.width = width; + vars.height = height; + } + } + return vars || cache; +}, _parseState = function _parseState2(targetsOrState, vars) { + return targetsOrState instanceof FlipState ? targetsOrState : new FlipState(targetsOrState, vars); +}, _getChangingElState = function _getChangingElState2(toState, fromState, id) { + var to1 = toState.idLookup[id], to2 = toState.alt[id]; + return to2.isVisible && (!(fromState.getElementState(to2.element) || to2).isVisible || !to1.isVisible) ? to2 : to1; +}, _bodyMetrics = [], _bodyProps = "width,height,overflowX,overflowY".split(","), _bodyLocked, _lockBodyScroll = function _lockBodyScroll2(lock) { + if (lock !== _bodyLocked) { + var s = _body$2.style, w = _body$2.clientWidth === window.outerWidth, h = _body$2.clientHeight === window.outerHeight, i = 4; + if (lock && (w || h)) { + while (i--) { + _bodyMetrics[i] = s[_bodyProps[i]]; + } + if (w) { + s.width = _body$2.clientWidth + "px"; + s.overflowY = "hidden"; + } + if (h) { + s.height = _body$2.clientHeight + "px"; + s.overflowX = "hidden"; + } + _bodyLocked = lock; + } else if (_bodyLocked) { + while (i--) { + _bodyMetrics[i] ? s[_bodyProps[i]] = _bodyMetrics[i] : s.removeProperty(_camelToDashed(_bodyProps[i])); + } + _bodyLocked = lock; + } + } +}, _fromTo = function _fromTo2(fromState, toState, vars, relative) { + fromState instanceof FlipState && toState instanceof FlipState || console.warn("Not a valid state object."); + vars = vars || {}; + var _vars = vars, clearProps2 = _vars.clearProps, onEnter = _vars.onEnter, onLeave = _vars.onLeave, absolute = _vars.absolute, absoluteOnLeave = _vars.absoluteOnLeave, custom = _vars.custom, delay = _vars.delay, paused = _vars.paused, repeat = _vars.repeat, repeatDelay = _vars.repeatDelay, yoyo = _vars.yoyo, toggleClass = _vars.toggleClass, nested = _vars.nested, _zIndex = _vars.zIndex, scale = _vars.scale, fade = _vars.fade, stagger = _vars.stagger, spin = _vars.spin, prune = _vars.prune, props = ("props" in vars ? vars : fromState).props, tweenVars = _copy$1(vars, _reserved), animation = gsap$4.timeline({ + delay, + paused, + repeat, + repeatDelay, + yoyo, + data: "isFlip" + }), remainingProps = tweenVars, entering = [], leaving = [], comps = [], swapOutTargets = [], spinNum = spin === true ? 1 : spin || 0, spinFunc = typeof spin === "function" ? spin : function() { + return spinNum; + }, interrupted = fromState.interrupted || toState.interrupted, addFunc = animation[relative !== 1 ? "to" : "from"], v, p, endTime, i, el, comp, state, targets, finalStates, fromNode, toNode, run, a, b; + for (p in toState.idLookup) { + toNode = !toState.alt[p] ? toState.idLookup[p] : _getChangingElState(toState, fromState, p); + el = toNode.element; + fromNode = fromState.idLookup[p]; + fromState.alt[p] && el === fromNode.element && (fromState.alt[p].isVisible || !toNode.isVisible) && (fromNode = fromState.alt[p]); + if (fromNode) { + comp = { + t: el, + b: fromNode, + a: toNode, + sd: fromNode.element === el ? 0 : toNode.isVisible ? 1 : -1 + }; + comps.push(comp); + if (comp.sd) { + if (comp.sd < 0) { + comp.b = toNode; + comp.a = fromNode; + } + interrupted && _recordInlineStyles(comp.b, props ? _memoizedRemoveProps[props] : _removeProps); + fade && comps.push(comp.swap = { + t: fromNode.element, + b: comp.b, + a: comp.a, + sd: -comp.sd, + swap: comp + }); + } + el._flip = fromNode.element._flip = _batch ? _batch.timeline : animation; + } else if (toNode.isVisible) { + comps.push({ + t: el, + b: _copy$1(toNode, { + isVisible: 1 + }), + a: toNode, + sd: 0, + entering: 1 + }); + el._flip = _batch ? _batch.timeline : animation; } - return html; } -}; -handlebarHelpers.eLog1 = function(...args) { - handlebarHelpers.eLog(...[1, ...args.slice(0, 7)]); -}; -handlebarHelpers.eLog2 = function(...args) { - handlebarHelpers.eLog(...[2, ...args.slice(0, 7)]); -}; -handlebarHelpers.eLog3 = function(...args) { - handlebarHelpers.eLog(...[3, ...args.slice(0, 7)]); -}; -handlebarHelpers.eLog4 = function(...args) { - handlebarHelpers.eLog(...[4, ...args.slice(0, 7)]); -}; -handlebarHelpers.eLog5 = function(...args) { - handlebarHelpers.eLog(...[5, ...args.slice(0, 7)]); -}; -Object.assign(handlebarHelpers); -function registerHandlebarHelpers() { - Object.entries(handlebarHelpers).forEach(([name, func]) => Handlebars.registerHelper(name, func)); -} -const gsapPlugins = [ - TextPlugin, - Flip, - MotionPathPlugin, - Draggable, - SplitText, - Observer$1, - CustomEase, - CustomWiggle, - CustomBounce, - EasePack -]; -const gsapEffects = { - // #region CLOCK KEYS - keyDrop: { - effect: (clockKey, config) => { - const [keyContainer] = $(clockKey).closest(".clock-key-container"); - return U.gsap.timeline({ - onComplete() { - if (config.callback) { - config.callback(); + props && (_memoizedProps[props] || _memoizeProps(props)).forEach(function(p2) { + return tweenVars[p2] = function(i2) { + return comps[i2].a.props[p2]; + }; + }); + comps.finalStates = finalStates = []; + run = function run2() { + _orderByDOMDepth(comps); + _lockBodyScroll(true); + for (i = 0; i < comps.length; i++) { + comp = comps[i]; + a = comp.a; + b = comp.b; + if (prune && !a.isDifferent(b) && !comp.entering) { + comps.splice(i--, 1); + } else { + el = comp.t; + nested && !(comp.sd < 0) && i && (a.matrix = getGlobalMatrix(el, false, false, true)); + if (b.isVisible && a.isVisible) { + if (comp.sd < 0) { + state = new ElementState(el, props, fromState.simple); + _fit(state, a, scale, 0, 0, state); + state.matrix = getGlobalMatrix(el, false, false, true); + state.css = comp.b.css; + comp.a = a = state; + fade && (el.style.opacity = interrupted ? b.opacity : a.opacity); + stagger && swapOutTargets.push(el); + } else if (comp.sd > 0 && fade) { + el.style.opacity = interrupted ? a.opacity - b.opacity : "0"; } - } - }).fromTo(keyContainer, { - y: config.yShift - }, { - y: 0, - autoAlpha: 1, - ease: "bounce", - duration: config.duration - }); - }, - defaults: { - duration: 1, - yShift: -800 - }, - extendTimeline: true - }, - keyPull: { - effect: (clockKey, config) => { - const [keyContainer] = $(clockKey).closest(".clock-key-container"); - return U.gsap.timeline({ - onComplete() { - if (config.callback) { - config.callback(); + _fit(a, b, scale, props); + } else if (b.isVisible !== a.isVisible) { + if (!b.isVisible) { + a.isVisible && entering.push(a); + comps.splice(i--, 1); + } else if (!a.isVisible) { + b.css = a.css; + leaving.push(b); + comps.splice(i--, 1); + absolute && nested && _fit(a, b, scale, props); } } - }).to(keyContainer, { - y: config.yDelta, - ease: config.ease, - duration: 0.75 * config.duration - }).to(keyContainer, { - opacity: 0, - ease: "power2.out", - duration: 0.25 * config.duration - }, 0.75 * config.duration); - }, - defaults: { - yDelta: -800, - duration: 1, - ease: "back.in(1)" - }, - extendTimeline: true - }, - keyControlPanelFlip: { - effect: (target, config) => { - return U.gsap.timeline({ - delay: config.delay, - onStart() { - if (target) { - const target$ = $(target); - const nextSibling$ = target$.next(".clock-control-flipper"); - if (nextSibling$.length) { - U.gsap.effects.keyControlPanelFlip(nextSibling$[0], { - ...config, - delay: 0.15 - }); - } - } + if (!scale) { + el.style.maxWidth = Math.max(a.width, b.width) + "px"; + el.style.maxHeight = Math.max(a.height, b.height) + "px"; + el.style.minWidth = Math.min(a.width, b.width) + "px"; + el.style.minHeight = Math.min(a.height, b.height) + "px"; } - }).to(target, { - rotateX: config.angle, - duration: 0.5, - ease: "back.inOut(2)" + nested && toggleClass && el.classList.add(toggleClass); + } + finalStates.push(a); + } + var classTargets; + if (toggleClass) { + classTargets = finalStates.map(function(s) { + return s.element; }); - }, - defaults: { - angle: 180, - delay: 0 - }, - extendTimeline: true - }, - // #endregion - // #region CHAT CONSEQUENCE EFFECTS - csqEnter: { - effect: (csqContainer, config) => { - const csqRoot = U.gsap.utils.selector(csqContainer); - const csqIconCircle = csqRoot(".consequence-icon-circle.base-consequence"); - const csqBaseTypeElem = csqRoot(".consequence-type.base-consequence"); - const csqAcceptTypeElem = csqRoot(".consequence-type.accept-consequence"); - const csqBaseNameElem = csqRoot(".consequence-name.base-consequence"); - const csqAcceptNameElem = csqRoot(".consequence-name.accept-consequence"); - const tl = U.gsap.timeline({ paused: true, defaults: {} }); - if (csqAcceptTypeElem.length > 0) { - tl.set(csqAcceptTypeElem, { opacity: 0 }, 0); + nested && classTargets.forEach(function(e) { + return e.classList.remove(toggleClass); + }); + } + _lockBodyScroll(false); + if (scale) { + tweenVars.scaleX = function(i2) { + return comps[i2].a.scaleX; + }; + tweenVars.scaleY = function(i2) { + return comps[i2].a.scaleY; + }; + } else { + tweenVars.width = function(i2) { + return comps[i2].a.width + "px"; + }; + tweenVars.height = function(i2) { + return comps[i2].a.height + "px"; + }; + tweenVars.autoRound = vars.autoRound || false; + } + tweenVars.x = function(i2) { + return comps[i2].a.x + "px"; + }; + tweenVars.y = function(i2) { + return comps[i2].a.y + "px"; + }; + tweenVars.rotation = function(i2) { + return comps[i2].a.rotation + (spin ? spinFunc(i2, targets[i2], targets) * 360 : 0); + }; + tweenVars.skewX = function(i2) { + return comps[i2].a.skewX; + }; + targets = comps.map(function(c) { + return c.t; + }); + if (_zIndex || _zIndex === 0) { + tweenVars.modifiers = { + zIndex: function zIndex() { + return _zIndex; + } + }; + tweenVars.zIndex = _zIndex; + tweenVars.immediateRender = vars.immediateRender !== false; + } + fade && (tweenVars.opacity = function(i2) { + return comps[i2].sd < 0 ? 0 : comps[i2].sd > 0 ? comps[i2].a.opacity : "+=0"; + }); + if (swapOutTargets.length) { + stagger = gsap$4.utils.distribute(stagger); + var dummyArray = targets.slice(swapOutTargets.length); + tweenVars.stagger = function(i2, el2) { + return stagger(~swapOutTargets.indexOf(el2) ? targets.indexOf(comps[i2].swap.t) : i2, el2, dummyArray); + }; + } + _callbacks.forEach(function(name) { + return vars[name] && animation.eventCallback(name, vars[name], vars[name + "Params"]); + }); + if (custom && targets.length) { + remainingProps = _copy$1(tweenVars, _reserved); + if ("scale" in custom) { + custom.scaleX = custom.scaleY = custom.scale; + delete custom.scale; + } + for (p in custom) { + v = _copy$1(custom[p], _fitReserved); + v[p] = tweenVars[p]; + !("duration" in v) && "duration" in tweenVars && (v.duration = tweenVars.duration); + v.stagger = tweenVars.stagger; + addFunc.call(animation, targets, v, 0); + delete remainingProps[p]; + } + } + if (targets.length || leaving.length || entering.length) { + toggleClass && animation.add(function() { + return _toggleClass(classTargets, toggleClass, animation._zTime < 0 ? "remove" : "add"); + }, 0) && !paused && _toggleClass(classTargets, toggleClass, "add"); + targets.length && addFunc.call(animation, targets, remainingProps, 0); + } + _handleCallback(onEnter, entering, animation); + _handleCallback(onLeave, leaving, animation); + var batchTl = _batch && _batch.timeline; + if (batchTl) { + batchTl.add(animation, 0); + _batch._final.push(function() { + return _setFinalStates(comps, !clearProps2); + }); + } + endTime = animation.duration(); + animation.call(function() { + var forward = animation.time() >= endTime; + forward && !batchTl && _setFinalStates(comps, !clearProps2); + toggleClass && _toggleClass(classTargets, toggleClass, forward ? "remove" : "add"); + }); + }; + absoluteOnLeave && (absolute = comps.filter(function(comp2) { + return !comp2.sd && !comp2.a.isVisible && comp2.b.isVisible; + }).map(function(comp2) { + return comp2.a.element; + })); + if (_batch) { + var _batch$_abs; + absolute && (_batch$_abs = _batch._abs).push.apply(_batch$_abs, _filterComps(comps, absolute)); + _batch._run.push(run); + } else { + absolute && _makeCompsAbsolute(_filterComps(comps, absolute)); + run(); + } + var anim = _batch ? _batch.timeline : animation; + anim.revert = function() { + return _killFlip(anim, 1, 1); + }; + return anim; +}, _interrupt2 = function _interrupt3(tl) { + tl.vars.onInterrupt && tl.vars.onInterrupt.apply(tl, tl.vars.onInterruptParams || []); + tl.getChildren(true, false, true).forEach(_interrupt3); +}, _killFlip = function _killFlip2(tl, action, force) { + if (tl && tl.progress() < 1 && (!tl.paused() || force)) { + if (action) { + _interrupt2(tl); + action < 2 && tl.progress(1); + tl.kill(); + } + return true; + } +}, _createLookup = function _createLookup2(state) { + var lookup = state.idLookup = {}, alt = state.alt = {}, elStates = state.elementStates, i = elStates.length, elState; + while (i--) { + elState = elStates[i]; + lookup[elState.id] ? alt[elState.id] = elState : lookup[elState.id] = elState; + } +}; +var FlipState = /* @__PURE__ */ function() { + function FlipState2(targets, vars, targetsAreElementStates) { + this.props = vars && vars.props; + this.simple = !!(vars && vars.simple); + if (targetsAreElementStates) { + this.targets = _elementsFromElementStates(targets); + this.elementStates = targets; + _createLookup(this); + } else { + this.targets = _toArray$2(targets); + var soft = vars && (vars.kill === false || vars.batch && !vars.kill); + _batch && !soft && _batch._kill.push(this); + this.update(soft || !!_batch); + } + } + var _proto = FlipState2.prototype; + _proto.update = function update(soft) { + var _this = this; + this.elementStates = this.targets.map(function(el) { + return new ElementState(el, _this.props, _this.simple); + }); + _createLookup(this); + this.interrupt(soft); + this.recordInlineStyles(); + return this; + }; + _proto.clear = function clear() { + this.targets.length = this.elementStates.length = 0; + _createLookup(this); + return this; + }; + _proto.fit = function fit(state, scale, nested) { + var elStatesInOrder = _orderByDOMDepth(this.elementStates.slice(0), false, true), toElStates = (state || this).idLookup, i = 0, fromNode, toNode; + for (; i < elStatesInOrder.length; i++) { + fromNode = elStatesInOrder[i]; + nested && (fromNode.matrix = getGlobalMatrix(fromNode.element, false, false, true)); + toNode = toElStates[fromNode.id]; + toNode && _fit(fromNode, toNode, scale, true, 0, fromNode); + fromNode.matrix = getGlobalMatrix(fromNode.element, false, false, true); + } + return this; + }; + _proto.getProperty = function getProperty3(element, property) { + var es = this.getElementState(element) || _emptyObj; + return (property in es ? es : es.props || _emptyObj)[property]; + }; + _proto.add = function add(state) { + var i = state.targets.length, lookup = this.idLookup, alt = this.alt, index, es, es2; + while (i--) { + es = state.elementStates[i]; + es2 = lookup[es.id]; + if (es2 && (es.element === es2.element || alt[es.id] && alt[es.id].element === es.element)) { + index = this.elementStates.indexOf(es.element === es2.element ? es2 : alt[es.id]); + this.targets.splice(index, 1, state.targets[i]); + this.elementStates.splice(index, 1, es); + } else { + this.targets.push(state.targets[i]); + this.elementStates.push(es); } - if (csqAcceptNameElem.length > 0) { - tl.set(csqAcceptNameElem, { opacity: 0 }, 0); + } + state.interrupted && (this.interrupted = true); + state.simple || (this.simple = false); + _createLookup(this); + return this; + }; + _proto.compare = function compare(state) { + var l1 = state.idLookup, l2 = this.idLookup, unchanged = [], changed = [], enter = [], leave = [], targets = [], a1 = state.alt, a2 = this.alt, place = function place2(s12, s22, el2) { + return (s12.isVisible !== s22.isVisible ? s12.isVisible ? enter : leave : s12.isVisible ? changed : unchanged).push(el2) && targets.push(el2); + }, placeIfDoesNotExist = function placeIfDoesNotExist2(s12, s22, el2) { + return targets.indexOf(el2) < 0 && place(s12, s22, el2); + }, s1, s2, p, el, s1Alt, s2Alt, c1, c2; + for (p in l1) { + s1Alt = a1[p]; + s2Alt = a2[p]; + s1 = !s1Alt ? l1[p] : _getChangingElState(state, this, p); + el = s1.element; + s2 = l2[p]; + if (s2Alt) { + c2 = s2.isVisible || !s2Alt.isVisible && el === s2.element ? s2 : s2Alt; + c1 = s1Alt && !s1.isVisible && !s1Alt.isVisible && c2.element === s1Alt.element ? s1Alt : s1; + if (c1.isVisible && c2.isVisible && c1.element !== c2.element) { + (c1.isDifferent(c2) ? changed : unchanged).push(c1.element, c2.element); + targets.push(c1.element, c2.element); + } else { + place(c1, c2, c1.element); + } + s1Alt && c1.element === s1Alt.element && (s1Alt = l1[p]); + placeIfDoesNotExist(c1.element !== s2.element && s1Alt ? s1Alt : c1, s2, s2.element); + placeIfDoesNotExist(s1Alt && s1Alt.element === s2Alt.element ? s1Alt : c1, s2Alt, s2Alt.element); + s1Alt && placeIfDoesNotExist(s1Alt, s2Alt.element === s1Alt.element ? s2Alt : s2, s1Alt.element); + } else { + !s2 ? enter.push(el) : !s2.isDifferent(s1) ? unchanged.push(el) : place(s1, s2, el); + s1Alt && placeIfDoesNotExist(s1Alt, s2, s1Alt.element); } - if (csqBaseTypeElem.length > 0) { - tl.fromTo(csqBaseTypeElem, { - opacity: 1 - }, { - opacity: 0, - duration: 0.25, - ease: "sine" - }, 0); + } + for (p in l2) { + if (!l1[p]) { + leave.push(l2[p].element); + a2[p] && leave.push(a2[p].element); } - if (csqAcceptTypeElem.length > 0) { - tl.fromTo(csqAcceptTypeElem, { - opacity: 0 - }, { - opacity: 1, - duration: 0.25, - ease: "sine" - }, 0); + } + return { + changed, + unchanged, + enter, + leave + }; + }; + _proto.recordInlineStyles = function recordInlineStyles() { + var props = _memoizedRemoveProps[this.props] || _removeProps, i = this.elementStates.length; + while (i--) { + _recordInlineStyles(this.elementStates[i], props); + } + }; + _proto.interrupt = function interrupt(soft) { + var _this2 = this; + var timelines = []; + this.targets.forEach(function(t) { + var tl = t._flip, foundInProgress = _killFlip(tl, soft ? 0 : 1); + soft && foundInProgress && timelines.indexOf(tl) < 0 && tl.add(function() { + return _this2.updateVisibility(); + }); + foundInProgress && timelines.push(tl); + }); + !soft && timelines.length && this.updateVisibility(); + this.interrupted || (this.interrupted = !!timelines.length); + }; + _proto.updateVisibility = function updateVisibility() { + this.elementStates.forEach(function(es) { + var b = es.element.getBoundingClientRect(); + es.isVisible = !!(b.width || b.height || b.top || b.left); + es.uncache = 1; + }); + }; + _proto.getElementState = function getElementState(element) { + return this.elementStates[this.targets.indexOf(_getEl(element))]; + }; + _proto.makeAbsolute = function makeAbsolute() { + return _orderByDOMDepth(this.elementStates.slice(0), true, true).map(_makeAbsolute); + }; + return FlipState2; +}(); +var ElementState = /* @__PURE__ */ function() { + function ElementState2(element, props, simple) { + this.element = element; + this.update(props, simple); + } + var _proto2 = ElementState2.prototype; + _proto2.isDifferent = function isDifferent(state) { + var b1 = this.bounds, b2 = state.bounds; + return b1.top !== b2.top || b1.left !== b2.left || b1.width !== b2.width || b1.height !== b2.height || !this.matrix.equals(state.matrix) || this.opacity !== state.opacity || this.props && state.props && JSON.stringify(this.props) !== JSON.stringify(state.props); + }; + _proto2.update = function update(props, simple) { + var self2 = this, element = self2.element, getProp = gsap$4.getProperty(element), cache = gsap$4.core.getCache(element), bounds = element.getBoundingClientRect(), bbox = element.getBBox && typeof element.getBBox === "function" && element.nodeName.toLowerCase() !== "svg" && element.getBBox(), m = simple ? new Matrix2D(1, 0, 0, 1, bounds.left + _getDocScrollLeft$1(), bounds.top + _getDocScrollTop$1()) : getGlobalMatrix(element, false, false, true); + self2.getProp = getProp; + self2.element = element; + self2.id = _getID(element); + self2.matrix = m; + self2.cache = cache; + self2.bounds = bounds; + self2.isVisible = !!(bounds.width || bounds.height || bounds.left || bounds.top); + self2.display = getProp("display"); + self2.position = getProp("position"); + self2.parent = element.parentNode; + self2.x = getProp("x"); + self2.y = getProp("y"); + self2.scaleX = cache.scaleX; + self2.scaleY = cache.scaleY; + self2.rotation = getProp("rotation"); + self2.skewX = getProp("skewX"); + self2.opacity = getProp("opacity"); + self2.width = bbox ? bbox.width : _closestTenth(getProp("width", "px"), 0.04); + self2.height = bbox ? bbox.height : _closestTenth(getProp("height", "px"), 0.04); + props && _recordProps(self2, _memoizedProps[props] || _memoizeProps(props)); + self2.ctm = element.getCTM && element.nodeName.toLowerCase() === "svg" && _getCTM(element).inverse(); + self2.simple = simple || _round$1(m.a) === 1 && !_round$1(m.b) && !_round$1(m.c) && _round$1(m.d) === 1; + self2.uncache = 0; + }; + return ElementState2; +}(); +var FlipAction = /* @__PURE__ */ function() { + function FlipAction2(vars, batch) { + this.vars = vars; + this.batch = batch; + this.states = []; + this.timeline = batch.timeline; + } + var _proto3 = FlipAction2.prototype; + _proto3.getStateById = function getStateById(id) { + var i = this.states.length; + while (i--) { + if (this.states[i].idLookup[id]) { + return this.states[i]; } - if (csqBaseNameElem.length > 0) { - tl.fromTo(csqBaseNameElem, { - opacity: 1 - }, { - opacity: 0, - duration: 0.25, - ease: "sine" - }, 0); + } + }; + _proto3.kill = function kill() { + this.batch.remove(this); + }; + return FlipAction2; +}(); +var FlipBatch = /* @__PURE__ */ function() { + function FlipBatch2(id) { + this.id = id; + this.actions = []; + this._kill = []; + this._final = []; + this._abs = []; + this._run = []; + this.data = {}; + this.state = new FlipState(); + this.timeline = gsap$4.timeline(); + } + var _proto4 = FlipBatch2.prototype; + _proto4.add = function add(config3) { + var result = this.actions.filter(function(action) { + return action.vars === config3; + }); + if (result.length) { + return result[0]; + } + result = new FlipAction(typeof config3 === "function" ? { + animate: config3 + } : config3, this); + this.actions.push(result); + return result; + }; + _proto4.remove = function remove2(action) { + var i = this.actions.indexOf(action); + i >= 0 && this.actions.splice(i, 1); + return this; + }; + _proto4.getState = function getState(merge) { + var _this3 = this; + var prevBatch = _batch, prevAction = _batchAction; + _batch = this; + this.state.clear(); + this._kill.length = 0; + this.actions.forEach(function(action) { + if (action.vars.getState) { + action.states.length = 0; + _batchAction = action; + action.state = action.vars.getState(action); + } + merge && action.states.forEach(function(s) { + return _this3.state.add(s); + }); + }); + _batchAction = prevAction; + _batch = prevBatch; + this.killConflicts(); + return this; + }; + _proto4.animate = function animate() { + var _this4 = this; + var prevBatch = _batch, tl = this.timeline, i = this.actions.length, finalStates, endTime; + _batch = this; + tl.clear(); + this._abs.length = this._final.length = this._run.length = 0; + this.actions.forEach(function(a) { + a.vars.animate && a.vars.animate(a); + var onEnter = a.vars.onEnter, onLeave = a.vars.onLeave, targets = a.targets, s, result; + if (targets && targets.length && (onEnter || onLeave)) { + s = new FlipState(); + a.states.forEach(function(state) { + return s.add(state); + }); + result = s.compare(Flip.getState(targets)); + result.enter.length && onEnter && onEnter(result.enter); + result.leave.length && onLeave && onLeave(result.leave); } - if (csqAcceptNameElem.length > 0) { - tl.fromTo(csqAcceptNameElem, { - opacity: 0 - }, { - opacity: 1, - duration: 0.25, - ease: "sine" - }, 0); + }); + _makeCompsAbsolute(this._abs); + this._run.forEach(function(f) { + return f(); + }); + endTime = tl.duration(); + finalStates = this._final.slice(0); + tl.add(function() { + if (endTime <= tl.time()) { + finalStates.forEach(function(f) { + return f(); + }); + _forEachBatch(_this4, "onComplete"); } - if (csqContainer) { - tl.fromTo(csqContainer, { - filter: "brightness(1)" - }, { - filter: `brightness(${config.brightness})`, - duration: config.duration / 3, - ease: "none" - }, 0); + }); + _batch = prevBatch; + while (i--) { + this.actions[i].vars.once && this.actions[i].kill(); + } + _forEachBatch(this, "onStart"); + tl.restart(); + return this; + }; + _proto4.loadState = function loadState(done) { + done || (done = function done2() { + return 0; + }); + var queue = []; + this.actions.forEach(function(c) { + if (c.vars.loadState) { + var i, f = function f2(targets) { + targets && (c.targets = targets); + i = queue.indexOf(f2); + if (~i) { + queue.splice(i, 1); + queue.length || done(); + } + }; + queue.push(f); + c.vars.loadState(f); } - if (csqIconCircle.length > 0) { - tl.fromTo(csqIconCircle, { - scale: 0.75, - outlineColor: C.Colors.dBLACK, - outlineWidth: 0 - }, { - scale: 0.85, - outlineColor: C.Colors.GREY, - outlineWidth: 1, - duration: 0.55, - ease: "sine.out" - }, 0); + }); + queue.length || done(); + return this; + }; + _proto4.setState = function setState() { + this.actions.forEach(function(c) { + return c.targets = c.vars.setState && c.vars.setState(c); + }); + return this; + }; + _proto4.killConflicts = function killConflicts(soft) { + this.state.interrupt(soft); + this._kill.forEach(function(state) { + return state.interrupt(soft); + }); + return this; + }; + _proto4.run = function run(skipGetState, merge) { + var _this5 = this; + if (this !== _batch) { + skipGetState || this.getState(merge); + this.loadState(function() { + if (!_this5._killed) { + _this5.setState(); + _this5.animate(); + } + }); + } + return this; + }; + _proto4.clear = function clear(stateOnly) { + this.state.clear(); + stateOnly || (this.actions.length = 0); + }; + _proto4.getStateById = function getStateById(id) { + var i = this.actions.length, s; + while (i--) { + s = this.actions[i].getStateById(id); + if (s) { + return s; } - return tl; - }, - defaults: { - brightness: 1.5, - duration: 0.5, - scale: 1.5, - stagger: 0.05, - ease: "sine", - easeStrength: 1.5 } - }, - csqClickIcon: { - effect: (csqIconContainer, config) => { - const csqContainer = $(csqIconContainer).closest(".comp.consequence-display-container"); - const csqRoot = U.gsap.utils.selector(csqContainer[0]); - const iconRoot = U.gsap.utils.selector(csqIconContainer); - const csqBackgroundImg = csqRoot(".consequence-bg-image"); - const csqInteractionPads = csqRoot(".consequence-interaction-pad"); - const csqIconCircleBase = iconRoot(".consequence-icon-circle.base-consequence"); - const csqIconCircleAccept = iconRoot(".consequence-icon-circle.accept-consequence"); - const csqButtonContainers = iconRoot(".consequence-button-container"); - const tl = U.gsap.timeline({ - paused: true, - onComplete: function() { - $(csqInteractionPads).css("pointerEvents", "auto"); - }, - onReverseComplete: function() { - $(csqInteractionPads).css("pointerEvents", "none"); - } - }); - if (csqBackgroundImg.length) { - tl.fromTo(csqBackgroundImg, { - xPercent: 110, - yPercent: -50 - }, { - xPercent: -60, - yPercent: -50, - duration: 0.5, - ease: "back" - }, 0); - } - if (csqIconCircleBase.length > 0) { - tl.fromTo(csqIconCircleBase, { - opacity: 1 - }, { - opacity: 0, - duration: 0.25, - ease: "sine.out" - }, 0); - } - if (csqIconCircleAccept.length > 0) { - tl.fromTo(csqIconCircleAccept, { - opacity: 0 - }, { - opacity: 1, - duration: 0.15, - ease: "sine" - }, 0).fromTo(csqIconCircleAccept, { - outlineWidth: 1, - scale: 0.85 - }, { - outlineWidth: 2, - scale: 1, - duration: 0.25, - ease: "sine" - }, 0.175); - } - if (csqButtonContainers.length > 0) { - tl.fromTo(csqButtonContainers, { - scale: config.scale, - opacity: 0, - filter: "blur(25px)" - }, { - scale: 1, - opacity: 1, - filter: "blur(0px)", - stagger: config.stagger, - duration: config.duration, - ease: `${config.ease}.inOut(${config.easeStrength})` - }, 0); - } - return tl; - }, - defaults: { - duration: 0.5, - scale: 1.5, - stagger: 0.05, - ease: "sine", - easeStrength: 1.5 + return this.state.idLookup[id] && this.state; + }; + _proto4.kill = function kill() { + this._killed = 1; + this.clear(); + delete _batchLookup[this.id]; + }; + return FlipBatch2; +}(); +var Flip = /* @__PURE__ */ function() { + function Flip2() { + } + Flip2.getState = function getState(targets, vars) { + var state = _parseState(targets, vars); + _batchAction && _batchAction.states.push(state); + vars && vars.batch && Flip2.batch(vars.batch).state.add(state); + return state; + }; + Flip2.from = function from(state, vars) { + vars = vars || {}; + "clearProps" in vars || (vars.clearProps = true); + return _fromTo(state, _parseState(vars.targets || state.targets, { + props: vars.props || state.props, + simple: vars.simple, + kill: !!vars.kill + }), vars, -1); + }; + Flip2.to = function to(state, vars) { + return _fromTo(state, _parseState(vars.targets || state.targets, { + props: vars.props || state.props, + simple: vars.simple, + kill: !!vars.kill + }), vars, 1); + }; + Flip2.fromTo = function fromTo(fromState, toState, vars) { + return _fromTo(fromState, toState, vars); + }; + Flip2.fit = function fit(fromEl, toEl, vars) { + var v = vars ? _copy$1(vars, _fitReserved) : {}, _ref = vars || v, absolute = _ref.absolute, scale = _ref.scale, getVars = _ref.getVars, props = _ref.props, runBackwards = _ref.runBackwards, onComplete = _ref.onComplete, simple = _ref.simple, fitChild = vars && vars.fitChild && _getEl(vars.fitChild), before = _parseElementState(toEl, props, simple, fromEl), after = _parseElementState(fromEl, 0, simple, before), inlineProps = props ? _memoizedRemoveProps[props] : _removeProps, ctx = gsap$4.context(); + props && _applyProps(v, before.props); + _recordInlineStyles(after, inlineProps); + if (runBackwards) { + "immediateRender" in v || (v.immediateRender = true); + v.onComplete = function() { + _applyInlineStyles(after); + onComplete && onComplete.apply(this, arguments); + }; } - }, - csqEnterRight: { - effect: (csqContainer) => { - const csqRoot = U.gsap.utils.selector(csqContainer); - const typeLine = csqRoot(".consequence-type-container .consequence-type.accept-consequence"); - const typeLineBg = csqRoot(".consequence-type-container .consequence-type-bg.accept-consequence"); - const buttonRoot = U.gsap.utils.selector(csqRoot(".consequence-button-container.consequence-accept-button-container")); - const buttonBg = buttonRoot(".consequence-button-bg"); - const buttonIcon = buttonRoot(".button-icon i"); - const buttonLabel = buttonRoot(".consequence-button-label"); - const tl = U.gsap.timeline({ paused: true, defaults: {} }); - if (typeLine.length > 0) { - tl.fromTo( - typeLine, - { - color: C.Colors.RED - }, - { - color: C.Colors.WHITE, - duration: 0.5, - ease: "sine.inOut" - }, - 0 - ); + absolute && _makeAbsolute(after, before); + v = _fit(after, before, scale || fitChild, props, fitChild, v.duration || getVars ? v : 0); + ctx && !getVars && ctx.add(function() { + return function() { + return _applyInlineStyles(after); + }; + }); + return getVars ? v : v.duration ? gsap$4.to(after.element, v) : null; + }; + Flip2.makeAbsolute = function makeAbsolute(targetsOrStates, vars) { + return (targetsOrStates instanceof FlipState ? targetsOrStates : new FlipState(targetsOrStates, vars)).makeAbsolute(); + }; + Flip2.batch = function batch(id) { + id || (id = "default"); + return _batchLookup[id] || (_batchLookup[id] = new FlipBatch(id)); + }; + Flip2.killFlipsOf = function killFlipsOf(targets, complete) { + (targets instanceof FlipState ? targets.targets : _toArray$2(targets)).forEach(function(t) { + return t && _killFlip(t._flip, complete !== false ? 1 : 2); + }); + }; + Flip2.isFlipping = function isFlipping(target) { + var f = Flip2.getByTarget(target); + return !!f && f.isActive(); + }; + Flip2.getByTarget = function getByTarget(target) { + return (_getEl(target) || _emptyObj)._flip; + }; + Flip2.getElementState = function getElementState(target, props) { + return new ElementState(_getEl(target), props); + }; + Flip2.convertCoordinates = function convertCoordinates2(fromElement, toElement, point) { + var m = getGlobalMatrix(toElement, true, true).multiply(getGlobalMatrix(fromElement)); + return point ? m.apply(point) : m; + }; + Flip2.register = function register2(core) { + _body$2 = typeof document !== "undefined" && document.body; + if (_body$2) { + gsap$4 = core; + _setDoc(_body$2); + _toArray$2 = gsap$4.utils.toArray; + _getStyleSaver$2 = gsap$4.core.getStyleSaver; + var snap3 = gsap$4.utils.snap(0.1); + _closestTenth = function _closestTenth2(value, add) { + return snap3(parseFloat(value) + add); + }; + } + }; + return Flip2; +}(); +Flip.version = "3.12.5"; +typeof window !== "undefined" && window.gsap && window.gsap.registerPlugin(Flip); +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) + descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) + _defineProperties(Constructor.prototype, protoProps); + if (staticProps) + _defineProperties(Constructor, staticProps); + return Constructor; +} +/*! + * Observer 3.12.5 + * https://gsap.com + * + * @license Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var gsap$3, _coreInitted$1, _win$1, _doc$1, _docEl, _body$1, _isTouch, _pointerType, ScrollTrigger, _root, _normalizer, _eventTypes, _context$1, _getGSAP$3 = function _getGSAP2() { + return gsap$3 || typeof window !== "undefined" && (gsap$3 = window.gsap) && gsap$3.registerPlugin && gsap$3; +}, _startup = 1, _observers = [], _scrollers = [], _proxies = [], _getTime$1 = Date.now, _bridge = function _bridge2(name, value) { + return value; +}, _integrate = function _integrate2() { + var core = ScrollTrigger.core, data = core.bridge || {}, scrollers = core._scrollers, proxies = core._proxies; + scrollers.push.apply(scrollers, _scrollers); + proxies.push.apply(proxies, _proxies); + _scrollers = scrollers; + _proxies = proxies; + _bridge = function _bridge3(name, value) { + return data[name](value); + }; +}, _getProxyProp = function _getProxyProp2(element, property) { + return ~_proxies.indexOf(element) && _proxies[_proxies.indexOf(element) + 1][property]; +}, _isViewport = function _isViewport2(el) { + return !!~_root.indexOf(el); +}, _addListener$1 = function _addListener(element, type, func, passive, capture) { + return element.addEventListener(type, func, { + passive: passive !== false, + capture: !!capture + }); +}, _removeListener$1 = function _removeListener(element, type, func, capture) { + return element.removeEventListener(type, func, !!capture); +}, _scrollLeft = "scrollLeft", _scrollTop = "scrollTop", _onScroll = function _onScroll2() { + return _normalizer && _normalizer.isPressed || _scrollers.cache++; +}, _scrollCacheFunc = function _scrollCacheFunc2(f, doNotCache) { + var cachingFunc = function cachingFunc2(value) { + if (value || value === 0) { + _startup && (_win$1.history.scrollRestoration = "manual"); + var isNormalizing = _normalizer && _normalizer.isPressed; + value = cachingFunc2.v = Math.round(value) || (_normalizer && _normalizer.iOS ? 1 : 0); + f(value); + cachingFunc2.cacheID = _scrollers.cache; + isNormalizing && _bridge("ss", value); + } else if (doNotCache || _scrollers.cache !== cachingFunc2.cacheID || _bridge("ref")) { + cachingFunc2.cacheID = _scrollers.cache; + cachingFunc2.v = f(); + } + return cachingFunc2.v + cachingFunc2.offset; + }; + cachingFunc.offset = 0; + return f && cachingFunc; +}, _horizontal = { + s: _scrollLeft, + p: "left", + p2: "Left", + os: "right", + os2: "Right", + d: "width", + d2: "Width", + a: "x", + sc: _scrollCacheFunc(function(value) { + return arguments.length ? _win$1.scrollTo(value, _vertical.sc()) : _win$1.pageXOffset || _doc$1[_scrollLeft] || _docEl[_scrollLeft] || _body$1[_scrollLeft] || 0; + }) +}, _vertical = { + s: _scrollTop, + p: "top", + p2: "Top", + os: "bottom", + os2: "Bottom", + d: "height", + d2: "Height", + a: "y", + op: _horizontal, + sc: _scrollCacheFunc(function(value) { + return arguments.length ? _win$1.scrollTo(_horizontal.sc(), value) : _win$1.pageYOffset || _doc$1[_scrollTop] || _docEl[_scrollTop] || _body$1[_scrollTop] || 0; + }) +}, _getTarget = function _getTarget2(t, self2) { + return (self2 && self2._ctx && self2._ctx.selector || gsap$3.utils.toArray)(t)[0] || (typeof t === "string" && gsap$3.config().nullTargetWarn !== false ? console.warn("Element not found:", t) : null); +}, _getScrollFunc = function _getScrollFunc2(element, _ref) { + var s = _ref.s, sc = _ref.sc; + _isViewport(element) && (element = _doc$1.scrollingElement || _docEl); + var i = _scrollers.indexOf(element), offset = sc === _vertical.sc ? 1 : 2; + !~i && (i = _scrollers.push(element) - 1); + _scrollers[i + offset] || _addListener$1(element, "scroll", _onScroll); + var prev = _scrollers[i + offset], func = prev || (_scrollers[i + offset] = _scrollCacheFunc(_getProxyProp(element, s), true) || (_isViewport(element) ? sc : _scrollCacheFunc(function(value) { + return arguments.length ? element[s] = value : element[s]; + }))); + func.target = element; + prev || (func.smooth = gsap$3.getProperty(element, "scrollBehavior") === "smooth"); + return func; +}, _getVelocityProp = function _getVelocityProp2(value, minTimeRefresh, useDelta) { + var v1 = value, v2 = value, t1 = _getTime$1(), t2 = t1, min = minTimeRefresh || 50, dropToZeroTime = Math.max(500, min * 3), update = function update2(value2, force) { + var t = _getTime$1(); + if (force || t - t1 > min) { + v2 = v1; + v1 = value2; + t2 = t1; + t1 = t; + } else if (useDelta) { + v1 += value2; + } else { + v1 = v2 + (value2 - v2) / (t - t2) * (t1 - t2); + } + }, reset = function reset2() { + v2 = v1 = useDelta ? 0 : v1; + t2 = t1 = 0; + }, getVelocity = function getVelocity2(latestValue) { + var tOld = t2, vOld = v2, t = _getTime$1(); + (latestValue || latestValue === 0) && latestValue !== v1 && update(latestValue); + return t1 === t2 || t - t2 > dropToZeroTime ? 0 : (v1 + (useDelta ? vOld : -vOld)) / ((useDelta ? t : t1) - tOld) * 1e3; + }; + return { + update, + reset, + getVelocity + }; +}, _getEvent = function _getEvent2(e, preventDefault) { + preventDefault && !e._gsapAllow && e.preventDefault(); + return e.changedTouches ? e.changedTouches[0] : e; +}, _getAbsoluteMax = function _getAbsoluteMax2(a) { + var max = Math.max.apply(Math, a), min = Math.min.apply(Math, a); + return Math.abs(max) >= Math.abs(min) ? max : min; +}, _setScrollTrigger = function _setScrollTrigger2() { + ScrollTrigger = gsap$3.core.globals().ScrollTrigger; + ScrollTrigger && ScrollTrigger.core && _integrate(); +}, _initCore$1 = function _initCore3(core) { + gsap$3 = core || _getGSAP$3(); + if (!_coreInitted$1 && gsap$3 && typeof document !== "undefined" && document.body) { + _win$1 = window; + _doc$1 = document; + _docEl = _doc$1.documentElement; + _body$1 = _doc$1.body; + _root = [_win$1, _doc$1, _docEl, _body$1]; + gsap$3.utils.clamp; + _context$1 = gsap$3.core.context || function() { + }; + _pointerType = "onpointerenter" in _body$1 ? "pointer" : "mouse"; + _isTouch = Observer$1.isTouch = _win$1.matchMedia && _win$1.matchMedia("(hover: none), (pointer: coarse)").matches ? 1 : "ontouchstart" in _win$1 || navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0 ? 2 : 0; + _eventTypes = Observer$1.eventTypes = ("ontouchstart" in _docEl ? "touchstart,touchmove,touchcancel,touchend" : !("onpointerdown" in _docEl) ? "mousedown,mousemove,mouseup,mouseup" : "pointerdown,pointermove,pointercancel,pointerup").split(","); + setTimeout(function() { + return _startup = 0; + }, 500); + _setScrollTrigger(); + _coreInitted$1 = 1; + } + return _coreInitted$1; +}; +_horizontal.op = _vertical; +_scrollers.cache = 0; +var Observer$1 = /* @__PURE__ */ function() { + function Observer2(vars) { + this.init(vars); + } + var _proto = Observer2.prototype; + _proto.init = function init6(vars) { + _coreInitted$1 || _initCore$1(gsap$3) || console.warn("Please gsap.registerPlugin(Observer)"); + ScrollTrigger || _setScrollTrigger(); + var tolerance = vars.tolerance, dragMinimum = vars.dragMinimum, type = vars.type, target = vars.target, lineHeight = vars.lineHeight, debounce = vars.debounce, preventDefault = vars.preventDefault, onStop = vars.onStop, onStopDelay = vars.onStopDelay, ignore = vars.ignore, wheelSpeed = vars.wheelSpeed, event = vars.event, onDragStart = vars.onDragStart, onDragEnd = vars.onDragEnd, onDrag = vars.onDrag, onPress = vars.onPress, onRelease = vars.onRelease, onRight = vars.onRight, onLeft = vars.onLeft, onUp = vars.onUp, onDown = vars.onDown, onChangeX = vars.onChangeX, onChangeY = vars.onChangeY, onChange = vars.onChange, onToggleX = vars.onToggleX, onToggleY = vars.onToggleY, onHover = vars.onHover, onHoverEnd = vars.onHoverEnd, onMove = vars.onMove, ignoreCheck = vars.ignoreCheck, isNormalizer = vars.isNormalizer, onGestureStart = vars.onGestureStart, onGestureEnd = vars.onGestureEnd, onWheel = vars.onWheel, onEnable = vars.onEnable, onDisable = vars.onDisable, onClick = vars.onClick, scrollSpeed = vars.scrollSpeed, capture = vars.capture, allowClicks = vars.allowClicks, lockAxis = vars.lockAxis, onLockAxis = vars.onLockAxis; + this.target = target = _getTarget(target) || _docEl; + this.vars = vars; + ignore && (ignore = gsap$3.utils.toArray(ignore)); + tolerance = tolerance || 1e-9; + dragMinimum = dragMinimum || 0; + wheelSpeed = wheelSpeed || 1; + scrollSpeed = scrollSpeed || 1; + type = type || "wheel,touch,pointer"; + debounce = debounce !== false; + lineHeight || (lineHeight = parseFloat(_win$1.getComputedStyle(_body$1).lineHeight) || 22); + var id, onStopDelayedCall, dragged, moved, wheeled, locked, axis, self2 = this, prevDeltaX = 0, prevDeltaY = 0, passive = vars.passive || !preventDefault, scrollFuncX = _getScrollFunc(target, _horizontal), scrollFuncY = _getScrollFunc(target, _vertical), scrollX = scrollFuncX(), scrollY = scrollFuncY(), limitToTouch = ~type.indexOf("touch") && !~type.indexOf("pointer") && _eventTypes[0] === "pointerdown", isViewport = _isViewport(target), ownerDoc = target.ownerDocument || _doc$1, deltaX = [0, 0, 0], deltaY = [0, 0, 0], onClickTime = 0, clickCapture = function clickCapture2() { + return onClickTime = _getTime$1(); + }, _ignoreCheck = function _ignoreCheck2(e, isPointerOrTouch) { + return (self2.event = e) && ignore && ~ignore.indexOf(e.target) || isPointerOrTouch && limitToTouch && e.pointerType !== "touch" || ignoreCheck && ignoreCheck(e, isPointerOrTouch); + }, onStopFunc = function onStopFunc2() { + self2._vx.reset(); + self2._vy.reset(); + onStopDelayedCall.pause(); + onStop && onStop(self2); + }, update = function update2() { + var dx = self2.deltaX = _getAbsoluteMax(deltaX), dy = self2.deltaY = _getAbsoluteMax(deltaY), changedX = Math.abs(dx) >= tolerance, changedY = Math.abs(dy) >= tolerance; + onChange && (changedX || changedY) && onChange(self2, dx, dy, deltaX, deltaY); + if (changedX) { + onRight && self2.deltaX > 0 && onRight(self2); + onLeft && self2.deltaX < 0 && onLeft(self2); + onChangeX && onChangeX(self2); + onToggleX && self2.deltaX < 0 !== prevDeltaX < 0 && onToggleX(self2); + prevDeltaX = self2.deltaX; + deltaX[0] = deltaX[1] = deltaX[2] = 0; + } + if (changedY) { + onDown && self2.deltaY > 0 && onDown(self2); + onUp && self2.deltaY < 0 && onUp(self2); + onChangeY && onChangeY(self2); + onToggleY && self2.deltaY < 0 !== prevDeltaY < 0 && onToggleY(self2); + prevDeltaY = self2.deltaY; + deltaY[0] = deltaY[1] = deltaY[2] = 0; + } + if (moved || dragged) { + onMove && onMove(self2); + if (dragged) { + onDrag(self2); + dragged = false; + } + moved = false; + } + locked && !(locked = false) && onLockAxis && onLockAxis(self2); + if (wheeled) { + onWheel(self2); + wheeled = false; + } + id = 0; + }, onDelta = function onDelta2(x, y, index) { + deltaX[index] += x; + deltaY[index] += y; + self2._vx.update(x); + self2._vy.update(y); + debounce ? id || (id = requestAnimationFrame(update)) : update(); + }, onTouchOrPointerDelta = function onTouchOrPointerDelta2(x, y) { + if (lockAxis && !axis) { + self2.axis = axis = Math.abs(x) > Math.abs(y) ? "x" : "y"; + locked = true; + } + if (axis !== "y") { + deltaX[2] += x; + self2._vx.update(x, true); + } + if (axis !== "x") { + deltaY[2] += y; + self2._vy.update(y, true); + } + debounce ? id || (id = requestAnimationFrame(update)) : update(); + }, _onDrag = function _onDrag2(e) { + if (_ignoreCheck(e, 1)) { + return; } - if (typeLineBg.length > 0) { - tl.fromTo(typeLineBg, { - x: 5, - scaleX: 0, - color: C.Colors.RED, - skewX: 0 - }, { - scaleX: 1, - skewX: -45, - color: C.Colors.RED, - duration: 0.5, - ease: "back.out" - }, 0); + e = _getEvent(e, preventDefault); + var x = e.clientX, y = e.clientY, dx = x - self2.x, dy = y - self2.y, isDragging = self2.isDragging; + self2.x = x; + self2.y = y; + if (isDragging || Math.abs(self2.startX - x) >= dragMinimum || Math.abs(self2.startY - y) >= dragMinimum) { + onDrag && (dragged = true); + isDragging || (self2.isDragging = true); + onTouchOrPointerDelta(dx, dy); + isDragging || onDragStart && onDragStart(self2); + } + }, _onPress = self2.onPress = function(e) { + if (_ignoreCheck(e, 1) || e && e.button) { + return; } - if (buttonBg.length > 0) { - tl.fromTo(buttonBg, { - scaleX: 0, - color: C.Colors.RED, - skewX: 0 - }, { - x: 0, - scaleX: 1, - skewX: -45, - color: C.Colors.RED, - duration: 0.25, - ease: "back.out" - }, 0); + self2.axis = axis = null; + onStopDelayedCall.pause(); + self2.isPressed = true; + e = _getEvent(e); + prevDeltaX = prevDeltaY = 0; + self2.startX = self2.x = e.clientX; + self2.startY = self2.y = e.clientY; + self2._vx.reset(); + self2._vy.reset(); + _addListener$1(isNormalizer ? target : ownerDoc, _eventTypes[1], _onDrag, passive, true); + self2.deltaX = self2.deltaY = 0; + onPress && onPress(self2); + }, _onRelease = self2.onRelease = function(e) { + if (_ignoreCheck(e, 1)) { + return; } - if (buttonIcon.length > 0) { - tl.fromTo( - buttonIcon, - { - color: C.Colors.GREY, - opacity: 0.75, - scale: 1 - }, - { - color: C.Colors.dBLACK, - scale: 1.25, - opacity: 1, - duration: 0.5, - ease: "sine" - }, - 0 - ); + _removeListener$1(isNormalizer ? target : ownerDoc, _eventTypes[1], _onDrag, true); + var isTrackingDrag = !isNaN(self2.y - self2.startY), wasDragging = self2.isDragging, isDragNotClick = wasDragging && (Math.abs(self2.x - self2.startX) > 3 || Math.abs(self2.y - self2.startY) > 3), eventData = _getEvent(e); + if (!isDragNotClick && isTrackingDrag) { + self2._vx.reset(); + self2._vy.reset(); + if (preventDefault && allowClicks) { + gsap$3.delayedCall(0.08, function() { + if (_getTime$1() - onClickTime > 300 && !e.defaultPrevented) { + if (e.target.click) { + e.target.click(); + } else if (ownerDoc.createEvent) { + var syntheticEvent = ownerDoc.createEvent("MouseEvents"); + syntheticEvent.initMouseEvent("click", true, true, _win$1, 1, eventData.screenX, eventData.screenY, eventData.clientX, eventData.clientY, false, false, false, false, 0, null); + e.target.dispatchEvent(syntheticEvent); + } + } + }); + } } - if (buttonLabel.length > 0) { - tl.fromTo( - buttonLabel, - { - color: C.Colors.GREY, - fontWeight: 400, - scale: 1 - }, - { - color: C.Colors.dBLACK, - fontWeight: 800, - duration: 0.75, - ease: "sine" - }, - 0 - ); + self2.isDragging = self2.isGesturing = self2.isPressed = false; + onStop && wasDragging && !isNormalizer && onStopDelayedCall.restart(true); + onDragEnd && wasDragging && onDragEnd(self2); + onRelease && onRelease(self2, isDragNotClick); + }, _onGestureStart = function _onGestureStart2(e) { + return e.touches && e.touches.length > 1 && (self2.isGesturing = true) && onGestureStart(e, self2.isDragging); + }, _onGestureEnd = function _onGestureEnd2() { + return (self2.isGesturing = false) || onGestureEnd(self2); + }, onScroll = function onScroll2(e) { + if (_ignoreCheck(e)) { + return; } - return tl; - }, - defaults: {} - }, - csqEnterLeft: { - effect: (csqContainer) => { - const csqRoot = U.gsap.utils.selector(csqContainer); - const typeLine = csqRoot(".consequence-type-container .consequence-type.accept-consequence"); - const nameLine = csqRoot(".consequence-name-container .consequence-name.accept-consequence"); - const acceptIconCircle = csqRoot(".consequence-icon-circle.accept-consequence"); - const acceptButton = csqRoot(".consequence-button-container.consequence-accept-button-container"); - const tl = U.gsap.timeline({ paused: true, defaults: {} }); - if (typeLine.length > 0) { - tl.to( - typeLine, - { - opacity: 0, - duration: 0.15, - ease: "sine.inOut" - }, - 0 - ); + var x = scrollFuncX(), y = scrollFuncY(); + onDelta((x - scrollX) * scrollSpeed, (y - scrollY) * scrollSpeed, 1); + scrollX = x; + scrollY = y; + onStop && onStopDelayedCall.restart(true); + }, _onWheel = function _onWheel2(e) { + if (_ignoreCheck(e)) { + return; } - if (nameLine.length > 0) { - tl.to(nameLine, { - opacity: 0, - duration: 0.15, - ease: "sine.inOut" - }, 0); + e = _getEvent(e, preventDefault); + onWheel && (wheeled = true); + var multiplier = (e.deltaMode === 1 ? lineHeight : e.deltaMode === 2 ? _win$1.innerHeight : 1) * wheelSpeed; + onDelta(e.deltaX * multiplier, e.deltaY * multiplier, 0); + onStop && !isNormalizer && onStopDelayedCall.restart(true); + }, _onMove = function _onMove2(e) { + if (_ignoreCheck(e)) { + return; } - if (acceptIconCircle.length > 0) { - tl.to( - acceptIconCircle, - { - opacity: 0, - duration: 0.15, - ease: "sine.inOut" - }, - 0 - ); + var x = e.clientX, y = e.clientY, dx = x - self2.x, dy = y - self2.y; + self2.x = x; + self2.y = y; + moved = true; + onStop && onStopDelayedCall.restart(true); + (dx || dy) && onTouchOrPointerDelta(dx, dy); + }, _onHover = function _onHover2(e) { + self2.event = e; + onHover(self2); + }, _onHoverEnd = function _onHoverEnd2(e) { + self2.event = e; + onHoverEnd(self2); + }, _onClick = function _onClick2(e) { + return _ignoreCheck(e) || _getEvent(e, preventDefault) && onClick(self2); + }; + onStopDelayedCall = self2._dc = gsap$3.delayedCall(onStopDelay || 0.25, onStopFunc).pause(); + self2.deltaX = self2.deltaY = 0; + self2._vx = _getVelocityProp(0, 50, true); + self2._vy = _getVelocityProp(0, 50, true); + self2.scrollX = scrollFuncX; + self2.scrollY = scrollFuncY; + self2.isDragging = self2.isGesturing = self2.isPressed = false; + _context$1(this); + self2.enable = function(e) { + if (!self2.isEnabled) { + _addListener$1(isViewport ? ownerDoc : target, "scroll", _onScroll); + type.indexOf("scroll") >= 0 && _addListener$1(isViewport ? ownerDoc : target, "scroll", onScroll, passive, capture); + type.indexOf("wheel") >= 0 && _addListener$1(target, "wheel", _onWheel, passive, capture); + if (type.indexOf("touch") >= 0 && _isTouch || type.indexOf("pointer") >= 0) { + _addListener$1(target, _eventTypes[0], _onPress, passive, capture); + _addListener$1(ownerDoc, _eventTypes[2], _onRelease); + _addListener$1(ownerDoc, _eventTypes[3], _onRelease); + allowClicks && _addListener$1(target, "click", clickCapture, true, true); + onClick && _addListener$1(target, "click", _onClick); + onGestureStart && _addListener$1(ownerDoc, "gesturestart", _onGestureStart); + onGestureEnd && _addListener$1(ownerDoc, "gestureend", _onGestureEnd); + onHover && _addListener$1(target, _pointerType + "enter", _onHover); + onHoverEnd && _addListener$1(target, _pointerType + "leave", _onHoverEnd); + onMove && _addListener$1(target, _pointerType + "move", _onMove); + } + self2.isEnabled = true; + e && e.type && _onPress(e); + onEnable && onEnable(self2); } - if (acceptButton.length > 0) { - tl.fromTo( - acceptButton, - { - opacity: 1 - }, - { - opacity: 0, - duration: 0.25, - ease: "sine.inOut" - }, - 0 - ); + return self2; + }; + self2.disable = function() { + if (self2.isEnabled) { + _observers.filter(function(o) { + return o !== self2 && _isViewport(o.target); + }).length || _removeListener$1(isViewport ? ownerDoc : target, "scroll", _onScroll); + if (self2.isPressed) { + self2._vx.reset(); + self2._vy.reset(); + _removeListener$1(isNormalizer ? target : ownerDoc, _eventTypes[1], _onDrag, true); + } + _removeListener$1(isViewport ? ownerDoc : target, "scroll", onScroll, capture); + _removeListener$1(target, "wheel", _onWheel, capture); + _removeListener$1(target, _eventTypes[0], _onPress, capture); + _removeListener$1(ownerDoc, _eventTypes[2], _onRelease); + _removeListener$1(ownerDoc, _eventTypes[3], _onRelease); + _removeListener$1(target, "click", clickCapture, true); + _removeListener$1(target, "click", _onClick); + _removeListener$1(ownerDoc, "gesturestart", _onGestureStart); + _removeListener$1(ownerDoc, "gestureend", _onGestureEnd); + _removeListener$1(target, _pointerType + "enter", _onHover); + _removeListener$1(target, _pointerType + "leave", _onHoverEnd); + _removeListener$1(target, _pointerType + "move", _onMove); + self2.isEnabled = self2.isPressed = self2.isDragging = false; + onDisable && onDisable(self2); } - return tl; - }, - defaults: {} - }, - csqEnterSubLeft: { - effect: (csqContainer, config) => { - const csqRoot = U.gsap.utils.selector(csqContainer); - const iconCircle = csqRoot(`.consequence-icon-circle.${config.type}-consequence`); - const typeLine = csqRoot(`.consequence-type-container .consequence-type.${config.type}-consequence`); - const nameLine = csqRoot(`.consequence-name.${config.type}-consequence`); - const footerBg = csqRoot(`.consequence-footer-container .consequence-footer-bg.${config.type}-consequence`); - const specialFooterMsg = csqRoot(`.consequence-footer-container .consequence-footer-message.${config.type}-consequence`); - const tl = U.gsap.timeline({ paused: true, defaults: {} }); - if (iconCircle.length > 0) { - tl.fromTo(iconCircle, { - opacity: 0 - }, { - opacity: 1, - duration: 0.5, - ease: "back.out" - }, 0); + }; + self2.kill = self2.revert = function() { + self2.disable(); + var i = _observers.indexOf(self2); + i >= 0 && _observers.splice(i, 1); + _normalizer === self2 && (_normalizer = 0); + }; + _observers.push(self2); + isNormalizer && _isViewport(target) && (_normalizer = self2); + self2.enable(event); + }; + _createClass(Observer2, [{ + key: "velocityX", + get: function get2() { + return this._vx.getVelocity(); + } + }, { + key: "velocityY", + get: function get2() { + return this._vy.getVelocity(); + } + }]); + return Observer2; +}(); +Observer$1.version = "3.12.5"; +Observer$1.create = function(vars) { + return new Observer$1(vars); +}; +Observer$1.register = _initCore$1; +Observer$1.getAll = function() { + return _observers.slice(); +}; +Observer$1.getById = function(id) { + return _observers.filter(function(o) { + return o.vars.id === id; + })[0]; +}; +_getGSAP$3() && gsap$3.registerPlugin(Observer$1); +function _assertThisInitialized(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; +} +function _inheritsLoose(subClass, superClass) { + subClass.prototype = Object.create(superClass.prototype); + subClass.prototype.constructor = subClass; + subClass.__proto__ = superClass; +} +var gsap$2, _win, _doc, _docElement, _body, _tempDiv$1, _placeholderDiv, _coreInitted, _checkPrefix, _toArray$1, _supportsPassive, _isTouchDevice, _touchEventLookup, _isMultiTouching, _isAndroid, InertiaPlugin, _defaultCursor, _supportsPointer, _context, _getStyleSaver$1, _dragCount = 0, _windowExists3 = function _windowExists4() { + return typeof window !== "undefined"; +}, _getGSAP$2 = function _getGSAP3() { + return gsap$2 || _windowExists3() && (gsap$2 = window.gsap) && gsap$2.registerPlugin && gsap$2; +}, _isFunction2 = function _isFunction3(value) { + return typeof value === "function"; +}, _isObject2 = function _isObject3(value) { + return typeof value === "object"; +}, _isUndefined3 = function _isUndefined4(value) { + return typeof value === "undefined"; +}, _emptyFunc$1 = function _emptyFunc2() { + return false; +}, _transformProp = "transform", _transformOriginProp = "transformOrigin", _round5 = function _round6(value) { + return Math.round(value * 1e4) / 1e4; +}, _isArray = Array.isArray, _createElement2 = function _createElement3(type, ns) { + var e = _doc.createElementNS ? _doc.createElementNS((ns || "http://www.w3.org/1999/xhtml").replace(/^https/, "http"), type) : _doc.createElement(type); + return e.style ? e : _doc.createElement(type); +}, _RAD2DEG = 180 / Math.PI, _bigNum = 1e20, _identityMatrix = new Matrix2D(), _getTime = Date.now || function() { + return (/* @__PURE__ */ new Date()).getTime(); +}, _renderQueue = [], _lookup = {}, _lookupCount = 0, _clickableTagExp = /^(?:a|input|textarea|button|select)$/i, _lastDragTime = 0, _temp1 = {}, _windowProxy = {}, _copy2 = function _copy3(obj, factor) { + var copy = {}, p; + for (p in obj) { + copy[p] = factor ? obj[p] * factor : obj[p]; + } + return copy; +}, _extend = function _extend2(obj, defaults2) { + for (var p in defaults2) { + if (!(p in obj)) { + obj[p] = defaults2[p]; + } + } + return obj; +}, _setTouchActionForAllDescendants = function _setTouchActionForAllDescendants2(elements, value) { + var i = elements.length, children; + while (i--) { + value ? elements[i].style.touchAction = value : elements[i].style.removeProperty("touch-action"); + children = elements[i].children; + children && children.length && _setTouchActionForAllDescendants2(children, value); + } +}, _renderQueueTick = function _renderQueueTick2() { + return _renderQueue.forEach(function(func) { + return func(); + }); +}, _addToRenderQueue = function _addToRenderQueue2(func) { + _renderQueue.push(func); + if (_renderQueue.length === 1) { + gsap$2.ticker.add(_renderQueueTick); + } +}, _renderQueueTimeout = function _renderQueueTimeout2() { + return !_renderQueue.length && gsap$2.ticker.remove(_renderQueueTick); +}, _removeFromRenderQueue = function _removeFromRenderQueue2(func) { + var i = _renderQueue.length; + while (i--) { + if (_renderQueue[i] === func) { + _renderQueue.splice(i, 1); + } + } + gsap$2.to(_renderQueueTimeout, { + overwrite: true, + delay: 15, + duration: 0, + onComplete: _renderQueueTimeout, + data: "_draggable" + }); +}, _setDefaults2 = function _setDefaults3(obj, defaults2) { + for (var p in defaults2) { + if (!(p in obj)) { + obj[p] = defaults2[p]; + } + } + return obj; +}, _addListener2 = function _addListener3(element, type, func, capture) { + if (element.addEventListener) { + var touchType = _touchEventLookup[type]; + capture = capture || (_supportsPassive ? { + passive: false + } : null); + element.addEventListener(touchType || type, func, capture); + touchType && type !== touchType && element.addEventListener(type, func, capture); + } +}, _removeListener2 = function _removeListener3(element, type, func, capture) { + if (element.removeEventListener) { + var touchType = _touchEventLookup[type]; + element.removeEventListener(touchType || type, func, capture); + touchType && type !== touchType && element.removeEventListener(type, func, capture); + } +}, _preventDefault = function _preventDefault2(event) { + event.preventDefault && event.preventDefault(); + event.preventManipulation && event.preventManipulation(); +}, _hasTouchID = function _hasTouchID2(list, ID) { + var i = list.length; + while (i--) { + if (list[i].identifier === ID) { + return true; + } + } +}, _onMultiTouchDocumentEnd = function _onMultiTouchDocumentEnd2(event) { + _isMultiTouching = event.touches && _dragCount < event.touches.length; + _removeListener2(event.target, "touchend", _onMultiTouchDocumentEnd2); +}, _onMultiTouchDocument = function _onMultiTouchDocument2(event) { + _isMultiTouching = event.touches && _dragCount < event.touches.length; + _addListener2(event.target, "touchend", _onMultiTouchDocumentEnd); +}, _getDocScrollTop2 = function _getDocScrollTop3(doc) { + return _win.pageYOffset || doc.scrollTop || doc.documentElement.scrollTop || doc.body.scrollTop || 0; +}, _getDocScrollLeft2 = function _getDocScrollLeft3(doc) { + return _win.pageXOffset || doc.scrollLeft || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0; +}, _addScrollListener = function _addScrollListener2(e, callback) { + _addListener2(e, "scroll", callback); + if (!_isRoot(e.parentNode)) { + _addScrollListener2(e.parentNode, callback); + } +}, _removeScrollListener = function _removeScrollListener2(e, callback) { + _removeListener2(e, "scroll", callback); + if (!_isRoot(e.parentNode)) { + _removeScrollListener2(e.parentNode, callback); + } +}, _isRoot = function _isRoot2(e) { + return !!(!e || e === _docElement || e.nodeType === 9 || e === _doc.body || e === _win || !e.nodeType || !e.parentNode); +}, _getMaxScroll = function _getMaxScroll2(element, axis) { + var dim = axis === "x" ? "Width" : "Height", scroll = "scroll" + dim, client = "client" + dim; + return Math.max(0, _isRoot(element) ? Math.max(_docElement[scroll], _body[scroll]) - (_win["inner" + dim] || _docElement[client] || _body[client]) : element[scroll] - element[client]); +}, _recordMaxScrolls = function _recordMaxScrolls2(e, skipCurrent) { + var x = _getMaxScroll(e, "x"), y = _getMaxScroll(e, "y"); + if (_isRoot(e)) { + e = _windowProxy; + } else { + _recordMaxScrolls2(e.parentNode, skipCurrent); + } + e._gsMaxScrollX = x; + e._gsMaxScrollY = y; + if (!skipCurrent) { + e._gsScrollX = e.scrollLeft || 0; + e._gsScrollY = e.scrollTop || 0; + } +}, _setStyle = function _setStyle2(element, property, value) { + var style = element.style; + if (!style) { + return; + } + if (_isUndefined3(style[property])) { + property = _checkPrefix(property, element) || property; + } + if (value == null) { + style.removeProperty && style.removeProperty(property.replace(/([A-Z])/g, "-$1").toLowerCase()); + } else { + style[property] = value; + } +}, _getComputedStyle = function _getComputedStyle2(element) { + return _win.getComputedStyle(element instanceof Element ? element : element.host || (element.parentNode || {}).host || element); +}, _tempRect = {}, _parseRect = function _parseRect2(e) { + if (e === _win) { + _tempRect.left = _tempRect.top = 0; + _tempRect.width = _tempRect.right = _docElement.clientWidth || e.innerWidth || _body.clientWidth || 0; + _tempRect.height = _tempRect.bottom = (e.innerHeight || 0) - 20 < _docElement.clientHeight ? _docElement.clientHeight : e.innerHeight || _body.clientHeight || 0; + return _tempRect; + } + var doc = e.ownerDocument || _doc, r = !_isUndefined3(e.pageX) ? { + left: e.pageX - _getDocScrollLeft2(doc), + top: e.pageY - _getDocScrollTop2(doc), + right: e.pageX - _getDocScrollLeft2(doc) + 1, + bottom: e.pageY - _getDocScrollTop2(doc) + 1 + } : !e.nodeType && !_isUndefined3(e.left) && !_isUndefined3(e.top) ? e : _toArray$1(e)[0].getBoundingClientRect(); + if (_isUndefined3(r.right) && !_isUndefined3(r.width)) { + r.right = r.left + r.width; + r.bottom = r.top + r.height; + } else if (_isUndefined3(r.width)) { + r = { + width: r.right - r.left, + height: r.bottom - r.top, + right: r.right, + left: r.left, + bottom: r.bottom, + top: r.top + }; + } + return r; +}, _dispatchEvent = function _dispatchEvent2(target, type, callbackName) { + var vars = target.vars, callback = vars[callbackName], listeners = target._listeners[type], result; + if (_isFunction2(callback)) { + result = callback.apply(vars.callbackScope || target, vars[callbackName + "Params"] || [target.pointerEvent]); + } + if (listeners && target.dispatchEvent(type) === false) { + result = false; + } + return result; +}, _getBounds = function _getBounds2(target, context3) { + var e = _toArray$1(target)[0], top, left, offset; + if (!e.nodeType && e !== _win) { + if (!_isUndefined3(target.left)) { + offset = { + x: 0, + y: 0 + }; + return { + left: target.left - offset.x, + top: target.top - offset.y, + width: target.width, + height: target.height + }; + } + left = target.min || target.minX || target.minRotation || 0; + top = target.min || target.minY || 0; + return { + left, + top, + width: (target.max || target.maxX || target.maxRotation || 0) - left, + height: (target.max || target.maxY || 0) - top + }; + } + return _getElementBounds(e, context3); +}, _point1 = {}, _getElementBounds = function _getElementBounds2(element, context3) { + context3 = _toArray$1(context3)[0]; + var isSVG = element.getBBox && element.ownerSVGElement, doc = element.ownerDocument || _doc, left, right, top, bottom, matrix, p1, p2, p3, p4, bbox, width, height, cs; + if (element === _win) { + top = _getDocScrollTop2(doc); + left = _getDocScrollLeft2(doc); + right = left + (doc.documentElement.clientWidth || element.innerWidth || doc.body.clientWidth || 0); + bottom = top + ((element.innerHeight || 0) - 20 < doc.documentElement.clientHeight ? doc.documentElement.clientHeight : element.innerHeight || doc.body.clientHeight || 0); + } else if (context3 === _win || _isUndefined3(context3)) { + return element.getBoundingClientRect(); + } else { + left = top = 0; + if (isSVG) { + bbox = element.getBBox(); + width = bbox.width; + height = bbox.height; + } else { + if (element.viewBox && (bbox = element.viewBox.baseVal)) { + left = bbox.x || 0; + top = bbox.y || 0; + width = bbox.width; + height = bbox.height; } - if (typeLine.length > 0) { - tl.fromTo(typeLine, { - opacity: 0 - }, { - opacity: 1, - duration: 0.5, - ease: "back.out" - }, 0); + if (!width) { + cs = _getComputedStyle(element); + bbox = cs.boxSizing === "border-box"; + width = (parseFloat(cs.width) || element.clientWidth || 0) + (bbox ? 0 : parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth)); + height = (parseFloat(cs.height) || element.clientHeight || 0) + (bbox ? 0 : parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth)); } - if (nameLine.length > 0) { - tl.fromTo(nameLine, { - scaleX: 0 - }, { - scaleX: 1, - duration: 0.5, - ease: "back.inOut" - }, 0); + } + right = width; + bottom = height; + } + if (element === context3) { + return { + left, + top, + width: right - left, + height: bottom - top + }; + } + matrix = getGlobalMatrix(context3, true).multiply(getGlobalMatrix(element)); + p1 = matrix.apply({ + x: left, + y: top + }); + p2 = matrix.apply({ + x: right, + y: top + }); + p3 = matrix.apply({ + x: right, + y: bottom + }); + p4 = matrix.apply({ + x: left, + y: bottom + }); + left = Math.min(p1.x, p2.x, p3.x, p4.x); + top = Math.min(p1.y, p2.y, p3.y, p4.y); + return { + left, + top, + width: Math.max(p1.x, p2.x, p3.x, p4.x) - left, + height: Math.max(p1.y, p2.y, p3.y, p4.y) - top + }; +}, _parseInertia = function _parseInertia2(draggable, snap3, max, min, factor, forceZeroVelocity) { + var vars = {}, a, i, l; + if (snap3) { + if (factor !== 1 && snap3 instanceof Array) { + vars.end = a = []; + l = snap3.length; + if (_isObject2(snap3[0])) { + for (i = 0; i < l; i++) { + a[i] = _copy2(snap3[i], factor); + } + } else { + for (i = 0; i < l; i++) { + a[i] = snap3[i] * factor; + } } - if (footerBg.length > 0) { - tl.fromTo(footerBg, { - scaleX: 0, - skewX: 0, - opacity: 1 - }, { - scaleX: 1, - skewX: -45, - opacity: 1, - duration: 0.5, - ease: "back.inOut" - }, 0); + max += 1.1; + min -= 1.1; + } else if (_isFunction2(snap3)) { + vars.end = function(value) { + var result = snap3.call(draggable, value), copy, p; + if (factor !== 1) { + if (_isObject2(result)) { + copy = {}; + for (p in result) { + copy[p] = result[p] * factor; + } + result = copy; + } else { + result *= factor; + } + } + return result; + }; + } else { + vars.end = snap3; + } + } + if (max || max === 0) { + vars.max = max; + } + if (min || min === 0) { + vars.min = min; + } + if (forceZeroVelocity) { + vars.velocity = 0; + } + return vars; +}, _isClickable = function _isClickable2(element) { + var data; + return !element || !element.getAttribute || element === _body ? false : (data = element.getAttribute("data-clickable")) === "true" || data !== "false" && (_clickableTagExp.test(element.nodeName + "") || element.getAttribute("contentEditable") === "true") ? true : _isClickable2(element.parentNode); +}, _setSelectable = function _setSelectable2(elements, selectable) { + var i = elements.length, e; + while (i--) { + e = elements[i]; + e.ondragstart = e.onselectstart = selectable ? null : _emptyFunc$1; + gsap$2.set(e, { + lazy: true, + userSelect: selectable ? "text" : "none" + }); + } +}, _isFixed2 = function _isFixed3(element) { + if (_getComputedStyle(element).position === "fixed") { + return true; + } + element = element.parentNode; + if (element && element.nodeType === 1) { + return _isFixed3(element); + } +}, _supports3D, _addPaddingBR, ScrollProxy = function ScrollProxy2(element, vars) { + element = gsap$2.utils.toArray(element)[0]; + vars = vars || {}; + var content = document.createElement("div"), style = content.style, node = element.firstChild, offsetTop = 0, offsetLeft = 0, prevTop = element.scrollTop, prevLeft = element.scrollLeft, scrollWidth = element.scrollWidth, scrollHeight = element.scrollHeight, extraPadRight = 0, maxLeft = 0, maxTop = 0, elementWidth, elementHeight, contentHeight, nextNode, transformStart, transformEnd; + if (_supports3D && vars.force3D !== false) { + transformStart = "translate3d("; + transformEnd = "px,0px)"; + } else if (_transformProp) { + transformStart = "translate("; + transformEnd = "px)"; + } + this.scrollTop = function(value, force) { + if (!arguments.length) { + return -this.top(); + } + this.top(-value, force); + }; + this.scrollLeft = function(value, force) { + if (!arguments.length) { + return -this.left(); + } + this.left(-value, force); + }; + this.left = function(value, force) { + if (!arguments.length) { + return -(element.scrollLeft + offsetLeft); + } + var dif = element.scrollLeft - prevLeft, oldOffset = offsetLeft; + if ((dif > 2 || dif < -2) && !force) { + prevLeft = element.scrollLeft; + gsap$2.killTweensOf(this, { + left: 1, + scrollLeft: 1 + }); + this.left(-prevLeft); + if (vars.onKill) { + vars.onKill(); } - if (specialFooterMsg.length > 0) { - tl.fromTo(specialFooterMsg, { - scaleX: 0, - opacity: 1 - }, { - scaleX: 1, - opacity: 1, - duration: 0.5, - ease: "back.inOut" - }, 0); + return; + } + value = -value; + if (value < 0) { + offsetLeft = value - 0.5 | 0; + value = 0; + } else if (value > maxLeft) { + offsetLeft = value - maxLeft | 0; + value = maxLeft; + } else { + offsetLeft = 0; + } + if (offsetLeft || oldOffset) { + if (!this._skip) { + style[_transformProp] = transformStart + -offsetLeft + "px," + -offsetTop + transformEnd; } - if (csqRoot(`.consequence-button-container.consequence-${config.type}-button-container`).length > 0) { - const buttonRoot = U.gsap.utils.selector(csqRoot(`.consequence-button-container.consequence-${config.type}-button-container`)); - const buttonBg = buttonRoot(".consequence-button-bg"); - const buttonIcon = buttonRoot(".button-icon i"); - const buttonLabel = buttonRoot(".consequence-button-label"); - if (buttonBg.length > 0) { - tl.fromTo(buttonBg, { - scaleX: 0, - skewX: 0, - opacity: 1 - }, { - scaleX: 1, - skewX: -45, - opacity: 1, - duration: 0.5, - ease: "back.inOut" - }, 0); + if (offsetLeft + extraPadRight >= 0) { + style.paddingRight = offsetLeft + extraPadRight + "px"; + } + } + element.scrollLeft = value | 0; + prevLeft = element.scrollLeft; + }; + this.top = function(value, force) { + if (!arguments.length) { + return -(element.scrollTop + offsetTop); + } + var dif = element.scrollTop - prevTop, oldOffset = offsetTop; + if ((dif > 2 || dif < -2) && !force) { + prevTop = element.scrollTop; + gsap$2.killTweensOf(this, { + top: 1, + scrollTop: 1 + }); + this.top(-prevTop); + if (vars.onKill) { + vars.onKill(); + } + return; + } + value = -value; + if (value < 0) { + offsetTop = value - 0.5 | 0; + value = 0; + } else if (value > maxTop) { + offsetTop = value - maxTop | 0; + value = maxTop; + } else { + offsetTop = 0; + } + if (offsetTop || oldOffset) { + if (!this._skip) { + style[_transformProp] = transformStart + -offsetLeft + "px," + -offsetTop + transformEnd; + } + } + element.scrollTop = value | 0; + prevTop = element.scrollTop; + }; + this.maxScrollTop = function() { + return maxTop; + }; + this.maxScrollLeft = function() { + return maxLeft; + }; + this.disable = function() { + node = content.firstChild; + while (node) { + nextNode = node.nextSibling; + element.appendChild(node); + node = nextNode; + } + if (element === content.parentNode) { + element.removeChild(content); + } + }; + this.enable = function() { + node = element.firstChild; + if (node === content) { + return; + } + while (node) { + nextNode = node.nextSibling; + content.appendChild(node); + node = nextNode; + } + element.appendChild(content); + this.calibrate(); + }; + this.calibrate = function(force) { + var widthMatches = element.clientWidth === elementWidth, cs, x, y; + prevTop = element.scrollTop; + prevLeft = element.scrollLeft; + if (widthMatches && element.clientHeight === elementHeight && content.offsetHeight === contentHeight && scrollWidth === element.scrollWidth && scrollHeight === element.scrollHeight && !force) { + return; + } + if (offsetTop || offsetLeft) { + x = this.left(); + y = this.top(); + this.left(-element.scrollLeft); + this.top(-element.scrollTop); + } + cs = _getComputedStyle(element); + if (!widthMatches || force) { + style.display = "block"; + style.width = "auto"; + style.paddingRight = "0px"; + extraPadRight = Math.max(0, element.scrollWidth - element.clientWidth); + if (extraPadRight) { + extraPadRight += parseFloat(cs.paddingLeft) + (_addPaddingBR ? parseFloat(cs.paddingRight) : 0); + } + } + style.display = "inline-block"; + style.position = "relative"; + style.overflow = "visible"; + style.verticalAlign = "top"; + style.boxSizing = "content-box"; + style.width = "100%"; + style.paddingRight = extraPadRight + "px"; + if (_addPaddingBR) { + style.paddingBottom = cs.paddingBottom; + } + elementWidth = element.clientWidth; + elementHeight = element.clientHeight; + scrollWidth = element.scrollWidth; + scrollHeight = element.scrollHeight; + maxLeft = element.scrollWidth - elementWidth; + maxTop = element.scrollHeight - elementHeight; + contentHeight = content.offsetHeight; + style.display = "block"; + if (x || y) { + this.left(x); + this.top(y); + } + }; + this.content = content; + this.element = element; + this._skip = false; + this.enable(); +}, _initCore4 = function _initCore5(required) { + if (_windowExists3() && document.body) { + var nav = window && window.navigator; + _win = window; + _doc = document; + _docElement = _doc.documentElement; + _body = _doc.body; + _tempDiv$1 = _createElement2("div"); + _supportsPointer = !!window.PointerEvent; + _placeholderDiv = _createElement2("div"); + _placeholderDiv.style.cssText = "visibility:hidden;height:1px;top:-1px;pointer-events:none;position:relative;clear:both;cursor:grab"; + _defaultCursor = _placeholderDiv.style.cursor === "grab" ? "grab" : "move"; + _isAndroid = nav && nav.userAgent.toLowerCase().indexOf("android") !== -1; + _isTouchDevice = "ontouchstart" in _docElement && "orientation" in _win || nav && (nav.MaxTouchPoints > 0 || nav.msMaxTouchPoints > 0); + _addPaddingBR = function() { + var div = _createElement2("div"), child = _createElement2("div"), childStyle = child.style, parent = _body, val; + childStyle.display = "inline-block"; + childStyle.position = "relative"; + div.style.cssText = "width:90px;height:40px;padding:10px;overflow:auto;visibility:hidden"; + div.appendChild(child); + parent.appendChild(div); + val = child.offsetHeight + 18 > div.scrollHeight; + parent.removeChild(div); + return val; + }(); + _touchEventLookup = function(types) { + var standard = types.split(","), converted = ("onpointerdown" in _tempDiv$1 ? "pointerdown,pointermove,pointerup,pointercancel" : "onmspointerdown" in _tempDiv$1 ? "MSPointerDown,MSPointerMove,MSPointerUp,MSPointerCancel" : types).split(","), obj = {}, i = 4; + while (--i > -1) { + obj[standard[i]] = converted[i]; + obj[converted[i]] = standard[i]; + } + try { + _docElement.addEventListener("test", null, Object.defineProperty({}, "passive", { + get: function get2() { + _supportsPassive = 1; + } + })); + } catch (e) { + } + return obj; + }("touchstart,touchmove,touchend,touchcancel"); + _addListener2(_doc, "touchcancel", _emptyFunc$1); + _addListener2(_win, "touchmove", _emptyFunc$1); + _body && _body.addEventListener("touchstart", _emptyFunc$1); + _addListener2(_doc, "contextmenu", function() { + for (var p in _lookup) { + if (_lookup[p].isPressed) { + _lookup[p].endDrag(); } - if (buttonIcon.length > 0) { - tl.fromTo( - buttonIcon, - { - color: C.Colors.GREY, - opacity: 0.75, - scale: 1 - }, - { - color: C.Colors.dBLACK, - scale: 1.25, - opacity: 1, - duration: 0.5, - ease: "sine" - }, - 0 - ); + } + }); + gsap$2 = _coreInitted = _getGSAP$2(); + } + if (gsap$2) { + InertiaPlugin = gsap$2.plugins.inertia; + _context = gsap$2.core.context || function() { + }; + _checkPrefix = gsap$2.utils.checkPrefix; + _transformProp = _checkPrefix(_transformProp); + _transformOriginProp = _checkPrefix(_transformOriginProp); + _toArray$1 = gsap$2.utils.toArray; + _getStyleSaver$1 = gsap$2.core.getStyleSaver; + _supports3D = !!_checkPrefix("perspective"); + } else if (required) { + console.warn("Please gsap.registerPlugin(Draggable)"); + } +}; +var EventDispatcher = /* @__PURE__ */ function() { + function EventDispatcher2(target) { + this._listeners = {}; + this.target = target || this; + } + var _proto = EventDispatcher2.prototype; + _proto.addEventListener = function addEventListener2(type, callback) { + var list = this._listeners[type] || (this._listeners[type] = []); + if (!~list.indexOf(callback)) { + list.push(callback); + } + }; + _proto.removeEventListener = function removeEventListener2(type, callback) { + var list = this._listeners[type], i = list && list.indexOf(callback); + i >= 0 && list.splice(i, 1); + }; + _proto.dispatchEvent = function dispatchEvent2(type) { + var _this = this; + var result; + (this._listeners[type] || []).forEach(function(callback) { + return callback.call(_this, { + type, + target: _this.target + }) === false && (result = false); + }); + return result; + }; + return EventDispatcher2; +}(); +var Draggable = /* @__PURE__ */ function(_EventDispatcher) { + _inheritsLoose(Draggable2, _EventDispatcher); + function Draggable2(target, vars) { + var _this2; + _this2 = _EventDispatcher.call(this) || this; + _coreInitted || _initCore4(1); + target = _toArray$1(target)[0]; + _this2.styles = _getStyleSaver$1 && _getStyleSaver$1(target, "transform,left,top"); + if (!InertiaPlugin) { + InertiaPlugin = gsap$2.plugins.inertia; + } + _this2.vars = vars = _copy2(vars || {}); + _this2.target = target; + _this2.x = _this2.y = _this2.rotation = 0; + _this2.dragResistance = parseFloat(vars.dragResistance) || 0; + _this2.edgeResistance = isNaN(vars.edgeResistance) ? 1 : parseFloat(vars.edgeResistance) || 0; + _this2.lockAxis = vars.lockAxis; + _this2.autoScroll = vars.autoScroll || 0; + _this2.lockedAxis = null; + _this2.allowEventDefault = !!vars.allowEventDefault; + gsap$2.getProperty(target, "x"); + var type = (vars.type || "x,y").toLowerCase(), xyMode = ~type.indexOf("x") || ~type.indexOf("y"), rotationMode = type.indexOf("rotation") !== -1, xProp = rotationMode ? "rotation" : xyMode ? "x" : "left", yProp = xyMode ? "y" : "top", allowX = !!(~type.indexOf("x") || ~type.indexOf("left") || type === "scroll"), allowY = !!(~type.indexOf("y") || ~type.indexOf("top") || type === "scroll"), minimumMovement = vars.minimumMovement || 2, self2 = _assertThisInitialized(_this2), triggers = _toArray$1(vars.trigger || vars.handle || target), killProps = {}, dragEndTime = 0, checkAutoScrollBounds = false, autoScrollMarginTop = vars.autoScrollMarginTop || 40, autoScrollMarginRight = vars.autoScrollMarginRight || 40, autoScrollMarginBottom = vars.autoScrollMarginBottom || 40, autoScrollMarginLeft = vars.autoScrollMarginLeft || 40, isClickable = vars.clickableTest || _isClickable, clickTime = 0, gsCache = target._gsap || gsap$2.core.getCache(target), isFixed = _isFixed2(target), getPropAsNum = function getPropAsNum2(property, unit) { + return parseFloat(gsCache.get(target, property, unit)); + }, ownerDoc = target.ownerDocument || _doc, enabled, scrollProxy, startPointerX, startPointerY, startElementX, startElementY, hasBounds, hasDragCallback, hasMoveCallback, maxX, minX, maxY, minY, touch, touchID, rotationOrigin, dirty, old, snapX, snapY, snapXY, isClicking, touchEventTarget, matrix, interrupted, allowNativeTouchScrolling, touchDragAxis, isDispatching, clickDispatch, trustedClickDispatch, isPreventingDefault, innerMatrix, dragged, onContextMenu = function onContextMenu2(e) { + _preventDefault(e); + e.stopImmediatePropagation && e.stopImmediatePropagation(); + return false; + }, render5 = function render6(suppressEvents) { + if (self2.autoScroll && self2.isDragging && (checkAutoScrollBounds || dirty)) { + var e = target, autoScrollFactor = self2.autoScroll * 15, parent, isRoot, rect, pointerX, pointerY, changeX, changeY, gap; + checkAutoScrollBounds = false; + _windowProxy.scrollTop = _win.pageYOffset != null ? _win.pageYOffset : ownerDoc.documentElement.scrollTop != null ? ownerDoc.documentElement.scrollTop : ownerDoc.body.scrollTop; + _windowProxy.scrollLeft = _win.pageXOffset != null ? _win.pageXOffset : ownerDoc.documentElement.scrollLeft != null ? ownerDoc.documentElement.scrollLeft : ownerDoc.body.scrollLeft; + pointerX = self2.pointerX - _windowProxy.scrollLeft; + pointerY = self2.pointerY - _windowProxy.scrollTop; + while (e && !isRoot) { + isRoot = _isRoot(e.parentNode); + parent = isRoot ? _windowProxy : e.parentNode; + rect = isRoot ? { + bottom: Math.max(_docElement.clientHeight, _win.innerHeight || 0), + right: Math.max(_docElement.clientWidth, _win.innerWidth || 0), + left: 0, + top: 0 + } : parent.getBoundingClientRect(); + changeX = changeY = 0; + if (allowY) { + gap = parent._gsMaxScrollY - parent.scrollTop; + if (gap < 0) { + changeY = gap; + } else if (pointerY > rect.bottom - autoScrollMarginBottom && gap) { + checkAutoScrollBounds = true; + changeY = Math.min(gap, autoScrollFactor * (1 - Math.max(0, rect.bottom - pointerY) / autoScrollMarginBottom) | 0); + } else if (pointerY < rect.top + autoScrollMarginTop && parent.scrollTop) { + checkAutoScrollBounds = true; + changeY = -Math.min(parent.scrollTop, autoScrollFactor * (1 - Math.max(0, pointerY - rect.top) / autoScrollMarginTop) | 0); + } + if (changeY) { + parent.scrollTop += changeY; + } + } + if (allowX) { + gap = parent._gsMaxScrollX - parent.scrollLeft; + if (gap < 0) { + changeX = gap; + } else if (pointerX > rect.right - autoScrollMarginRight && gap) { + checkAutoScrollBounds = true; + changeX = Math.min(gap, autoScrollFactor * (1 - Math.max(0, rect.right - pointerX) / autoScrollMarginRight) | 0); + } else if (pointerX < rect.left + autoScrollMarginLeft && parent.scrollLeft) { + checkAutoScrollBounds = true; + changeX = -Math.min(parent.scrollLeft, autoScrollFactor * (1 - Math.max(0, pointerX - rect.left) / autoScrollMarginLeft) | 0); + } + if (changeX) { + parent.scrollLeft += changeX; + } + } + if (isRoot && (changeX || changeY)) { + _win.scrollTo(parent.scrollLeft, parent.scrollTop); + setPointerPosition(self2.pointerX + changeX, self2.pointerY + changeY); + } + e = parent; } - if (buttonLabel.length > 0) { - tl.fromTo( - buttonLabel, - { - color: C.Colors.GREY, - fontWeight: 400, - scale: 1 - }, - { - color: C.Colors.dBLACK, - fontWeight: 800, - duration: 0.75, - ease: "sine" - }, - 0 - ); + } + if (dirty) { + var x = self2.x, y = self2.y; + if (rotationMode) { + self2.deltaX = x - parseFloat(gsCache.rotation); + self2.rotation = x; + gsCache.rotation = x + "deg"; + gsCache.renderTransform(1, gsCache); + } else { + if (scrollProxy) { + if (allowY) { + self2.deltaY = y - scrollProxy.top(); + scrollProxy.top(y); + } + if (allowX) { + self2.deltaX = x - scrollProxy.left(); + scrollProxy.left(x); + } + } else if (xyMode) { + if (allowY) { + self2.deltaY = y - parseFloat(gsCache.y); + gsCache.y = y + "px"; + } + if (allowX) { + self2.deltaX = x - parseFloat(gsCache.x); + gsCache.x = x + "px"; + } + gsCache.renderTransform(1, gsCache); + } else { + if (allowY) { + self2.deltaY = y - parseFloat(target.style.top || 0); + target.style.top = y + "px"; + } + if (allowX) { + self2.deltaX = x - parseFloat(target.style.left || 0); + target.style.left = x + "px"; + } + } + } + if (hasDragCallback && !suppressEvents && !isDispatching) { + isDispatching = true; + if (_dispatchEvent(self2, "drag", "onDrag") === false) { + if (allowX) { + self2.x -= self2.deltaX; + } + if (allowY) { + self2.y -= self2.deltaY; + } + render6(true); + } + isDispatching = false; } } - return tl; - }, - defaults: {} - }, - // #endregion - // #region CHARACTER SHEET EFFECTS - fillCoins: { - effect: (targets, config) => { - return U.gsap.to( - targets, - { - duration: config.duration / 2, - scale: config.scale, - filter: config.filter, - ease: config.ease, - stagger: { - amount: 0.25, - from: "start", - repeat: 1, - yoyo: true + dirty = false; + }, syncXY = function syncXY2(skipOnUpdate, skipSnap) { + var x = self2.x, y = self2.y, snappedValue, cs; + if (!target._gsap) { + gsCache = gsap$2.core.getCache(target); + } + gsCache.uncache && gsap$2.getProperty(target, "x"); + if (xyMode) { + self2.x = parseFloat(gsCache.x); + self2.y = parseFloat(gsCache.y); + } else if (rotationMode) { + self2.x = self2.rotation = parseFloat(gsCache.rotation); + } else if (scrollProxy) { + self2.y = scrollProxy.top(); + self2.x = scrollProxy.left(); + } else { + self2.y = parseFloat(target.style.top || (cs = _getComputedStyle(target)) && cs.top) || 0; + self2.x = parseFloat(target.style.left || (cs || {}).left) || 0; + } + if ((snapX || snapY || snapXY) && !skipSnap && (self2.isDragging || self2.isThrowing)) { + if (snapXY) { + _temp1.x = self2.x; + _temp1.y = self2.y; + snappedValue = snapXY(_temp1); + if (snappedValue.x !== self2.x) { + self2.x = snappedValue.x; + dirty = true; + } + if (snappedValue.y !== self2.y) { + self2.y = snappedValue.y; + dirty = true; } } - ); - }, - defaults: { - duration: 1, - scale: 1, - filter: "saturate(1) brightness(2)", - ease: "power2.in" - }, - extendTimeline: true - }, - // #endregion - // #region GENERAL: 'blurRemove', 'hoverTooltip', 'textJitter' - blurRemove: { - effect: (targets, config) => U.gsap.timeline({ stagger: config.stagger }).to( - targets, - { - skewX: config.skewX, - duration: config.duration / 2, - ease: "power4.out" + if (snapX) { + snappedValue = snapX(self2.x); + if (snappedValue !== self2.x) { + self2.x = snappedValue; + if (rotationMode) { + self2.rotation = snappedValue; + } + dirty = true; + } + } + if (snapY) { + snappedValue = snapY(self2.y); + if (snappedValue !== self2.y) { + self2.y = snappedValue; + } + dirty = true; + } } - ).to( - targets, - { - x: config.x, - marginBottom: config.ignoreMargin ? void 0 : function(i, target) { - return U.get(target, "height") * -1; - }, - marginRight: config.ignoreMargin ? void 0 : function(i, target) { - return U.get(target, "width") * -1; - }, - scale: config.scale, - filter: `blur(${config.blur}px)`, - duration: 3 / 4 * config.duration - }, - config.duration / 4 - ).to( - targets, - { - autoAlpha: 0, - duration: config.duration / 2, - ease: "power3.in" - }, - config.duration / 2 - ), - defaults: { - ignoreMargin: false, - skewX: -20, - duration: 0.5, - x: "+=300", - scale: 1.5, - blur: 10, - stagger: 0 - }, - extendTimeline: true - }, - blurReveal: { - effect: (targets, config) => U.gsap.timeline().fromTo( - targets, - { - x: config.x, - marginBottom: config.ignoreMargin ? void 0 : function(i, target) { - return U.get(target, "height") * -1; - }, - marginRight: config.ignoreMargin ? void 0 : function(i, target) { - return U.get(target, "width") * -1; - }, - scale: config.scale, - filter: `blur(${config.blur}px)` - }, - { - x: 0, - marginBottom: 0, - marginRight: 0, - scale: 1, - filter: "blur(0px)", - duration: 3 / 4 * config.duration - }, - 0 - ).fromTo( - targets, - { - autoAlpha: 0 - }, - { - autoAlpha: 1, - duration: config.duration / 2, - ease: "power3.in" - }, - 0 - ).fromTo( - targets, - { - skewX: config.skewX - }, - { - skewX: 0, - duration: config.duration / 2, - ease: "power4.out" - }, - config.duration / 2 - ), - defaults: { - ignoreMargin: false, - skewX: -20, - duration: 0.5, - x: "+=300", - scale: 1.5, - blur: 10 - }, - extendTimeline: true - }, - scaleUpReveal: { - effect: (target, config) => { - const tl = U.gsap.timeline().fromTo(target, { - autoAlpha: 0, - scale: 0.5 * config.scale - }, { - autoAlpha: 1, - scale: config.scale, - duration: config.duration, - ease: config.ease - }); - return tl; - }, - defaults: { - scale: 1, - duration: 0.5, - ease: "power2" - }, - extendTimeline: true - }, - scaleDownRemove: { - effect: (target, config) => { - const tl = U.gsap.timeline().to(target, { - autoAlpha: 0, - scale: 0.5 * config.scale, - duration: config.duration, - ease: config.ease - }); - return tl; - }, - defaults: { - scale: 1, - duration: 0.5, - ease: "power2" - }, - extendTimeline: true - }, - blurRevealTooltip: { - effect: (target, config) => { - if (!target) { - throw new Error(`blurRevealTooltip effect: tooltip element is ${target === null ? "null" : typeof target}`); + dirty && render5(true); + if (!skipOnUpdate) { + self2.deltaX = self2.x - x; + self2.deltaY = self2.y - y; + _dispatchEvent(self2, "throwupdate", "onThrowUpdate"); } - const tooltip$ = $(target); - return U.gsap.timeline({ - paused: true, - onReverseComplete: config.onReverseComplete - }).fromTo( - tooltip$, - { - filter: `blur(${config.blurStrength}px)`, - autoAlpha: 0, - xPercent: 50, - yPercent: -200, - scale: config.scale - }, - { - filter: "blur(0px)", - autoAlpha: 1, - xPercent: -50, - yPercent: -100, - scale: 1, - ease: config.ease, - duration: config.duration + }, buildSnapFunc = function buildSnapFunc2(snap3, min, max, factor) { + if (min == null) { + min = -_bigNum; + } + if (max == null) { + max = _bigNum; + } + if (_isFunction2(snap3)) { + return function(n) { + var edgeTolerance = !self2.isPressed ? 1 : 1 - self2.edgeResistance; + return snap3.call(self2, (n > max ? max + (n - max) * edgeTolerance : n < min ? min + (n - min) * edgeTolerance : n) * factor) * factor; + }; + } + if (_isArray(snap3)) { + return function(n) { + var i = snap3.length, closest = 0, absDif = _bigNum, val, dif; + while (--i > -1) { + val = snap3[i]; + dif = val - n; + if (dif < 0) { + dif = -dif; + } + if (dif < absDif && val >= min && val <= max) { + closest = i; + absDif = dif; + } + } + return snap3[closest]; + }; + } + return isNaN(snap3) ? function(n) { + return n; + } : function() { + return snap3 * factor; + }; + }, buildPointSnapFunc = function buildPointSnapFunc2(snap3, minX2, maxX2, minY2, maxY2, radius, factor) { + radius = radius && radius < _bigNum ? radius * radius : _bigNum; + if (_isFunction2(snap3)) { + return function(point) { + var edgeTolerance = !self2.isPressed ? 1 : 1 - self2.edgeResistance, x = point.x, y = point.y, result, dx, dy; + point.x = x = x > maxX2 ? maxX2 + (x - maxX2) * edgeTolerance : x < minX2 ? minX2 + (x - minX2) * edgeTolerance : x; + point.y = y = y > maxY2 ? maxY2 + (y - maxY2) * edgeTolerance : y < minY2 ? minY2 + (y - minY2) * edgeTolerance : y; + result = snap3.call(self2, point); + if (result !== point) { + point.x = result.x; + point.y = result.y; + } + if (factor !== 1) { + point.x *= factor; + point.y *= factor; + } + if (radius < _bigNum) { + dx = point.x - x; + dy = point.y - y; + if (dx * dx + dy * dy > radius) { + point.x = x; + point.y = y; + } + } + return point; + }; + } + if (_isArray(snap3)) { + return function(p) { + var i = snap3.length, closest = 0, minDist = _bigNum, x, y, point, dist; + while (--i > -1) { + point = snap3[i]; + x = point.x - p.x; + y = point.y - p.y; + dist = x * x + y * y; + if (dist < minDist) { + closest = i; + minDist = dist; + } + } + return minDist <= radius ? snap3[closest] : p; + }; + } + return function(n) { + return n; + }; + }, calculateBounds = function calculateBounds2() { + var bounds, targetBounds, snap3, snapIsRaw; + hasBounds = false; + if (scrollProxy) { + scrollProxy.calibrate(); + self2.minX = minX = -scrollProxy.maxScrollLeft(); + self2.minY = minY = -scrollProxy.maxScrollTop(); + self2.maxX = maxX = self2.maxY = maxY = 0; + hasBounds = true; + } else if (!!vars.bounds) { + bounds = _getBounds(vars.bounds, target.parentNode); + if (rotationMode) { + self2.minX = minX = bounds.left; + self2.maxX = maxX = bounds.left + bounds.width; + self2.minY = minY = self2.maxY = maxY = 0; + } else if (!_isUndefined3(vars.bounds.maxX) || !_isUndefined3(vars.bounds.maxY)) { + bounds = vars.bounds; + self2.minX = minX = bounds.minX; + self2.minY = minY = bounds.minY; + self2.maxX = maxX = bounds.maxX; + self2.maxY = maxY = bounds.maxY; + } else { + targetBounds = _getBounds(target, target.parentNode); + self2.minX = minX = Math.round(getPropAsNum(xProp, "px") + bounds.left - targetBounds.left); + self2.minY = minY = Math.round(getPropAsNum(yProp, "px") + bounds.top - targetBounds.top); + self2.maxX = maxX = Math.round(minX + (bounds.width - targetBounds.width)); + self2.maxY = maxY = Math.round(minY + (bounds.height - targetBounds.height)); + } + if (minX > maxX) { + self2.minX = maxX; + self2.maxX = maxX = minX; + minX = self2.minX; + } + if (minY > maxY) { + self2.minY = maxY; + self2.maxY = maxY = minY; + minY = self2.minY; + } + if (rotationMode) { + self2.minRotation = minX; + self2.maxRotation = maxX; + } + hasBounds = true; + } + if (vars.liveSnap) { + snap3 = vars.liveSnap === true ? vars.snap || {} : vars.liveSnap; + snapIsRaw = _isArray(snap3) || _isFunction2(snap3); + if (rotationMode) { + snapX = buildSnapFunc(snapIsRaw ? snap3 : snap3.rotation, minX, maxX, 1); + snapY = null; + } else { + if (snap3.points) { + snapXY = buildPointSnapFunc(snapIsRaw ? snap3 : snap3.points, minX, maxX, minY, maxY, snap3.radius, scrollProxy ? -1 : 1); + } else { + if (allowX) { + snapX = buildSnapFunc(snapIsRaw ? snap3 : snap3.x || snap3.left || snap3.scrollLeft, minX, maxX, scrollProxy ? -1 : 1); + } + if (allowY) { + snapY = buildSnapFunc(snapIsRaw ? snap3 : snap3.y || snap3.top || snap3.scrollTop, minY, maxY, scrollProxy ? -1 : 1); + } + } } - ); - }, - defaults: { - scale: 1.5, - blurStrength: 15, - ease: "back.out", - duration: 0.25, - onReverseComplete: void 0 - }, - extendTimeline: true - }, - textJitter: { - effect: (target, config) => { - const [targetElem] = $(target); - if (!targetElem) { - throw new Error("textJitter effect: target not found"); } - const split = new SplitText(targetElem, { type: "chars" }); - return U.gsap.timeline().to(targetElem, { - autoAlpha: 1, - duration: config.duration, - ease: "none" - }).fromTo(split.chars, { - y: -config.yAmp - }, { - y: config.yAmp, - duration: config.duration, - ease: "sine.inOut", - stagger: { - repeat: -1, - yoyo: true, - from: "random", - each: config.stagger + }, onThrowComplete = function onThrowComplete2() { + self2.isThrowing = false; + _dispatchEvent(self2, "throwcomplete", "onThrowComplete"); + }, onThrowInterrupt = function onThrowInterrupt2() { + self2.isThrowing = false; + }, animate = function animate2(inertia, forceZeroVelocity) { + var snap3, snapIsRaw, tween, overshootTolerance; + if (inertia && InertiaPlugin) { + if (inertia === true) { + snap3 = vars.snap || vars.liveSnap || {}; + snapIsRaw = _isArray(snap3) || _isFunction2(snap3); + inertia = { + resistance: (vars.throwResistance || vars.resistance || 1e3) / (rotationMode ? 10 : 1) + }; + if (rotationMode) { + inertia.rotation = _parseInertia(self2, snapIsRaw ? snap3 : snap3.rotation, maxX, minX, 1, forceZeroVelocity); + } else { + if (allowX) { + inertia[xProp] = _parseInertia(self2, snapIsRaw ? snap3 : snap3.points || snap3.x || snap3.left, maxX, minX, scrollProxy ? -1 : 1, forceZeroVelocity || self2.lockedAxis === "x"); + } + if (allowY) { + inertia[yProp] = _parseInertia(self2, snapIsRaw ? snap3 : snap3.points || snap3.y || snap3.top, maxY, minY, scrollProxy ? -1 : 1, forceZeroVelocity || self2.lockedAxis === "y"); + } + if (snap3.points || _isArray(snap3) && _isObject2(snap3[0])) { + inertia.linkedProps = xProp + "," + yProp; + inertia.radius = snap3.radius; + } + } } - }, 0).fromTo(split.chars, { - rotateZ: -config.rotateAmp - }, { - rotateZ: config.rotateAmp, - duration: config.duration, - ease: CustomWiggle.create("myWiggle", { wiggles: 10, type: "random" }), - stagger: { - repeat: -1, - from: "random", - yoyo: true, - each: config.stagger + self2.isThrowing = true; + overshootTolerance = !isNaN(vars.overshootTolerance) ? vars.overshootTolerance : vars.edgeResistance === 1 ? 0 : 1 - self2.edgeResistance + 0.2; + if (!inertia.duration) { + inertia.duration = { + max: Math.max(vars.minDuration || 0, "maxDuration" in vars ? vars.maxDuration : 2), + min: !isNaN(vars.minDuration) ? vars.minDuration : overshootTolerance === 0 || _isObject2(inertia) && inertia.resistance > 1e3 ? 0 : 0.5, + overshoot: overshootTolerance + }; } - }, 0); - }, - defaults: { - yAmp: 2, - rotateAmp: 2, - duration: 1, - stagger: 0.05 - }, - extendTimeline: true - } - // #endregion + self2.tween = tween = gsap$2.to(scrollProxy || target, { + inertia, + data: "_draggable", + inherit: false, + onComplete: onThrowComplete, + onInterrupt: onThrowInterrupt, + onUpdate: vars.fastMode ? _dispatchEvent : syncXY, + onUpdateParams: vars.fastMode ? [self2, "onthrowupdate", "onThrowUpdate"] : snap3 && snap3.radius ? [false, true] : [] + }); + if (!vars.fastMode) { + if (scrollProxy) { + scrollProxy._skip = true; + } + tween.render(1e9, true, true); + syncXY(true, true); + self2.endX = self2.x; + self2.endY = self2.y; + if (rotationMode) { + self2.endRotation = self2.x; + } + tween.play(0); + syncXY(true, true); + if (scrollProxy) { + scrollProxy._skip = false; + } + } + } else if (hasBounds) { + self2.applyBounds(); + } + }, updateMatrix = function updateMatrix2(shiftStart) { + var start = matrix, p; + matrix = getGlobalMatrix(target.parentNode, true); + if (shiftStart && self2.isPressed && !matrix.equals(start || new Matrix2D())) { + p = start.inverse().apply({ + x: startPointerX, + y: startPointerY + }); + matrix.apply(p, p); + startPointerX = p.x; + startPointerY = p.y; + } + if (matrix.equals(_identityMatrix)) { + matrix = null; + } + }, recordStartPositions = function recordStartPositions2() { + var edgeTolerance = 1 - self2.edgeResistance, offsetX = isFixed ? _getDocScrollLeft2(ownerDoc) : 0, offsetY = isFixed ? _getDocScrollTop2(ownerDoc) : 0, parsedOrigin, x, y; + if (xyMode) { + gsCache.x = getPropAsNum(xProp, "px") + "px"; + gsCache.y = getPropAsNum(yProp, "px") + "px"; + gsCache.renderTransform(); + } + updateMatrix(false); + _point1.x = self2.pointerX - offsetX; + _point1.y = self2.pointerY - offsetY; + matrix && matrix.apply(_point1, _point1); + startPointerX = _point1.x; + startPointerY = _point1.y; + if (dirty) { + setPointerPosition(self2.pointerX, self2.pointerY); + render5(true); + } + innerMatrix = getGlobalMatrix(target); + if (scrollProxy) { + calculateBounds(); + startElementY = scrollProxy.top(); + startElementX = scrollProxy.left(); + } else { + if (isTweening2()) { + syncXY(true, true); + calculateBounds(); + } else { + self2.applyBounds(); + } + if (rotationMode) { + parsedOrigin = target.ownerSVGElement ? [gsCache.xOrigin - target.getBBox().x, gsCache.yOrigin - target.getBBox().y] : (_getComputedStyle(target)[_transformOriginProp] || "0 0").split(" "); + rotationOrigin = self2.rotationOrigin = getGlobalMatrix(target).apply({ + x: parseFloat(parsedOrigin[0]) || 0, + y: parseFloat(parsedOrigin[1]) || 0 + }); + syncXY(true, true); + x = self2.pointerX - rotationOrigin.x - offsetX; + y = rotationOrigin.y - self2.pointerY + offsetY; + startElementX = self2.x; + startElementY = self2.y = Math.atan2(y, x) * _RAD2DEG; + } else { + startElementY = getPropAsNum(yProp, "px"); + startElementX = getPropAsNum(xProp, "px"); + } + } + if (hasBounds && edgeTolerance) { + if (startElementX > maxX) { + startElementX = maxX + (startElementX - maxX) / edgeTolerance; + } else if (startElementX < minX) { + startElementX = minX - (minX - startElementX) / edgeTolerance; + } + if (!rotationMode) { + if (startElementY > maxY) { + startElementY = maxY + (startElementY - maxY) / edgeTolerance; + } else if (startElementY < minY) { + startElementY = minY - (minY - startElementY) / edgeTolerance; + } + } + } + self2.startX = startElementX = _round5(startElementX); + self2.startY = startElementY = _round5(startElementY); + }, isTweening2 = function isTweening3() { + return self2.tween && self2.tween.isActive(); + }, removePlaceholder = function removePlaceholder2() { + if (_placeholderDiv.parentNode && !isTweening2() && !self2.isDragging) { + _placeholderDiv.parentNode.removeChild(_placeholderDiv); + } + }, onPress = function onPress2(e, force) { + var i; + if (!enabled || self2.isPressed || !e || (e.type === "mousedown" || e.type === "pointerdown") && !force && _getTime() - clickTime < 30 && _touchEventLookup[self2.pointerEvent.type]) { + isPreventingDefault && e && enabled && _preventDefault(e); + return; + } + interrupted = isTweening2(); + dragged = false; + self2.pointerEvent = e; + if (_touchEventLookup[e.type]) { + touchEventTarget = ~e.type.indexOf("touch") ? e.currentTarget || e.target : ownerDoc; + _addListener2(touchEventTarget, "touchend", onRelease); + _addListener2(touchEventTarget, "touchmove", onMove); + _addListener2(touchEventTarget, "touchcancel", onRelease); + _addListener2(ownerDoc, "touchstart", _onMultiTouchDocument); + } else { + touchEventTarget = null; + _addListener2(ownerDoc, "mousemove", onMove); + } + touchDragAxis = null; + if (!_supportsPointer || !touchEventTarget) { + _addListener2(ownerDoc, "mouseup", onRelease); + e && e.target && _addListener2(e.target, "mouseup", onRelease); + } + isClicking = isClickable.call(self2, e.target) && vars.dragClickables === false && !force; + if (isClicking) { + _addListener2(e.target, "change", onRelease); + _dispatchEvent(self2, "pressInit", "onPressInit"); + _dispatchEvent(self2, "press", "onPress"); + _setSelectable(triggers, true); + isPreventingDefault = false; + return; + } + allowNativeTouchScrolling = !touchEventTarget || allowX === allowY || self2.vars.allowNativeTouchScrolling === false || self2.vars.allowContextMenu && e && (e.ctrlKey || e.which > 2) ? false : allowX ? "y" : "x"; + isPreventingDefault = !allowNativeTouchScrolling && !self2.allowEventDefault; + if (isPreventingDefault) { + _preventDefault(e); + _addListener2(_win, "touchforcechange", _preventDefault); + } + if (e.changedTouches) { + e = touch = e.changedTouches[0]; + touchID = e.identifier; + } else if (e.pointerId) { + touchID = e.pointerId; + } else { + touch = touchID = null; + } + _dragCount++; + _addToRenderQueue(render5); + startPointerY = self2.pointerY = e.pageY; + startPointerX = self2.pointerX = e.pageX; + _dispatchEvent(self2, "pressInit", "onPressInit"); + if (allowNativeTouchScrolling || self2.autoScroll) { + _recordMaxScrolls(target.parentNode); + } + if (target.parentNode && self2.autoScroll && !scrollProxy && !rotationMode && target.parentNode._gsMaxScrollX && !_placeholderDiv.parentNode && !target.getBBox) { + _placeholderDiv.style.width = target.parentNode.scrollWidth + "px"; + target.parentNode.appendChild(_placeholderDiv); + } + recordStartPositions(); + self2.tween && self2.tween.kill(); + self2.isThrowing = false; + gsap$2.killTweensOf(scrollProxy || target, killProps, true); + scrollProxy && gsap$2.killTweensOf(target, { + scrollTo: 1 + }, true); + self2.tween = self2.lockedAxis = null; + if (vars.zIndexBoost || !rotationMode && !scrollProxy && vars.zIndexBoost !== false) { + target.style.zIndex = Draggable2.zIndex++; + } + self2.isPressed = true; + hasDragCallback = !!(vars.onDrag || self2._listeners.drag); + hasMoveCallback = !!(vars.onMove || self2._listeners.move); + if (vars.cursor !== false || vars.activeCursor) { + i = triggers.length; + while (--i > -1) { + gsap$2.set(triggers[i], { + cursor: vars.activeCursor || vars.cursor || (_defaultCursor === "grab" ? "grabbing" : _defaultCursor) + }); + } + } + _dispatchEvent(self2, "press", "onPress"); + }, onMove = function onMove2(e) { + var originalEvent = e, touches, pointerX, pointerY, i, dx, dy; + if (!enabled || _isMultiTouching || !self2.isPressed || !e) { + isPreventingDefault && e && enabled && _preventDefault(e); + return; + } + self2.pointerEvent = e; + touches = e.changedTouches; + if (touches) { + e = touches[0]; + if (e !== touch && e.identifier !== touchID) { + i = touches.length; + while (--i > -1 && (e = touches[i]).identifier !== touchID && e.target !== target) { + } + if (i < 0) { + return; + } + } + } else if (e.pointerId && touchID && e.pointerId !== touchID) { + return; + } + if (touchEventTarget && allowNativeTouchScrolling && !touchDragAxis) { + _point1.x = e.pageX - (isFixed ? _getDocScrollLeft2(ownerDoc) : 0); + _point1.y = e.pageY - (isFixed ? _getDocScrollTop2(ownerDoc) : 0); + matrix && matrix.apply(_point1, _point1); + pointerX = _point1.x; + pointerY = _point1.y; + dx = Math.abs(pointerX - startPointerX); + dy = Math.abs(pointerY - startPointerY); + if (dx !== dy && (dx > minimumMovement || dy > minimumMovement) || _isAndroid && allowNativeTouchScrolling === touchDragAxis) { + touchDragAxis = dx > dy && allowX ? "x" : "y"; + if (allowNativeTouchScrolling && touchDragAxis !== allowNativeTouchScrolling) { + _addListener2(_win, "touchforcechange", _preventDefault); + } + if (self2.vars.lockAxisOnTouchScroll !== false && allowX && allowY) { + self2.lockedAxis = touchDragAxis === "x" ? "y" : "x"; + _isFunction2(self2.vars.onLockAxis) && self2.vars.onLockAxis.call(self2, originalEvent); + } + if (_isAndroid && allowNativeTouchScrolling === touchDragAxis) { + onRelease(originalEvent); + return; + } + } + } + if (!self2.allowEventDefault && (!allowNativeTouchScrolling || touchDragAxis && allowNativeTouchScrolling !== touchDragAxis) && originalEvent.cancelable !== false) { + _preventDefault(originalEvent); + isPreventingDefault = true; + } else if (isPreventingDefault) { + isPreventingDefault = false; + } + if (self2.autoScroll) { + checkAutoScrollBounds = true; + } + setPointerPosition(e.pageX, e.pageY, hasMoveCallback); + }, setPointerPosition = function setPointerPosition2(pointerX, pointerY, invokeOnMove) { + var dragTolerance = 1 - self2.dragResistance, edgeTolerance = 1 - self2.edgeResistance, prevPointerX = self2.pointerX, prevPointerY = self2.pointerY, prevStartElementY = startElementY, prevX = self2.x, prevY = self2.y, prevEndX = self2.endX, prevEndY = self2.endY, prevEndRotation = self2.endRotation, prevDirty = dirty, xChange, yChange, x, y, dif, temp; + self2.pointerX = pointerX; + self2.pointerY = pointerY; + if (isFixed) { + pointerX -= _getDocScrollLeft2(ownerDoc); + pointerY -= _getDocScrollTop2(ownerDoc); + } + if (rotationMode) { + y = Math.atan2(rotationOrigin.y - pointerY, pointerX - rotationOrigin.x) * _RAD2DEG; + dif = self2.y - y; + if (dif > 180) { + startElementY -= 360; + self2.y = y; + } else if (dif < -180) { + startElementY += 360; + self2.y = y; + } + if (self2.x !== startElementX || Math.abs(startElementY - y) > minimumMovement) { + self2.y = y; + x = startElementX + (startElementY - y) * dragTolerance; + } else { + x = startElementX; + } + } else { + if (matrix) { + temp = pointerX * matrix.a + pointerY * matrix.c + matrix.e; + pointerY = pointerX * matrix.b + pointerY * matrix.d + matrix.f; + pointerX = temp; + } + yChange = pointerY - startPointerY; + xChange = pointerX - startPointerX; + if (yChange < minimumMovement && yChange > -minimumMovement) { + yChange = 0; + } + if (xChange < minimumMovement && xChange > -minimumMovement) { + xChange = 0; + } + if ((self2.lockAxis || self2.lockedAxis) && (xChange || yChange)) { + temp = self2.lockedAxis; + if (!temp) { + self2.lockedAxis = temp = allowX && Math.abs(xChange) > Math.abs(yChange) ? "y" : allowY ? "x" : null; + if (temp && _isFunction2(self2.vars.onLockAxis)) { + self2.vars.onLockAxis.call(self2, self2.pointerEvent); + } + } + if (temp === "y") { + yChange = 0; + } else if (temp === "x") { + xChange = 0; + } + } + x = _round5(startElementX + xChange * dragTolerance); + y = _round5(startElementY + yChange * dragTolerance); + } + if ((snapX || snapY || snapXY) && (self2.x !== x || self2.y !== y && !rotationMode)) { + if (snapXY) { + _temp1.x = x; + _temp1.y = y; + temp = snapXY(_temp1); + x = _round5(temp.x); + y = _round5(temp.y); + } + if (snapX) { + x = _round5(snapX(x)); + } + if (snapY) { + y = _round5(snapY(y)); + } + } + if (hasBounds) { + if (x > maxX) { + x = maxX + Math.round((x - maxX) * edgeTolerance); + } else if (x < minX) { + x = minX + Math.round((x - minX) * edgeTolerance); + } + if (!rotationMode) { + if (y > maxY) { + y = Math.round(maxY + (y - maxY) * edgeTolerance); + } else if (y < minY) { + y = Math.round(minY + (y - minY) * edgeTolerance); + } + } + } + if (self2.x !== x || self2.y !== y && !rotationMode) { + if (rotationMode) { + self2.endRotation = self2.x = self2.endX = x; + dirty = true; + } else { + if (allowY) { + self2.y = self2.endY = y; + dirty = true; + } + if (allowX) { + self2.x = self2.endX = x; + dirty = true; + } + } + if (!invokeOnMove || _dispatchEvent(self2, "move", "onMove") !== false) { + if (!self2.isDragging && self2.isPressed) { + self2.isDragging = dragged = true; + _dispatchEvent(self2, "dragstart", "onDragStart"); + } + } else { + self2.pointerX = prevPointerX; + self2.pointerY = prevPointerY; + startElementY = prevStartElementY; + self2.x = prevX; + self2.y = prevY; + self2.endX = prevEndX; + self2.endY = prevEndY; + self2.endRotation = prevEndRotation; + dirty = prevDirty; + } + } + }, onRelease = function onRelease2(e, force) { + if (!enabled || !self2.isPressed || e && touchID != null && !force && (e.pointerId && e.pointerId !== touchID && e.target !== target || e.changedTouches && !_hasTouchID(e.changedTouches, touchID))) { + isPreventingDefault && e && enabled && _preventDefault(e); + return; + } + self2.isPressed = false; + var originalEvent = e, wasDragging = self2.isDragging, isContextMenuRelease = self2.vars.allowContextMenu && e && (e.ctrlKey || e.which > 2), placeholderDelayedCall = gsap$2.delayedCall(1e-3, removePlaceholder), touches, i, syntheticEvent, eventTarget, syntheticClick; + if (touchEventTarget) { + _removeListener2(touchEventTarget, "touchend", onRelease2); + _removeListener2(touchEventTarget, "touchmove", onMove); + _removeListener2(touchEventTarget, "touchcancel", onRelease2); + _removeListener2(ownerDoc, "touchstart", _onMultiTouchDocument); + } else { + _removeListener2(ownerDoc, "mousemove", onMove); + } + _removeListener2(_win, "touchforcechange", _preventDefault); + if (!_supportsPointer || !touchEventTarget) { + _removeListener2(ownerDoc, "mouseup", onRelease2); + e && e.target && _removeListener2(e.target, "mouseup", onRelease2); + } + dirty = false; + if (wasDragging) { + dragEndTime = _lastDragTime = _getTime(); + self2.isDragging = false; + } + _removeFromRenderQueue(render5); + if (isClicking && !isContextMenuRelease) { + if (e) { + _removeListener2(e.target, "change", onRelease2); + self2.pointerEvent = originalEvent; + } + _setSelectable(triggers, false); + _dispatchEvent(self2, "release", "onRelease"); + _dispatchEvent(self2, "click", "onClick"); + isClicking = false; + return; + } + i = triggers.length; + while (--i > -1) { + _setStyle(triggers[i], "cursor", vars.cursor || (vars.cursor !== false ? _defaultCursor : null)); + } + _dragCount--; + if (e) { + touches = e.changedTouches; + if (touches) { + e = touches[0]; + if (e !== touch && e.identifier !== touchID) { + i = touches.length; + while (--i > -1 && (e = touches[i]).identifier !== touchID && e.target !== target) { + } + if (i < 0 && !force) { + return; + } + } + } + self2.pointerEvent = originalEvent; + self2.pointerX = e.pageX; + self2.pointerY = e.pageY; + } + if (isContextMenuRelease && originalEvent) { + _preventDefault(originalEvent); + isPreventingDefault = true; + _dispatchEvent(self2, "release", "onRelease"); + } else if (originalEvent && !wasDragging) { + isPreventingDefault = false; + if (interrupted && (vars.snap || vars.bounds)) { + animate(vars.inertia || vars.throwProps); + } + _dispatchEvent(self2, "release", "onRelease"); + if ((!_isAndroid || originalEvent.type !== "touchmove") && originalEvent.type.indexOf("cancel") === -1) { + _dispatchEvent(self2, "click", "onClick"); + if (_getTime() - clickTime < 300) { + _dispatchEvent(self2, "doubleclick", "onDoubleClick"); + } + eventTarget = originalEvent.target || target; + clickTime = _getTime(); + syntheticClick = function syntheticClick2() { + if (clickTime !== clickDispatch && self2.enabled() && !self2.isPressed && !originalEvent.defaultPrevented) { + if (eventTarget.click) { + eventTarget.click(); + } else if (ownerDoc.createEvent) { + syntheticEvent = ownerDoc.createEvent("MouseEvents"); + syntheticEvent.initMouseEvent("click", true, true, _win, 1, self2.pointerEvent.screenX, self2.pointerEvent.screenY, self2.pointerX, self2.pointerY, false, false, false, false, 0, null); + eventTarget.dispatchEvent(syntheticEvent); + } + } + }; + if (!_isAndroid && !originalEvent.defaultPrevented) { + gsap$2.delayedCall(0.05, syntheticClick); + } + } + } else { + animate(vars.inertia || vars.throwProps); + if (!self2.allowEventDefault && originalEvent && (vars.dragClickables !== false || !isClickable.call(self2, originalEvent.target)) && wasDragging && (!allowNativeTouchScrolling || touchDragAxis && allowNativeTouchScrolling === touchDragAxis) && originalEvent.cancelable !== false) { + isPreventingDefault = true; + _preventDefault(originalEvent); + } else { + isPreventingDefault = false; + } + _dispatchEvent(self2, "release", "onRelease"); + } + isTweening2() && placeholderDelayedCall.duration(self2.tween.duration()); + wasDragging && _dispatchEvent(self2, "dragend", "onDragEnd"); + return true; + }, updateScroll = function updateScroll2(e) { + if (e && self2.isDragging && !scrollProxy) { + var parent = e.target || target.parentNode, deltaX = parent.scrollLeft - parent._gsScrollX, deltaY = parent.scrollTop - parent._gsScrollY; + if (deltaX || deltaY) { + if (matrix) { + startPointerX -= deltaX * matrix.a + deltaY * matrix.c; + startPointerY -= deltaY * matrix.d + deltaX * matrix.b; + } else { + startPointerX -= deltaX; + startPointerY -= deltaY; + } + parent._gsScrollX += deltaX; + parent._gsScrollY += deltaY; + setPointerPosition(self2.pointerX, self2.pointerY); + } + } + }, onClick = function onClick2(e) { + var time = _getTime(), recentlyClicked = time - clickTime < 100, recentlyDragged = time - dragEndTime < 50, alreadyDispatched = recentlyClicked && clickDispatch === clickTime, defaultPrevented = self2.pointerEvent && self2.pointerEvent.defaultPrevented, alreadyDispatchedTrusted = recentlyClicked && trustedClickDispatch === clickTime, trusted = e.isTrusted || e.isTrusted == null && recentlyClicked && alreadyDispatched; + if ((alreadyDispatched || recentlyDragged && self2.vars.suppressClickOnDrag !== false) && e.stopImmediatePropagation) { + e.stopImmediatePropagation(); + } + if (recentlyClicked && !(self2.pointerEvent && self2.pointerEvent.defaultPrevented) && (!alreadyDispatched || trusted && !alreadyDispatchedTrusted)) { + if (trusted && alreadyDispatched) { + trustedClickDispatch = clickTime; + } + clickDispatch = clickTime; + return; + } + if (self2.isPressed || recentlyDragged || recentlyClicked) { + if (!trusted || !e.detail || !recentlyClicked || defaultPrevented) { + _preventDefault(e); + } + } + if (!recentlyClicked && !recentlyDragged && !dragged) { + e && e.target && (self2.pointerEvent = e); + _dispatchEvent(self2, "click", "onClick"); + } + }, localizePoint = function localizePoint2(p) { + return matrix ? { + x: p.x * matrix.a + p.y * matrix.c + matrix.e, + y: p.x * matrix.b + p.y * matrix.d + matrix.f + } : { + x: p.x, + y: p.y + }; + }; + old = Draggable2.get(target); + old && old.kill(); + _this2.startDrag = function(event, align) { + var r1, r2, p1, p2; + onPress(event || self2.pointerEvent, true); + if (align && !self2.hitTest(event || self2.pointerEvent)) { + r1 = _parseRect(event || self2.pointerEvent); + r2 = _parseRect(target); + p1 = localizePoint({ + x: r1.left + r1.width / 2, + y: r1.top + r1.height / 2 + }); + p2 = localizePoint({ + x: r2.left + r2.width / 2, + y: r2.top + r2.height / 2 + }); + startPointerX -= p1.x - p2.x; + startPointerY -= p1.y - p2.y; + } + if (!self2.isDragging) { + self2.isDragging = dragged = true; + _dispatchEvent(self2, "dragstart", "onDragStart"); + } + }; + _this2.drag = onMove; + _this2.endDrag = function(e) { + return onRelease(e || self2.pointerEvent, true); + }; + _this2.timeSinceDrag = function() { + return self2.isDragging ? 0 : (_getTime() - dragEndTime) / 1e3; + }; + _this2.timeSinceClick = function() { + return (_getTime() - clickTime) / 1e3; + }; + _this2.hitTest = function(target2, threshold) { + return Draggable2.hitTest(self2.target, target2, threshold); + }; + _this2.getDirection = function(from, diagonalThreshold) { + var mode = from === "velocity" && InertiaPlugin ? from : _isObject2(from) && !rotationMode ? "element" : "start", xChange, yChange, ratio, direction, r1, r2; + if (mode === "element") { + r1 = _parseRect(self2.target); + r2 = _parseRect(from); + } + xChange = mode === "start" ? self2.x - startElementX : mode === "velocity" ? InertiaPlugin.getVelocity(target, xProp) : r1.left + r1.width / 2 - (r2.left + r2.width / 2); + if (rotationMode) { + return xChange < 0 ? "counter-clockwise" : "clockwise"; + } else { + diagonalThreshold = diagonalThreshold || 2; + yChange = mode === "start" ? self2.y - startElementY : mode === "velocity" ? InertiaPlugin.getVelocity(target, yProp) : r1.top + r1.height / 2 - (r2.top + r2.height / 2); + ratio = Math.abs(xChange / yChange); + direction = ratio < 1 / diagonalThreshold ? "" : xChange < 0 ? "left" : "right"; + if (ratio < diagonalThreshold) { + if (direction !== "") { + direction += "-"; + } + direction += yChange < 0 ? "up" : "down"; + } + } + return direction; + }; + _this2.applyBounds = function(newBounds, sticky) { + var x, y, forceZeroVelocity, e, parent, isRoot; + if (newBounds && vars.bounds !== newBounds) { + vars.bounds = newBounds; + return self2.update(true, sticky); + } + syncXY(true); + calculateBounds(); + if (hasBounds && !isTweening2()) { + x = self2.x; + y = self2.y; + if (x > maxX) { + x = maxX; + } else if (x < minX) { + x = minX; + } + if (y > maxY) { + y = maxY; + } else if (y < minY) { + y = minY; + } + if (self2.x !== x || self2.y !== y) { + forceZeroVelocity = true; + self2.x = self2.endX = x; + if (rotationMode) { + self2.endRotation = x; + } else { + self2.y = self2.endY = y; + } + dirty = true; + render5(true); + if (self2.autoScroll && !self2.isDragging) { + _recordMaxScrolls(target.parentNode); + e = target; + _windowProxy.scrollTop = _win.pageYOffset != null ? _win.pageYOffset : ownerDoc.documentElement.scrollTop != null ? ownerDoc.documentElement.scrollTop : ownerDoc.body.scrollTop; + _windowProxy.scrollLeft = _win.pageXOffset != null ? _win.pageXOffset : ownerDoc.documentElement.scrollLeft != null ? ownerDoc.documentElement.scrollLeft : ownerDoc.body.scrollLeft; + while (e && !isRoot) { + isRoot = _isRoot(e.parentNode); + parent = isRoot ? _windowProxy : e.parentNode; + if (allowY && parent.scrollTop > parent._gsMaxScrollY) { + parent.scrollTop = parent._gsMaxScrollY; + } + if (allowX && parent.scrollLeft > parent._gsMaxScrollX) { + parent.scrollLeft = parent._gsMaxScrollX; + } + e = parent; + } + } + } + if (self2.isThrowing && (forceZeroVelocity || self2.endX > maxX || self2.endX < minX || self2.endY > maxY || self2.endY < minY)) { + animate(vars.inertia || vars.throwProps, forceZeroVelocity); + } + } + return self2; + }; + _this2.update = function(applyBounds, sticky, ignoreExternalChanges) { + if (sticky && self2.isPressed) { + var m = getGlobalMatrix(target), p = innerMatrix.apply({ + x: self2.x - startElementX, + y: self2.y - startElementY + }), m2 = getGlobalMatrix(target.parentNode, true); + m2.apply({ + x: m.e - p.x, + y: m.f - p.y + }, p); + self2.x -= p.x - m2.e; + self2.y -= p.y - m2.f; + render5(true); + recordStartPositions(); + } + var x = self2.x, y = self2.y; + updateMatrix(!sticky); + if (applyBounds) { + self2.applyBounds(); + } else { + dirty && ignoreExternalChanges && render5(true); + syncXY(true); + } + if (sticky) { + setPointerPosition(self2.pointerX, self2.pointerY); + dirty && render5(true); + } + if (self2.isPressed && !sticky && (allowX && Math.abs(x - self2.x) > 0.01 || allowY && Math.abs(y - self2.y) > 0.01 && !rotationMode)) { + recordStartPositions(); + } + if (self2.autoScroll) { + _recordMaxScrolls(target.parentNode, self2.isDragging); + checkAutoScrollBounds = self2.isDragging; + render5(true); + _removeScrollListener(target, updateScroll); + _addScrollListener(target, updateScroll); + } + return self2; + }; + _this2.enable = function(type2) { + var setVars = { + lazy: true + }, id, i, trigger; + if (vars.cursor !== false) { + setVars.cursor = vars.cursor || _defaultCursor; + } + if (gsap$2.utils.checkPrefix("touchCallout")) { + setVars.touchCallout = "none"; + } + if (type2 !== "soft") { + _setTouchActionForAllDescendants(triggers, allowX === allowY ? "none" : vars.allowNativeTouchScrolling && target.scrollHeight === target.clientHeight === (target.scrollWidth === target.clientHeight) || vars.allowEventDefault ? "manipulation" : allowX ? "pan-y" : "pan-x"); + i = triggers.length; + while (--i > -1) { + trigger = triggers[i]; + _supportsPointer || _addListener2(trigger, "mousedown", onPress); + _addListener2(trigger, "touchstart", onPress); + _addListener2(trigger, "click", onClick, true); + gsap$2.set(trigger, setVars); + if (trigger.getBBox && trigger.ownerSVGElement && allowX !== allowY) { + gsap$2.set(trigger.ownerSVGElement, { + touchAction: vars.allowNativeTouchScrolling || vars.allowEventDefault ? "manipulation" : allowX ? "pan-y" : "pan-x" + }); + } + vars.allowContextMenu || _addListener2(trigger, "contextmenu", onContextMenu); + } + _setSelectable(triggers, false); + } + _addScrollListener(target, updateScroll); + enabled = true; + if (InertiaPlugin && type2 !== "soft") { + InertiaPlugin.track(scrollProxy || target, xyMode ? "x,y" : rotationMode ? "rotation" : "top,left"); + } + target._gsDragID = id = "d" + _lookupCount++; + _lookup[id] = self2; + if (scrollProxy) { + scrollProxy.enable(); + scrollProxy.element._gsDragID = id; + } + (vars.bounds || rotationMode) && recordStartPositions(); + vars.bounds && self2.applyBounds(); + return self2; + }; + _this2.disable = function(type2) { + var dragging = self2.isDragging, i = triggers.length, trigger; + while (--i > -1) { + _setStyle(triggers[i], "cursor", null); + } + if (type2 !== "soft") { + _setTouchActionForAllDescendants(triggers, null); + i = triggers.length; + while (--i > -1) { + trigger = triggers[i]; + _setStyle(trigger, "touchCallout", null); + _removeListener2(trigger, "mousedown", onPress); + _removeListener2(trigger, "touchstart", onPress); + _removeListener2(trigger, "click", onClick, true); + _removeListener2(trigger, "contextmenu", onContextMenu); + } + _setSelectable(triggers, true); + if (touchEventTarget) { + _removeListener2(touchEventTarget, "touchcancel", onRelease); + _removeListener2(touchEventTarget, "touchend", onRelease); + _removeListener2(touchEventTarget, "touchmove", onMove); + } + _removeListener2(ownerDoc, "mouseup", onRelease); + _removeListener2(ownerDoc, "mousemove", onMove); + } + _removeScrollListener(target, updateScroll); + enabled = false; + if (InertiaPlugin && type2 !== "soft") { + InertiaPlugin.untrack(scrollProxy || target, xyMode ? "x,y" : rotationMode ? "rotation" : "top,left"); + self2.tween && self2.tween.kill(); + } + scrollProxy && scrollProxy.disable(); + _removeFromRenderQueue(render5); + self2.isDragging = self2.isPressed = isClicking = false; + dragging && _dispatchEvent(self2, "dragend", "onDragEnd"); + return self2; + }; + _this2.enabled = function(value, type2) { + return arguments.length ? value ? self2.enable(type2) : self2.disable(type2) : enabled; + }; + _this2.kill = function() { + self2.isThrowing = false; + self2.tween && self2.tween.kill(); + self2.disable(); + gsap$2.set(triggers, { + clearProps: "userSelect" + }); + delete _lookup[target._gsDragID]; + return self2; + }; + _this2.revert = function() { + this.kill(); + this.styles && this.styles.revert(); + }; + if (~type.indexOf("scroll")) { + scrollProxy = _this2.scrollProxy = new ScrollProxy(target, _extend({ + onKill: function onKill() { + self2.isPressed && onRelease(null); + } + }, vars)); + target.style.overflowY = allowY && !_isTouchDevice ? "auto" : "hidden"; + target.style.overflowX = allowX && !_isTouchDevice ? "auto" : "hidden"; + target = scrollProxy.content; + } + if (rotationMode) { + killProps.rotation = 1; + } else { + if (allowX) { + killProps[xProp] = 1; + } + if (allowY) { + killProps[yProp] = 1; + } + } + gsCache.force3D = "force3D" in vars ? vars.force3D : true; + _context(_assertThisInitialized(_this2)); + _this2.enable(); + return _this2; + } + Draggable2.register = function register2(core) { + gsap$2 = core; + _initCore4(); + }; + Draggable2.create = function create(targets, vars) { + _coreInitted || _initCore4(true); + return _toArray$1(targets).map(function(target) { + return new Draggable2(target, vars); + }); + }; + Draggable2.get = function get2(target) { + return _lookup[(_toArray$1(target)[0] || {})._gsDragID]; + }; + Draggable2.timeSinceDrag = function timeSinceDrag() { + return (_getTime() - _lastDragTime) / 1e3; + }; + Draggable2.hitTest = function hitTest(obj1, obj2, threshold) { + if (obj1 === obj2) { + return false; + } + var r1 = _parseRect(obj1), r2 = _parseRect(obj2), top = r1.top, left = r1.left, right = r1.right, bottom = r1.bottom, width = r1.width, height = r1.height, isOutside = r2.left > right || r2.right < left || r2.top > bottom || r2.bottom < top, overlap, area, isRatio; + if (isOutside || !threshold) { + return !isOutside; + } + isRatio = (threshold + "").indexOf("%") !== -1; + threshold = parseFloat(threshold) || 0; + overlap = { + left: Math.max(left, r2.left), + top: Math.max(top, r2.top) + }; + overlap.width = Math.min(right, r2.right) - overlap.left; + overlap.height = Math.min(bottom, r2.bottom) - overlap.top; + if (overlap.width < 0 || overlap.height < 0) { + return false; + } + if (isRatio) { + threshold *= 0.01; + area = overlap.width * overlap.height; + return area >= width * height * threshold || area >= r2.width * r2.height * threshold; + } + return overlap.width > threshold && overlap.height > threshold; + }; + return Draggable2; +}(EventDispatcher); +_setDefaults2(Draggable.prototype, { + pointerX: 0, + pointerY: 0, + startX: 0, + startY: 0, + deltaX: 0, + deltaY: 0, + isDragging: false, + isPressed: false +}); +Draggable.zIndex = 1e3; +Draggable.version = "3.12.5"; +_getGSAP$2() && gsap$2.registerPlugin(Draggable); +/*! + * MotionPathPlugin 3.12.5 + * https://gsap.com + * + * @license Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _xProps = "x,translateX,left,marginLeft,xPercent".split(","), _yProps = "y,translateY,top,marginTop,yPercent".split(","), _DEG2RAD = Math.PI / 180, gsap$1, PropTween, _getUnit, _toArray, _getStyleSaver2, _reverting, _getGSAP$1 = function _getGSAP4() { + return gsap$1 || typeof window !== "undefined" && (gsap$1 = window.gsap) && gsap$1.registerPlugin && gsap$1; +}, _populateSegmentFromArray = function _populateSegmentFromArray2(segment, values, property, mode) { + var l = values.length, si = mode === 2 ? 0 : mode, i = 0; + for (; i < l; i++) { + segment[si] = parseFloat(values[i][property]); + mode === 2 && (segment[si + 1] = 0); + si += 2; + } + return segment; +}, _getPropNum = function _getPropNum2(target, prop, unit) { + return parseFloat(target._gsap.get(target, prop, unit || "px")) || 0; +}, _relativize = function _relativize2(segment) { + var x = segment[0], y = segment[1], i; + for (i = 2; i < segment.length; i += 2) { + x = segment[i] += x; + y = segment[i + 1] += y; + } +}, _segmentToRawPath = function _segmentToRawPath2(plugin, segment, target, x, y, slicer, vars, unitX, unitY) { + if (vars.type === "cubic") { + segment = [segment]; + } else { + vars.fromCurrent !== false && segment.unshift(_getPropNum(target, x, unitX), y ? _getPropNum(target, y, unitY) : 0); + vars.relative && _relativize(segment); + var pointFunc = y ? pointsToSegment : flatPointsToSegment; + segment = [pointFunc(segment, vars.curviness)]; + } + segment = slicer(_align(segment, target, vars)); + _addDimensionalPropTween(plugin, target, x, segment, "x", unitX); + y && _addDimensionalPropTween(plugin, target, y, segment, "y", unitY); + return cacheRawPathMeasurements(segment, vars.resolution || (vars.curviness === 0 ? 20 : 12)); +}, _emptyFunc3 = function _emptyFunc4(v) { + return v; +}, _numExp = /[-+\.]*\d+\.?(?:e-|e\+)?\d*/g, _originToPoint = function _originToPoint2(element, origin, parentMatrix) { + var m = getGlobalMatrix(element), x = 0, y = 0, svg; + if ((element.tagName + "").toLowerCase() === "svg") { + svg = element.viewBox.baseVal; + svg.width || (svg = { + width: +element.getAttribute("width"), + height: +element.getAttribute("height") + }); + } else { + svg = origin && element.getBBox && element.getBBox(); + } + if (origin && origin !== "auto") { + x = origin.push ? origin[0] * (svg ? svg.width : element.offsetWidth || 0) : origin.x; + y = origin.push ? origin[1] * (svg ? svg.height : element.offsetHeight || 0) : origin.y; + } + return parentMatrix.apply(x || y ? m.apply({ + x, + y + }) : { + x: m.e, + y: m.f + }); +}, _getAlignMatrix = function _getAlignMatrix2(fromElement, toElement, fromOrigin, toOrigin) { + var parentMatrix = getGlobalMatrix(fromElement.parentNode, true, true), m = parentMatrix.clone().multiply(getGlobalMatrix(toElement)), fromPoint = _originToPoint(fromElement, fromOrigin, parentMatrix), _originToPoint22 = _originToPoint(toElement, toOrigin, parentMatrix), x = _originToPoint22.x, y = _originToPoint22.y, p; + m.e = m.f = 0; + if (toOrigin === "auto" && toElement.getTotalLength && toElement.tagName.toLowerCase() === "path") { + p = toElement.getAttribute("d").match(_numExp) || []; + p = m.apply({ + x: +p[0], + y: +p[1] + }); + x += p.x; + y += p.y; + } + if (p) { + p = m.apply(toElement.getBBox()); + x -= p.x; + y -= p.y; + } + m.e = x - fromPoint.x; + m.f = y - fromPoint.y; + return m; +}, _align = function _align2(rawPath, target, _ref) { + var align = _ref.align, matrix = _ref.matrix, offsetX = _ref.offsetX, offsetY = _ref.offsetY, alignOrigin = _ref.alignOrigin; + var x = rawPath[0][0], y = rawPath[0][1], curX = _getPropNum(target, "x"), curY = _getPropNum(target, "y"), alignTarget, m, p; + if (!rawPath || !rawPath.length) { + return getRawPath("M0,0L0,0"); + } + if (align) { + if (align === "self" || (alignTarget = _toArray(align)[0] || target) === target) { + transformRawPath(rawPath, 1, 0, 0, 1, curX - x, curY - y); + } else { + if (alignOrigin && alignOrigin[2] !== false) { + gsap$1.set(target, { + transformOrigin: alignOrigin[0] * 100 + "% " + alignOrigin[1] * 100 + "%" + }); + } else { + alignOrigin = [_getPropNum(target, "xPercent") / -100, _getPropNum(target, "yPercent") / -100]; + } + m = _getAlignMatrix(target, alignTarget, alignOrigin, "auto"); + p = m.apply({ + x, + y + }); + transformRawPath(rawPath, m.a, m.b, m.c, m.d, curX + m.e - (p.x - m.e), curY + m.f - (p.y - m.f)); + } + } + if (matrix) { + transformRawPath(rawPath, matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f); + } else if (offsetX || offsetY) { + transformRawPath(rawPath, 1, 0, 0, 1, offsetX || 0, offsetY || 0); + } + return rawPath; +}, _addDimensionalPropTween = function _addDimensionalPropTween2(plugin, target, property, rawPath, pathProperty, forceUnit) { + var cache = target._gsap, harness = cache.harness, alias = harness && harness.aliases && harness.aliases[property], prop = alias && alias.indexOf(",") < 0 ? alias : property, pt = plugin._pt = new PropTween(plugin._pt, target, prop, 0, 0, _emptyFunc3, 0, cache.set(target, prop, plugin)); + pt.u = _getUnit(cache.get(target, prop, forceUnit)) || 0; + pt.path = rawPath; + pt.pp = pathProperty; + plugin._props.push(prop); +}, _sliceModifier = function _sliceModifier2(start, end) { + return function(rawPath) { + return start || end !== 1 ? sliceRawPath(rawPath, start, end) : rawPath; + }; +}; +var MotionPathPlugin = { + version: "3.12.5", + name: "motionPath", + register: function register(core, Plugin, propTween) { + gsap$1 = core; + _getUnit = gsap$1.utils.getUnit; + _toArray = gsap$1.utils.toArray; + _getStyleSaver2 = gsap$1.core.getStyleSaver; + _reverting = gsap$1.core.reverting || function() { + }; + PropTween = propTween; + }, + init: function init4(target, vars, tween) { + if (!gsap$1) { + console.warn("Please gsap.registerPlugin(MotionPathPlugin)"); + return false; + } + if (!(typeof vars === "object" && !vars.style) || !vars.path) { + vars = { + path: vars + }; + } + var rawPaths = [], _vars = vars, path = _vars.path, autoRotate = _vars.autoRotate, unitX = _vars.unitX, unitY = _vars.unitY, x = _vars.x, y = _vars.y, firstObj = path[0], slicer = _sliceModifier(vars.start, "end" in vars ? vars.end : 1), rawPath, p; + this.rawPaths = rawPaths; + this.target = target; + this.tween = tween; + this.styles = _getStyleSaver2 && _getStyleSaver2(target, "transform"); + if (this.rotate = autoRotate || autoRotate === 0) { + this.rOffset = parseFloat(autoRotate) || 0; + this.radians = !!vars.useRadians; + this.rProp = vars.rotation || "rotation"; + this.rSet = target._gsap.set(target, this.rProp, this); + this.ru = _getUnit(target._gsap.get(target, this.rProp)) || 0; + } + if (Array.isArray(path) && !("closed" in path) && typeof firstObj !== "number") { + for (p in firstObj) { + if (!x && ~_xProps.indexOf(p)) { + x = p; + } else if (!y && ~_yProps.indexOf(p)) { + y = p; + } + } + if (x && y) { + rawPaths.push(_segmentToRawPath(this, _populateSegmentFromArray(_populateSegmentFromArray([], path, x, 0), path, y, 1), target, x, y, slicer, vars, unitX || _getUnit(path[0][x]), unitY || _getUnit(path[0][y]))); + } else { + x = y = 0; + } + for (p in firstObj) { + p !== x && p !== y && rawPaths.push(_segmentToRawPath(this, _populateSegmentFromArray([], path, p, 2), target, p, 0, slicer, vars, _getUnit(path[0][p]))); + } + } else { + rawPath = slicer(_align(getRawPath(vars.path), target, vars)); + cacheRawPathMeasurements(rawPath, vars.resolution); + rawPaths.push(rawPath); + _addDimensionalPropTween(this, target, vars.x || "x", rawPath, "x", vars.unitX || "px"); + _addDimensionalPropTween(this, target, vars.y || "y", rawPath, "y", vars.unitY || "px"); + } + }, + render: function render3(ratio, data) { + var rawPaths = data.rawPaths, i = rawPaths.length, pt = data._pt; + if (data.tween._time || !_reverting()) { + if (ratio > 1) { + ratio = 1; + } else if (ratio < 0) { + ratio = 0; + } + while (i--) { + getPositionOnPath(rawPaths[i], ratio, !i && data.rotate, rawPaths[i]); + } + while (pt) { + pt.set(pt.t, pt.p, pt.path[pt.pp] + pt.u, pt.d, ratio); + pt = pt._next; + } + data.rotate && data.rSet(data.target, data.rProp, rawPaths[0].angle * (data.radians ? _DEG2RAD : 1) + data.rOffset + data.ru, data, ratio); + } else { + data.styles.revert(); + } + }, + getLength: function getLength(path) { + return cacheRawPathMeasurements(getRawPath(path)).totalLength; + }, + sliceRawPath, + getRawPath, + pointsToSegment, + stringToRawPath, + rawPathToString, + transformRawPath, + getGlobalMatrix, + getPositionOnPath, + cacheRawPathMeasurements, + convertToPath: function convertToPath$1(targets, swap) { + return _toArray(targets).map(function(target) { + return convertToPath(target, swap !== false); + }); + }, + convertCoordinates: function convertCoordinates(fromElement, toElement, point) { + var m = getGlobalMatrix(toElement, true, true).multiply(getGlobalMatrix(fromElement)); + return point ? m.apply(point) : m; + }, + getAlignMatrix: _getAlignMatrix, + getRelativePosition: function getRelativePosition(fromElement, toElement, fromOrigin, toOrigin) { + var m = _getAlignMatrix(fromElement, toElement, fromOrigin, toOrigin); + return { + x: m.e, + y: m.f + }; + }, + arrayToRawPath: function arrayToRawPath(value, vars) { + vars = vars || {}; + var segment = _populateSegmentFromArray(_populateSegmentFromArray([], value, vars.x || "x", 0), value, vars.y || "y", 1); + vars.relative && _relativize(segment); + return [vars.type === "cubic" ? segment : pointsToSegment(segment, vars.curviness)]; + } +}; +_getGSAP$1() && gsap$1.registerPlugin(MotionPathPlugin); +/*! + * strings: 3.12.5 + * https://gsap.com + * + * Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var _trimExp = /(?:^\s+|\s+$)/g; +var emojiExp = /([\uD800-\uDBFF][\uDC00-\uDFFF](?:[\u200D\uFE0F][\uD800-\uDBFF][\uDC00-\uDFFF]){2,}|\uD83D\uDC69(?:\u200D(?:(?:\uD83D\uDC69\u200D)?\uD83D\uDC67|(?:\uD83D\uDC69\u200D)?\uD83D\uDC66)|\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC69\u200D(?:\uD83D\uDC69\u200D)?\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D(?:\uD83D\uDC69\u200D)?\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]\uFE0F|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC6F\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3C-\uDD3E\uDDD6-\uDDDF])\u200D[\u2640\u2642]\uFE0F|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uFE0F\u200D[\u2640\u2642]|(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642])\uFE0F|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC69\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708]))\uFE0F|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83D\uDC69\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69]))|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67)\uDB40\uDC7F|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC66\u200D\uD83D\uDC66|(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]))|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|\uD83D\uDC68(?:\u200D(?:(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC67|(?:(?:\uD83D[\uDC68\uDC69])\u200D)?\uD83D\uDC66)|\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDD1-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])?|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF8]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD4C\uDD50-\uDD6B\uDD80-\uDD97\uDDC0\uDDD0-\uDDE6])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u2660\u2663\u2665\u2666\u2668\u267B\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF8]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD4C\uDD50-\uDD6B\uDD80-\uDD97\uDDC0\uDDD0-\uDDE6])\uFE0F)/; +function getText(e) { + var type = e.nodeType, result = ""; + if (type === 1 || type === 9 || type === 11) { + if (typeof e.textContent === "string") { + return e.textContent; + } else { + for (e = e.firstChild; e; e = e.nextSibling) { + result += getText(e); + } + } + } else if (type === 3 || type === 4) { + return e.nodeValue; + } + return result; +} +function splitInnerHTML(element, delimiter, trim, preserveSpaces) { + var node = element.firstChild, result = [], s; + while (node) { + if (node.nodeType === 3) { + s = (node.nodeValue + "").replace(/^\n+/g, ""); + if (!preserveSpaces) { + s = s.replace(/\s+/g, " "); + } + result.push.apply(result, emojiSafeSplit(s, delimiter, trim, preserveSpaces)); + } else if ((node.nodeName + "").toLowerCase() === "br") { + result[result.length - 1] += "
"; + } else { + result.push(node.outerHTML); + } + node = node.nextSibling; + } + s = result.length; + while (s--) { + result[s] === "&" && result.splice(s, 1, "&"); + } + return result; +} +function emojiSafeSplit(text, delimiter, trim, preserveSpaces) { + text += ""; + trim && (text = text.trim ? text.trim() : text.replace(_trimExp, "")); + if (delimiter && delimiter !== "") { + return text.replace(/>/g, ">").replace(/= 55296 && character.charCodeAt(0) <= 56319 || text.charCodeAt(i + 1) >= 65024 && text.charCodeAt(i + 1) <= 65039) { + j = ((text.substr(i, 12).split(emojiExp) || [])[1] || "").length || 2; + character = text.substr(i, j); + result.emoji = 1; + i += j - 1; + } + result.push(character === ">" ? ">" : character === "<" ? "<" : preserveSpaces && character === " " && (text.charAt(i - 1) === " " || text.charAt(i + 1) === " ") ? " " : character); + } + return result; +} +/*! + * TextPlugin 3.12.5 + * https://gsap.com + * + * @license Copyright 2008-2024, GreenSock. All rights reserved. + * Subject to the terms at https://gsap.com/standard-license or for + * Club GSAP members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ +var gsap, _tempDiv, _getGSAP5 = function _getGSAP6() { + return gsap || typeof window !== "undefined" && (gsap = window.gsap) && gsap.registerPlugin && gsap; +}; +var TextPlugin = { + version: "3.12.5", + name: "text", + init: function init5(target, value, tween) { + typeof value !== "object" && (value = { + value + }); + var i = target.nodeName.toUpperCase(), data = this, _value = value, newClass = _value.newClass, oldClass = _value.oldClass, preserveSpaces = _value.preserveSpaces, rtl = _value.rtl, delimiter = data.delimiter = value.delimiter || "", fillChar = data.fillChar = value.fillChar || (value.padSpace ? " " : ""), _short, text, original, j, condensedText, condensedOriginal, aggregate, s; + data.svg = target.getBBox && (i === "TEXT" || i === "TSPAN"); + if (!("innerHTML" in target) && !data.svg) { + return false; + } + data.target = target; + if (!("value" in value)) { + data.text = data.original = [""]; + return; + } + original = splitInnerHTML(target, delimiter, false, preserveSpaces); + _tempDiv || (_tempDiv = document.createElement("div")); + _tempDiv.innerHTML = value.value; + text = splitInnerHTML(_tempDiv, delimiter, false, preserveSpaces); + data.from = tween._from; + if ((data.from || rtl) && !(rtl && data.from)) { + i = original; + original = text; + text = i; + } + data.hasClass = !!(newClass || oldClass); + data.newClass = rtl ? oldClass : newClass; + data.oldClass = rtl ? newClass : oldClass; + i = original.length - text.length; + _short = i < 0 ? original : text; + if (i < 0) { + i = -i; + } + while (--i > -1) { + _short.push(fillChar); + } + if (value.type === "diff") { + j = 0; + condensedText = []; + condensedOriginal = []; + aggregate = ""; + for (i = 0; i < text.length; i++) { + s = text[i]; + if (s === original[i]) { + aggregate += s; + } else { + condensedText[j] = aggregate + s; + condensedOriginal[j++] = aggregate + original[i]; + aggregate = ""; + } + } + text = condensedText; + original = condensedOriginal; + if (aggregate) { + text.push(aggregate); + original.push(aggregate); + } + } + value.speed && tween.duration(Math.min(0.05 / value.speed * _short.length, value.maxDuration || 9999)); + data.rtl = rtl; + data.original = original; + data.text = text; + data._props.push("text"); + }, + render: function render4(ratio, data) { + if (ratio > 1) { + ratio = 1; + } else if (ratio < 0) { + ratio = 0; + } + if (data.from) { + ratio = 1 - ratio; + } + var text = data.text, hasClass = data.hasClass, newClass = data.newClass, oldClass = data.oldClass, delimiter = data.delimiter, target = data.target, fillChar = data.fillChar, original = data.original, rtl = data.rtl, l = text.length, i = (rtl ? 1 - ratio : ratio) * l + 0.5 | 0, applyNew, applyOld, str; + if (hasClass && ratio) { + applyNew = newClass && i; + applyOld = oldClass && i !== l; + str = (applyNew ? "" : "") + text.slice(0, i).join(delimiter) + (applyNew ? "" : "") + (applyOld ? "" : "") + delimiter + original.slice(i).join(delimiter) + (applyOld ? "" : ""); + } else { + str = text.slice(0, i).join(delimiter) + delimiter + original.slice(i).join(delimiter); + } + if (data.svg) { + target.textContent = str; + } else { + target.innerHTML = fillChar === " " && ~str.indexOf(" ") ? str.split(" ").join("  ") : str; + } + } +}; +TextPlugin.splitInnerHTML = splitInnerHTML; +TextPlugin.emojiSafeSplit = emojiSafeSplit; +TextPlugin.getText = getText; +_getGSAP5() && gsap.registerPlugin(TextPlugin); +gsapWithCSS.registerPlugin(MotionPathPlugin); +const _noCapWords = "a|above|after|an|and|at|below|but|by|down|for|for|from|in|nor|of|off|on|onto|or|out|so|the|to|under|up|with|yet".split("|").map((word) => new RegExp(`\\b${word}\\b`, "gui")); +const _capWords = [ + "I", + /[^a-z]{3,}|[.0-9]/gu +].map((word) => /RegExp/.test(Object.prototype.toString.call(word)) ? word : new RegExp(`\\b${word}\\b`, "gui")); +const _loremIpsumText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse ultricies +nibh sed massa euismod lacinia. Aliquam nec est ac nunc ultricies scelerisque porta vulputate odio. +Integer gravida mattis odio, semper volutpat tellus. Ut elit leo, auctor eget fermentum hendrerit, +aliquet ac nunc. Suspendisse porta turpis vitae mi posuere molestie. Cras lectus lacus, vulputate a +vestibulum in, mattis vel mi. Mauris quis semper mauris. Praesent blandit nec diam eget tincidunt. Nunc +aliquet consequat massa ac lacinia. Ut posuere velit sagittis, vehicula nisl eget, fringilla nibh. Duis +volutpat mattis libero, a porttitor sapien viverra ut. Phasellus vulputate imperdiet ligula, eget +eleifend metus tempor nec. Nam eget sapien risus. Praesent id suscipit elit. Sed pellentesque ligula +diam, non aliquet magna feugiat vitae. Pellentesque ut tortor id erat placerat dignissim. Pellentesque +ut dui vel leo laoreet sodales nec ac tellus. In hac habitasse platea dictumst. Proin sed ex sed augue +sollicitudin interdum. Sed id lacus porttitor nisi vestibulum tincidunt. Nulla facilisi. Vestibulum +feugiat finibus magna in pretium. Proin consectetur lectus nisi, non commodo lectus tempor et. Cras +viverra, mi in consequat aliquet, justo mauris fringilla tellus, at accumsan magna metus in eros. Sed +vehicula, diam ut sagittis semper, purus massa mattis dolor, in posuere.`; +const _randomWords = ` +aboveboard|account|achiever|acoustics|act|action|activity|actor|addition|adjustment|advertisement|advice|afterglow|afterimage|afterlife|aftermath|afternoon|afterthought|agreement +air|aircraft|airfield|airlift|airline|airmen|airplane|airport|airtime|alarm|allover|allspice|alongside|also|amount|amusement|anger|angle|animal|another|ants|anyhow|anymore +anyone|anyplace|anytime|anywhere|apparatus|apparel|appliance|approval|arch|argument|arithmetic|arm|army|around|art|ashtray|attack|attraction|aunt|authority|babies|baby|babysitter +back|backache|backbone|backbreaker|backdrop|backfire|background|backhand|backlash|backlog|backpack|backside|backslap|backslide|backspace|backspin|backstroke|backtrack|backward +badge|bag|bait|balance|ball|ballroom|bankbook|bankroll|base|baseball|basin|basket|basketball|bat|bath|battle|beachcomb|bead|bear|because|become|bed|bedrock|bedroll|bedroom +beds|bee|beef|beginner|behavior|belief|believe|bell|bellboy|bellhop|bells|below|berry|bike|bikes|bird|birds|birth|birthday|bit|bite|blackball|blackberries|blackbird|blackboard +blackjack|blacklist|blackmail|blackout|blacksmith|blacktop|blade|blood|blow|blowgun|bluebell|blueberry|bluebird|bluefish|bluegrass|blueprint|board|boardwalk|boat|bodyguard +bomb|bone|book|bookcase|bookend|bookkeeper|bookmark|bookmobile|books|bookseller|bookshelf|bookworm|boot|border|bottle|boundary|bowlegs|bowtie|box|boy|brainchild|brake|branch +brass|breath|brick|bridge|brother|bubble|bucket|bugspray|building|bulb|burst|bushes|business|butter|butterball|buttercup|butterfingers|buttermilk|butternut|butterscotch|button +bypass|cabbage|cabdriver|cable|cactus|cake|cakes|calculator|calendar|camera|camp|can|cancan|candlelight|candlestick|cannon|cannot|canvas|cap|caption|car|card|cardsharp|care +carefree|careworn|carfare|carload|carpenter|carpool|carport|carriage|cars|carsick|cart|cartwheel|cast|cat|cats|cattle|catwalk|cause|cave|caveman|celery|cellar|cemetery|cent +centercut|chalk|chance|change|channel|cheese|cheeseburger|cherries|cherry|chess|chicken|chickens|children|chin|church|circle|clam|class|clockwise|cloth|clover|club|coach|coal +coast|coat|cobweb|coffeemaker|coil|collar|color|comeback|committee|commonplace|commonwealth|company|comparison|competition|condition|connection|control|cook|copper|corn|cornmeal +cough|country|courthouse|cover|cow|cows|crack|cracker|crate|crayon|cream|creator|creature|credit|crewcut|crib|crime|crook|crossbow|crossbreed|crosscut|crossover|crosswalk +crow|crowd|crown|cub|cup|current|curtain|curve|cushion|dad|dairymaid|daisywheel|daughter|day|daybed|daybook|daybreak|daydream|daylight|daytime|deadend|deadline|death|debt +decision|deer|degree|design|desire|desk|destruction|detail|development|digestion|dime|dinner|dinosaurs|direction|dirt|discovery|discussion|dishcloth|dishpan|dishwasher|dishwater +diskdrive|distance|distribution|division|dock|doctor|dog|dogs|doll|dolls|donkey|door|doorstop|downtown|downunder|drain|drawbridge|drawer|dress|drink|driveway|driving|drop +duck|duckbill|duckpin|ducks|dust|ear|earache|earring|earth|earthquake|earthward|earthworm|edge|education|effect|egg|egghead|eggnog|eggs|eggshell|elbow|end|engine|error|event +everything|example|exchange|existence|expansion|experience|expert|eye|eyeballs|eyecatching|eyeglasses|eyelash|eyelid|eyes|eyesight|eyewitness|face|fact|fairies|fall|fang|farm +fatherland|fear|feeling|field|finger|fire|fireball|fireboat|firebomb|firebreak|firecracker|firefighter|firehouse|fireman|fireproof|fireworks|fish|fishbowl|fisherman|fisheye +fishhook|fishmonger|fishnet|fishpond|fishtail|flag|flame|flavor|flesh|flight|flock|floor|flower|flowers|fly|fog|fold|food|foot|football|foothill|footlights|footlocker|footprints +forbearer|force|forearm|forebear|forebrain|forecast|foreclose|foreclosure|foredoom|forefather|forefeet|forefinger|forefoot|forego|foregone|forehand|forehead|foreknowledge +foreleg|foreman|forepaws|foresee|foreshadow|forestall|forethought|foretold|forever|forewarn|foreword|forget|fork|forklift|form|fowl|frame|friction|friend|friends|frog|frogs +front|fruit|fruitcup|fuel|furniture|gate|gearshift|geese|ghost|giants|giraffe|girl|girls|glass|glassmaking|glove|gold|goodbye|goodnight|government|governor|grade|grain|grandaunt +granddaughter|grandfather|grandmaster|grandmother|grandnephew|grandparent|grandson|grandstand|granduncle|grape|grass|grassland|graveyard|grip|ground|group|growth|guide|guitar +gumball|gun|hair|haircut|hall|hamburger|hammer|hand|handbook|handgun|handmade|handout|hands|harbor|harmony|hat|hate|head|headache|headlight|headline|headquarters|health|heat +hereafter|hereby|herein|hereupon|highchair|highland|highway|hill|himself|history|hobbies|hole|holiday|home|homemade|hometown|honey|honeybee|honeydew|honeysuckle|hook|hookup +hope|horn|horse|horseback|horsefly|horsehair|horseman|horseplay|horsepower|horseradish|horses|hose|hospital|hot|hour|house|houseboat|household|housekeeper|houses|housetop +however|humor|hydrant|ice|icicle|idea|impulse|income|increase|industry|ink|insect|inside|instrument|insurance|intake|interest|invention|iron|island|itself|jail|jailbait|jam +jar|jeans|jelly|jellybean|jellyfish|jetliner|jetport|jewel|join|judge|juice|jump|jumpshot|kettle|key|keyboard|keyhole|keynote|keypad|keypunch|keystone|keystroke|keyword|kick +kiss|kittens|kitty|knee|knife|knot|knowledge|laborer|lace|ladybug|lake|lamp|land|language|laugh|leather|leg|legs|letter|letters|lettuce|level|library|lifeblood|lifeguard|lifelike +lifeline|lifelong|lifetime|lifework|limelight|limestone|limit|line|linen|lip|liquid|loaf|lock|locket|longhand|look|loss|love|low|lukewarm|lumber|lunch|lunchroom|machine|magic +maid|mailbox|mainline|man|marble|mark|market|mask|mass|match|matchbox|meal|meantime|meanwhile|measure|meat|meeting|memory|men|metal|mice|middle|milk|mind|mine|minister|mint +minute|mist|mitten|mom|money|monkey|month|moon|moonbeam|moonlight|moonlit|moonscape|moonshine|moonstruck|moonwalk|moreover|morning|mother|motion|motorcycle|mountain|mouth +move|muscle|name|nation|nearby|neck|need|needle|nerve|nest|nevermore|newsboy|newsbreak|newscaster|newsdealer|newsletter|newsman|newspaper|newsprint|newsreel|newsroom|night +nightfall|nobody|noise|noisemaker|north|northeast|nose|note|notebook|nowhere|number|nursemaid|nut|nutcracker|oatmeal|observation|ocean|offer|office|oil|oneself|onetime|orange +oranges|order|oven|overboard|overcoat|overflow|overland|pacemaker|page|pail|pan|pancake|paper|parcel|part|partner|party|passbook|passenger|passkey|Passover|passport|payment +peace|pear|pen|pencil|peppermint|person|pest|pet|pets|pickle|pickup|picture|pie|pies|pig|pigs|pin|pinhole|pinstripe|pinup|pinwheel|pipe|pizzas|place|plane|planes|plant|plantation +plants|plastic|plate|play|playback|playground|playhouse|playthings|pleasure|plot|plough|pocket|point|poison|pollution|ponytail|popcorn|porter|position|postcard|pot|potato +powder|power|price|produce|profit|property|prose|protest|pull|pump|punishment|purpose|push|quarter|quartz|queen|question|quicksand|quiet|quill|quilt|quince|quiver|rabbit|rabbits +racquetball|rail|railroad|railway|rain|raincheck|raincoat|rainstorm|rainwater|rake|range|rat|rate|rattlesnake|rattletrap|ray|reaction|reading|reason|receipt|recess|record +regret|relation|religion|repairman|representative|request|respect|rest|reward|rhythm|rice|riddle|rifle|ring|rings|river|riverbanks|road|robin|rock|rod|roll|roof|room|root +rose|route|rub|rubberband|rule|run|sack|sail|sailboat|salesclerk|salt|sand|sandlot|sandstone|saucepan|scale|scapegoat|scarecrow|scarf|scene|scent|school|schoolbook|schoolboy +schoolbus|schoolhouse|science|scissors|screw|sea|seashore|seat|secretary|seed|selection|self|sense|servant|shade|shadyside|shake|shame|shape|sharecropper|sharpshooter|sheep +sheepskin|sheet|shelf|ship|shirt|shock|shoe|shoelace|shoemaker|shoes|shop|shortbread|show|showoff|showplace|side|sidekick|sidewalk|sign|silk|silver|silversmith|sink|sister +sisterhood|sisters|sixfold|size|skate|skateboard|skin|skintight|skirt|sky|skylark|skylight|slave|sleep|sleet|slip|slope|slowdown|slumlord|smash|smell|smile|smoke|snail|snails +snake|snakes|snakeskin|sneeze|snow|snowball|snowbank|snowbird|snowdrift|snowshovel|soap|society|sock|soda|sofa|softball|somebody|someday|somehow|someone|someplace|something +sometimes|somewhat|somewhere|son|song|songs|sort|sound|soundproof|soup|southeast|southwest|soybean|space|spacewalk|spade|spark|spearmint|spiders|spillway|spokesperson|sponge +spoon|spot|spring|spy|square|squirrel|stage|stagehand|stamp|standby|standoff|standout|standpoint|star|starfish|start|statement|station|steam|steamship|steel|stem|step|stepson +stew|stick|sticks|stitch|stocking|stockroom|stomach|stone|stop|stoplight|stopwatch|store|story|stove|stranger|straw|stream|street|stretch|string|stronghold|structure|substance +subway|sugar|suggestion|suit|summer|sun|sunbaked|sunbathe|sundial|sundown|sunfish|sunflower|sunglasses|sunlit|sunray|sunroof|sunup|supercargo|supercharge|supercool|superego +superfine|supergiant|superhero|superhighways|superhuman|superimpose|supermarket|supermen|supernatural|superpower|superscript|supersensitive|supersonic|superstar|superstrong +superstructure|supertanker|superweapon|superwoman|support|surprise|sweater|sweetheart|sweetmeat|swim|swing|system|table|tablecloth|tablespoon|tabletop|tableware|tail|tailcoat +tailgate|taillight|taillike|tailpiece|tailspin|takeoff|takeout|takeover|talebearer|taleteller|talk|tank|tapeworm|taproom|taproot|target|taskmaster|taste|tax|taxicab|taxpayer +teaching|teacup|team|teammate|teamwork|teapot|teaspoon|teenager|teeth|telltale|temper|tendency|tenderfoot|tenfold|tent|territory|test|textbook|texture|theory|therefore|thing +things|thought|thread|thrill|throat|throne|throwaway|throwback|thumb|thunder|thunderbird|thunderstorm|ticket|tiger|time|timekeeper|timesaving|timeshare|timetable|tin|title +toad|toe|toes|together|tomatoes|tongue|toolbox|tooth|toothbrush|toothpaste|toothpick|top|touch|touchdown|town|township|toy|toys|trade|trail|train|trains|tramp|transport|tray +treatment|tree|trees|trick|trip|trouble|trousers|truck|trucks|tub|turkey|turn|turnabout|turnaround|turnbuckle|turndown|turnkey|turnoff|turntable|twig|twist|typewriter|umbrella +uncle|underachieve|underage|underarm|underbelly|underbid|undercharge|underclothes|undercover|undercut|underdevelop|underestimate|underexpose|underfoot|underground|underwear +unit|upbeat|upbringing|upcoming|update|upend|upgrade|upheaval|uphill|uphold|upkeep|upland|uplift|upload|upmarket|upon|uppercase|upperclassman|uppercut|uproar|uproot|upset +upshot|upside|upstage|upstairs|upstanding|upstart|upstate|upstream|uptake|upthrust|uptight|uptime|uptown|upward|upwind|use|vacation|value|van|vase|vegetable|veil|vein|verse +vessel|vest|view|visitor|voice|volcano|volleyball|voyage|waistline|walk|walkways|wall|walleyed|wallpaper|war|wardroom|warfare|warmblooded|warpath|wash|washbowl|washcloth|washhouse +washout|washrag|washroom|washstand|washtub|waste|wastebasket|wasteland|wastepaper|wastewater|watch|watchband|watchdog|watchmaker|watchman|watchtower|watchword|water|watercolor +watercooler|watercraft|waterfall|waterfront|waterline|waterlog|watermelon|waterpower|waterproof|waterscape|watershed|waterside|waterspout|watertight|wave|wavelike|waves|wax +waxwork|way|waybill|wayfarer|waylaid|wayside|wayward|wealth|weather|weathercock|weatherman|weatherproof|week|weekday|weekend|weeknight|weight|whatever|whatsoever|wheel|wheelchair +wheelhouse|whip|whistle|whitecap|whitefish|whitewall|whitewash|widespread|wilderness|wind|window|wine|wing|winter|wipeout|wire|wish|without|woman|women|wood|woodshop|wool +word|work|worm|wound|wren|wrench|wrist|writer|writing|yak|yam|yard|yarn|year|yoke|zebra|zephyr|zinc|zipper|zoo +`.split("|"); +const _numberWords = { + ones: [ + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "ten", + "eleven", + "twelve", + "thirteen", + "fourteen", + "fifteen", + "sixteen", + "seventeen", + "eighteen", + "nineteen", + "twenty" + ], + tens: ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"], + tiers: ["", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion"], + bigPrefixes: ["", "un", "duo", "tre", "quattuor", "quin", "sex", "octo", "novem"], + bigSuffixes: ["", "decillion", "vigintillion", "trigintillion", "quadragintillion", "quinquagintillion", "sexagintillion", "septuagintillion", "octogintillion", "nonagintillion", "centillion"] +}; +const _ordinals = { + zero: "zeroeth", + one: "first", + two: "second", + three: "third", + four: "fourth", + five: "fifth", + eight: "eighth", + nine: "ninth", + twelve: "twelfth", + twenty: "twentieth", + thirty: "thirtieth", + forty: "fortieth", + fifty: "fiftieth", + sixty: "sixtieth", + seventy: "seventieth", + eighty: "eightieth", + ninety: "ninetieth" +}; +const _romanNumerals = { + grouped: [ + ["", "Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", "Ⅶ", "Ⅷ", "Ⅸ"], + ["", "Ⅹ", "ⅩⅩ", "ⅩⅩⅩ", "ⅩⅬ", "Ⅼ", "ⅬⅩ", "ⅬⅩⅩ", "ⅬⅩⅩⅩ", "ⅩⅭ"], + ["", "Ⅽ", "ⅭⅭ", "ⅭⅭⅭ", "ⅭⅮ", "Ⅾ", "ⅮⅭ", "ⅮⅭⅭ", "ⅮⅭⅭⅭ", "ⅭⅯ"], + ["", "Ⅿ", "ⅯⅯ", "ⅯⅯⅯ", "Ⅿↁ", "ↁ", "ↁⅯ", "ↁⅯⅯ", "ↁⅯⅯⅯ", "ↁↂ"], + ["", "ↂ", "ↂↂ", "ↂↂↂ", "ↂↇ", "ↇ", "ↇↂ", "ↇↂↂ", "ↇↂↂↂ", "ↇↈ"], + ["", "ↈ", "ↈↈ", "ↈↈↈ"] + ], + ungrouped: [ + ["", "Ⅰ", "ⅠⅠ", "ⅠⅠⅠ", "ⅠⅤ", "Ⅴ", "ⅤⅠ", "ⅤⅠⅠ", "ⅤⅠⅠⅠ", "ⅠⅩ"], + ["", "Ⅹ", "ⅩⅩ", "ⅩⅩⅩ", "ⅩⅬ", "Ⅼ", "ⅬⅩ", "ⅬⅩⅩ", "ⅬⅩⅩⅩ", "ⅩⅭ"], + ["", "Ⅽ", "ⅭⅭ", "ⅭⅭⅭ", "ⅭⅮ", "Ⅾ", "ⅮⅭ", "ⅮⅭⅭ", "ⅮⅭⅭⅭ", "ⅭⅯ"], + ["", "Ⅿ", "ⅯⅯ", "ⅯⅯⅯ", "Ⅿↁ", "ↁ", "ↁⅯ", "ↁⅯⅯ", "ↁⅯⅯⅯ", "ↁↂ"], + ["", "ↂ", "ↂↂ", "ↂↂↂ", "ↂↇ", "ↇ", "ↇↂ", "ↇↂↂ", "ↇↂↂↂ", "ↇↈ"], + ["", "ↈ", "ↈↈ", "ↈↈↈ"] + ] +}; +const UUIDLOG = []; +const GMID = () => { + var _a, _b; + return ((_b = (_a = game == null ? void 0 : game.user) == null ? void 0 : _a.find((user) => user.isGM)) == null ? void 0 : _b.id) ?? false; +}; +const isNumber = (ref) => typeof ref === "number" && !isNaN(ref); +const isNumString = (ref) => typeof ref === "string" && !isNaN(parseFloat(ref)) && isFinite(parseFloat(ref)); +const isBooleanString = (ref) => typeof ref === "string" && (ref === "true" || ref === "false"); +const isArray = (ref) => Array.isArray(ref); +const isSimpleObj = (ref) => ref === Object(ref) && !isArray(ref); +const isList = (ref) => ref === Object(ref) && !isArray(ref); +const isFunc = (ref) => typeof ref === "function"; +const isInt = (ref) => isNumber(ref) && Math.round(ref) === ref; +const isFloat = (ref) => isNumber(ref) && /\./.test(`${ref}`); +const isPosInt = (ref) => isInt(ref) && ref >= 0; +const isIndex = (ref) => isList(ref) || isArray(ref); +const isIterable = (ref) => typeof ref === "object" && ref !== null && Symbol.iterator in ref; +const isHTMLCode = (ref) => typeof ref === "string" && /^<.*>$/u.test(ref); +const isHexColor = (ref) => typeof ref === "string" && /^#(([0-9a-fA-F]{2}){3,4}|[0-9a-fA-F]{3,4})$/.test(ref); +const isRGBColor = (ref) => typeof ref === "string" && /^rgba?\((\d{1,3},\s*){1,2}?\d{1,3},\s*\d{1,3}(\.\d+)?\)$/.test(ref); +const isUndefined = (ref) => ref === void 0; +const isDefined = (ref) => !isUndefined(ref); +const isEmpty = (ref) => Object.keys(ref).length === 0; +const hasItems = (ref) => !isEmpty(ref); +const isInstance = (classRef, ref) => ref instanceof classRef; +const isNullish = (ref) => isUndefined(ref) || ref === null; +function assertNonNullType(val, type) { + let valStr; + try { + valStr = JSON.stringify(val); + } catch { + valStr = String(val); + } + if (val === void 0) { + throw new Error(`Value ${valStr} is undefined!`); + } + if (typeof type === "string") { + if (typeof val !== type) { + throw new Error(`Value ${valStr} is not a ${type}!`); + } + } else if (!(val instanceof type)) { + throw new Error(`Value ${valStr} is not a ${type.name}!`); + } +} +const areFuzzyEqual = (val1, val2) => { + if ([null, void 0].includes(val1) && [null, void 0].includes(val2)) { + return true; + } + if ([null, void 0].includes(val1) || [null, void 0].includes(val2)) { + return false; + } + if (typeof val1 === "number" && typeof val2 === "number") { + return val1 === val2; + } + if (typeof val1 === "boolean" && typeof val2 === "boolean") { + return val1 === val2; + } + if (typeof val1 === "string" && typeof val2 === "string") { + return val1 === val2; + } + if (typeof val1 === "number" && typeof val2 === "string") { + return val1 === Number(val2); + } + if (typeof val1 === "string" && typeof val2 === "number") { + return Number(val1) === val2; + } + if (typeof val1 === "boolean" && typeof val2 === "object") { + return false; + } + if (typeof val1 === "object" && typeof val2 === "boolean") { + return false; + } + if (typeof val1 === "boolean" && typeof val2 === "string") { + return val1 && val2 !== "" || !val1 && val2 === ""; + } + if (typeof val1 === "string" && typeof val2 === "boolean") { + return val2 && val1 !== "" || !val2 && val1 === ""; + } + if ((typeof val1 === "number" || typeof val1 === "string") && typeof val2 === "object") { + return false; + } + if (typeof val1 === "object" && (typeof val2 === "number" || typeof val2 === "string")) { + return false; + } + if (typeof val1 === "object" && typeof val2 === "object") { + return val1 === val2; + } + return false; +}; +const areEqual = (...refs) => { + do { + const ref = refs.pop(); + if (refs.length && !areFuzzyEqual(ref, refs[0])) { + return false; + } + } while (refs.length); + return true; +}; +const pFloat = (ref, sigDigits, isStrict = false) => { + if (typeof ref === "string") { + ref = parseFloat(ref); + } + if (typeof ref === "number") { + if (isNaN(ref)) { + return isStrict ? NaN : 0; + } + if (isUndefined(sigDigits)) { + return ref; + } + return Math.round(ref * 10 ** sigDigits) / 10 ** sigDigits; + } + return isStrict ? NaN : 0; +}; +const pInt = (ref, isStrictOrIndex, _arr) => { + let isStrict = false; + if (typeof isStrictOrIndex === "boolean") { + isStrict = isStrictOrIndex; + } + return isNaN(pFloat(ref, 0, isStrict)) ? NaN : Math.round(pFloat(ref, 0, isStrict)); +}; +const pBool = (ref) => { + if (typeof ref === "boolean") { + return ref; + } + if ([0, null, void 0, ""].includes(ref)) { + return false; + } + if (typeof ref === "string") { + return !["0", "false", "null", "undefined", ""].includes(ref); + } + if (isArray(ref) && ref.length === 0) { + return false; + } + if (isList(ref) && isEmpty(ref)) { + return false; + } + return true; +}; +const radToDeg = (rad, isConstrained = true) => { + rad = isConstrained ? rad % (2 * Math.PI) : rad; + rad *= 180 / Math.PI; + return rad; +}; +const degToRad = (deg, isConstrained = true) => { + deg = isConstrained ? deg % 360 : deg; + deg *= Math.PI / 180; + return deg; +}; +const getKey = (key, obj) => { + if (key in obj) { + return obj[key]; + } + return null; +}; +const FILTERS = { + IsInstance: (classRef) => (item) => typeof classRef === "function" && item instanceof classRef +}; +const uCase = (str) => String(str).toUpperCase(); +const lCase = (str) => String(str).toLowerCase(); +const sCase = (str) => { + let [first, ...rest] = `${str ?? ""}`.split(/\s+/); + first = testRegExp(first, _capWords) ? first : `${uCase(first.charAt(0))}${lCase(first.slice(1))}`; + if (hasItems(rest)) { + rest = rest.map((word) => testRegExp(word, _capWords) ? word : lCase(word)); + } + return [first, ...rest].join(" ").trim(); +}; +const tCase = (str) => String(str).split(/\s/).map((word, i) => i && testRegExp(word, _noCapWords) ? lCase(word) : sCase(word)).join(" ").trim(); +const testRegExp = (str, patterns = [], flags = "gui", isTestingAll = false) => patterns.map((pattern) => pattern instanceof RegExp ? pattern : new RegExp(`\\b${pattern}\\b`, flags))[isTestingAll ? "every" : "some"]((pattern) => pattern.test(`${str}`)); +const regExtract = (ref, pattern, flags) => { + const splitFlags = []; + [...(flags ?? "").replace(/g/g, ""), "u"].forEach((flag) => { + if (flag && !splitFlags.includes(flag)) { + splitFlags.push(flag); + } + }); + const isGrouping = /[)(]/.test(pattern.toString().replace(/\\\)|\\\(/g, "")); + if (isGrouping) { + splitFlags.push("g"); + } + flags = splitFlags.join(""); + pattern = new RegExp(pattern, flags); + const matches = `${ref}`.match(pattern) || []; + return isGrouping ? Array.from(matches) : matches.pop(); +}; +const unhyphenate = (str) => `${str}`.replace(/[\u00AD\u200B]/gu, ""); +const parseArticles = (str) => `${str}`.replace(/\b([aA])\s([aeiouAEIOU])/gu, "$1n $2"); +const pluralize = (singular, num = 2, plural) => { + if (pFloat(num) === 1) { + return singular; + } + return plural ?? `${singular.replace(/y$/, "ie").replace(/s$/, "se")}s`; +}; +const oxfordize = (items, useOxfordComma = true, andString = "and") => { + if (items.length === 0) { + return ""; + } + if (items.length === 1) { + return `${items[0]}`; + } + const lastItem = items.pop(); + return [ + items.join(", "), + useOxfordComma ? "," : "", + ` ${andString} `, + lastItem + ].join(""); +}; +const ellipsize = (text, maxLength) => { + const str = String(text); + return str.length > maxLength ? `${str.slice(0, maxLength - 3)}…` : str; +}; +const pad = (text, minLength, delim = " ") => { + const str = `${text}`; + if (str.length < minLength) { + return `${delim.repeat(minLength - str.length)}${str}`; + } + return str; +}; +const toKey = (text) => (text ?? "").toLowerCase().replace(/ /g, "-").replace(/default/, "DEFAULT"); +const signNum = (num, delim = "", zeroSign = "+") => { + let sign; + const parsedNum = pFloat(num); + if (parsedNum < 0) { + sign = "-"; + } else if (parsedNum === 0) { + sign = zeroSign; + } else { + sign = "+"; + } + return `${sign}${delim}${Math.abs(parsedNum)}`; +}; +const padNum = (num, numDecDigits, includePlus = false) => { + const prefix = includePlus && num >= 0 ? "+" : ""; + const [leftDigits, rightDigits] = `${pFloat(num)}`.split(/\./); + if (getType(rightDigits) === "int") { + if (rightDigits.length > numDecDigits) { + return `${prefix}${pFloat(num, numDecDigits)}`; + } else if (rightDigits.length < numDecDigits) { + return `${prefix}${leftDigits}.${rightDigits}${"0".repeat(numDecDigits - rightDigits.length)}`; + } else { + return `${prefix}${pFloat(num)}`; + } + } + return `${prefix}${leftDigits}.${"0".repeat(numDecDigits)}`; +}; +const stringifyNum = (num) => { + var _a; + if (pFloat(num) === 0) { + return "0"; + } + const stringyNum = lCase(num).replace(/[^\d.e+-]/g, ""); + const base = regExtract(stringyNum, /^-?[\d.]+/); + const exp = pInt(regExtract(stringyNum, /e([+-]?\d+)$/)); + if (typeof base === "string" && typeof exp === "string") { + let baseInts = regExtract(base, /^-?(\d+)/); + let baseDecs = regExtract(base, /\.(\d+)/); + if (isArray(baseInts) && isArray(baseDecs)) { + baseInts = (_a = baseInts.pop()) == null ? void 0 : _a.replace(/^0+/, ""); + baseDecs = lCase(baseDecs == null ? void 0 : baseDecs.pop()).replace(/0+$/, ""); + if (!isUndefined(baseInts) && !isUndefined(baseDecs)) { + const numFinalInts = Math.max(0, baseInts.length + exp); + const numFinalDecs = Math.max(0, baseDecs.length - exp); + const finalInts = [ + baseInts.slice(0, numFinalInts), + baseDecs.slice(0, Math.max(0, exp)) + ].join("") || "0"; + const finalDecs = [ + baseInts.length - numFinalInts > 0 ? baseInts.slice(baseInts.length - numFinalInts - 1) : "", + baseDecs.slice(baseDecs.length - numFinalDecs) + ].join(""); + return [ + stringyNum.charAt(0) === "-" ? "-" : "", + finalInts, + "0".repeat(Math.max(0, numFinalInts - finalInts.length)), + finalDecs.length ? "." : "", + "0".repeat(Math.max(0, numFinalDecs - finalDecs.length)), + finalDecs + ].join(""); + } + } + } + return `${num}`; +}; +const verbalizeNum = (num) => { + var _a; + num = stringifyNum(num); + const getTier = (trioNum) => { + if (trioNum < _numberWords.tiers.length) { + return _numberWords.tiers[trioNum]; + } + return [ + _numberWords.bigPrefixes[trioNum % 10 - 1], + _numberWords.bigSuffixes[Math.floor(trioNum / 10)] + ].join(""); + }; + const parseThreeDigits = (trio) => { + if (pInt(trio) === 0) { + return ""; + } + const digits = `${trio}`.split("").map((digit) => pInt(digit)); + let result = ""; + if (digits.length === 3) { + const hundreds = digits.shift(); + if (isUndefined(hundreds)) { + throw new Error(`[U.verbalizeNum] Undefined digit in trio '${digits.join("")}'.`); + } + result += hundreds > 0 ? `${_numberWords.ones[hundreds]} hundred` : ""; + if (hundreds && (digits[0] || digits[1])) { + result += " and "; + } + } + if (pInt(digits.join("")) <= _numberWords.ones.length) { + result += _numberWords.ones[pInt(digits.join(""))]; + } else { + const tens = _numberWords.tens[pInt(digits.shift())]; + const ones = pInt(digits[0]) > 0 ? `-${_numberWords.ones[pInt(digits[0])]}` : ""; + result += `${tens}${ones}`; + } + return result; + }; + const numWords = []; + if (num.charAt(0) === "-") { + numWords.push("negative"); + } + const [integers, decimals] = num.replace(/[,\s-]/g, "").split("."); + const intArray = ((_a = [...integers.split("")].reverse().join("").match(/.{1,3}/g)) == null ? void 0 : _a.map((v) => [...v.split("")].reverse().join(""))) ?? []; + const intStrings = []; + while (intArray.length) { + const thisTrio = intArray.pop(); + if (thisTrio) { + const theseWords = parseThreeDigits(thisTrio); + if (theseWords) { + intStrings.push(`${theseWords} ${getTier(intArray.length)}`); + } + } + } + numWords.push(intStrings.join(", ").trim()); + if (getType(decimals) === "int") { + if (integers === "0") { + numWords.push("zero"); + } + numWords.push("point"); + for (const digit of decimals.split("")) { + numWords.push(_numberWords.ones[pInt(digit)]); + } + } + return numWords.join(" "); +}; +const ordinalizeNum = (num, isReturningWords = false) => { + if (isReturningWords) { + const [numText, suffix] = lCase(verbalizeNum(num)).match(/.*?[-\s]?(\w*)$/i) ?? ["", ""]; + return numText.replace( + new RegExp(`${suffix}$`), + suffix in _ordinals ? _ordinals[suffix] : `${suffix}th` + ); + } + if (/(\.)|(1[1-3]$)/.test(`${num}`)) { + return `${num}th`; + } + return `${num}${["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"][pInt(`${num}`.charAt(`${num}`.length - 1))]}`; +}; +const romanizeNum = (num, isUsingGroupedChars = true) => { + if (isFloat(num)) { + throw new Error(`Error: Can't Romanize Floats (${num})`); + } + if (num >= 4e5) { + throw new Error(`Error: Can't Romanize >= 400,000 (${num})`); + } + if (num < 0) { + throw new Error(`Error: Can't Romanize Negative Numbers (${num})`); + } + if (num === 0) { + return "0"; + } + const romanRef = _romanNumerals[isUsingGroupedChars ? "grouped" : "ungrouped"]; + const romanNum = [...stringifyNum(num).split("")].reverse().map((digit, i) => romanRef[i][pInt(digit)]).reverse().join(""); + return isUsingGroupedChars ? romanNum.replace(/ⅩⅠ/gu, "Ⅺ").replace(/ⅩⅡ/gu, "Ⅻ") : romanNum; +}; +const loremIpsum = (numWords = 200) => { + const lrWordList = _loremIpsumText.split(/\n?\s+/g); + const words = [...lrWordList[randNum(0, lrWordList.length - 1)]]; + while (words.length < numWords) { + words.push(...lrWordList); + } + words.length = numWords; + return `${sCase(words.join(" ")).trim().replace(/[^a-z\s]*$/ui, "")}.`; +}; +const randString = (length = 5) => Array.from({ length }).map(() => String.fromCharCode(randInt(...["a", "z"].map((char) => char.charCodeAt(0))))).join(""); +const randWord = (numWords = 1, wordList = _randomWords) => Array.from({ length: numWords }).map(() => randElem([...wordList])).join(" "); +const getUID = (id) => { + const indexNum = Math.max( + 0, + ...UUIDLOG.filter(([genericID]) => genericID.startsWith(id)).map(([, , num]) => num) + ) + 1; + const uuid = indexNum === 1 ? id : `${id}_${indexNum}`; + UUIDLOG.push([id, uuid, indexNum]); + eLog.log(`UUIDify(${id}) --> [${uuid}, ${indexNum}]`); + Object.assign(globalThis, { UUIDLOG }); + return uuid; +}; +const fuzzyMatch = (val1, val2) => { + const [str1, str2] = [val1, val2].map((val) => lCase(String(val).replace(/[^a-zA-Z0-9.+-]/g, "").trim())); + return str1.length > 0 && str1 === str2; +}; +const isIn = (needle, haystack = [], fuzziness = 0) => { + const SearchTests = [ + (ndl, item) => new RegExp(`^${ndl}$`, "gu").test(`${item}`), + (ndl, item) => new RegExp(`^${ndl}$`, "gui").test(`${item}`) + ]; + if (fuzziness >= 1) { + const fuzzyTests = [ + (ndl, item) => new RegExp(`^${ndl}`, "gui").test(`${item}`), + (ndl, item) => new RegExp(`${ndl}$`, "gui").test(`${item}`), + (ndl, item) => new RegExp(`${ndl}`, "gui").test(`${item}`), + (ndl, item) => new RegExp(`${item}`, "gui").test(`${ndl}`) + ]; + SearchTests.push(...fuzzyTests); + if (fuzziness >= 2) { + SearchTests.push(...fuzzyTests.map((func) => (ndl, item) => func(`${ndl}`.replace(/\W/g, ""), `${item}`.replace(/\W/gu, "")))); + if (fuzziness >= 3) { + SearchTests.push(() => false); + } + } + } + const searchNeedle = `${needle}`; + const searchStack = (() => { + if (isArray(haystack)) { + return [...haystack]; + } + if (isList(haystack)) { + return Object.keys(haystack); + } + try { + return Array.from(haystack); + } catch { + throw new Error(`Haystack type must be [list, array], not ${typeof haystack}: ${JSON.stringify(haystack)}`); + } + })(); + if (!isArray(searchStack)) { + return false; + } + let matchIndex = -1; + while (!isPosInt(matchIndex)) { + const testFunc = SearchTests.shift(); + if (!testFunc) { + return false; + } + matchIndex = searchStack.findIndex((item) => testFunc(searchNeedle, `${item}`)); + } + if (isPosInt(matchIndex)) { + return isList(haystack) ? Object.values(haystack)[matchIndex] : haystack[matchIndex]; + } + return false; +}; +const isInExact = (needle, haystack) => isIn(needle, haystack, 0); +const randNum = (min, max, snap3 = 0) => gsapWithCSS.utils.random(min, max, snap3); +const randInt = (min, max) => randNum(min, max, 1); +const coinFlip = () => randNum(0, 1, 1) === 1; +const cycleNum = (num, [min = 0, max = Infinity] = []) => gsapWithCSS.utils.wrap(min, max, num); +const clampNum = (num, [min = 0, max = Infinity] = []) => gsapWithCSS.utils.clamp(min, max, num); +const cycleAngle = (angle, range = [0, 360]) => cycleNum(angle, range); +const roundNum = (num, sigDigits = 0) => sigDigits === 0 ? pInt(num) : pFloat(num, sigDigits); +const sum = (...nums) => Object.values(nums.flat()).reduce((num, tot) => tot + num, 0); +const average = (...nums) => sum(...nums) / nums.flat().length; +const getDistance = ({ x: x1, y: y1 }, { x: x2, y: y2 }) => ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5; +const getAngle = ({ x: x1, y: y1 }, { x: x2, y: y2 }, { x: xO, y: yO } = { x: 0, y: 0 }, range = [0, 360]) => { + x1 -= xO; + y1 -= yO; + x2 -= xO; + y2 -= yO; + return cycleAngle(radToDeg(Math.atan2(y2 - y1, x2 - x1)), range); +}; +const getAngleDelta = (angleStart, angleEnd, range = [0, 360]) => cycleAngle(angleEnd - angleStart, range); +const getBoundingRectangle = (arrayOfShapes) => { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const shape of arrayOfShapes) { + let shapeMinX; + let shapeMinY; + let shapeMaxX; + let shapeMaxY; + if (shape.radius !== void 0) { + shapeMinX = shape.x - shape.radius; + shapeMinY = shape.y - shape.radius; + shapeMaxX = shape.x + shape.radius; + shapeMaxY = shape.y + shape.radius; + } else if (shape.size !== void 0) { + shapeMinX = (shape.x - shape.size) / 2; + shapeMinY = (shape.y - shape.size) / 2; + shapeMaxX = (shape.x + shape.size) / 2; + shapeMaxY = (shape.y + shape.size) / 2; + } else if (shape.width !== void 0 || shape.height !== void 0) { + shape.width ?? (shape.width = shape.height); + shape.height ?? (shape.height = shape.width); + shapeMinX = (shape.x - shape.width) / 2; + shapeMinY = (shape.y - shape.height) / 2; + shapeMaxX = (shape.x + shape.width) / 2; + shapeMaxY = (shape.y + shape.height) / 2; + } else { + throw new Error(`[getBoundingRectangle] Error: shape must be a circle, square, or rectangle, not ${JSON.stringify(shape)}`); + } + minX = Math.min(minX, shapeMinX); + minY = Math.min(minY, shapeMinY); + maxX = Math.max(maxX, shapeMaxX); + maxY = Math.max(maxY, shapeMaxY); + } + const width = maxX - minX; + const height = maxY - minY; + const x = (minX + width) / 2; + const y = (minY + height) / 2; + return { x, y, width, height }; +}; +const randElem = (array) => gsapWithCSS.utils.random(array); +const randIndex = (array) => randInt(0, array.length - 1); +const makeIntRange = (min, max) => { + const intRange = []; + for (let i = min; i <= max; i++) { + intRange.push(i); + } + return intRange; +}; +const makeCycler = (array, index = 0) => { + const wrapper = gsapWithCSS.utils.wrap(array); + index--; + return function* () { + while (true) { + index++; + yield wrapper(index); + } + }(); +}; +function getLast(array) { + array = Object.values(array); + if (array.length === 0) { + throw new Error("Cannot get last element of an empty array."); + } + return array[array.length - 1]; +} +const unique = (array) => { + const returnArray = []; + array.forEach((item) => { + if (!returnArray.includes(item)) { + returnArray.push(item); + } + }); + return returnArray; +}; +const group = (array, key) => { + const returnObj = {}; + array.forEach((item) => { + const returnKey = item[key]; + let returnVal = returnObj[returnKey]; + if (!returnVal) { + returnVal = []; + returnObj[returnKey] = returnVal; + } + returnVal.push(item); + }); + return returnObj; +}; +const sample = (array, numElems = 1, isUniqueOnly = true, uniqueTestFunc = (e, a) => !a.includes(e)) => { + const elems = []; + let overloadCounter = 0; + while (elems.length < numElems && overloadCounter < 1e6) { + const randomElem = randElem(array); + if (isUniqueOnly && uniqueTestFunc(randomElem, elems)) { + elems.push(randomElem); + } + overloadCounter++; + } + return elems; +}; +const removeFirst = (array, element) => array.splice(array.findIndex((v) => v === element)); +function pullElement(array, checkFunc) { + let testFunction; + if (typeof checkFunc !== "function") { + testFunction = (_v) => _v === checkFunc; + } else { + testFunction = checkFunc; + } + const index = array.findIndex((v, i, a) => testFunction(v, i, a)); + if (index === -1) { + return void 0; + } + return array.splice(index, 1).pop(); +} +const pullIndex = (array, index) => pullElement(array, (_, i) => i === index); +const subGroup = (array, groupSize) => { + const subArrays = []; + while (array.length > groupSize) { + const subArray = []; + while (subArray.length < groupSize) { + subArray.push(array.shift()); + } + subArrays.push(subArray); + } + subArrays.push(array); + return subArrays; +}; +const shuffle2 = (array) => { + let currentIndex = array.length; + let randomIndex; + while (currentIndex !== 0) { + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex--; + [array[currentIndex], array[randomIndex]] = [ + array[randomIndex], + array[currentIndex] + ]; + } + return array; +}; +const toArray2 = (target) => { + return gsapWithCSS.utils.toArray(target); +}; +const checkVal = ({ k, v }, checkTest) => { + if (typeof checkTest === "function") { + if (isDefined(v)) { + return checkTest(v, k); + } + return checkTest(k); + } + if (typeof checkTest === "number") { + checkTest = `${checkTest}`; + } + return new RegExp(checkTest).test(`${v}`); +}; +const remove = (obj, checkTest) => { + if (isArray(obj)) { + const index = obj.findIndex((v) => checkVal({ v }, checkTest)); + if (index >= 0) { + return removeElementFromArray(obj, index); + } + } else if (isList(obj)) { + const [remKey] = Object.entries(obj).find(([k, v]) => checkVal({ k, v }, checkTest)) ?? []; + if (remKey) { + return removeElementFromList(obj, remKey); + } + } + return false; +}; +const removeElementFromArray = (array, index) => { + let remVal; + for (let i = 0; i <= array.length; i++) { + if (i === index) { + remVal = array.shift(); + } else { + array.push(array.shift()); + } + } + return remVal; +}; +const removeElementFromList = (list, key) => { + const remVal = list[key]; + delete list[key]; + return remVal; +}; +const replace = (obj, checkTest, repVal) => { + let repKey; + if (isList(obj)) { + [repKey] = Object.entries(obj).find((v) => checkVal({ v }, checkTest)) || [false]; + if (repKey === false) { + return false; + } + } else if (isArray(obj)) { + repKey = obj.findIndex((v) => checkVal({ v }, checkTest)); + if (repKey === -1) { + return false; + } + } + if (typeof repKey !== "number") { + repKey = `${repKey}`; + } + if (typeof repVal === "function") { + obj[repKey] = repVal(obj[repKey], repKey); + } else { + obj[repKey] = repVal; + } + return true; +}; +const objClean = (data, remVals = [void 0, null, "", {}, []]) => { + const remStrings = remVals.map((rVal) => JSON.stringify(rVal)); + if (remStrings.includes(JSON.stringify(data)) || remVals.includes(data)) { + return "KILL"; + } + if (Array.isArray(data)) { + const newData = data.map((elem) => objClean(elem, remVals)).filter((elem) => elem !== "KILL"); + return Array.isArray(newData) && newData.length ? newData : "KILL"; + } + if (data && typeof data === "object" && JSON.stringify(data).startsWith("{")) { + const newData = Object.entries(data).map(([key, val]) => [key, objClean(val, remVals)]).filter(([, val]) => val !== "KILL"); + return newData.length ? Object.fromEntries(newData) : "KILL"; + } + return data; +}; +const partition = (obj, predicate = () => true) => [ + objFilter(obj, predicate), + objFilter(obj, (v, k) => !predicate(v, k)) +]; +const zip = (keys, values) => { + if (keys.length !== values.length) { + throw new Error("The arrays must be of equal length."); + } + if (new Set(keys).size !== keys.length) { + throw new Error("The keys must be unique."); + } + const result = {}; + keys.forEach((key, i) => { + result[key] = values[i]; + }); + return result; +}; +function objMap(obj, keyFunc, valFunc) { + let valFuncTyped = valFunc; + let keyFuncTyped = keyFunc; + if (!valFuncTyped) { + valFuncTyped = keyFunc; + keyFuncTyped = false; + } + if (!keyFuncTyped) { + keyFuncTyped = (k) => k; + } + if (Array.isArray(obj)) { + return obj.map(valFuncTyped); + } + return Object.fromEntries(Object.entries(obj).map(([key, val]) => { + assertNonNullType(valFuncTyped, "function"); + return [keyFuncTyped(key, val), valFuncTyped(val, key)]; + })); +} +const objSize = (obj) => { + if (isSimpleObj(obj)) { + return Object.keys(obj).length; + } + if (isArray(obj)) { + return obj.length; + } + if (obj === false || obj === null || obj === void 0) { + return 0; + } + return 1; +}; +function objFindKey(obj, keyFunc, valFunc) { + if (!valFunc) { + valFunc = keyFunc; + keyFunc = false; + } + if (!keyFunc) { + keyFunc = (k) => k; + } + if (isArray(obj)) { + return obj.findIndex(valFunc); + } + const kFunc = keyFunc || (() => true); + const vFunc = valFunc || (() => true); + const validEntry = Object.entries(obj).find(([k, v]) => kFunc(k, v) && vFunc(v, k)); + if (validEntry) { + return validEntry[0]; + } + return false; +} +const objFilter = (obj, keyFunc, valFunc, isMutating = false) => { + if (!valFunc) { + valFunc = keyFunc; + keyFunc = false; + } + if (!keyFunc) { + keyFunc = (k) => k; + } + if (isArray(obj)) { + const keptValues = obj.filter(valFunc); + if (isMutating) { + obj.splice(0, obj.length, ...keptValues); + return obj; + } + return keptValues; + } + const kFunc = keyFunc || (() => true); + const vFunc = valFunc || (() => true); + if (isMutating) { + const entriesToRemove = Object.entries(obj).filter(([key, val]) => !(kFunc(key, val) && vFunc(val, key))); + for (const [key] of entriesToRemove) { + delete obj[key]; + } + return obj; + } + return Object.fromEntries( + Object.entries(obj).filter(([key, val]) => kFunc(key, val) && vFunc(val, key)) + ); +}; +const objForEach = (obj, func) => { + if (isArray(obj)) { + obj.forEach(func); + } else { + Object.entries(obj).forEach(([key, val]) => func(val, key)); + } +}; +const objCompact = (obj, removeWhiteList = [void 0, null], isMutating = false) => objFilter(obj, (val) => !removeWhiteList.includes(val), void 0, isMutating); +const objClone = (obj, isStrictlySafe = false) => { + const cloneArray = (arr) => [...arr]; + const cloneObject = (o) => ({ ...o }); + try { + return JSON.parse(JSON.stringify(obj)); + } catch (err) { + if (isStrictlySafe) { + throw err; + } + if (Array.isArray(obj)) { + return cloneArray(obj); + } + if (typeof obj === "object") { + return cloneObject(obj); + } + } + return obj; }; -function Initialize() { - if (gsapPlugins.length) { - U.gsap.config({ - nullTargetWarn: true - }); - U.gsap.registerPlugin(...gsapPlugins); - Object.assign( - globalThis, - { - TextPlugin, - Flip, - MotionPathPlugin, - Dragger: Draggable, - SplitText, - Observer: Observer$1, - CustomEase, - CustomWiggle, - CustomBounce, - EasePack +function objMerge(target, source, { + isMutatingOk = false, + isStrictlySafe = false, + isConcatenatingArrays = true, + isReplacingArrays = false +} = {}) { + target = isMutatingOk ? target : objClone(target, isStrictlySafe); + if (source && typeof source === "object" && "id" in source && isDocID(source.id) || isUndefined(target)) { + return source; + } + if (isUndefined(source)) { + return target; + } + if (!isIndex(source)) { + return target; + } + for (const [key, val] of Object.entries(source)) { + const targetVal = target[key]; + if (isReplacingArrays && isArray(targetVal) && isArray(val)) { + target[key] = val; + } else if (isConcatenatingArrays && isArray(targetVal) && isArray(val)) { + target[key].push(...val); + } else if (val !== null && typeof val === "object") { + if (isUndefined(targetVal) && !(val instanceof Application)) { + target[key] = new (Object.getPrototypeOf(val)).constructor(); } - ); + target[key] = objMerge( + target[key], + val, + { isMutatingOk: true, isStrictlySafe } + ); + } else { + target[key] = val; + } } - Object.entries(gsapEffects).forEach(([name, effect]) => { - U.gsap.registerEffect(Object.assign(effect, { name })); - }); + return target; } -function ApplyTooltipAnimations(html) { - html.find(".tooltip-trigger").each((_, el) => { - const tooltipElem = $(el).find(".tooltip")[0] ?? $(el).next(".tooltip")[0]; - if (!tooltipElem) { - return; +function objDiff(obj1, obj2) { + const diff = {}; + const bothObj1AndObj2Keys = Object.keys(obj2).filter((key) => Object.hasOwn(obj2, key) && Object.hasOwn(obj1, key)); + const onlyObj2Keys = Object.keys(obj2).filter((key) => Object.hasOwn(obj2, key) && !Object.hasOwn(obj1, key)); + for (const key of bothObj1AndObj2Keys) { + if (typeof obj1[key] === "object" && typeof obj2[key] === "object" && !Array.isArray(obj1[key]) && !Array.isArray(obj2[key])) { + const nestedDiff = objDiff(obj1[key], obj2[key]); + if (Object.keys(nestedDiff).length > 0) { + diff[key] = nestedDiff; + } + } else if (Array.isArray(obj1[key]) && Array.isArray(obj2[key])) { + const array1 = obj1[key]; + const array2 = obj2[key]; + if (array1.toString() !== array2.toString()) { + diff[key] = obj2[key]; + } + } else if (obj1[key] !== obj2[key]) { + diff[key] = obj2[key]; } - const tooltip$ = $(tooltipElem); - const tooltipContainer$ = tooltip$.parent(); - if (tooltipContainer$.css("position") !== "relative" && tooltipContainer$.css("position") !== "absolute") { - tooltipContainer$.css("position", "relative"); + } + for (const key of onlyObj2Keys) { + diff[`-=${key}`] = obj2[key]; + } + return diff; +} +const objExpand = (obj) => { + const expObj = {}; + for (const [key, val] of Object.entries(obj)) { + if (isList(val)) { + const expandedVal = objExpand(val); + setProperty(expObj, key, expandedVal); + } else { + setProperty(expObj, key, val); } - tooltip$.css("position", "absolute"); - const tooltipID = `tooltip-${randomID()}`; - tooltip$.attr("id", tooltipID); - if (tooltip$.hasClass("tooltip-wide")) { - U.adjustTextContainerAspectRatio(tooltipElem, 6); + } + function arrayify(o) { + if (isList(o)) { + if (/^\d+$/.test(Object.keys(o).join(""))) { + return Object.values(o).map(arrayify); + } + return objMap(o, (v) => arrayify(v)); } - $(el).on({ - mouseenter: function() { - game.eunoblades.Director.displayTooltip(tooltipElem); - }, - mouseleave: function() { - game.eunoblades.Director.clearTooltip(tooltipID); + if (isArray(o)) { + return o.map(arrayify); + } + return o; + } + return arrayify(expObj); +}; +const objFlatten = (obj) => { + const flatObj = {}; + for (const [key, val] of Object.entries(obj)) { + if ((isArray(val) || isList(val)) && hasItems(val)) { + for (const [subKey, subVal] of Object.entries(objFlatten(val))) { + flatObj[`${key}.${subKey}`] = subVal; } + } else { + flatObj[key] = val; + } + } + return flatObj; +}; +function objNullify(obj) { + if (!isIndex(obj)) { + return obj; + } + if (Array.isArray(obj)) { + obj.forEach((_, i) => { + obj[i] = null; }); + return obj; + } + Object.keys(obj).forEach((objKey) => { + obj[objKey] = null; }); + return obj; } -const G = U.gsap; -const _BladesTargetLink = class _BladesTargetLink { - constructor(dataOrConfig, parentLinkData) { - __privateAdd(this, _updateTargetViaMerge); - __privateAdd(this, _updateTargetPropVal); - __publicField(this, "_id"); - __publicField(this, "_targetID"); - __publicField(this, "_targetKey"); - __publicField(this, "_targetFlagKey"); - __publicField(this, "_isScopingById", true); - __publicField(this, "_initialSchema"); - __publicField(this, "_target"); - __publicField(this, "initPromise"); - __publicField(this, "isInitPromiseResolved", false); - var _a; - let linkData; - let schema; - const subclassConstructor = this.constructor; - if (subclassConstructor.IsValidData(dataOrConfig)) { - ({ linkData } = subclassConstructor.PartitionSchemaData(dataOrConfig)); - const target2 = fromUuidSync(linkData.targetID); - if (!target2) { - throw new Error(`[new BladesTargetLink()] Unable to resolve target from uuid '${linkData.targetID}'`); - } - if ("targetKey" in linkData) { - schema = getProperty(target2, `${linkData.targetKey}.${linkData.id}`); - } else { - schema = target2.getFlag(C.SYSTEM_ID, `${linkData.targetFlagKey}.${linkData.id}`); +function objFreezeProps(data, ...keysOrSchema) { + const firstArg = keysOrSchema[0]; + if (firstArg instanceof Object && !Array.isArray(firstArg)) { + const schema = firstArg; + for (const key in schema) { + if (data[key] === void 0) { + throw new Error(`Missing value for ${key}`); } - this.isInitPromiseResolved = true; - } else { - const parsedData = __privateMethod(_a = _BladesTargetLink, _ParseConfigToData, ParseConfigToData_fn).call(_a, dataOrConfig, parentLinkData); - let partialSchema; - ({ linkData, partialSchema } = subclassConstructor.PartitionSchemaData(parsedData)); - schema = subclassConstructor._ApplySchemaDefaults(partialSchema); - } - this._id = linkData.id; - this._targetID = linkData.targetID; - if ("targetKey" in linkData) { - this._targetKey = linkData.targetKey; - } else { - this._targetFlagKey = linkData.targetFlagKey; } - const target = fromUuidSync(this.targetID); - if (!target) { - throw new Error(`[new BladesTargetLink()] Unable to resolve target from uuid '${this._targetID}'`); + } else { + for (const key of keysOrSchema) { + if (data[key] === void 0) { + throw new Error(`Missing value for ${String(key)}`); + } } - this._target = target; - this._initialSchema = schema; } - // #region STATIC METHODS ~ - static get ValidTargetClasses() { - return [ - BladesActor$1, - BladesItem$1, - BladesChat$1, - User - ]; + return data; +} +const getDynamicFunc = (funcName, func, context3) => { + if (typeof func === "function") { + const dFunc = { [funcName](...args) { + return func(...args); + } }[funcName]; + return context3 ? dFunc.bind(context3) : dFunc; } - static IsValidConfig(ref) { - return U.isSimpleObj(ref) && (U.isDocID(ref.target) || U.isDocUUID(ref.target) || U.isDocID(ref.targetID) || U.isDocUUID(ref.targetID) || this.ValidTargetClasses.some((cls) => ref.target instanceof cls)) && (U.isTargetKey(ref.targetKey) || U.isTargetFlagKey(ref.targetFlagKey)) && !(U.isTargetKey(ref.targetKey) && U.isTargetFlagKey(ref.targetFlagKey)); + return false; +}; +const withLog = (fn) => { + return (...args) => { + console.log(`calling ${fn.name}`); + return fn(...args); + }; +}; +const changeContainer = (elem, container, isCloning = false) => { + elem = $(elem)[0]; + container = $(container)[0]; + const curContainer = $(elem).parent()[0]; + const curPosition = { + x: gsapWithCSS.getProperty(elem, "x"), + y: gsapWithCSS.getProperty(elem, "y") + }; + const relPos = MotionPathPlugin.convertCoordinates( + curContainer, + container, + curPosition + ); + eLog.checkLog3("changeContainer", "Target Element", { elem, container, curContainer, curPosition, relPos }); + if (isCloning) { + elem = $(elem).clone()[0]; + } + $(elem).appendTo($(container)); + gsapWithCSS.set(elem, relPos); + return elem; +}; +const adjustTextContainerAspectRatio = (textContainer, targetRatio, maxHeight, maxWidth, minFontSize = 8) => { + textContainer = $(textContainer)[0]; + if (!maxWidth) { + textContainer.style.setProperty("width", "max-content", "important"); + } else { + textContainer.style.setProperty("width", `${maxWidth}px`, "important"); + } + function recurAdjustment() { + textContainer = $(textContainer)[0]; + const newFontSize = parseFloat(style.fontSize) * 0.8; + const newLineHeight = parseFloat(style.lineHeight) * 0.8; + if (newFontSize < minFontSize) { + return false; + } + textContainer.style.fontSize = `${newFontSize}px`; + textContainer.style.lineHeight = `${newLineHeight}px`; + return adjustTextContainerAspectRatio(textContainer, targetRatio, lineCount ?? maxHeight, maxWidth, minFontSize); } - static IsValidData(ref) { - return U.isSimpleObj(ref) && U.isDocID(ref.id) && U.isDocUUID(ref.targetID) && (U.isTargetKey(ref.targetKey) || U.isTargetFlagKey(ref.targetFlagKey)) && !(U.isTargetKey(ref.targetKey) && U.isTargetFlagKey(ref.targetFlagKey)); + const style = window.getComputedStyle(textContainer); + const lineHeight = parseFloat(style.lineHeight); + let lineCount = void 0; + if (isInt(maxHeight) && maxHeight < lineHeight) { + lineCount = maxHeight; } - static BuildLinkConfig(partialConfig) { - if ("target" in partialConfig) { - if ("targetKey" in partialConfig) { - return { - target: partialConfig.target, - targetKey: partialConfig.targetKey, - isScopingById: partialConfig.isScopingById - }; - } else if ("targetFlagKey" in partialConfig) { - return { - target: partialConfig.target, - targetFlagKey: partialConfig.targetFlagKey, - isScopingById: partialConfig.isScopingById - }; + const initialWidth = parseFloat(style.width); + let bestWidth = initialWidth; + let isAtMaxLineCount = false; + for (let lines = 1; ; lines++) { + const expectedHeight = lineHeight * lines; + const expectedWidth = initialWidth / lines; + const expectedRatio = expectedWidth / expectedHeight; + if (expectedRatio < targetRatio) { + break; + } + if (isInt(lineCount)) { + if (lines > lineCount) { + if (recurAdjustment()) { + return; + } + break; } - throw new Error("[BladesTargetLink.BuildConfig] Must provide a targetKey or targetFlagKey."); - } else if ("targetID" in partialConfig) { - if ("targetKey" in partialConfig) { - return { - targetID: partialConfig.targetID, - targetKey: partialConfig.targetKey, - isScopingById: partialConfig.isScopingById - }; - } else if ("targetFlagKey" in partialConfig) { - return { - targetID: partialConfig.targetID, - targetFlagKey: partialConfig.targetFlagKey, - isScopingById: partialConfig.isScopingById - }; + } else if (maxHeight && expectedHeight > maxHeight) { + if (recurAdjustment()) { + return; } - throw new Error("[BladesTargetLink.BuildConfig] Must provide a targetKey or targetFlagKey."); + break; } - throw new Error("[BladesTargetLink.BuildConfig] Must provide a target or targetID."); - } - /** - * This static method parses the provided data into a format suitable for BladesTargetLink. - * Subclasses can override this method to include their own parse logic. - * If the provided data is already valid, it is returned as is. - * Otherwise, the data is passed to the private #ParseConfig method for further processing. - * Note: The 'id' property is defined at the return step, within #ParseConfig: Subclass - * functionality that depends on the id property should be placed after the super call to this method. - * - * @template Schema - The data schema required by the subclass. - * @param {(BladesTargetLink.Config | BladesTargetLink.Data) & Partial} data - The data to be parsed. - * @returns {BladesTargetLink.Data & Partial} - The parsed data, suitable for BladesTargetLink. - */ - static ParseConfigToData(data, parentLinkData) { - if (this.IsValidData(data)) { - return __privateMethod(this, _ParseChildLinkData, ParseChildLinkData_fn).call(this, data, parentLinkData); + bestWidth = expectedWidth; + if (isInt(lineCount) && lines === lineCount) { + isAtMaxLineCount = true; + break; } - return __privateMethod(this, _ParseConfigToData, ParseConfigToData_fn).call(this, data, parentLinkData); } - static PartitionSchemaData(dataOrConfig) { - const { - id, - target, - targetID, - targetKey, - targetFlagKey, - isScopingById, - ...schemaData - } = dataOrConfig; - const partialSchema = schemaData; - if (U.isDocID(id)) { - if (!this.IsValidData({ id, targetID, targetKey, targetFlagKey, isScopingById })) { - eLog.error("BladesTargetLink", "Bad Constructor DATA", { dataOrConfig }); - throw new Error("[new BladesTargetLink()] Bad Constructor DATA (see log)"); - } - let linkData; - if (targetKey) { - linkData = { id, targetID, targetKey, isScopingById: isScopingById ?? true }; - } else if (targetFlagKey) { - linkData = { id, targetID, targetFlagKey, isScopingById: isScopingById ?? true }; - } else { - eLog.error("BladesTargetLink", "Bad Constructor DATA", { dataOrConfig }); - throw new Error("[BladesTargetLink.PartitionSchemaData] Bad Constructor DATA (see log)"); - } - return { - linkData, - partialSchema - }; + if (!isAtMaxLineCount && maxWidth && bestWidth > maxWidth) { + if (recurAdjustment()) { + return; } - return { - linkConfig: this.BuildLinkConfig({ - ...{ isScopingById: isScopingById ?? true }, - ..."targetID" in dataOrConfig ? { targetID: dataOrConfig.targetID } : { target: dataOrConfig.target }, - ..."targetKey" in dataOrConfig ? { targetKey: dataOrConfig.targetKey } : { targetFlagKey: dataOrConfig.targetFlagKey } - }), - partialSchema - }; } - static _ApplySchemaDefaults(schemaData) { - return this.ApplySchemaDefaults(schemaData); + textContainer.style.setProperty("width", `${bestWidth}px`, "important"); +}; +const getSvgCode = (svgDotKey, svgPathKeys) => { + const svgData = getProperty(SVGDATA, svgDotKey); + if (!svgData) { + return ""; } - /** - * This static method applies defaults to any values missing from the class' data Schema. - * 'Schema' is defined by subclasses to BladesTargetLink. - * Subclasses must override this method to apply their own defaults. - * - * @template Schema - The data schema required by the subclass. - * @param {Partial} schemaData - Schema data overriding the defaults. - * @returns {Schema} - The schema data with defaults applied. - * @throws {Error} - Throws an error if this method is not overridden in a subclass. - */ - static ApplySchemaDefaults(schemaData) { - throw new Error("[BladesTargetLink.ApplySchemaDefaults] Static Method ApplySchemaDefaults must be overridden in subclass"); + const { viewBox, paths, classes } = svgData; + svgPathKeys ?? (svgPathKeys = Object.keys(paths).join("|")); + if (typeof svgPathKeys === "string") { + svgPathKeys = svgPathKeys.split("|"); } - /** - * Creates a new instance of BladesTargetLink and initializes it with the provided configuration. - * The configuration is parsed into a data object which is then used to initialize the target link. - * The function logs the parsed data for debugging purposes. - * - * @template Schema - The schema type parameter that extends the data structure. - * @param {BladesTargetLink.Config & Partial} config - The configuration object containing both the target link configuration and the schema configuration. - * - * @returns {Promise & BladesTargetLink.Subclass>} - A promise that resolves to a new instance of BladesTargetLink, initialized with the provided data. - * - * @throws {Error} - Throws an error if the initialization of the target link fails. - */ - static async Create(config, parentLinkData) { - const tLink = new this(config, parentLinkData); - await tLink.initTargetLink(); - return tLink; + return [ + ``, + ...svgPathKeys.map((path) => ``), + "" + ].join("\n"); +}; +const getRawCirclePath = (r, { x: xO, y: yO } = { x: 0, y: 0 }) => { + [r, xO, yO] = [r, xO, yO].map((val) => roundNum(val, 2)); + const [b1, b2] = [0.4475 * r, (1 - 0.4475) * r]; + const [xT, yT] = [xO, yO - r]; + return [[ + ...[xT, yT], + ...[b2, 0, r, b1, r, r], + ...[0, b2, -b1, r, -r, r], + ...[-b2, 0, -r, -b1, -r, -r], + ...[0, -b2, b1, -r, r, -r] + ]]; +}; +const drawCirclePath = (radius, origin) => { + const [[xT, yT, ...segments]] = getRawCirclePath(radius, origin); + const path = [`m ${xT} ${yT}`]; + segments.forEach((coord, i) => { + if (i % 6 === 0) { + path.push("c"); + } + path.push(coord); + }); + path.push("z"); + return path.join(" "); +}; +const getColorVals = (red, green, blue, alpha) => { + var _a; + if (isRGBColor(red)) { + [red, green, blue, alpha] = red.replace(/[^\d.,]/g, "").split(/,/).map((color) => isUndefined(color) ? void 0 : parseFloat(color)); } - // #endregion - // #region GETTERS ~ - get isGM() { - return game.user.isGM; + if (isHexColor(red)) { + if ([4, 5].includes(red.length)) { + red = red.replace(/([^#])/g, "$1$1"); + } + [red, green, blue, alpha] = ((_a = red.match(/[^#]{2}/g)) == null ? void 0 : _a.map((val) => parseInt(val, 16))) ?? []; } - get id() { - return this._id; + if ([red, green, blue].every((color) => /^\d+$/.test(`${color}`))) { + return [red, green, blue, alpha].filter((color) => /^[\d.]+$/.test(`${color}`)); } - get targetID() { - return this._targetID; + return null; +}; +const getRGBString = (red, green, blue, alpha) => { + if (isRGBColor(red) || isHexColor(red)) { + [red, green, blue, alpha] = getColorVals(red) ?? []; } - get targetKey() { - return this._targetKey; + if ([red, green, blue].every((color) => /^[.\d]+$/.test(`${color}`))) { + let colorString = "rgb"; + const colors = [red, green, blue]; + if (/^[.\d]+$/.test(`${alpha}`)) { + colors.push(alpha >= 1 ? pInt(alpha) : pFloat(alpha, 2)); + colorString += "a"; + } + return `${colorString}(${colors.join(", ")})`; } - get targetFlagKey() { - return this._targetFlagKey; + return null; +}; +const getHEXString = (red, green, blue) => { + function componentToHex(c) { + const hex = c.toString(16); + return hex.length === 1 ? `0${hex}` : hex; } - get isScopingById() { - return this._isScopingById; + if (isHexColor(red)) { + return red; } - get initialSchema() { - return this._initialSchema; + if (isRGBColor(red)) { + [red, green, blue] = getColorVals(red) ?? []; } - get targetKeyPrefix() { - if (!this.targetKey) { - return void 0; - } - if (!this.isScopingById) { - return this.targetKey; - } - return this.targetKey ? `${this.targetKey}.${this.id}` : void 0; + if (isDefined(red) && isDefined(green) && isDefined(blue) && [red, green, blue].every((color) => /^[.\d]+$/.test(`${color}`))) { + return `#${componentToHex(red ?? 0)}${componentToHex(green ?? 0)}${componentToHex(blue ?? 0)}`; + } + return null; +}; +const getContrastingColor = (...colorVals) => { + const [red, green, blue] = getColorVals(...colorVals) ?? []; + if ([red, green, blue].every(isNumber)) { + const YIQ = (red * 299 + green * 587 + blue * 114) / 1e3; + return YIQ >= 128 ? "rgba(0, 0, 0, 1)" : "rgba(255, 255, 255, 0.8)"; } - get targetKeyNullPrefix() { - if (!this.targetKey) { - return void 0; - } - if (this.isScopingById) { - return `${this.targetKey}.-=${this.id}`; - } - if (/^.+\..+$/g.test(this.targetKey)) { - return this.targetKey.replace(/\.([^.]+)$/, ".-=$1"); - } - throw new Error(`[BladesTargetLink.targetKeyNullPrefix] Can't Nullify TargetKey '${this.targetKey}'`); + return null; +}; +const getRandomColor = () => getRGBString( + gsapWithCSS.utils.random(0, 255, 1), + gsapWithCSS.utils.random(0, 255, 1), + gsapWithCSS.utils.random(0, 255, 1) +); +const getSiblings = (elem) => { + const siblings = []; + if (!elem.parentNode) { + return siblings; } - get targetFlagKeyPrefix() { - if (!this.targetFlagKey) { - return void 0; + Array.from(elem.parentNode.children).forEach((sibling) => { + if (sibling !== elem) { + siblings.push(sibling); } - if (!this.isScopingById) { - return this.targetFlagKey; + }); + return siblings; +}; +const escapeHTML = (str) => typeof str === "string" ? str.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/[`']/g, "'") : str; +const testFuncPerformance = (func, ...params) => { + const start = performance.now(); + let tally = 0; + const handleResult = () => { + if (performance.now() - start < 1e4) { + runFunc(); + tally++; + } else { + const elapsedTime = performance.now() - start; + const timePerCall = roundNum(elapsedTime / tally / 4e3, 4); + eLog.checkLog3("performance", `[TestPerformance] Function Ran ${tally} Times in ${roundNum(elapsedTime / 1e3, 4)}s, Averaging ${timePerCall}s per Call`); } - return this.targetFlagKey ? `${this.targetFlagKey}.${this.id}` : void 0; - } - get isLinkInitialized() { - return this.isInitPromiseResolved; - } - get linkData() { - if (this.targetKey) { - return { - id: this.id, - targetID: this.targetID, - targetKey: this.targetKey, - isScopingById: this.isScopingById - }; + }; + const runFunc = () => { + const result = func(...params); + if (result instanceof Promise) { + result.then(handleResult); + } else { + handleResult(); } - if (this.targetFlagKey) { - return { - id: this.id, - targetID: this.targetID, - targetFlagKey: this.targetFlagKey, - isScopingById: this.isScopingById - }; + }; + runFunc(); +}; +const set = (targets, vars) => gsapWithCSS.set(targets, vars); +function get(target, property, unit) { + if (unit) { + const propVal = regExtract(gsapWithCSS.getProperty(target, property, unit), /[\d.]+/); + if (typeof propVal === "string") { + return pFloat(propVal); } - throw new Error(`[BladesTargetLink.linkData] Missing targetKey and targetFlagKey for '${this.id}'`); + throw new Error(`Unable to extract property '${property}' in '${unit}' units from ${target}`); } - get target() { - return this._target; + return gsapWithCSS.getProperty(target, property); +} +const getGSAngleDelta = (startAngle, endAngle) => signNum(roundNum(getAngleDelta(startAngle, endAngle), 2)).replace(/^(.)/, "$1="); +const getNearestLabel = (tl, matchTest) => { + if (!tl) { + return void 0; } - get localData() { - return { - ...this.initialSchema, - ...this.linkData - }; + if (!objSize(tl.labels)) { + return void 0; } - get data() { - if (this.isLinkInitialized) { - let data; - if (this.targetFlagKeyPrefix) { - data = this.target.getFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix); - } else if (this.targetKeyPrefix) { - data = getProperty(this.target, this.targetKeyPrefix); - } - if (!data) { - throw new Error("[BladesTargetLink.data] Error retrieving data."); - } - return data; - } else { - eLog.warn("BladesTargetLink", "Attempt to access data of uninitiated BladesTargetLink: Returning local data only.", { bladesTargetLink: this, localData: this.localData }); - return this.localData; - } + if (typeof matchTest === "string") { + matchTest = new RegExp(matchTest); } - // #endregion - // #region ASYNC UPDATE & DELETE METHODS ~ - getDotKeyToProp(prop, isNullifying = false) { - if (this.targetKeyPrefix) { - if (prop === void 0) { - return isNullifying ? this.targetKeyNullPrefix : this.targetKeyPrefix; - } - return `${this.targetKeyPrefix}.${isNullifying ? "-=" : ""}${prop}`; - } - if (this.targetFlagKeyPrefix) { - if (prop === void 0) { - return this.targetFlagKeyPrefix; - } - return `${this.targetFlagKeyPrefix}.${prop}`; + const labelTimes = Object.entries(tl.labels).filter(([label]) => { + return matchTest instanceof RegExp ? matchTest.test(label) : true; + }).sort((a, b) => a[1] - b[1]); + const nearestTime = gsapWithCSS.utils.snap(labelTimes.map(([_label, time]) => time), tl.time()); + const [nearestLabel] = labelTimes.find(([_label, time]) => time === nearestTime); + return nearestLabel; +}; +const reverseRepeatingTimeline = (tl) => { + if (tl.repeat() === -1) { + tl.totalTime(tl.time()); + } else { + const [tw] = tl.getChildren(false, true, true, tl.time()); + if (tw && tw.repeat() === -1) { + tw.totalTime(tw.time()); } - throw new Error("[BladesTargetLink.getDotKeyToProp()] Missing 'targetKeyPrefix' and 'targetFlagKeyPrefix'"); + tl.reverse(); } - getFlagParamsToProp(prop) { - return [C.SYSTEM_ID, this.getDotKeyToProp(prop)]; + return tl; +}; +const sleep = (duration) => new Promise( + (resolve) => { + setTimeout(resolve, duration >= 100 ? duration : duration * 1e3); } - async updateTargetFlag(prop, val) { - if (!this.targetFlagKeyPrefix) { - return; +); +function waitFor(waitForTarget) { + return new Promise( + (resolve, reject) => { + if (waitForTarget instanceof Promise || waitForTarget instanceof gsapWithCSS.core.Animation) { + waitForTarget.then(() => resolve()).catch(reject); + } else if (Array.isArray(waitForTarget)) { + Promise.all(waitForTarget.map((target) => waitFor(target))).then(() => resolve()).catch(reject); + } else { + resolve(); + } } - if (val === null) { - await this.target.unsetFlag(...this.getFlagParamsToProp(prop)); - } else if (this.target instanceof BladesActor$1) { - await this.target.setFlag(...this.getFlagParamsToProp(prop), val); - } else if (this.target instanceof BladesItem$1) { - await this.target.setFlag(...this.getFlagParamsToProp(prop), val); - } else if (this.target instanceof User) { - await this.target.setFlag(...this.getFlagParamsToProp(prop), val); - } else if (this.target instanceof BladesChat$1) { - await this.target.setFlag(...this.getFlagParamsToProp(prop), val); + ); +} +const EventHandlers = { + onTextInputBlur: async (inst, event) => { + const elem = event.target; + const { action, target, flagTarget } = elem.dataset; + if (!action) { + throw new Error("Input text elements require a data-action attribute."); } - } - async updateTargetKey(prop, val) { - if (!this.targetKeyPrefix) { - return; + if (!target && !flagTarget) { + throw new Error("Input text elements require a 'data-target' or 'data-flag-target' attribute."); } - await this.target.update({ [this.getDotKeyToProp(prop, val === null)]: val }, { render: false }); - } - /** - * Initializes a target link by updating the target's data with the provided data object. - * If a targetKey is provided, the data is updated directly on the target. - * If a targetFlagKey is provided, the data is set as a flag on the target. - * - * This method need only be run once, when the document is first created and its data must be written to server storage. - * External functions can synchronously check the status of initialization via the isInitPromiseResolved property, while - * asynchronous functions can await the initPromise property. - * - * TargetLink documents whose data already exists in server storage can be constructed directly (i.e. new BladesTargetLink(data)) - * without needing to call this method. - * - * @param {BladesTargetLink.Data & Schema} data - The combined data object containing both the target link data and the schema data. - * @returns {Promise} - A promise that resolves when the server update is complete. - */ - async initTargetLink() { - this.isInitPromiseResolved = false; - const data = { - ...this.linkData, - ...this.initialSchema - }; - this.initPromise = new Promise((resolve, reject) => { - if (this.targetKeyPrefix) { - const updateData = mergeObject( - getProperty(this.target, this.targetKeyPrefix) ?? {}, - data - ); - this.target.update({ [this.targetKeyPrefix]: updateData }, { render: false }).then(() => { - this.isInitPromiseResolved = true; - resolve(); - }).catch(reject); - } else if (this.targetFlagKeyPrefix) { - const updateData = mergeObject( - this.target.getFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix) ?? {}, - data - ); - this.target.setFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix, updateData).then(() => { - this.isInitPromiseResolved = true; - resolve(); - }).catch(reject); + if (target) { + await inst.document.update({ [target]: elem.value }); + } else if (flagTarget) { + if (elem.value === "") { + await inst.document.unsetFlag(C.SYSTEM_ID, flagTarget); } else { - reject(); + await inst.document.setFlag(C.SYSTEM_ID, flagTarget, elem.value); } - }); - return this.initPromise; - } - async updateTarget(propOrData, valOrWaitFor, waitFor2) { - if (typeof propOrData === "string") { - if (getProperty(this.data, propOrData) === valOrWaitFor) { - return; + } + }, + onSelectChange: async (inst, event) => { + const elem = event.currentTarget; + const { action, dtype, target, flagTarget } = elem.dataset; + if (!action) { + throw new Error("Select elements require a data-action attribute."); + } + if (!target && !flagTarget) { + throw new Error("Select elements require a 'data-target' or 'data-flag-target' attribute."); + } + const dataType = lCase(dtype); + let value; + switch (dataType) { + case "number": + value = pFloat(elem.value); + break; + case "boolean": + value = lCase(`${elem.value}`) === "true"; + break; + case "string": + value = `${elem.value}`; + break; + default: { + if (isNumString(value)) { + throw new Error(`You must set 'data-dtype="Number"' for elements with boolean values.`); + } + value = `${elem.value}`; + break; } - return __privateMethod(this, _updateTargetPropVal, updateTargetPropVal_fn).call(this, propOrData, valOrWaitFor, waitFor2); } - if (typeof propOrData === "object") { - return __privateMethod(this, _updateTargetViaMerge, updateTargetViaMerge_fn).call(this, propOrData, valOrWaitFor); - } else { - throw new Error(`[BladesTargetLink.updateTarget()] Bad updateData for id '${this.id}': ${propOrData}`); + if (target) { + await inst.document.update({ [target]: value }); + } else if (flagTarget) { + if (elem.value === "") { + await inst.document.unsetFlag(C.SYSTEM_ID, flagTarget); + } else { + await inst.document.setFlag(C.SYSTEM_ID, flagTarget, value); + } } } - async updateTargetData(val, waitFor2) { - if (val) { - val = { - ...val, - ...this.linkData - }; - } - await U.waitFor([this.initPromise, waitFor2]); - if (this.targetFlagKeyPrefix) { - await this.updateTargetFlag(void 0, val); - } else { - await this.updateTargetKey(void 0, val); +}; +const isDocID = (ref) => { + return typeof ref === "string" && /^[A-Za-z0-9]{16}$/.test(ref); +}; +const isDocUUID = (ref) => { + if (typeof ref !== "string") { + return false; + } + const [docName, docID] = ref.split(/\./); + if (!isDocID(docID)) { + return false; + } + return game.collections.has(docName); +}; +const isDotKey = (ref) => { + return typeof ref === "string"; +}; +const isTargetKey = (ref) => { + if (!isDotKey(ref)) { + return false; + } + if (["name", "img", "id", "_id"].includes(ref)) { + return true; + } + if (ref.startsWith("system")) { + return true; + } + if (ref.startsWith("flag")) { + return true; + } + return false; +}; +const isTargetFlagKey = (ref) => { + if (!isDotKey(ref)) { + return false; + } + if (isTargetKey(ref)) { + return false; + } + return true; +}; +const parseDocRefToUUID = (ref) => { + var _a; + if (isDocUUID(ref)) { + return ref; + } else if (isDocID(ref)) { + const doc = (_a = game.collections.find((collection) => collection.has(ref))) == null ? void 0 : _a.get(ref); + if (doc && "uuid" in doc) { + return doc.uuid; } + throw new Error(`[U.parseDocRefToUUID] Unable to find document with id '${ref}'`); + } else if (ref && typeof ref === "object" && "uuid" in ref && typeof ref.uuid === "string") { + return ref.uuid; } - async delete(collection, waitFor2) { - if (collection) { - collection.delete(this.id); + throw new Error(`[U.parseDocRefToUUID] Unrecognized reference: '${ref}'`); +}; +const loc = (locRef, formatDict = {}) => { + if (/[a-z]/.test(locRef)) { + locRef = locRef.replace(new RegExp(`^(${C.SYSTEM_ID}.)*`), `${C.SYSTEM_ID}.`); + } + if (typeof game.i18n.localize(locRef) === "string") { + for (const [key, val] of Object.entries(formatDict)) { + formatDict[key] = loc(val); } - await U.waitFor([this.initPromise, waitFor2]); - await this.updateTargetData(null); + return game.i18n.format(locRef, formatDict) || game.i18n.localize(locRef) || locRef; } - // #endregion + return locRef; +}; +const getSetting = (setting) => { + if (game.settings.settings.has(`${C.SYSTEM_ID}.${setting}`)) { + return game.settings.get(C.SYSTEM_ID, setting); + } + return void 0; +}; +function getTemplatePath(subFolder, fileName) { + if (typeof fileName === "string") { + return `${C.TEMPLATE_ROOT}/${subFolder}/${fileName.replace(/\..*$/, "")}.hbs`; + } + return fileName.map((fName) => getTemplatePath(subFolder, fName)); +} +function displayImageSelector(callback, pathRoot = `systems/${C.SYSTEM_ID}/assets`, position = { top: 200, left: 200 }) { + const fp = new FilePicker({ + type: "image", + activeSource: "public", + displayMode: "tiles", + callback, + top: position.top ?? 200 + 40, + left: position.left ?? 200 + 10 + }); + return fp.browse(pathRoot); +} +const U = { + // ████████ GETTERS: Basic Data Lookup & Retrieval ████████ + GMID, + getUID, + // ████████ TYPES: Type Checking, Validation, Conversion, Casting ████████ + isNumber, + isNumString, + isBooleanString, + isSimpleObj, + isList, + isArray, + isFunc, + isInt, + isFloat, + isPosInt, + isIterable, + isHTMLCode, + isRGBColor, + isHexColor, + isUndefined, + isDefined, + isEmpty, + hasItems, + isInstance, + isNullish, + areEqual, + areFuzzyEqual, + pFloat, + pInt, + pBool, + radToDeg, + degToRad, + getKey, + assertNonNullType, + FILTERS, + // ████████ REGEXP: Regular Expressions, Replacing, Matching ████████ + testRegExp, + regExtract, + // ████████ STRINGS: String Parsing, Manipulation, Conversion ████████ + // ░░░░░░░ Case Conversion ░░░░░░░ + uCase, + lCase, + sCase, + tCase, + // ░░░░░░░ Formatting ░░░░░░░ + /* hyphenate, */ + unhyphenate, + pluralize, + oxfordize, + ellipsize, + pad, + toKey, + parseArticles, + signNum, + padNum, + stringifyNum, + verbalizeNum, + ordinalizeNum, + romanizeNum, + // ░░░░░░░ Content ░░░░░░░ + loremIpsum, + randString, + randWord, + // ████████ SEARCHING: Searching Various Data Types w/ Fuzzy Matching ████████ + fuzzyMatch, + isIn, + isInExact, + // ████████ NUMBERS: Number Casting, Mathematics, Conversion ████████ + randNum, + randInt, + coinFlip, + cycleNum, + cycleAngle, + roundNum, + clampNum, + sum, + average, + // ░░░░░░░ Positioning ░░░░░░░ + getDistance, + getAngle, + getAngleDelta, + getBoundingRectangle, + // ████████ ARRAYS: Array Manipulation ████████ + randElem, + randIndex, + makeIntRange, + makeCycler, + unique, + group, + sample, + getLast, + removeFirst, + pullElement, + pullIndex, + subGroup, + shuffle: shuffle2, + toArray: toArray2, + // ████████ OBJECTS: Manipulation of Simple Key/Val Objects ████████ + remove, + replace, + partition, + zip, + objClean, + objSize, + objMap, + objFindKey, + objFilter, + objForEach, + objCompact, + objClone, + objMerge, + objDiff, + objExpand, + objFlatten, + objNullify, + objFreezeProps, + // ████████ FUNCTIONS: Function Wrapping, Queuing, Manipulation ████████ + getDynamicFunc, + withLog, + // ████████ HTML: Parsing HTML Code, Manipulating DOM Objects ████████ + getSvgCode, + changeContainer, + adjustTextContainerAspectRatio, + getRawCirclePath, + drawCirclePath, + getColorVals, + getRGBString, + getHEXString, + getContrastingColor, + getRandomColor, + getSiblings, + escapeHTML, + // ████████ PERFORMANCE: Performance Testing & Metrics ████████ + testFuncPerformance, + // ░░░░░░░ GreenSock ░░░░░░░ + gsap: gsapWithCSS, + get, + set, + getGSAngleDelta, + getNearestLabel, + reverseRepeatingTimeline, + /* to, from, fromTo, */ + /* TextPlugin, Flip, */ + MotionPathPlugin, + // ████████ ASYNC: Async Functions, Asynchronous Flow Control ████████ + sleep, + waitFor, + // EVENT HANDLERS + EventHandlers, + // ░░░░░░░ SYSTEM: System-Specific Functions (Requires Configuration of System ID in constants.js) ░░░░░░░ + isDocID, + isDocUUID, + isDotKey, + isTargetKey, + isTargetFlagKey, + parseDocRefToUUID, + loc, + getSetting, + getTemplatePath, + displayImageSelector }; -_ParseChildLinkData = new WeakSet(); -ParseChildLinkData_fn = function(childData, parentLinkData) { - if (!parentLinkData) { - return childData; - } - const keyPrefixParts = "targetKey" in parentLinkData ? [parentLinkData.targetKey] : [parentLinkData.targetFlagKey]; - if (parentLinkData.isScopingById) { - keyPrefixParts.push(parentLinkData.id); - } - const keyPrefix = keyPrefixParts.join("."); - if ("targetKey" in childData && "targetKey" in parentLinkData) { - if (childData.targetKey.startsWith(`${keyPrefix}.`)) { - childData.targetKey = childData.targetKey.slice(keyPrefix.length + 1); - } - childData.targetKey = [ - parentLinkData.targetKey, - parentLinkData.isScopingById ? parentLinkData.id : void 0, - childData.targetKey - ].filter(Boolean).join("."); - } else if ("targetFlagKey" in childData && "targetFlagKey" in parentLinkData) { - if (childData.targetFlagKey.startsWith(`${keyPrefix}.`)) { - childData.targetFlagKey = childData.targetFlagKey.slice(keyPrefix.length + 1); +const registerSettings = function() { + game.settings.register("eunos-blades", "debug", { + name: "Debug Level", + hint: "The verbosity of the debug messages to console.", + scope: "client", + // This specifies a world-level setting + config: true, + // This specifies that the setting appears in the configuration view + type: Number, + range: { + // If range is specified, the resulting setting will be a range slider + min: 0, + max: 5, + step: 1 + }, + default: 3 + // The default value for the setting + }); + game.settings.register("eunos-blades", "debugHooks", { + name: "Debug HOOKS", + hint: "Whether all Hooks are logged to the console.", + scope: "client", + config: true, + type: Boolean, + default: false + }); + game.settings.register("eunos-blades", "openAPIModelLevel", { + name: "AI Base Quality", + hint: "Lower values are cheaper to run, at the cost of quality.", + scope: "client", + // This specifies a world-level setting + config: true, + // This specifies that the setting appears in the configuration view + type: Number, + range: { + // If range is specified, the resulting setting will be a range slider + min: 0, + max: 2, + step: 1 } - childData.targetFlagKey = [ - parentLinkData.targetFlagKey, - parentLinkData.isScopingById ? parentLinkData.id : void 0, - childData.targetFlagKey - ].filter(Boolean).join("."); - } else { - throw new Error("[BladesTargetLink.ParseChildLinkData] targetKey/targetFlagKey mismatch between provided partialConfig and parentLinkData."); - } - return childData; -}; -_ParseConfigToData = new WeakSet(); -ParseConfigToData_fn = function(config, parentLinkData) { - if (this.IsValidData(config)) { - return this.ParseConfigToData(config, parentLinkData); - } - const { linkConfig, partialSchema } = this.PartitionSchemaData(config); - const fullConfig = this.BuildLinkConfig(linkConfig); - if ("targetKey" in fullConfig) { - return this.ParseConfigToData({ - id: randomID(), - ...partialSchema, - targetID: U.parseDocRefToUUID("target" in fullConfig ? fullConfig.target : fullConfig.targetID), - targetKey: fullConfig.targetKey - }, parentLinkData); - } - return this.ParseConfigToData({ - id: randomID(), - ...partialSchema, - targetID: U.parseDocRefToUUID("target" in fullConfig ? fullConfig.target : fullConfig.targetID), - targetFlagKey: fullConfig.targetFlagKey - }, parentLinkData); -}; -_updateTargetViaMerge = new WeakSet(); -updateTargetViaMerge_fn = async function(updateData, waitFor2) { - await U.waitFor(waitFor2); - if (this.targetKeyPrefix) { - updateData = U.objMap(updateData, false, (key) => `${this.targetKeyPrefix || this.targetFlagKeyPrefix}.${key}`); - return this.target.update(updateData, { render: false }); - } else if (this.targetFlagKeyPrefix) { - const existingFlagData = this.target.getFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix) ?? {}; - const flattenedFlagData = flattenObject(existingFlagData); - const mergedFlagData = mergeObject(flattenedFlagData, updateData); - return this.target.setFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix, mergedFlagData); - } else { - throw new Error(`[BladesTargetLink.#updateTargetViaMerge] Unable to update target data for BladesTargetLink id '${this.id}': Missing both 'targetKeyPrefix' and 'targetFlagKeyPrefix'`); - } -}; -_updateTargetPropVal = new WeakSet(); -updateTargetPropVal_fn = async function(prop, val, waitFor2) { - await U.waitFor(waitFor2); - if (this.targetKeyPrefix) { - return this.target.update({ [`${this.targetKeyPrefix}.${prop}`]: val }); - } else if (this.targetFlagKeyPrefix) { - return this.updateTargetFlag(prop, val); - } + }); + game.settings.register("eunos-blades", "blacklist", { + name: "Debug Blacklist", + hint: "Comma-delimited list of categories of debug messages to silence.", + scope: "client", + // This specifies a world-level setting + config: true, + // This specifies that the setting appears in the configuration view + type: String, + default: "" + // The default value for the setting + }); + game.settings.register("eunos-blades", "openAPIKey", { + name: "OpenAI API Key", + hint: "Your personal OpenAI API Key (necessary to enable AI functionality)", + scope: "client", + // This specifies a world-level setting + config: true, + // This specifies that the setting appears in the configuration view + type: String, + default: "" + // The default value for the setting + }); + game.settings.register("eunos-blades", "whitelist", { + name: "Debug Whitelist", + hint: "Comma-delimited list of categories of debug messages to promote.", + scope: "client", + // This specifies a world-level setting + config: true, + // This specifies that the setting appears in the configuration view + type: String, + default: "" + // The default value for the setting + }); + game.settings.register("eunos-blades", "systemMigrationVersion", { + name: "System Migration Version", + scope: "world", + config: false, + type: Number, + default: 0 + }); }; -__privateAdd(_BladesTargetLink, _ParseChildLinkData); -/** - * This private static method is used to transform a configuration object into a data object for BladesTargetLink. - * It checks if the provided configuration object is already valid data, and if so, returns it directly. - * Otherwise, it partitions the configuration object into link-specific configuration and additional schema data, - * constructs a full link configuration, and then creates a data object with a new random ID and the target UUID. - * The method ensures that either 'targetKey' or 'targetFlagKey' is present and throws an error if the configuration is invalid. - * - * @template Schema - The additional schema data required by the subclass. - * @param {BladesTargetLink.Config | BladesTargetLink.Data & Partial} config - The configuration object that may contain BladesTargetLink properties and any subclass-specific schema data. - * @returns {BladesTargetLink.Data & Partial} - The fully constructed data object with necessary properties for BladesTargetLink. - * @throws {Error} - Throws an error if the configuration object is invalid, lacks a target reference, or if both 'targetKey' and 'targetFlagKey' are provided. - */ -__privateAdd(_BladesTargetLink, _ParseConfigToData); -let BladesTargetLink = _BladesTargetLink; -function isElemPosData(obj) { - return U.isList(obj) && typeof obj.x === "number" && typeof obj.y === "number" && typeof obj.width === "number" && typeof obj.height === "number"; -} -class BladesClockKey extends BladesTargetLink { - constructor(dataOrConfig) { - super(dataOrConfig); - __publicField(this, "positionDragger"); - game.eunoblades.ClockKeys.set(this.id, this); - Object.values(dataOrConfig.clocksData ?? {}).forEach((clockData) => new BladesClock(clockData)); - } - // #region STATIC METHODS ~ - static Initialize() { - function registerClockKeys(doc) { - if ("clocksData" in doc.system) { - Object.values(doc.system.clocksData ?? {}).forEach((keyData) => { - try { - new BladesClockKey(keyData); - } catch (err) { - eLog.error("BladesClockKey", "[BladesClockKey.Initialize] Error initializing clock key.", err, keyData); - } - }); - } +function initTinyMCEStyles() { + CONFIG.TinyMCE = { + ...CONFIG.TinyMCE, + ...{ + skin: "skin", + skin_url: "systems/eunos-blades/tinymce/skin", + content_css: `systems/eunos-blades/tinymce/content.css?${(/* @__PURE__ */ new Date()).getTime()}`, + font_css: "systems/eunos-blades/fonts.css", + max_height: 500, + min_height: 40, + autoresize_overflow_padding: 0, + autoresize_bottom_margin: 0, + // 25, + menubar: false, + statusbar: false, + // True, + elementPath: true, + branding: false, + resize: false, + plugins: "lists image table code save autoresize searchreplace quickbars template", + save_enablewhendirty: false, + // Table_default_styles: {}, + style_formats: [ + { + title: "Headings", + items: [ + { title: "Heading 1", block: "h1", wrapper: false }, + { title: "Heading 2", block: "h2", wrapper: false }, + { title: "Heading 3", block: "h3", wrapper: false }, + { title: "Heading 4", block: "h4", wrapper: false } + ] + }, + { + title: "Blocks", + items: [ + { title: "Paragraph", block: "p", wrapper: false }, + { title: "Block Quote", block: "blockquote", wrapper: true } + // {title: "Secret", block: "span", classes: "text-secret", attributes: {"data-is-secret": "true"}, wrapper: false} + ] + }, + { + title: "Inline", + items: [ + { title: "Bold", inline: "b", wrapper: false }, + { title: "Italics", inline: "i", wrapper: false }, + { title: "Underline", inline: "u", wrapper: false }, + { title: "Secret", inline: "span", classes: "text-secret", attributes: { "data-is-secret": "true" }, wrapper: false } + ] + } + ], + style_formats_merge: false, + toolbar: "styles | searchreplace | formatting alignment lists elements | removeformat | code | save", + toolbar_groups: { + formatting: { + icon: "color-picker", + tooltip: "Formatting", + items: "bold italic underline" + }, + alignment: { + icon: "align-left", + tooltip: "Alignment", + items: "alignleft aligncenter alignright alignjustify | outdent indent" + }, + lists: { + icon: "unordered-list", + tooltip: "Lists", + items: "bullist numlist" + }, + elements: { + icon: "duplicate", + tooltip: "Insert Element", + items: "tableinsertdialog image hr | template" + } + }, + toolbar_mode: "floating", + quickbars_link_toolbar: false, + quickbars_selection_toolbar: "styles | bold italic underline", + quickbars_insert_toolbar: "hr image table", + quickbars_table_toolbar: "tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol" } - game.items.contents.filter( - (item) => BladesItem$1.IsType( - item, - BladesItemType.clock_keeper, - BladesItemType.project, - BladesItemType.cohort_gang, - BladesItemType.cohort_expert, - BladesItemType.ritual, - BladesItemType.design, - BladesItemType.location, - BladesItemType.score - ) - ).forEach(registerClockKeys); - game.actors.contents.filter( - (actor) => BladesActor$1.IsType( - actor, - BladesActorType.pc, - BladesActorType.faction - ) - ).forEach(registerClockKeys); - return loadTemplates([ - "systems/eunos-blades/templates/components/clock-key.hbs", - "systems/eunos-blades/templates/components/clock.hbs" - ]); - } - static ApplySchemaDefaults(schemaData) { - return { - name: "", - isVisible: false, - isNameVisible: false, - isSpotlit: false, - clocksData: {}, - sceneIDs: [], - displayMode: ClockKeyDisplayMode.full, - oneKeyIndex: U.gsap.utils.random(0, 4, 1), - ...schemaData + }; +} +function initCanvasStyles() { + CONFIG.canvasTextStyle = new PIXI.TextStyle({ + align: "center", + dropShadow: true, + dropShadowAngle: U.degToRad(45), + dropShadowBlur: 8, + dropShadowColor: C.Colors.BLACK, + dropShadowDistance: 4, + fill: [ + C.Colors.bWHITE, + C.Colors.bGREY + ], + fillGradientType: 1, + fillGradientStops: [ + 0, + 0.3 + ], + fontFamily: "Kirsty", + fontSize: 32, + letterSpacing: 2, + lineHeight: 32, + lineJoin: "round", + padding: 4, + stroke: C.Colors.dBLACK, + strokeThickness: 3, + trim: true, + whiteSpace: "normal", + wordWrap: true, + wordWrapWidth: 0.1 + }); +} +function initDOMStyles() { + $("body.vtt.game.system-eunos-blades").append(`
`); + $("#interface").append(`
+
`); +} +async function preloadHandlebarsTemplates() { + const templatePaths = [ + // General Components + "systems/eunos-blades/templates/components/toggle-icon.hbs", + "systems/eunos-blades/templates/components/button-icon.hbs", + "systems/eunos-blades/templates/components/dotline.hbs", + "systems/eunos-blades/templates/components/armor.hbs", + "systems/eunos-blades/templates/components/comp.hbs", + "systems/eunos-blades/templates/components/select.hbs", + "systems/eunos-blades/templates/components/portrait.hbs", + "systems/eunos-blades/templates/components/clock.hbs", + "systems/eunos-blades/templates/components/roll-collab-mod.hbs", + "systems/eunos-blades/templates/components/slide-out-controls.hbs", + "systems/eunos-blades/templates/components/consequence.hbs", + "systems/eunos-blades/templates/components/consequence-accepted.hbs", + // Partials + "systems/eunos-blades/templates/parts/tier-block.hbs", + "systems/eunos-blades/templates/parts/turf-list.hbs", + "systems/eunos-blades/templates/parts/cohort-block.hbs", + "systems/eunos-blades/templates/parts/roll-opposition-creator.hbs", + "systems/eunos-blades/templates/parts/active-effects.hbs", + "systems/eunos-blades/templates/parts/gm-pc-summary.hbs", + "systems/eunos-blades/templates/components/clock-key.hbs" + ]; + return loadTemplates(templatePaths); +} +const handlebarHelpers = { + randString(param1 = 10) { + return U.randString(param1); + }, + test(param1, operator, param2) { + const stringMap = { + true: true, + false: false, + null: null, + undefined: void 0 }; - } - static async Create(config, _parentLinkData, clocksInitialData = []) { - if (clocksInitialData.length > 6) { - eLog.error("BladesClockKey", "[BladesClockKey.Create] Too many clock configs! (Max 6.) Eliminating extras.", clocksInitialData); - clocksInitialData = clocksInitialData.slice(0, 6); - } else if (clocksInitialData.length === 0) { - clocksInitialData.push({}); + if (["!", "not", "=??"].includes(String(param1))) { + [operator, param1] = [String(param1), operator]; } - const tempLink = new BladesTargetLink(config); - if (tempLink.targetKeyPrefix) { - config.clocksData = Object.fromEntries( - clocksInitialData.map((cSchema, i) => { - const cData = BladesClock.ParseConfigToData({ - ...BladesClock.ApplySchemaDefaults(cSchema), - index: i, - targetID: tempLink.targetID, - targetKey: `${tempLink.targetKeyPrefix}.clocksData`, - isScopingById: true - }); - return [ - cData.id, - cData - ]; - }) - ); - } else if (tempLink.targetFlagKeyPrefix) { - config.clocksData = Object.fromEntries( - clocksInitialData.map((cSchema, i) => { - const cData = BladesClock.ParseConfigToData({ - ...BladesClock.ApplySchemaDefaults(cSchema), - targetID: tempLink.targetID, - targetFlagKey: `${tempLink.targetFlagKeyPrefix}.clocksData`, - isScopingById: true - }); - return [ - cData.id, - cData - ]; - }) - ); - } else { - throw new Error("BladesClockKey.Create: No targetKey or targetFlagKey provided."); + if (typeof param1 === "string" && param1 in stringMap) { + param1 = stringMap[param1]; } - const clockKeyLink = await super.Create(tempLink.data); - const clockKey = new BladesClockKey(clockKeyLink.data); - clockKey.renderTargetAndKeeper(); - return clockKey; - } - static GetFromElement(elem) { - const keyElem$ = $(elem).closest(".clock-key-container").find(".clock-key"); - if (keyElem$.length === 0) { - return void 0; + if (typeof param2 === "string" && param2 in stringMap) { + param2 = stringMap[param2]; } - const clockKeyID = keyElem$.attr("id"); - if (!clockKeyID) { - return void 0; + switch (operator) { + case "!": + case "not": { + return !param1; + } + case "=??": { + return [void 0, null].includes(param1); + } + case "&&": { + return param1 && param2; + } + case "||": { + return param1 || param2; + } + case "==": { + return U.areFuzzyEqual(param1, param2); + } + case "===": { + return param1 === param2; + } + case "!=": + case "!==": { + return param1 !== param2; + } + case ">": { + return typeof param1 === "number" && typeof param2 === "number" && param1 > param2; + } + case "<": { + return typeof param1 === "number" && typeof param2 === "number" && param1 < param2; + } + case ">=": { + return typeof param1 === "number" && typeof param2 === "number" && param1 >= param2; + } + case "<=": { + return typeof param1 === "number" && typeof param2 === "number" && param1 <= param2; + } + case "??": { + return param1 ?? param2; + } + case "includes": { + return Array.isArray(param1) && param1.includes(param2); + } + case "in": { + if (Array.isArray(param2)) { + return param2.includes(param1); + } + if (U.isList(param2) && (typeof param1 === "number" || typeof param1 === "string")) { + return param1 in param2; + } + if (typeof param2 === "string") { + return new RegExp(String(param1), "gu").test(String(param2)); + } + return false; + } + default: { + return false; + } } - return game.eunoblades.ClockKeys.get(clockKeyID); - } - // #endregion - // #region GETTERS & SETTERS ~ - // #region -- Shortcut Schema Getters ~ - get data() { - return this.linkData; - } - get name() { - return this.data.name; - } - set name(val) { - this.updateTarget("name", val).then(() => { - this.renderTargetAndKeeper(); - }); - } - get isVisible() { - return this.data.isVisible; - } - set isVisible(val) { - this.updateTarget("isVisible", U.pBool(val)).then(() => { - this.renderTargetAndKeeper(); - }); - } - get isNameVisible() { - return this.data.isNameVisible; - } - set isNameVisible(val) { - this.updateTarget("isNameVisible", U.pBool(val)).then(() => { - this.renderTargetAndKeeper(); - }); - } - get isSpotlit() { - return this.data.isSpotlit; - } - set isSpotlit(val) { - this.updateTarget("isSpotlit", val).then(() => { - this.renderTargetAndKeeper(); - }); - } - get clocksData() { - return this.data.clocksData; - } - get displayMode() { - return this.data.displayMode; - } - get oneKeyIndex() { - let { oneKeyIndex } = this.data; - if (!oneKeyIndex) { - oneKeyIndex = U.gsap.utils.random(0, 4, 1); - this.updateTarget("oneKeyIndex", oneKeyIndex).then(() => { - this.renderTargetAndKeeper(); - }); + }, + calc(...params) { + const calcs = { + "+": (p1, p2) => U.pInt(p1) + U.pInt(p2), + "-": (p1, p2) => U.pInt(p1) - U.pInt(p2), + "*": (p1, p2) => U.pInt(p1) * U.pInt(p2), + "/": (p1, p2) => U.pInt(p1) / U.pInt(p2), + "%": (p1, p2) => U.pInt(p1) % U.pInt(p2), + max: (p1, p2) => Math.max(U.pInt(p1), U.pInt(p2)), + min: (p1, p2) => Math.min(U.pInt(p1), U.pInt(p2)), + ceil: (p1) => Math.ceil(U.pFloat(p1)), + floor: (p1) => Math.floor(U.pFloat(p1)) + }; + const [param1, operator, param2] = typeof params[0] === "string" && params[0] in calcs ? [params[1], params[0]] : params; + return calcs[operator](param1, param2); + }, + isIn(...args) { + const [testStr, ...contents] = args; + return contents.includes(testStr); + }, + case(mode, str) { + switch (mode) { + case "upper": + return U.uCase(str); + case "lower": + return U.lCase(str); + case "sentence": + return U.sCase(str); + case "title": + return U.tCase(str); + default: + return str; } - return oneKeyIndex; - } - get sceneIDs() { - return this.data.sceneIDs ?? []; - } - get overlayPosition() { - var _a; - return (_a = this.data.overlayPosition) == null ? void 0 : _a[game.scenes.current.id]; - } - set overlayPosition(val) { - if (val) { - this.updateTarget(`overlayPosition.${game.scenes.current.id}`, val).then(() => { - this.renderTargetAndKeeper(); - }); - } else { - this.updateTarget(`overlayPosition.-=${game.scenes.current.id}`, null).then(() => { - this.renderTargetAndKeeper(); - }); + }, + romanize(val) { + return U.romanizeNum(U.pInt(val)); + }, + count(param) { + if (Array.isArray(param) || U.isList(param)) { + return Object.values(param).filter((val) => val !== null && val !== void 0).length; + } else if (typeof param === "string") { + return param.length; } - } - // #endregion - get clocks() { - return new Collection( - Object.entries(this.clocksData).sort((a, b) => a[1].index - b[1].index).map(([id, data]) => { - return [id, new BladesClock(data)]; - }) - ); - } - getClockByID(clockID) { - return this.clocks.get(clockID); - } - getClockByIndex(index) { - return this.clocks.find((clock) => clock.index === index); - } - get size() { - return this.clocks.size; - } - get isComplete() { - return Array.from(this.clocks).every((clock) => clock.isComplete); - } - get isClockKeeperKey() { - return this.target instanceof BladesClockKeeper$1; - } - get isFactionKey() { - return this.target instanceof BladesFaction$1; - } - get isProjectKey() { - return this.target instanceof BladesProject$1; - } - get isScoreKey() { - return this.target instanceof BladesScore$1; - } - get visibleClocks() { - return this.clocks.filter((clock) => clock.isVisible); - } - get activeClocks() { - return this.visibleClocks.filter((clock) => clock.isActive); - } - get inProgressClocks() { - return this.visibleClocks.filter((clock) => !clock.isComplete && clock.value > 0); - } - get unstartedClocks() { - return this.visibleClocks.filter((clock) => clock.value === 0); - } - get completedClocks() { - return this.visibleClocks.filter((clock) => clock.isComplete); - } - get currentClock() { - if (this.activeClocks.length > 0) { - return this.getEarliestClock(this.activeClocks); + return param ? 1 : 0; + }, + // Concat helper + // Usage: (concat 'first 'second') + concat(...args) { + let outStr = ""; + for (const arg of args) { + if (typeof arg === "string" || typeof arg === "number") { + outStr += arg; + } } - if (this.completedClocks.length > 0) { - return this.getLatestClock(this.completedClocks); + return outStr; + }, + // Merge helper - To merge additional properties into a template's context + merge(context3, ...args) { + args.pop(); + return args.reduce((acc, val) => Object.assign(acc, val), context3); + }, + // For loop: {{#for [from = 0, to, stepSize = 1]}}{{/for}} + for: (...args) => { + const options = args.pop(); + let [from, to, stepSize] = args; + from = U.pInt(from); + to = U.pInt(to); + stepSize = U.pInt(stepSize) || 1; + if (from > to) { + return ""; } - if (this.visibleClocks.length > 0) { - return this.getEarliestClock(this.visibleClocks); + let html = ""; + for (let i = parseInt(from || 0, 10); i <= parseInt(to || 0, 10); i += stepSize) { + html += options.fn(i); } - return this.getEarliestClock(Array.from(this.clocks)); - } - get fullDisplayPosData() { - const x = this.svgData.width / 2; - const y = this.svgData.height / 2; - return { - x, - y, - width: this.svgData.width, - height: this.svgData.height - }; - } - get clocksDisplayPosData() { - return this.getClocksBoundingBox(Array.from(this.clocks)); - } - get visibleClocksDisplayPosData() { - return this.getClocksBoundingBox(this.visibleClocks); - } - get activeClocksDisplayPosData() { - return this.getClocksBoundingBox(this.activeClocks); - } - getClocksBoundingBox(clocks) { - const { size, ...allClocksPosData } = this.svgData.clocks; - const clocksPosData = Object.fromEntries( - Object.entries(allClocksPosData).filter(([index]) => clocks.map((clock) => clock.index).includes(U.pInt(index))).map(([index, posData]) => [U.pInt(index), posData]) - ); - const clockWidthPosData = Object.values(clocksPosData).sort((a, b) => a.x - b.x); - const clockHeightPosData = Object.values(clocksPosData).sort((a, b) => a.y - b.y); - const xLowest = clockWidthPosData[0].x; - const xHighest = clockWidthPosData[clockWidthPosData.length - 1].x; - const yLowest = clockHeightPosData[0].y; - const yHighest = clockHeightPosData[clockHeightPosData.length - 1].y; - return { - // Determine the center point in both x and y axes - x: (xLowest + xHighest) / 2, - y: (yLowest + yHighest) / 2, - // Determine height and width of bounding box, accounting for clock size - width: xHighest - xLowest + size, - height: yHighest - yLowest + size + return html; + }, + signNum(num) { + return U.signNum(num); + }, + compileSvg(...args) { + const [svgDotKey, svgPaths] = args; + return U.getSvgCode(svgDotKey, svgPaths); + }, + eLog(...args) { + args.pop(); + let dbLevel = 3; + if ([0, 1, 2, 3, 4, 5].includes(args[0])) { + dbLevel = args.shift(); + } + eLog.hbsLog(...args, dbLevel); + }, + // Does the name of this turf block represent a standard 'Turf' claim? + isTurfBlock: (name) => U.fuzzyMatch(name, "Turf"), + // Which other connection does this connector overlap with? + getConnectorPartner: (index, direction) => { + index = parseInt(`${index}`, 10); + const partners = { + 1: { right: 2, bottom: 6 }, + 2: { left: 1, right: 3, bottom: 7 }, + 3: { left: 2, right: 4, bottom: 8 }, + 4: { left: 3, right: 5, bottom: 9 }, + 5: { left: 4, bottom: 10 }, + 6: { top: 1, right: 7, bottom: 11 }, + 7: { top: 2, left: 6, right: 8, bottom: 12 }, + 8: { top: 3, left: 7, right: 9, bottom: 13 }, + 9: { top: 4, left: 8, right: 10, bottom: 14 }, + 10: { top: 5, left: 9, bottom: 15 }, + 11: { top: 6, right: 12 }, + 12: { top: 7, left: 11, right: 13 }, + 13: { top: 8, left: 12, right: 14 }, + 14: { top: 9, left: 13, right: 15 }, + 15: { top: 10, left: 14 } }; - } - /** This function accepts any number of arrays of BladesClock, then returns an array - * containing those BladesClock instances that appear in ALL provided arrays. - */ - getClocksIn(...clockArrays) { - if (clockArrays.length === 0) - return []; - return clockArrays.reduce((acc, currentArray) => { - return acc.filter((clock) => currentArray.includes(clock)); + const partnerDir = { left: "right", right: "left", top: "bottom", bottom: "top" }[direction]; + const partnerNum = partners[index][direction] ?? 0; + if (partnerNum) { + return `${partnerNum}-${partnerDir}`; + } + return null; + }, + // Is the value Turf side. + isTurfOnEdge: (index, direction) => { + index = parseInt(`${index}`, 10); + const edges = { + 1: ["top", "left"], + 2: ["top"], + 3: ["top"], + 4: ["top"], + 5: ["top", "right"], + 6: ["left"], + 7: [], + 8: [], + 9: [], + 10: ["right"], + 11: ["left", "bottom"], + 12: ["bottom"], + 13: ["bottom"], + 14: ["bottom"], + 15: ["right", "bottom"] + }; + if (!(index in edges)) { + return true; + } + return edges[index].includes(direction); + }, + // Multiboxes + multiboxes(selected, options) { + let html = options.fn(this); + selected = [selected].flat(1); + selected.forEach((selectedVal) => { + if (selectedVal !== false) { + const escapedValue = RegExp.escape(Handlebars.escapeExpression(String(selectedVal))); + const rgx = new RegExp(` value="${escapedValue}"`); + html = html.replace(rgx, '$& checked="checked"'); + } }); - } - /** This function accepts an array of BladesClock, and returns the BladesClock - * instance with the lowest index property. - */ - getEarliestClock(clockArray) { - if (clockArray.length) { - return clockArray.sort((a, b) => a.index - b.index)[0]; + return html; + }, + repturf: (turfsAmount, options) => { + let html = options.fn(void 0); + let turfsAmountInt = parseInt(turfsAmount, 10); + if (turfsAmountInt > 6) { + turfsAmountInt = 6; } - return void 0; + for (let i = 13 - turfsAmountInt; i <= 12; i++) { + const rgx = new RegExp(` value="${i}"`); + html = html.replace(rgx, '$& disabled="disabled"'); + } + return html; } - /** This function accepts an array of BladesClock, and returns the BladesClock - * instance with the highest index property. - */ - getLatestClock(clockArray) { - if (clockArray.length) { - return clockArray.sort((a, b) => b.index - a.index)[0]; +}; +handlebarHelpers.eLog1 = function(...args) { + handlebarHelpers.eLog(...[1, ...args.slice(0, 7)]); +}; +handlebarHelpers.eLog2 = function(...args) { + handlebarHelpers.eLog(...[2, ...args.slice(0, 7)]); +}; +handlebarHelpers.eLog3 = function(...args) { + handlebarHelpers.eLog(...[3, ...args.slice(0, 7)]); +}; +handlebarHelpers.eLog4 = function(...args) { + handlebarHelpers.eLog(...[4, ...args.slice(0, 7)]); +}; +handlebarHelpers.eLog5 = function(...args) { + handlebarHelpers.eLog(...[5, ...args.slice(0, 7)]); +}; +Object.assign(handlebarHelpers); +function registerHandlebarHelpers() { + Object.entries(handlebarHelpers).forEach(([name, func]) => Handlebars.registerHelper(name, func)); +} +const gsapPlugins = [ + TextPlugin, + Flip, + MotionPathPlugin, + Draggable, + // SplitText, + Observer$1, + CustomEase + // CustomWiggle, + // CustomBounce, + // EasePack +]; +const gsapEffects = { + // #region CLOCK KEYS + keyDrop: { + effect: (clockKey, config3) => { + const [keyContainer] = $(clockKey).closest(".clock-key-container"); + return U.gsap.timeline({ + onComplete() { + if (config3.callback) { + config3.callback(); + } + } + }).fromTo(keyContainer, { + y: config3.yShift + }, { + y: 0, + autoAlpha: 1, + ease: "bounce", + duration: config3.duration + }); + }, + defaults: { + duration: 1, + yShift: -800 + }, + extendTimeline: true + }, + keyPull: { + effect: (clockKey, config3) => { + const [keyContainer] = $(clockKey).closest(".clock-key-container"); + return U.gsap.timeline({ + onComplete() { + if (config3.callback) { + config3.callback(); + } + } + }).to(keyContainer, { + y: config3.yDelta, + ease: config3.ease, + duration: 0.75 * config3.duration + }).to(keyContainer, { + opacity: 0, + ease: "power2.out", + duration: 0.25 * config3.duration + }, 0.75 * config3.duration); + }, + defaults: { + yDelta: -800, + duration: 1, + ease: "back.in(1)" + }, + extendTimeline: true + }, + keyControlPanelFlip: { + effect: (target, config3) => { + return U.gsap.timeline({ + delay: config3.delay, + onStart() { + if (target) { + const target$ = $(target); + const nextSibling$ = target$.next(".clock-control-flipper"); + if (nextSibling$.length) { + U.gsap.effects.keyControlPanelFlip(nextSibling$[0], { + ...config3, + delay: 0.15 + }); + } + } + } + }).to(target, { + rotateX: config3.angle, + duration: 0.5, + ease: "back.inOut(2)" + }); + }, + defaults: { + angle: 180, + delay: 0 + }, + extendTimeline: true + }, + // #endregion + // #region CHAT CONSEQUENCE EFFECTS + csqEnter: { + effect: (csqContainer, config3) => { + const csqRoot = U.gsap.utils.selector(csqContainer); + const csqIconCircle = csqRoot(".consequence-icon-circle.base-consequence"); + const csqBaseTypeElem = csqRoot(".consequence-type.base-consequence"); + const csqAcceptTypeElem = csqRoot(".consequence-type.accept-consequence"); + const csqBaseNameElem = csqRoot(".consequence-name.base-consequence"); + const csqAcceptNameElem = csqRoot(".consequence-name.accept-consequence"); + const tl = U.gsap.timeline({ paused: true, defaults: {} }); + if (csqAcceptTypeElem.length > 0) { + tl.set(csqAcceptTypeElem, { opacity: 0 }, 0); + } + if (csqAcceptNameElem.length > 0) { + tl.set(csqAcceptNameElem, { opacity: 0 }, 0); + } + if (csqBaseTypeElem.length > 0) { + tl.fromTo(csqBaseTypeElem, { + opacity: 1 + }, { + opacity: 0, + duration: 0.25, + ease: "sine" + }, 0); + } + if (csqAcceptTypeElem.length > 0) { + tl.fromTo(csqAcceptTypeElem, { + opacity: 0 + }, { + opacity: 1, + duration: 0.25, + ease: "sine" + }, 0); + } + if (csqBaseNameElem.length > 0) { + tl.fromTo(csqBaseNameElem, { + opacity: 1 + }, { + opacity: 0, + duration: 0.25, + ease: "sine" + }, 0); + } + if (csqAcceptNameElem.length > 0) { + tl.fromTo(csqAcceptNameElem, { + opacity: 0 + }, { + opacity: 1, + duration: 0.25, + ease: "sine" + }, 0); + } + if (csqContainer) { + tl.fromTo(csqContainer, { + filter: "brightness(1)" + }, { + filter: `brightness(${config3.brightness})`, + duration: config3.duration / 3, + ease: "none" + }, 0); + } + if (csqIconCircle.length > 0) { + tl.fromTo(csqIconCircle, { + scale: 0.75, + outlineColor: C.Colors.dBLACK, + outlineWidth: 0 + }, { + scale: 0.85, + outlineColor: C.Colors.GREY, + outlineWidth: 1, + duration: 0.55, + ease: "sine.out" + }, 0); + } + return tl; + }, + defaults: { + brightness: 1.5, + duration: 0.5, + scale: 1.5, + stagger: 0.05, + ease: "sine", + easeStrength: 1.5 } - return void 0; - } - isInScene(sceneID = game.scenes.current.id) { - return this.sceneIDs.includes(sceneID); - } - get isInCurrentScene() { - return this.isInScene(game.scenes.current.id); - } - get displaySelectOptions() { - const options = [ - { value: ClockKeyDisplayMode.full, display: "Full Key" }, - { value: ClockKeyDisplayMode.clocks, display: "Clocks" }, - { value: ClockKeyDisplayMode.activeClocks, display: "Active Clocks" } - ]; - for (let i = 0; i < this.size; i++) { - options.push(...[ - { value: i, display: `Clock #${i}` }, - { value: `present${i}`, display: `Present Clock #${i}` } - ]); + }, + csqClickIcon: { + effect: (csqIconContainer, config3) => { + const csqContainer = $(csqIconContainer).closest(".comp.consequence-display-container"); + const csqRoot = U.gsap.utils.selector(csqContainer[0]); + const iconRoot = U.gsap.utils.selector(csqIconContainer); + const csqBackgroundImg = csqRoot(".consequence-bg-image"); + const csqInteractionPads = csqRoot(".consequence-interaction-pad"); + const csqIconCircleBase = iconRoot(".consequence-icon-circle.base-consequence"); + const csqIconCircleAccept = iconRoot(".consequence-icon-circle.accept-consequence"); + const csqButtonContainers = iconRoot(".consequence-button-container"); + const tl = U.gsap.timeline({ + paused: true, + onComplete: function() { + $(csqInteractionPads).css("pointerEvents", "auto"); + }, + onReverseComplete: function() { + $(csqInteractionPads).css("pointerEvents", "none"); + } + }); + if (csqBackgroundImg.length) { + tl.fromTo(csqBackgroundImg, { + xPercent: 110, + yPercent: -50 + }, { + xPercent: -60, + yPercent: -50, + duration: 0.5, + ease: "back" + }, 0); + } + if (csqIconCircleBase.length > 0) { + tl.fromTo(csqIconCircleBase, { + opacity: 1 + }, { + opacity: 0, + duration: 0.25, + ease: "sine.out" + }, 0); + } + if (csqIconCircleAccept.length > 0) { + tl.fromTo(csqIconCircleAccept, { + opacity: 0 + }, { + opacity: 1, + duration: 0.15, + ease: "sine" + }, 0).fromTo(csqIconCircleAccept, { + outlineWidth: 1, + scale: 0.85 + }, { + outlineWidth: 2, + scale: 1, + duration: 0.25, + ease: "sine" + }, 0.175); + } + if (csqButtonContainers.length > 0) { + tl.fromTo(csqButtonContainers, { + scale: config3.scale, + opacity: 0, + filter: "blur(25px)" + }, { + scale: 1, + opacity: 1, + filter: "blur(0px)", + stagger: config3.stagger, + duration: config3.duration, + ease: `${config3.ease}.inOut(${config3.easeStrength})` + }, 0); + } + return tl; + }, + defaults: { + duration: 0.5, + scale: 1.5, + stagger: 0.05, + ease: "sine", + easeStrength: 1.5 } - return options; - } - // parseClockConfig(config: BladesClock.Config, indexOverride?: ClockIndex): BladesClock.Data { - // if (this.size === 6) {throw new Error("Cannot add a clock to a clock key with 6 clocks.");} - // if (indexOverride !== undefined && indexOverride < 0) {throw new Error("Cannot add a clock with a negative index.");} - // // Remove target so it doesn't conflict with key's targetID - // // delete config.target; - // const {target, targetID, targetKey, targetFlagKey, ...partialSchema} = config; - // const linkData: BladesTargetLink.LinkData = this.targetKey - // ? { - // targetID: this.targetID, - // targetKey: `${this.targetKeyPrefix}.clocksData` as TargetKey - // } - // : { - // targetID: this.targetID, - // targetFlagKey: `${this.targetFlagKeyPrefix}.clocksData` as TargetFlagKey - // }; - // // Derive clock's targetID and targetKey/targetFlagKey from key's values - // data.targetID = this.targetID; - // if (this.targetKey) { - // data.targetKey = `${this.targetKeyPrefix}.clocksData` as TargetKey; - // } else if (this.targetFlagKey) { - // data.targetFlagKey = `${this.targetFlagKeyPrefix}.clocksData` as TargetFlagKey; - // } - // // Assign 'parentKeyID' and 'index' - // config.parentKeyID = this.id; - // config.index = indexOverride ?? this.size; - // // Parse config to full data object - // return BladesClock.ApplySchemaDefaults( - // BladesClock.ParseConfigToData(config as BladesClock.Config) - // ); - // } - // #endregion - // #region HTML INTERACTION ~ - // #region Get Elements$ ~ - getElemFromDisplayContext(displayContext) { - let elem$; - const DOM$ = $(".vtt.game.system-eunos-blades"); - switch (displayContext) { - case ClockDisplayContext.overlay: { - elem$ = DOM$.find(`#blades-overlay #${this.id}`); - break; + }, + csqEnterRight: { + effect: (csqContainer) => { + const csqRoot = U.gsap.utils.selector(csqContainer); + const typeLine = csqRoot(".consequence-type-container .consequence-type.accept-consequence"); + const typeLineBg = csqRoot(".consequence-type-container .consequence-type-bg.accept-consequence"); + const buttonRoot = U.gsap.utils.selector(csqRoot(".consequence-button-container.consequence-accept-button-container")); + const buttonBg = buttonRoot(".consequence-button-bg"); + const buttonIcon = buttonRoot(".button-icon i"); + const buttonLabel = buttonRoot(".consequence-button-label"); + const tl = U.gsap.timeline({ paused: true, defaults: {} }); + if (typeLine.length > 0) { + tl.fromTo( + typeLine, + { + color: C.Colors.RED + }, + { + color: C.Colors.WHITE, + duration: 0.5, + ease: "sine.inOut" + }, + 0 + ); } - case ClockDisplayContext.pcSheet: { - elem$ = DOM$.find(`.actor.sheet .pc #${this.id}`); - break; + if (typeLineBg.length > 0) { + tl.fromTo(typeLineBg, { + x: 5, + scaleX: 0, + color: C.Colors.RED, + skewX: 0 + }, { + scaleX: 1, + skewX: -45, + color: C.Colors.RED, + duration: 0.5, + ease: "back.out" + }, 0); } - case ClockDisplayContext.factionSheet: { - elem$ = DOM$.find(`.actor.sheet .faction #${this.id}`); - break; + if (buttonBg.length > 0) { + tl.fromTo(buttonBg, { + scaleX: 0, + color: C.Colors.RED, + skewX: 0 + }, { + x: 0, + scaleX: 1, + skewX: -45, + color: C.Colors.RED, + duration: 0.25, + ease: "back.out" + }, 0); + } + if (buttonIcon.length > 0) { + tl.fromTo( + buttonIcon, + { + color: C.Colors.GREY, + opacity: 0.75, + scale: 1 + }, + { + color: C.Colors.dBLACK, + scale: 1.25, + opacity: 1, + duration: 0.5, + ease: "sine" + }, + 0 + ); + } + if (buttonLabel.length > 0) { + tl.fromTo( + buttonLabel, + { + color: C.Colors.GREY, + fontWeight: 400, + scale: 1 + }, + { + color: C.Colors.dBLACK, + fontWeight: 800, + duration: 0.75, + ease: "sine" + }, + 0 + ); + } + return tl; + }, + defaults: {} + }, + csqEnterLeft: { + effect: (csqContainer) => { + const csqRoot = U.gsap.utils.selector(csqContainer); + const typeLine = csqRoot(".consequence-type-container .consequence-type.accept-consequence"); + const nameLine = csqRoot(".consequence-name-container .consequence-name.accept-consequence"); + const acceptIconCircle = csqRoot(".consequence-icon-circle.accept-consequence"); + const acceptButton = csqRoot(".consequence-button-container.consequence-accept-button-container"); + const tl = U.gsap.timeline({ paused: true, defaults: {} }); + if (typeLine.length > 0) { + tl.to( + typeLine, + { + opacity: 0, + duration: 0.15, + ease: "sine.inOut" + }, + 0 + ); } - case ClockDisplayContext.projectSheet: { - elem$ = DOM$.find(`.item.sheet .project #${this.id}`); - break; + if (nameLine.length > 0) { + tl.to(nameLine, { + opacity: 0, + duration: 0.15, + ease: "sine.inOut" + }, 0); } - case ClockDisplayContext.scoreSheet: { - elem$ = DOM$.find(`.item.sheet .score #${this.id}`); - break; + if (acceptIconCircle.length > 0) { + tl.to( + acceptIconCircle, + { + opacity: 0, + duration: 0.15, + ease: "sine.inOut" + }, + 0 + ); } - case ClockDisplayContext.rollCollab: { - elem$ = DOM$.find(`.roll-collab-sheet #${this.id}`); - break; + if (acceptButton.length > 0) { + tl.fromTo( + acceptButton, + { + opacity: 1 + }, + { + opacity: 0, + duration: 0.25, + ease: "sine.inOut" + }, + 0 + ); } - case ClockDisplayContext.chatMessage: { - elem$ = DOM$.find(`#chat #${this.id}`); - break; + return tl; + }, + defaults: {} + }, + csqEnterSubLeft: { + effect: (csqContainer, config3) => { + const csqRoot = U.gsap.utils.selector(csqContainer); + const iconCircle = csqRoot(`.consequence-icon-circle.${config3.type}-consequence`); + const typeLine = csqRoot(`.consequence-type-container .consequence-type.${config3.type}-consequence`); + const nameLine = csqRoot(`.consequence-name.${config3.type}-consequence`); + const footerBg = csqRoot(`.consequence-footer-container .consequence-footer-bg.${config3.type}-consequence`); + const specialFooterMsg = csqRoot(`.consequence-footer-container .consequence-footer-message.${config3.type}-consequence`); + const tl = U.gsap.timeline({ paused: true, defaults: {} }); + if (iconCircle.length > 0) { + tl.fromTo(iconCircle, { + opacity: 0 + }, { + opacity: 1, + duration: 0.5, + ease: "back.out" + }, 0); } - } - if (!elem$.length) { - throw new Error(`[BladesClockKey.getElemFromDisplayContext] Error elem$ not found for key '${this.id}' for display context '${displayContext}'.`); - } - return elem$; - } - getElements$(displayContext) { - let elem$; - if (typeof displayContext === "string") { - displayContext = this.getElemFromDisplayContext(displayContext); - } - elem$ = $(displayContext).find(`#${this.id}`); - if (!elem$.length) { - elem$ = $(displayContext).closest(`#${this.id}`); - } - if (!(elem$ == null ? void 0 : elem$.length)) { - throw new Error(`[BladesClockKey.getElements$] Cannot find elements for display context '${displayContext}' of clockKey '${this.id}'.`); - } - const keyElems$ = { - elem$ - }; - if (!elem$.length) { - throw new Error(`[BladesClockKey.renderClockKey] Error '.clock-key-container' not found for key '${this.id}'.`); - } - keyElems$.container$ = elem$.closest(".clock-key-container"); - const imgContainer$ = elem$.find(".key-image-container"); - if (!imgContainer$.length) { - throw new Error(`[BladesClockKey.renderClockKey] Error '.key-image-container' not found for key '${this.id}'.`); - } - keyElems$.imgContainer$ = imgContainer$; - const label$ = elem$.find(".key-label"); - if (!label$.length) { - throw new Error(`[BladesClockKey.renderClockKey] Error label$ not found for key '${this.id}'.`); - } - keyElems$.label$ = label$; - const factionLabel$ = elem$.find(".faction-label"); - if (factionLabel$.length) { - keyElems$.factionLabel$ = factionLabel$; - } - const projectLabel$ = elem$.find(".project-label"); - if (projectLabel$.length) { - keyElems$.projectLabel$ = projectLabel$; - } - const scoreLabel$ = elem$.find(".score-label"); - if (scoreLabel$.length) { - keyElems$.scoreLabel$ = scoreLabel$; - } - this.clocks.forEach((clock) => { - keyElems$.clocks ?? (keyElems$.clocks = {}); - keyElems$.clocks[clock.id] = clock.getElements$(displayContext); - }); - eLog.checkLog3("BladesClockKey", "Clock Key Elements", keyElems$); - return keyElems$; - } - // #endregion - // #region Initial Rendering ~ - async renderTo(parentElem) { - const parent$ = $(parentElem); - if (!parent$.length) { - throw new Error(`[BladesClockKey.renderClockKeyTo] Error parent element not provided for key '${this.id}'.`); - } - const clockKeyHTML = await renderTemplate( - "systems/eunos-blades/templates/components/clock-key.hbs", - this - ); - $(clockKeyHTML).appendTo(parent$); - } - /** - * This function generates a partial GSAP.TweenVars object that will display the key in a given mode within the bounds of a provided container. - * - * @param {ClockKeyDisplayMode | number} [displayMode="full"] - The display mode. Options include: - * - "full" - displays the entire clock key - * - "clocks" - zooms in to display only the clocks - * - "activeClocks" - zooms in to the active clocks - * - "presentN" (where N is a clock index number) - zooms in to the clock at index N, and presents whichever side has the next available segment towards the camera. - * - A clock index number - zooms in to the clock at index N - * - * @param {HTMLElement | JQuery | {x: number, y: number, width: number, height: number}} [container$] - The container within which the key will be displayed. - * This can be: - * - An HTMLElement - * - A JQuery - * - A {x, y, width, height} position definition - * If not provided, it defaults to the clock key's container element (only if the key is already rendered in the DOM). - * - * @returns {gsap.TweenVars} - A partial GSAP.TweenVars object that describes how to display the key in the given mode within the bounds of the provided container. The returned object may include the following properties: - * - 'scale' (number): A multiple to be applied to scale at "full" display mode. - * - 'top' (number): A delta vertical shift from "full" display mode position. - * - 'left' (number): A delta horizontal shift from "full" display mode position. - * - 'transformOrigin': An absolute value. - * - 'rotationZ': An absolute value for the keySwing axis. - * - 'rotationY': An absolute value for rotation in/out of the screen. - * Any variables left undefined default to "full" display mode. - */ - getVarsForDisplayMode(keyElems$, displayMode = ClockKeyDisplayMode.full, container$) { - const keyTweenVars = {}; - const keyImgContTweenVars = {}; - container$ ?? (container$ = keyElems$.container$); - let targetPosData; - if (container$ instanceof HTMLElement || container$ instanceof jQuery) { - const containerPosData = U.gsap.getProperty($(container$)[0]); - targetPosData = { - x: containerPosData("x"), - y: containerPosData("y"), - width: containerPosData("width"), - height: containerPosData("height") - }; - } else if (isElemPosData(container$)) { - targetPosData = container$; - } else { - throw new Error(`[BladesClockKey.getVarsForDisplayMode] Error container$ '${container$}' is not a valid type.`); - } - let presentingClock; - let focusPosData; - switch (displayMode) { - case ClockKeyDisplayMode.full: { - focusPosData = { - x: this.svgData.width / 2, - y: this.svgData.height / 2, - width: this.svgData.width, - height: this.svgData.height - }; - break; + if (typeLine.length > 0) { + tl.fromTo(typeLine, { + opacity: 0 + }, { + opacity: 1, + duration: 0.5, + ease: "back.out" + }, 0); } - case ClockKeyDisplayMode.clocks: { - focusPosData = this.getClocksBoundingBox(Array.from(this.clocks)); - break; + if (nameLine.length > 0) { + tl.fromTo(nameLine, { + scaleX: 0 + }, { + scaleX: 1, + duration: 0.5, + ease: "back.inOut" + }, 0); } - case ClockKeyDisplayMode.activeClocks: { - focusPosData = this.getClocksBoundingBox(this.getClocksIn(this.activeClocks, this.visibleClocks)); - break; + if (footerBg.length > 0) { + tl.fromTo(footerBg, { + scaleX: 0, + skewX: 0, + opacity: 1 + }, { + scaleX: 1, + skewX: -45, + opacity: 1, + duration: 0.5, + ease: "back.inOut" + }, 0); } - case ClockKeyDisplayMode.presentCurrentClock: { - presentingClock = this.currentClock; - displayMode = presentingClock.index; + if (specialFooterMsg.length > 0) { + tl.fromTo(specialFooterMsg, { + scaleX: 0, + opacity: 1 + }, { + scaleX: 1, + opacity: 1, + duration: 0.5, + ease: "back.inOut" + }, 0); } - default: { - if (typeof displayMode === "string" && displayMode.startsWith("present")) { - displayMode = U.pInt(displayMode.toString().slice(7)); - presentingClock = this.getClockByIndex(displayMode); + if (csqRoot(`.consequence-button-container.consequence-${config3.type}-button-container`).length > 0) { + const buttonRoot = U.gsap.utils.selector(csqRoot(`.consequence-button-container.consequence-${config3.type}-button-container`)); + const buttonBg = buttonRoot(".consequence-button-bg"); + const buttonIcon = buttonRoot(".button-icon i"); + const buttonLabel = buttonRoot(".consequence-button-label"); + if (buttonBg.length > 0) { + tl.fromTo(buttonBg, { + scaleX: 0, + skewX: 0, + opacity: 1 + }, { + scaleX: 1, + skewX: -45, + opacity: 1, + duration: 0.5, + ease: "back.inOut" + }, 0); + } + if (buttonIcon.length > 0) { + tl.fromTo( + buttonIcon, + { + color: C.Colors.GREY, + opacity: 0.75, + scale: 1 + }, + { + color: C.Colors.dBLACK, + scale: 1.25, + opacity: 1, + duration: 0.5, + ease: "sine" + }, + 0 + ); } - if (!U.isInt(displayMode) || displayMode < 0 || displayMode >= this.size) { - throw new Error(`[BladesClockKey.getVarsForDisplayMode] Error display mode '${displayMode}' is not a valid clock index for key '${this.id}'.`); + if (buttonLabel.length > 0) { + tl.fromTo( + buttonLabel, + { + color: C.Colors.GREY, + fontWeight: 400, + scale: 1 + }, + { + color: C.Colors.dBLACK, + fontWeight: 800, + duration: 0.75, + ease: "sine" + }, + 0 + ); } - const focusClockData = this.svgData.clocks[displayMode]; - focusPosData = { - x: focusClockData.x, - y: focusClockData.y, - width: this.svgData.clocks.size, - height: this.svgData.clocks.size - }; - break; } - } - keyTweenVars.scale = Math.min( - targetPosData.height / focusPosData.height, - targetPosData.width / focusPosData.width - ); - keyImgContTweenVars.top = 0.5 * C.ClockKeySquareSize - focusPosData.y; - keyImgContTweenVars.left = 0.5 * C.ClockKeySquareSize - focusPosData.x; - keyImgContTweenVars.transformOrigin = `${focusPosData.x}px ${focusPosData.y}px`; - keyImgContTweenVars.rotateY = 0; - if (presentingClock) { - keyTweenVars.scale *= 2; - if (presentingClock.getActiveSide() === "left") { - keyImgContTweenVars.rotateY = 30; - keyImgContTweenVars.left += this.size === 1 ? 45 : 25; - } else if (presentingClock.getActiveSide() === "right") { - keyImgContTweenVars.rotateY = -30; - keyImgContTweenVars.left -= this.size === 1 ? 45 : 25; + return tl; + }, + defaults: {} + }, + // #endregion + // #region CHARACTER SHEET EFFECTS + fillCoins: { + effect: (targets, config3) => { + return U.gsap.to( + targets, + { + duration: config3.duration / 2, + scale: config3.scale, + filter: config3.filter, + ease: config3.ease, + stagger: { + amount: 0.25, + from: "start", + repeat: 1, + yoyo: true + } + } + ); + }, + defaults: { + duration: 1, + scale: 1, + filter: "saturate(1) brightness(2)", + ease: "power2.in" + }, + extendTimeline: true + }, + // #endregion + // #region GENERAL: 'blurRemove', 'hoverTooltip', 'textJitter' + blurRemove: { + effect: (targets, config3) => U.gsap.timeline({ stagger: config3.stagger }).to( + targets, + { + skewX: config3.skewX, + duration: config3.duration / 2, + ease: "power4.out" } - } - return { keyTweenVars, keyImgContTweenVars }; - } - // public fitKeyToContainer( - // keyElems$: ClockKeyElems$, - // posOverrides?: Partial - // ) { - // const {container$, elem$, imgContainer$} = keyElems$; - // // Get position data for the container$ element (x, y, width, height) - // const keyPosition: ElemPosData = { - // x: U.gsap.getProperty(container$[0], "x") as number, - // y: U.gsap.getProperty(container$[0], "y") as number, - // width: U.gsap.getProperty(container$[0], "width") as number, - // height: U.gsap.getProperty(container$[0], "height") as number - // }; - // const {xShift, yShift, scaleMult, ...focusPosOverrides} = posOverrides ?? {}; - // const focusPosition: ElemPosData = { - // ...this.fullDisplayPosData, - // ...focusPosOverrides - // }; - // eLog.checkLog3("BladesClockKey", "[BladesClockKey] Key Positions", { - // keyPosition, - // focusPosition, - // widthScale: keyPosition.width / focusPosition.width, - // heightScale: keyPosition.height / focusPosition.height - // }); - // // Apply scale factor to elem$ to fit default key position inside container$ - // U.gsap.set(elem$, { - // scale: Math.min( - // keyPosition.width / focusPosition.width, - // keyPosition.height / focusPosition.height - // ) * (scaleMult ?? 1) - // }); - // // Apply top, left and transformOrigin value to keyImgContainer, accounting for x/yPercent -50 - // U.gsap.set(imgContainer$, { - // top: (0.5 * C.ClockKeySquareSize) - focusPosition.y + (yShift ?? 0), - // left: (0.5 * C.ClockKeySquareSize) - focusPosition.x + (xShift ?? 0), - // transformOrigin: `${focusPosition.x + (xShift ?? 0)}px ${focusPosition.y + (yShift ?? 0)}px` - // }); - // } - formatLabels(keyElems$) { - const { label$, clocks, factionLabel$, projectLabel$, scoreLabel$ } = keyElems$; - [ - [label$, 2, 4], - factionLabel$ ? [factionLabel$, 2, 2] : void 0, - projectLabel$ ? [projectLabel$, 2, 2] : void 0, - scoreLabel$ ? [scoreLabel$, 2, 2] : void 0, - ...this.clocks.map((clock) => [clocks[clock.id].clockLabel$, 2.5, 3]) - ].filter(Boolean).forEach(([labelElem$, aspectRatio, maxLines]) => { - U.adjustTextContainerAspectRatio(labelElem$, aspectRatio, maxLines); - }); - } - setToDisplayMode(keyElems$, displayMode, isUpdatingTarget = true) { - const { keyTweenVars, keyImgContTweenVars } = this.getVarsForDisplayMode(keyElems$, displayMode); - U.gsap.set(keyElems$.elem$, keyTweenVars); - U.gsap.set(keyElems$.imgContainer$, keyImgContTweenVars); - if (isUpdatingTarget && displayMode !== this.displayMode) { - this.updateTarget("displayMode", displayMode); - } - } - initElementsInContext(html, displayMode, isUpdatingTarget = true) { - const keyElems$ = this.getElements$(html); - displayMode ?? (displayMode = this.displayMode); - this.setToDisplayMode(keyElems$, displayMode, isUpdatingTarget); - this.formatLabels(keyElems$); - if (displayMode.toString().startsWith("present") || Number.isInteger(displayMode)) { - U.gsap.to(keyElems$.container$.find(".clock-label, .clock-key-label"), { autoAlpha: 0, duration: 0 }); - } - return keyElems$; + ).to( + targets, + { + x: config3.x, + marginBottom: config3.ignoreMargin ? void 0 : function(i, target) { + return U.get(target, "height") * -1; + }, + marginRight: config3.ignoreMargin ? void 0 : function(i, target) { + return U.get(target, "width") * -1; + }, + scale: config3.scale, + filter: `blur(${config3.blur}px)`, + duration: 3 / 4 * config3.duration + }, + config3.duration / 4 + ).to( + targets, + { + autoAlpha: 0, + duration: config3.duration / 2, + ease: "power3.in" + }, + config3.duration / 2 + ), + defaults: { + ignoreMargin: false, + skewX: -20, + duration: 0.5, + x: "+=300", + scale: 1.5, + blur: 10, + stagger: 0 + }, + extendTimeline: true + }, + blurReveal: { + effect: (targets, config3) => U.gsap.timeline().fromTo( + targets, + { + x: config3.x, + marginBottom: config3.ignoreMargin ? void 0 : function(i, target) { + return U.get(target, "height") * -1; + }, + marginRight: config3.ignoreMargin ? void 0 : function(i, target) { + return U.get(target, "width") * -1; + }, + scale: config3.scale, + filter: `blur(${config3.blur}px)` + }, + { + x: 0, + marginBottom: 0, + marginRight: 0, + scale: 1, + filter: "blur(0px)", + duration: 3 / 4 * config3.duration + }, + 0 + ).fromTo( + targets, + { + autoAlpha: 0 + }, + { + autoAlpha: 1, + duration: config3.duration / 2, + ease: "power3.in" + }, + 0 + ).fromTo( + targets, + { + skewX: config3.skewX + }, + { + skewX: 0, + duration: config3.duration / 2, + ease: "power4.out" + }, + config3.duration / 2 + ), + defaults: { + ignoreMargin: false, + skewX: -20, + duration: 0.5, + x: "+=300", + scale: 1.5, + blur: 10 + }, + extendTimeline: true + }, + scaleUpReveal: { + effect: (target, config3) => { + const tl = U.gsap.timeline().fromTo(target, { + autoAlpha: 0, + scale: 0.5 * config3.scale + }, { + autoAlpha: 1, + scale: config3.scale, + duration: config3.duration, + ease: config3.ease + }); + return tl; + }, + defaults: { + scale: 1, + duration: 0.5, + ease: "power2" + }, + extendTimeline: true + }, + scaleDownRemove: { + effect: (target, config3) => { + const tl = U.gsap.timeline().to(target, { + autoAlpha: 0, + scale: 0.5 * config3.scale, + duration: config3.duration, + ease: config3.ease + }); + return tl; + }, + defaults: { + scale: 1, + duration: 0.5, + ease: "power2" + }, + extendTimeline: true + }, + blurRevealTooltip: { + effect: (target, config3) => { + if (!target) { + throw new Error(`blurRevealTooltip effect: tooltip element is ${target === null ? "null" : typeof target}`); + } + const tooltip$ = $(target); + return U.gsap.timeline({ + paused: true, + onReverseComplete: config3.onReverseComplete + }).fromTo( + tooltip$, + { + filter: `blur(${config3.blurStrength}px)`, + autoAlpha: 0, + xPercent: 50, + yPercent: -200, + scale: config3.scale + }, + { + filter: "blur(0px)", + autoAlpha: 1, + xPercent: -50, + yPercent: -100, + scale: 1, + ease: config3.ease, + duration: config3.duration + } + ); + }, + defaults: { + scale: 1.5, + blurStrength: 15, + ease: "back.out", + duration: 0.25, + onReverseComplete: void 0 + }, + extendTimeline: true + }, + textJitter: { + effect: (target, config3) => { + const [targetElem] = $(target); + if (!targetElem) { + throw new Error("textJitter effect: target not found"); + } + const split = new SplitText(targetElem, { type: "chars" }); + return U.gsap.timeline().to(targetElem, { + autoAlpha: 1, + duration: config3.duration, + ease: "none" + }).fromTo(split.chars, { + y: -config3.yAmp + }, { + y: config3.yAmp, + duration: config3.duration, + ease: "sine.inOut", + stagger: { + repeat: -1, + yoyo: true, + from: "random", + each: config3.stagger + } + }, 0).fromTo(split.chars, { + rotateZ: -config3.rotateAmp + }, { + rotateZ: config3.rotateAmp, + duration: config3.duration, + ease: CustomWiggle.create("myWiggle", { wiggles: 10, type: "random" }), + stagger: { + repeat: -1, + from: "random", + yoyo: true, + each: config3.stagger + } + }, 0); + }, + defaults: { + yAmp: 2, + rotateAmp: 2, + duration: 1, + stagger: 0.05 + }, + extendTimeline: true } // #endregion - async addToScene(sceneID = game.scenes.current.id) { - if (this.isInScene(sceneID)) { - return; - } - const { sceneIDs } = this; - sceneIDs.push(sceneID); - await this.updateTarget({ - isVisible: false, - sceneIDs +}; +function Initialize() { + if (gsapPlugins.length) { + U.gsap.config({ + nullTargetWarn: true }); - this.renderTargetAndKeeper(); + U.gsap.registerPlugin(...gsapPlugins); + Object.assign( + globalThis, + { + TextPlugin, + Flip, + MotionPathPlugin, + Dragger: Draggable, + // SplitText, + Observer: Observer$1, + CustomEase + // CustomWiggle, + // CustomBounce, + // EasePack + } + ); } - async removeFromScene(sceneID = game.scenes.current.id) { - if (!this.isInScene(sceneID)) { + Object.entries(gsapEffects).forEach(([name, effect]) => { + U.gsap.registerEffect(Object.assign(effect, { name })); + }); +} +function ApplyTooltipAnimations(html) { + html.find(".tooltip-trigger").each((_, el) => { + const tooltipElem = $(el).find(".tooltip")[0] ?? $(el).next(".tooltip")[0]; + if (!tooltipElem) { return; } - const { sceneIDs } = this; - U.remove(sceneIDs, sceneID); - await this.updateTarget("sceneIDs", sceneIDs); - this.renderTargetAndKeeper(); - } - closeClockKey({ container$ }) { - container$.remove(); - } - get svgData() { - if (this.size === 0) { - throw new Error("[BladesClockKey.svgData] Error size is 0."); - } - const keyData = ClockKey_SVGDATA[this.size]; - let path; - if (this.size === 1 && keyData.paths) { - path = keyData.paths[this.oneKeyIndex]; - } else if (keyData.path) { - path = keyData.path; - } else { - throw new Error("[BladesClockKey.svgData] Error path is not defined."); - } - return { - width: keyData.width, - height: keyData.height, - path, - clocks: keyData.clocks - }; - } - isInOverlay(elem) { - return $(elem).hasClass(".overlay-section") || $(elem).closest(".overlay-section").length > 0; - } - get keyHeight() { - return this.svgData.height; - } - get keyWidth() { - return this.svgData.width; - } - get keyViewbox() { - return `0 0 ${this.svgData.width} ${this.svgData.height}`; - } - get keyPath() { - return this.svgData.path; - } - get clockSize() { - return this.svgData.clocks.size; - } - getClockPosition(clockIndex = 0) { - if (clockIndex > this.size) { - throw new Error(`[BladesClockKey.getClockPosition] Error clockIndex '${clockIndex}' is greater than key size '${this.size}'.`); - } - if (clockIndex < 0) { - throw new Error(`[BladesClockKey.getClockPosition] Error clockIndex '${clockIndex}' is less than 0.`); - } - return this.svgData.clocks[clockIndex]; - } - removePositionDragger() { - var _a, _b; - (_a = this.positionDragger) == null ? void 0 : _a.target.remove(); - (_b = this.positionDragger) == null ? void 0 : _b.kill(); - delete this.positionDragger; - } - spawnPositionDragger(containerElem$ = game.eunoblades.Director.clockKeySection$) { - const self = this; - if (this.positionDragger) { - this.removePositionDragger(); + const tooltip$ = $(tooltipElem); + const tooltipContainer$ = tooltip$.parent(); + if (tooltipContainer$.css("position") !== "relative" && tooltipContainer$.css("position") !== "absolute") { + tooltipContainer$.css("position", "relative"); } - const dragElem$ = $(`
`).appendTo(containerElem$); - if (this.overlayPosition) { - dragElem$.css({ - left: this.overlayPosition.x, - top: this.overlayPosition.y - }); + tooltip$.css("position", "absolute"); + const tooltipID = `tooltip-${randomID()}`; + tooltip$.attr("id", tooltipID); + if (tooltip$.hasClass("tooltip-wide")) { + U.adjustTextContainerAspectRatio(tooltipElem, 6); } - this.positionDragger = new Draggable(dragElem$, { - type: "top,left", - onDragStart() { - $(this.target).css("background", "rgba(255, 255, 0, 0.25)"); - $(this.target).css("outlineColor", "rgba(255, 255, 0, 1)"); + $(el).on({ + mouseenter: function() { + game.eunoblades.Director.displayTooltip(tooltipElem); }, - onDragEnd() { - $(this.target).css("background", "rgba(255, 0, 255, 0.25)"); - $(this.target).css("outlineColor", "rgba(255, 0, 255, 1)"); - self.overlayPosition = { x: this.endX, y: this.endY }; + mouseleave: function() { + game.eunoblades.Director.clearTooltip(tooltipID); } }); - } - switchToMode(keyElems$, displayMode, extendKeyVars = {}, extendKeyContainerVars = {}, isUpdatingTarget = true, callback) { - const { elem$, imgContainer$ } = keyElems$; - const { keyTweenVars, keyImgContTweenVars } = this.getVarsForDisplayMode(keyElems$, displayMode); - const currentDisplayMode = this.displayMode; - const randomID2 = U.gsap.utils.random(1, 1e3, 1); - return U.gsap.timeline({ - callbackScope: this, - paused: true, - onStart() { - eLog.checkLog2("BladesClockKey", `switchToMode #${randomID2} - START`, { key: this, keyElems$, displayMode }); - }, - onComplete() { - eLog.checkLog3("BladesClockKey", `switchToMode #${randomID2} - COMPLETE`, { key: this, keyElems$, displayMode }); - if (isUpdatingTarget && displayMode !== this.currentDisplayMode) { - this.updateTarget("displayMode", displayMode).then(() => callback == null ? void 0 : callback()); - } else { - callback == null ? void 0 : callback(); - } - }, - onReverseComplete() { - eLog.checkLog3("BladesClockKey", `switchToMode #${randomID2} - REVERSE COMPLETE`, { key: this, keyElems$, displayMode }); - if (isUpdatingTarget) { - this.updateTarget("displayMode", currentDisplayMode); - } + }); +} +const G = U.gsap; +const _BladesTargetLink = class _BladesTargetLink { + constructor(dataOrConfig, parentLinkData) { + __privateAdd(this, _updateTargetViaMerge); + __privateAdd(this, _updateTargetPropVal); + __publicField(this, "_id"); + __publicField(this, "_targetID"); + __publicField(this, "_targetKey"); + __publicField(this, "_targetFlagKey"); + __publicField(this, "_isScopingById", true); + __publicField(this, "_initialSchema"); + __publicField(this, "_target"); + __publicField(this, "initPromise"); + __publicField(this, "isInitPromiseResolved", false); + var _a; + let linkData; + let schema; + const subclassConstructor = this.constructor; + if (subclassConstructor.IsValidData(dataOrConfig)) { + ({ linkData } = subclassConstructor.PartitionSchemaData(dataOrConfig)); + const target2 = fromUuidSync(linkData.targetID); + if (!target2) { + throw new Error(`[new BladesTargetLink()] Unable to resolve target from uuid '${linkData.targetID}'`); + } + if ("targetKey" in linkData) { + schema = getProperty(target2, `${linkData.targetKey}.${linkData.id}`); + } else { + schema = target2.getFlag(C.SYSTEM_ID, `${linkData.targetFlagKey}.${linkData.id}`); } - }).to(elem$, { ...keyTweenVars, ...extendKeyVars }, 0).to(imgContainer$, { ...keyImgContTweenVars, ...extendKeyContainerVars }, 0); - } - // #endregion - // #region ANIMATED UPDATES (Both GM-Only AND Socket Calls) - // #region > SOCKET CALLS: _SocketCall / static _SocketResponse / _Animation - fadeInName_Animation(keyElems$) { - if (!this.name) { - return void 0; - } - return U.gsap.effects.blurReveal(keyElems$.label$, { - ignoreMargin: true, - duration: 0.75 - }); - } - async fadeInName_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("fadeInName_SocketCall", displayContext, this.id); - } - static fadeInName_SocketResponse(displayContext, keyID) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!key) { - return; + this.isInitPromiseResolved = true; + } else { + const parsedData = __privateMethod(_a = _BladesTargetLink, _ParseConfigToData, ParseConfigToData_fn).call(_a, dataOrConfig, parentLinkData); + let partialSchema; + ({ linkData, partialSchema } = subclassConstructor.PartitionSchemaData(parsedData)); + schema = subclassConstructor._ApplySchemaDefaults(partialSchema); } - key.fadeInName_Animation(key.getElements$(displayContext)); - } - fadeOutName_Animation(keyElems$) { - if (!this.name) { - return void 0; + this._id = linkData.id; + this._targetID = linkData.targetID; + if ("targetKey" in linkData) { + this._targetKey = linkData.targetKey; + } else { + this._targetFlagKey = linkData.targetFlagKey; } - return U.gsap.effects.blurRemove(keyElems$.label$, { - ignoreMargin: true, - duration: 0.75 - }); - } - async fadeOutName_SocketCall(displayContext) { - if (!game.user.isGM) { - return; + const target = fromUuidSync(this.targetID); + if (!target) { + throw new Error(`[new BladesTargetLink()] Unable to resolve target from uuid '${this._targetID}'`); } - this.fadeOutName_Animation(this.getElements$(displayContext)); - socketlib.system.executeForOthers("fadeOutName_SocketCall", displayContext, this.id); + this._target = target; + this._initialSchema = schema; } - static fadeOutName_SocketResponse(displayContext, keyID) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!key) { - return; - } - key.fadeOutName_Animation(key.getElements$(displayContext)); + // #region STATIC METHODS ~ + static get ValidTargetClasses() { + return [ + BladesActor$1, + BladesItem$1, + BladesChat$1, + User + ]; } - // #endregion - // #endregion - // #region Adding & Removing Clocks ~ - async updateClockIndices() { - await this.updateTarget("clocksData", Object.fromEntries( - Object.entries(this.clocksData).map(([id, data], index) => [id, { ...data, index }]) - )); - return this.clocks; + static IsValidConfig(ref) { + return U.isSimpleObj(ref) && (U.isDocID(ref.target) || U.isDocUUID(ref.target) || U.isDocID(ref.targetID) || U.isDocUUID(ref.targetID) || this.ValidTargetClasses.some((cls) => ref.target instanceof cls)) && (U.isTargetKey(ref.targetKey) || U.isTargetFlagKey(ref.targetFlagKey)) && !(U.isTargetKey(ref.targetKey) && U.isTargetFlagKey(ref.targetFlagKey)); } - async addClock(clockSchema = {}) { - const cData = BladesClock.ParseConfigToData({ - ...BladesClock.ApplySchemaDefaults(clockSchema), - index: this.size, - targetID: this.targetID, - targetKey: `${this.targetKeyPrefix}.clocksData`, - isScopingById: true - }); - await this.updateTarget(`clocksData.${cData.id}`, cData); - void this.clocks; - this.renderTargetAndKeeper(); + static IsValidData(ref) { + return U.isSimpleObj(ref) && U.isDocID(ref.id) && U.isDocUUID(ref.targetID) && (U.isTargetKey(ref.targetKey) || U.isTargetFlagKey(ref.targetFlagKey)) && !(U.isTargetKey(ref.targetKey) && U.isTargetFlagKey(ref.targetFlagKey)); } - async deleteClock(clockID) { - var _a, _b; - if (this.size <= 1) { - throw new Error("[BladesClockKey.deleteClock()] Cannot reduce number of clocks below 1!"); + static BuildLinkConfig(partialConfig) { + if ("target" in partialConfig) { + if ("targetKey" in partialConfig) { + return { + target: partialConfig.target, + targetKey: partialConfig.targetKey, + isScopingById: partialConfig.isScopingById + }; + } else if ("targetFlagKey" in partialConfig) { + return { + target: partialConfig.target, + targetFlagKey: partialConfig.targetFlagKey, + isScopingById: partialConfig.isScopingById + }; + } + throw new Error("[BladesTargetLink.BuildConfig] Must provide a targetKey or targetFlagKey."); + } else if ("targetID" in partialConfig) { + if ("targetKey" in partialConfig) { + return { + targetID: partialConfig.targetID, + targetKey: partialConfig.targetKey, + isScopingById: partialConfig.isScopingById + }; + } else if ("targetFlagKey" in partialConfig) { + return { + targetID: partialConfig.targetID, + targetFlagKey: partialConfig.targetFlagKey, + isScopingById: partialConfig.isScopingById + }; + } + throw new Error("[BladesTargetLink.BuildConfig] Must provide a targetKey or targetFlagKey."); } - clockID ?? (clockID = (_a = Array.from(this.clocks).pop()) == null ? void 0 : _a.id); - if (!clockID) { - return; + throw new Error("[BladesTargetLink.BuildConfig] Must provide a target or targetID."); + } + /** + * This static method parses the provided data into a format suitable for BladesTargetLink. + * Subclasses can override this method to include their own parse logic. + * If the provided data is already valid, it is returned as is. + * Otherwise, the data is passed to the private #ParseConfig method for further processing. + * Note: The 'id' property is defined at the return step, within #ParseConfig: Subclass + * functionality that depends on the id property should be placed after the super call to this method. + * + * @template Schema - The data schema required by the subclass. + * @param {(BladesTargetLink.Config | BladesTargetLink.Data) & Partial} data - The data to be parsed. + * @returns {BladesTargetLink.Data & Partial} - The parsed data, suitable for BladesTargetLink. + */ + static ParseConfigToData(data, parentLinkData) { + if (this.IsValidData(data)) { + return __privateMethod(this, _ParseChildLinkData, ParseChildLinkData_fn).call(this, data, parentLinkData); } - await ((_b = this.getClockByID(clockID)) == null ? void 0 : _b.delete()); - await this.updateClockIndices(); - void this.clocks; + return __privateMethod(this, _ParseConfigToData, ParseConfigToData_fn).call(this, data, parentLinkData); } - // #endregion - // #region OVERRIDES: Async Update Methods - renderTargetAndKeeper() { - var _a; - this.renderTarget(); - (_a = game.eunoblades.ClockKeeper.sheet) == null ? void 0 : _a.render(); + static PartitionSchemaData(dataOrConfig) { + const { + id, + target, + targetID, + targetKey, + targetFlagKey, + isScopingById, + ...schemaData + } = dataOrConfig; + const partialSchema = schemaData; + if (U.isDocID(id)) { + if (!this.IsValidData({ id, targetID, targetKey, targetFlagKey, isScopingById })) { + eLog.error("BladesTargetLink", "Bad Constructor DATA", { dataOrConfig }); + throw new Error("[new BladesTargetLink()] Bad Constructor DATA (see log)"); + } + let linkData; + if (targetKey) { + linkData = { id, targetID, targetKey, isScopingById: isScopingById ?? true }; + } else if (targetFlagKey) { + linkData = { id, targetID, targetFlagKey, isScopingById: isScopingById ?? true }; + } else { + eLog.error("BladesTargetLink", "Bad Constructor DATA", { dataOrConfig }); + throw new Error("[BladesTargetLink.PartitionSchemaData] Bad Constructor DATA (see log)"); + } + return { + linkData, + partialSchema + }; + } + return { + linkConfig: this.BuildLinkConfig({ + ...{ isScopingById: isScopingById ?? true }, + ..."targetID" in dataOrConfig ? { targetID: dataOrConfig.targetID } : { target: dataOrConfig.target }, + ..."targetKey" in dataOrConfig ? { targetKey: dataOrConfig.targetKey } : { targetFlagKey: dataOrConfig.targetFlagKey } + }), + partialSchema + }; } - renderTarget() { - var _a; - (_a = this.target.sheet) == null ? void 0 : _a.render(); + static _ApplySchemaDefaults(schemaData) { + return this.ApplySchemaDefaults(schemaData); } - // #endregion -} -class BladesClock extends BladesTargetLink { - // #region STATIC METHODS ~ + /** + * This static method applies defaults to any values missing from the class' data Schema. + * 'Schema' is defined by subclasses to BladesTargetLink. + * Subclasses must override this method to apply their own defaults. + * + * @template Schema - The data schema required by the subclass. + * @param {Partial} schemaData - Schema data overriding the defaults. + * @returns {Schema} - The schema data with defaults applied. + * @throws {Error} - Throws an error if this method is not overridden in a subclass. + */ static ApplySchemaDefaults(schemaData) { - const namedValueMax = { - name: schemaData.name ?? "", - value: schemaData.value ?? 0, - max: schemaData.max ?? 8 - }; - return { - index: 0, - color: ClockColor.white, - isVisible: !U.isInt(schemaData.index) || schemaData.index === 0, - isNameVisible: false, - isHighlighted: false, - isActive: !U.isInt(schemaData.index) || schemaData.index === 0, - ...schemaData, - ...namedValueMax - }; + throw new Error("[BladesTargetLink.ApplySchemaDefaults] Static Method ApplySchemaDefaults must be overridden in subclass"); } - // #endregion - // #region GETTERS & SETTERS ~ - get canEdit() { - console.log("NOTE: All Clocks currently Editable; see line 71 of BladesClock.ts"); - return this.isVisible && this.isActive; + /** + * Creates a new instance of BladesTargetLink and initializes it with the provided configuration. + * The configuration is parsed into a data object which is then used to initialize the target link. + * The function logs the parsed data for debugging purposes. + * + * @template Schema - The schema type parameter that extends the data structure. + * @param {BladesTargetLink.Config & Partial} config - The configuration object containing both the target link configuration and the schema configuration. + * + * @returns {Promise & BladesTargetLink.Subclass>} - A promise that resolves to a new instance of BladesTargetLink, initialized with the provided data. + * + * @throws {Error} - Throws an error if the initialization of the target link fails. + */ + static async Create(config3, parentLinkData) { + const tLink = new this(config3, parentLinkData); + await tLink.initTargetLink(); + return tLink; } - get data() { - return this.linkData; + // #endregion + // #region GETTERS ~ + get isGM() { + return game.user.isGM; } - get name() { - return this.data.name; + get id() { + return this._id; } - set name(val) { - this.updateTarget("name", val).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + get targetID() { + return this._targetID; } - get value() { - return U.pInt(this.data.value); + get targetKey() { + return this._targetKey; } - set value(val) { - this.updateTarget("value", U.pInt(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + get targetFlagKey() { + return this._targetFlagKey; } - get max() { - return U.pInt(this.data.max); + get isScopingById() { + return this._isScopingById; } - set max(val) { - this.updateTarget("max", U.pInt(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + get initialSchema() { + return this._initialSchema; } - get color() { - return this.data.color ?? ClockColor.white; + get targetKeyPrefix() { + if (!this.targetKey) { + return void 0; + } + if (!this.isScopingById) { + return this.targetKey; + } + return this.targetKey ? `${this.targetKey}.${this.id}` : void 0; } - set color(val) { - this.updateTarget("color", val).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + get targetKeyNullPrefix() { + if (!this.targetKey) { + return void 0; + } + if (this.isScopingById) { + return `${this.targetKey}.-=${this.id}`; + } + if (/^.+\..+$/g.test(this.targetKey)) { + return this.targetKey.replace(/\.([^.]+)$/, ".-=$1"); + } + throw new Error(`[BladesTargetLink.targetKeyNullPrefix] Can't Nullify TargetKey '${this.targetKey}'`); } - get isActive() { - return U.pBool(this.data.isActive); + get targetFlagKeyPrefix() { + if (!this.targetFlagKey) { + return void 0; + } + if (!this.isScopingById) { + return this.targetFlagKey; + } + return this.targetFlagKey ? `${this.targetFlagKey}.${this.id}` : void 0; } - set isActive(val) { - this.updateTarget("isActive", U.pBool(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + get isLinkInitialized() { + return this.isInitPromiseResolved; } - get parentKey() { - const pKey = game.eunoblades.ClockKeys.get(this.data.parentKeyID); - if (!pKey) { - throw new Error(`[BladesClockKey.parentKey] No parent key found for clock ${this.id}`); + get linkData() { + if (this.targetKey) { + return { + id: this.id, + targetID: this.targetID, + targetKey: this.targetKey, + isScopingById: this.isScopingById + }; } - return pKey; + if (this.targetFlagKey) { + return { + id: this.id, + targetID: this.targetID, + targetFlagKey: this.targetFlagKey, + isScopingById: this.isScopingById + }; + } + throw new Error(`[BladesTargetLink.linkData] Missing targetKey and targetFlagKey for '${this.id}'`); } - get isNameVisible() { - return U.pBool(this.data.isNameVisible); + get target() { + return this._target; } - set isNameVisible(val) { - this.updateTarget("isNameVisible", U.pBool(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + get localData() { + return { + ...this.initialSchema, + ...this.linkData + }; } - get isVisible() { - return U.pBool(this.data.isVisible); + get data() { + if (this.isLinkInitialized) { + let data; + if (this.targetFlagKeyPrefix) { + data = this.target.getFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix); + } else if (this.targetKeyPrefix) { + data = getProperty(this.target, this.targetKeyPrefix); + } + if (!data) { + throw new Error("[BladesTargetLink.data] Error retrieving data."); + } + return data; + } else { + eLog.warn("BladesTargetLink", "Attempt to access data of uninitiated BladesTargetLink: Returning local data only.", { bladesTargetLink: this, localData: this.localData }); + return this.localData; + } } - set isVisible(val) { - this.updateTarget("isVisible", U.pBool(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + // #endregion + // #region ASYNC UPDATE & DELETE METHODS ~ + getDotKeyToProp(prop, isNullifying = false) { + if (this.targetKeyPrefix) { + if (prop === void 0) { + return isNullifying ? this.targetKeyNullPrefix : this.targetKeyPrefix; + } + return `${this.targetKeyPrefix}.${isNullifying ? "-=" : ""}${prop}`; + } + if (this.targetFlagKeyPrefix) { + if (prop === void 0) { + return this.targetFlagKeyPrefix; + } + return `${this.targetFlagKeyPrefix}.${prop}`; + } + throw new Error("[BladesTargetLink.getDotKeyToProp()] Missing 'targetKeyPrefix' and 'targetFlagKeyPrefix'"); } - get isHighlighted() { - return U.pBool(this.data.isHighlighted); + getFlagParamsToProp(prop) { + return [C.SYSTEM_ID, this.getDotKeyToProp(prop)]; } - set isHighlighted(val) { - this.updateTarget("isHighlighted", U.pBool(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); - }); + async updateTargetFlag(prop, val) { + if (!this.targetFlagKeyPrefix) { + return; + } + if (val === null) { + await this.target.unsetFlag(...this.getFlagParamsToProp(prop)); + } else if (this.target instanceof BladesActor$1) { + await this.target.setFlag(...this.getFlagParamsToProp(prop), val); + } else if (this.target instanceof BladesItem$1) { + await this.target.setFlag(...this.getFlagParamsToProp(prop), val); + } else if (this.target instanceof User) { + await this.target.setFlag(...this.getFlagParamsToProp(prop), val); + } else if (this.target instanceof BladesChat$1) { + await this.target.setFlag(...this.getFlagParamsToProp(prop), val); + } } - get index() { - return U.pInt(this.data.index); + async updateTargetKey(prop, val) { + if (!this.targetKeyPrefix) { + return; + } + await this.target.update({ [this.getDotKeyToProp(prop, val === null)]: val }, { render: false }); } - set index(val) { - this.updateTarget("index", U.pInt(val)).then(() => { - this.parentKey.renderTargetAndKeeper(); + /** + * Initializes a target link by updating the target's data with the provided data object. + * If a targetKey is provided, the data is updated directly on the target. + * If a targetFlagKey is provided, the data is set as a flag on the target. + * + * This method need only be run once, when the document is first created and its data must be written to server storage. + * External functions can synchronously check the status of initialization via the isInitPromiseResolved property, while + * asynchronous functions can await the initPromise property. + * + * TargetLink documents whose data already exists in server storage can be constructed directly (i.e. new BladesTargetLink(data)) + * without needing to call this method. + * + * @param {BladesTargetLink.Data & Schema} data - The combined data object containing both the target link data and the schema data. + * @returns {Promise} - A promise that resolves when the server update is complete. + */ + async initTargetLink() { + this.isInitPromiseResolved = false; + const data = { + ...this.linkData, + ...this.initialSchema + }; + this.initPromise = new Promise((resolve, reject) => { + if (this.targetKeyPrefix) { + const updateData = mergeObject( + getProperty(this.target, this.targetKeyPrefix) ?? {}, + data + ); + this.target.update({ [this.targetKeyPrefix]: updateData }, { render: false }).then(() => { + this.isInitPromiseResolved = true; + resolve(); + }).catch(reject); + } else if (this.targetFlagKeyPrefix) { + const updateData = mergeObject( + this.target.getFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix) ?? {}, + data + ); + this.target.setFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix, updateData).then(() => { + this.isInitPromiseResolved = true; + resolve(); + }).catch(reject); + } else { + reject(); + } }); + return this.initPromise; } - get isEmpty() { - return this.value === 0; + async updateTarget(propOrData, valOrWaitFor, waitFor2) { + if (typeof propOrData === "string") { + if (getProperty(this.data, propOrData) === valOrWaitFor) { + return; + } + return __privateMethod(this, _updateTargetPropVal, updateTargetPropVal_fn).call(this, propOrData, valOrWaitFor, waitFor2); + } + if (typeof propOrData === "object") { + return __privateMethod(this, _updateTargetViaMerge, updateTargetViaMerge_fn).call(this, propOrData, valOrWaitFor); + } else { + throw new Error(`[BladesTargetLink.updateTarget()] Bad updateData for id '${this.id}': ${propOrData}`); + } + } + async updateTargetData(val, waitFor2) { + if (val) { + val = { + ...val, + ...this.linkData + }; + } + await U.waitFor([this.initPromise, waitFor2]); + if (this.targetFlagKeyPrefix) { + await this.updateTargetFlag(void 0, val); + } else { + await this.updateTargetKey(void 0, val); + } + } + async delete(collection, waitFor2) { + if (collection) { + collection.delete(this.id); + } + await U.waitFor([this.initPromise, waitFor2]); + await this.updateTargetData(null); } - get isComplete() { - return this.value >= this.max; + // #endregion +}; +_ParseChildLinkData = new WeakSet(); +ParseChildLinkData_fn = function(childData, parentLinkData) { + if (!parentLinkData) { + return childData; } - get rollOppClock() { - return this; + const keyPrefixParts = "targetKey" in parentLinkData ? [parentLinkData.targetKey] : [parentLinkData.targetFlagKey]; + if (parentLinkData.isScopingById) { + keyPrefixParts.push(parentLinkData.id); } - get rollOppName() { - return this.name; + const keyPrefix = keyPrefixParts.join("."); + if ("targetKey" in childData && "targetKey" in parentLinkData) { + if (childData.targetKey.startsWith(`${keyPrefix}.`)) { + childData.targetKey = childData.targetKey.slice(keyPrefix.length + 1); + } + childData.targetKey = [ + parentLinkData.targetKey, + parentLinkData.isScopingById ? parentLinkData.id : void 0, + childData.targetKey + ].filter(Boolean).join("."); + } else if ("targetFlagKey" in childData && "targetFlagKey" in parentLinkData) { + if (childData.targetFlagKey.startsWith(`${keyPrefix}.`)) { + childData.targetFlagKey = childData.targetFlagKey.slice(keyPrefix.length + 1); + } + childData.targetFlagKey = [ + parentLinkData.targetFlagKey, + parentLinkData.isScopingById ? parentLinkData.id : void 0, + childData.targetFlagKey + ].filter(Boolean).join("."); + } else { + throw new Error("[BladesTargetLink.ParseChildLinkData] targetKey/targetFlagKey mismatch between provided partialConfig and parentLinkData."); } - get rollOppType() { - return "clock"; + return childData; +}; +_ParseConfigToData = new WeakSet(); +ParseConfigToData_fn = function(config3, parentLinkData) { + if (this.IsValidData(config3)) { + return this.ParseConfigToData(config3, parentLinkData); } - get colorSelectOptions() { - return [ - { value: ClockColor.white, display: "🔘" }, - { value: ClockColor.yellow, display: "📀" }, - { value: ClockColor.cyan, display: "🔵" }, - { value: ClockColor.red, display: "🔴" } - ]; + const { linkConfig, partialSchema } = this.PartitionSchemaData(config3); + const fullConfig = this.BuildLinkConfig(linkConfig); + if ("targetKey" in fullConfig) { + return this.ParseConfigToData({ + id: randomID(), + ...partialSchema, + targetID: U.parseDocRefToUUID("target" in fullConfig ? fullConfig.target : fullConfig.targetID), + targetKey: fullConfig.targetKey + }, parentLinkData); } - get maxSelectOptions() { - return [ - { value: 2, display: 2 }, - { value: 3, display: 3 }, - { value: 4, display: 4 }, - { value: 5, display: 5 }, - { value: 6, display: 6 }, - { value: 8, display: 8 }, - { value: 10, display: 10 }, - { value: 12, display: 12 } - ]; + return this.ParseConfigToData({ + id: randomID(), + ...partialSchema, + targetID: U.parseDocRefToUUID("target" in fullConfig ? fullConfig.target : fullConfig.targetID), + targetFlagKey: fullConfig.targetFlagKey + }, parentLinkData); +}; +_updateTargetViaMerge = new WeakSet(); +updateTargetViaMerge_fn = async function(updateData, waitFor2) { + await U.waitFor(waitFor2); + if (this.targetKeyPrefix) { + updateData = U.objMap(updateData, false, (key) => `${this.targetKeyPrefix || this.targetFlagKeyPrefix}.${key}`); + return this.target.update(updateData, { render: false }); + } else if (this.targetFlagKeyPrefix) { + const existingFlagData = this.target.getFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix) ?? {}; + const flattenedFlagData = flattenObject(existingFlagData); + const mergedFlagData = mergeObject(flattenedFlagData, updateData); + return this.target.setFlag(C.SYSTEM_ID, this.targetFlagKeyPrefix, mergedFlagData); + } else { + throw new Error(`[BladesTargetLink.#updateTargetViaMerge] Unable to update target data for BladesTargetLink id '${this.id}': Missing both 'targetKeyPrefix' and 'targetFlagKeyPrefix'`); } - get valueSelectOptions() { - const returnVals = []; - for (let i = 0; i <= this.max; i++) { - returnVals.push({ value: i, display: i }); - } - return returnVals; +}; +_updateTargetPropVal = new WeakSet(); +updateTargetPropVal_fn = async function(prop, val, waitFor2) { + await U.waitFor(waitFor2); + if (this.targetKeyPrefix) { + return this.target.update({ [`${this.targetKeyPrefix}.${prop}`]: val }); + } else if (this.targetFlagKeyPrefix) { + return this.updateTargetFlag(prop, val); } - // Returns which hemisphere of the clock will show the final change if segmentDelta segments are added/removed. - getActiveSide(segmentDelta = 0) { - const finalClockValue = Math.min(this.max, Math.max(0, this.value + segmentDelta)); - const halfClockValue = this.max / 2; - if (segmentDelta === 0) { - return finalClockValue >= halfClockValue ? "left" : "right"; - } - return finalClockValue > halfClockValue ? "left" : "right"; +}; +__privateAdd(_BladesTargetLink, _ParseChildLinkData); +/** + * This private static method is used to transform a configuration object into a data object for BladesTargetLink. + * It checks if the provided configuration object is already valid data, and if so, returns it directly. + * Otherwise, it partitions the configuration object into link-specific configuration and additional schema data, + * constructs a full link configuration, and then creates a data object with a new random ID and the target UUID. + * The method ensures that either 'targetKey' or 'targetFlagKey' is present and throws an error if the configuration is invalid. + * + * @template Schema - The additional schema data required by the subclass. + * @param {BladesTargetLink.Config | BladesTargetLink.Data & Partial} config - The configuration object that may contain BladesTargetLink properties and any subclass-specific schema data. + * @returns {BladesTargetLink.Data & Partial} - The fully constructed data object with necessary properties for BladesTargetLink. + * @throws {Error} - Throws an error if the configuration object is invalid, lacks a target reference, or if both 'targetKey' and 'targetFlagKey' are provided. + */ +__privateAdd(_BladesTargetLink, _ParseConfigToData); +let BladesTargetLink = _BladesTargetLink; +function isElemPosData(obj) { + return U.isList(obj) && typeof obj.x === "number" && typeof obj.y === "number" && typeof obj.width === "number" && typeof obj.height === "number"; +} +class BladesClockKey extends BladesTargetLink { + constructor(dataOrConfig) { + super(dataOrConfig); + __publicField(this, "positionDragger"); + game.eunoblades.ClockKeys.set(this.id, this); + Object.values(dataOrConfig.clocksData ?? {}).forEach((clockData) => new BladesClock(clockData)); } - // #endregion - // #region HTML INTERACTION ~ - getElemFromDisplayContext(displayContext) { - let elem$; - const DOM$ = $(".vtt.game.system-eunos-blades"); - switch (displayContext) { - case ClockDisplayContext.overlay: { - elem$ = DOM$.find(`#blades-overlay #${this.id}`); - break; - } - case ClockDisplayContext.pcSheet: { - elem$ = DOM$.find(`.actor.sheet .pc #${this.id}`); - break; - } - case ClockDisplayContext.factionSheet: { - elem$ = DOM$.find(`.actor.sheet .faction #${this.id}`); - break; - } - case ClockDisplayContext.projectSheet: { - elem$ = DOM$.find(`.item.sheet .project #${this.id}`); - break; - } - case ClockDisplayContext.scoreSheet: { - elem$ = DOM$.find(`.item.sheet .score #${this.id}`); - break; - } - case ClockDisplayContext.rollCollab: { - elem$ = DOM$.find(`.roll-collab-sheet #${this.id}`); - break; - } - case ClockDisplayContext.chatMessage: { - elem$ = DOM$.find(`#chat #${this.id}`); - break; + // #region STATIC METHODS ~ + static Initialize() { + function registerClockKeys(doc) { + if ("clocksData" in doc.system) { + Object.values(doc.system.clocksData ?? {}).forEach((keyData) => { + try { + new BladesClockKey(keyData); + } catch (err) { + eLog.error("BladesClockKey", "[BladesClockKey.Initialize] Error initializing clock key.", err, keyData); + } + }); } } - if (!elem$.length) { - throw new Error(`[BladesClockKey.getElemFromDisplayContext] Error elem$ not found for key '${this.id}' for display context '${displayContext}'.`); - } - return elem$; + game.items.contents.filter( + (item) => BladesItem$1.IsType( + item, + BladesItemType.clock_keeper, + BladesItemType.project, + BladesItemType.cohort_gang, + BladesItemType.cohort_expert, + BladesItemType.ritual, + BladesItemType.design, + BladesItemType.location, + BladesItemType.score + ) + ).forEach(registerClockKeys); + game.actors.contents.filter( + (actor) => BladesActor$1.IsType( + actor, + BladesActorType.pc, + BladesActorType.faction + ) + ).forEach(registerClockKeys); + return loadTemplates([ + "systems/eunos-blades/templates/components/clock-key.hbs", + "systems/eunos-blades/templates/components/clock.hbs" + ]); } - getElements$(displayContext) { - let elem$; - if (typeof displayContext === "string") { - displayContext = this.getElemFromDisplayContext(displayContext); - } - elem$ = $(displayContext).find(`#${this.id}`); - if (!elem$.length) { - elem$ = $(displayContext).closest(`#${this.id}`); - } - if (!(elem$ == null ? void 0 : elem$.length)) { - throw new Error(`[BladesClock.getElements$] Cannot find elements for display context '${displayContext}' of clock '${this.id}' of key '${this.parentKey.id}'.`); - } - const clockElems$ = { - clockElem$: elem$ - }; - const container$ = elem$.closest(".clock-container"); - if (!container$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-container' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); - } - clockElems$.clockContainer$ = container$; - const label$ = elem$.find(".clock-label"); - if (!label$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-label' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); - } - clockElems$.clockLabel$ = label$; - const bg$ = elem$.find(".clock-bg"); - if (!bg$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-bg' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); - } - clockElems$.bg$ = bg$; - const frame$ = elem$.find(".clock-frame"); - if (!frame$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-frame' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); - } - clockElems$.frame$ = frame$; - const fill$ = elem$.find(".clock-fill"); - if (!fill$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-fill' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + static ApplySchemaDefaults(schemaData) { + return { + name: "", + isVisible: false, + isNameVisible: false, + isSpotlit: false, + clocksData: {}, + sceneIDs: [], + displayMode: ClockKeyDisplayMode.full, + oneKeyIndex: U.gsap.utils.random(0, 4, 1), + ...schemaData + }; + } + static async Create(config3, _parentLinkData, clocksInitialData = []) { + if (clocksInitialData.length > 6) { + eLog.error("BladesClockKey", "[BladesClockKey.Create] Too many clock configs! (Max 6.) Eliminating extras.", clocksInitialData); + clocksInitialData = clocksInitialData.slice(0, 6); + } else if (clocksInitialData.length === 0) { + clocksInitialData.push({}); } - clockElems$.fill$ = fill$; - const glow$ = elem$.find(".clock-glow"); - if (!glow$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-glow' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + const tempLink = new BladesTargetLink(config3); + if (tempLink.targetKeyPrefix) { + config3.clocksData = Object.fromEntries( + clocksInitialData.map((cSchema, i) => { + const cData = BladesClock.ParseConfigToData({ + ...BladesClock.ApplySchemaDefaults(cSchema), + index: i, + targetID: tempLink.targetID, + targetKey: `${tempLink.targetKeyPrefix}.clocksData`, + isScopingById: true + }); + return [ + cData.id, + cData + ]; + }) + ); + } else if (tempLink.targetFlagKeyPrefix) { + config3.clocksData = Object.fromEntries( + clocksInitialData.map((cSchema, i) => { + const cData = BladesClock.ParseConfigToData({ + ...BladesClock.ApplySchemaDefaults(cSchema), + targetID: tempLink.targetID, + targetFlagKey: `${tempLink.targetFlagKeyPrefix}.clocksData`, + isScopingById: true + }); + return [ + cData.id, + cData + ]; + }) + ); + } else { + throw new Error("BladesClockKey.Create: No targetKey or targetFlagKey provided."); } - clockElems$.glow$ = glow$; - const cover$ = elem$.find(".clock-cover"); - if (!cover$.length) { - throw new Error(`[BladesClock.getElements$] Error '.clock-cover' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + const clockKeyLink = await super.Create(tempLink.data); + const clockKey = new BladesClockKey(clockKeyLink.data); + clockKey.renderTargetAndKeeper(); + return clockKey; + } + static GetFromElement(elem) { + const keyElem$ = $(elem).closest(".clock-key-container").find(".clock-key"); + if (keyElem$.length === 0) { + return void 0; } - clockElems$.cover$ = cover$; - const oneSegments$ = elem$.find(".clock-one-segment"); - if (oneSegments$.length !== 3) { - throw new Error(`[BladesClock.getElements$] Error '.clock-one-segment' elements not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + const clockKeyID = keyElem$.attr("id"); + if (!clockKeyID) { + return void 0; } - clockElems$.oneSegments$ = oneSegments$; - return clockElems$; + return game.eunoblades.ClockKeys.get(clockKeyID); } // #endregion - // #region ANIMATED UPDATES (Both GM-Only AND Socket Calls) - reveal_Animation(clockElems$, callback) { - const fadeInElements = [ - clockElems$.frame$, - clockElems$.fill$ - ].filter((el$) => el$ !== void 0); - const tl = U.gsap.timeline({ - callbackScope: this, - onComplete() { - callback == null ? void 0 : callback(); - } - }); - tl.to(clockElems$.cover$, { scale: 2, autoAlpha: 0, duration: 0.5, ease: "power2" }); - tl.fromTo(fadeInElements, { - autoAlpha: 0, - scale: 2 - }, { - autoAlpha: 1, - scale: 1, - duration: 0.5, - stagger: 0.2, - ease: "power2" + // #region GETTERS & SETTERS ~ + // #region -- Shortcut Schema Getters ~ + get data() { + return this.linkData; + } + get name() { + return this.data.name; + } + set name(val) { + this.updateTarget("name", val).then(() => { + this.renderTargetAndKeeper(); }); - if (this.name && this.isNameVisible) { - tl.blurReveal(clockElems$.clockLabel$, { - ignoreMargin: true, - duration: 0.75 - }, "<+0.05"); - } - if (this.isHighlighted) { - tl.scaleUpReveal(clockElems$.glow$, { - scale: 3, - duration: 0.5 - }, "<+0.05"); - } - if (this.isActive) { - tl.add(() => this.activate_Animation(clockElems$), "<+0.05"); - } else { - tl.add(() => this.deactivate_Animation(clockElems$), "<+0.05"); - } - return tl; } - async reveal_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("reveal_SocketCall", displayContext, this.parentKey.id, this.index); + get isVisible() { + return this.data.isVisible; } - static reveal_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; - } - const clock = key.getClockByIndex(index); - if (!clock) { - return; - } - const clockElems$ = clock.getElements$(displayContext); - clock.reveal_Animation(clockElems$); + set isVisible(val) { + this.updateTarget("isVisible", U.pBool(val)).then(() => { + this.renderTargetAndKeeper(); + }); } - hide_Animation(clockElems$, callback) { - const fadeOutElements = [ - clockElems$.frame$, - clockElems$.fill$ - ].filter((el$) => el$ !== void 0); - const tl = U.gsap.timeline({ - callbackScope: this, - onComplete() { - callback == null ? void 0 : callback(); - } + get isNameVisible() { + return this.data.isNameVisible; + } + set isNameVisible(val) { + this.updateTarget("isNameVisible", U.pBool(val)).then(() => { + this.renderTargetAndKeeper(); }); - tl.to(fadeOutElements, { - autoAlpha: 0, - scale: 2, - duration: 0.5, - stagger: 0.2, - ease: "power2" + } + get isSpotlit() { + return this.data.isSpotlit; + } + set isSpotlit(val) { + this.updateTarget("isSpotlit", val).then(() => { + this.renderTargetAndKeeper(); }); - if (this.name && this.isNameVisible) { - tl.blurRemove(clockElems$.clockLabel$, { - ignoreMargin: true, - duration: 0.75 - }, "<+0.05"); - } - if (this.isHighlighted) { - tl.scaleDownRemove(clockElems$.glow$, { - scale: 3, - duration: 0.5 - }, "<+0.05"); - } - tl.to(clockElems$.cover$, { scale: 1, autoAlpha: 1, duration: 0.5, ease: "power2" }); - return tl; } - async hide_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("hide_SocketCall", displayContext, this.parentKey.id, this.index); + get clocksData() { + return this.data.clocksData; } - static hide_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; + get displayMode() { + return this.data.displayMode; + } + get oneKeyIndex() { + let { oneKeyIndex } = this.data; + if (!oneKeyIndex) { + oneKeyIndex = U.gsap.utils.random(0, 4, 1); + this.updateTarget("oneKeyIndex", oneKeyIndex).then(() => { + this.renderTargetAndKeeper(); + }); } - const clock = key.getClockByIndex(index); - if (!clock) { - return; + return oneKeyIndex; + } + get sceneIDs() { + return this.data.sceneIDs ?? []; + } + get overlayPosition() { + var _a; + return (_a = this.data.overlayPosition) == null ? void 0 : _a[game.scenes.current.id]; + } + set overlayPosition(val) { + if (val) { + this.updateTarget(`overlayPosition.${game.scenes.current.id}`, val).then(() => { + this.renderTargetAndKeeper(); + }); + } else { + this.updateTarget(`overlayPosition.-=${game.scenes.current.id}`, null).then(() => { + this.renderTargetAndKeeper(); + }); } - const clockElems$ = clock.getElements$(displayContext); - clock.hide_Animation(clockElems$); } - activate_Animation(clockElems$, callback) { - U.gsap.to(clockElems$.bg$, { autoAlpha: 1, duration: 0.5, ease: "power2" }); - U.gsap.to(clockElems$.frame$, { - filter: "brightness(0.5)", - duration: 0.5, - ease: "power2", - onComplete: callback - }); + // #endregion + get clocks() { + return new Collection( + Object.entries(this.clocksData).sort((a, b) => a[1].index - b[1].index).map(([id, data]) => { + return [id, new BladesClock(data)]; + }) + ); + } + getClockByID(clockID) { + return this.clocks.get(clockID); + } + getClockByIndex(index) { + return this.clocks.find((clock) => clock.index === index); + } + get size() { + return this.clocks.size; + } + get isComplete() { + return Array.from(this.clocks).every((clock) => clock.isComplete); + } + get isClockKeeperKey() { + return this.target instanceof BladesClockKeeper$1; + } + get isFactionKey() { + return this.target instanceof BladesFaction$1; } - async activate_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("activate_SocketCall", displayContext, this.parentKey.id, this.index); + get isProjectKey() { + return this.target instanceof BladesProject$1; } - static activate_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; - } - const clock = key.getClockByIndex(index); - if (!clock) { - return; - } - clock.activate_Animation(clock.getElements$(displayContext)); + get isScoreKey() { + return this.target instanceof BladesScore$1; } - deactivate_Animation(clockElems$, callback) { - U.gsap.to(clockElems$.bg$, { autoAlpha: 0, duration: 0.5, ease: "power2" }); - U.gsap.to(clockElems$.frame$, { - filter: "brightness(1) blur(5px)", - duration: 0.5, - ease: "power2", - onComplete: callback - }); + get visibleClocks() { + return this.clocks.filter((clock) => clock.isVisible); } - async deactivate_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("deactivate_SocketCall", displayContext, this.parentKey.id, this.index); + get activeClocks() { + return this.visibleClocks.filter((clock) => clock.isActive); } - static deactivate_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; - } - const clock = key.getClockByIndex(index); - if (!clock) { - return; - } - clock.deactivate_Animation(clock.getElements$(displayContext)); + get inProgressClocks() { + return this.visibleClocks.filter((clock) => !clock.isComplete && clock.value > 0); } - fadeInClockName_Animation(clockElems$) { - U.gsap.effects.blurReveal(clockElems$.clockLabel$, { - ignoreMargin: true, - duration: 0.75 - }); + get unstartedClocks() { + return this.visibleClocks.filter((clock) => clock.value === 0); } - async fadeInClockName_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("fadeInClockName_SocketCall", displayContext, this.parentKey.id, this.index); + get completedClocks() { + return this.visibleClocks.filter((clock) => clock.isComplete); } - static fadeInClockName_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; + get currentClock() { + if (this.activeClocks.length > 0) { + return this.getEarliestClock(this.activeClocks); } - const clock = key.getClockByIndex(index); - if (!clock) { - return; + if (this.completedClocks.length > 0) { + return this.getLatestClock(this.completedClocks); } - clock.fadeInClockName_Animation(clock.getElements$(displayContext)); + if (this.visibleClocks.length > 0) { + return this.getEarliestClock(this.visibleClocks); + } + return this.getEarliestClock(Array.from(this.clocks)); } - fadeOutClockName_Animation(clockElems$) { - U.gsap.effects.blurRemove(clockElems$.clockLabel$, { - ignoreMargin: true, - duration: 0.75 - }); + get fullDisplayPosData() { + const x = this.svgData.width / 2; + const y = this.svgData.height / 2; + return { + x, + y, + width: this.svgData.width, + height: this.svgData.height + }; } - async fadeOutClockName_SocketCall(displayContext) { - if (!game.user.isGM) { - return; - } - socketlib.system.executeForEveryone("fadeOutClockName_SocketCall", displayContext, this.parentKey.id, this.index); + get clocksDisplayPosData() { + return this.getClocksBoundingBox(Array.from(this.clocks)); } - static fadeOutClockName_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; - } - const clock = key.getClockByIndex(index); - if (!clock) { - return; - } - clock.fadeOutClockName_Animation(clock.getElements$(displayContext)); + get visibleClocksDisplayPosData() { + return this.getClocksBoundingBox(this.visibleClocks); } - highlight_Animation(clockElems$) { - U.gsap.effects.scaleUpReveal(clockElems$.glow$, { - duration: 0.5, - scale: 3 + get activeClocksDisplayPosData() { + return this.getClocksBoundingBox(this.activeClocks); + } + getClocksBoundingBox(clocks) { + const { size, ...allClocksPosData } = this.svgData.clocks; + const clocksPosData = Object.fromEntries( + Object.entries(allClocksPosData).filter(([index]) => clocks.map((clock) => clock.index).includes(U.pInt(index))).map(([index, posData]) => [U.pInt(index), posData]) + ); + const clockWidthPosData = Object.values(clocksPosData).sort((a, b) => a.x - b.x); + const clockHeightPosData = Object.values(clocksPosData).sort((a, b) => a.y - b.y); + const xLowest = clockWidthPosData[0].x; + const xHighest = clockWidthPosData[clockWidthPosData.length - 1].x; + const yLowest = clockHeightPosData[0].y; + const yHighest = clockHeightPosData[clockHeightPosData.length - 1].y; + return { + // Determine the center point in both x and y axes + x: (xLowest + xHighest) / 2, + y: (yLowest + yHighest) / 2, + // Determine height and width of bounding box, accounting for clock size + width: xHighest - xLowest + size, + height: yHighest - yLowest + size + }; + } + /** This function accepts any number of arrays of BladesClock, then returns an array + * containing those BladesClock instances that appear in ALL provided arrays. + */ + getClocksIn(...clockArrays) { + if (clockArrays.length === 0) + return []; + return clockArrays.reduce((acc, currentArray) => { + return acc.filter((clock) => currentArray.includes(clock)); }); } - async highlight_SocketCall(displayContext) { - if (!game.user.isGM) { - return; + /** This function accepts an array of BladesClock, and returns the BladesClock + * instance with the lowest index property. + */ + getEarliestClock(clockArray) { + if (clockArray.length) { + return clockArray.sort((a, b) => a.index - b.index)[0]; } - socketlib.system.executeForEveryone("highlight_SocketCall", displayContext, this.parentKey.id, this.index); + return void 0; } - static highlight_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; - } - const clock = key.getClockByIndex(index); - if (!clock) { - return; + /** This function accepts an array of BladesClock, and returns the BladesClock + * instance with the highest index property. + */ + getLatestClock(clockArray) { + if (clockArray.length) { + return clockArray.sort((a, b) => b.index - a.index)[0]; } - clock.highlight_Animation(clock.getElements$(displayContext)); + return void 0; } - unhighlight_Animation(clockElems$) { - U.gsap.effects.scaleDownRemove(clockElems$.glow$, { - duration: 0.5, - scale: 3 - }); + isInScene(sceneID = game.scenes.current.id) { + return this.sceneIDs.includes(sceneID); } - async unhighlight_SocketCall(displayContext) { - if (!game.user.isGM) { - return; + get isInCurrentScene() { + return this.isInScene(game.scenes.current.id); + } + get displaySelectOptions() { + const options = [ + { value: ClockKeyDisplayMode.full, display: "Full Key" }, + { value: ClockKeyDisplayMode.clocks, display: "Clocks" }, + { value: ClockKeyDisplayMode.activeClocks, display: "Active Clocks" } + ]; + for (let i = 0; i < this.size; i++) { + options.push(...[ + { value: i, display: `Clock #${i}` }, + { value: `present${i}`, display: `Present Clock #${i}` } + ]); } - socketlib.system.executeForEveryone("unhighlight_SocketCall", displayContext, this.parentKey.id, this.index); + return options; } - static unhighlight_SocketResponse(displayContext, keyID, index) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; + // parseClockConfig(config: BladesClock.Config, indexOverride?: ClockIndex): BladesClock.Data { + // if (this.size === 6) {throw new Error("Cannot add a clock to a clock key with 6 clocks.");} + // if (indexOverride !== undefined && indexOverride < 0) {throw new Error("Cannot add a clock with a negative index.");} + // // Remove target so it doesn't conflict with key's targetID + // // delete config.target; + // const {target, targetID, targetKey, targetFlagKey, ...partialSchema} = config; + // const linkData: BladesTargetLink.LinkData = this.targetKey + // ? { + // targetID: this.targetID, + // targetKey: `${this.targetKeyPrefix}.clocksData` as TargetKey + // } + // : { + // targetID: this.targetID, + // targetFlagKey: `${this.targetFlagKeyPrefix}.clocksData` as TargetFlagKey + // }; + // // Derive clock's targetID and targetKey/targetFlagKey from key's values + // data.targetID = this.targetID; + // if (this.targetKey) { + // data.targetKey = `${this.targetKeyPrefix}.clocksData` as TargetKey; + // } else if (this.targetFlagKey) { + // data.targetFlagKey = `${this.targetFlagKeyPrefix}.clocksData` as TargetFlagKey; + // } + // // Assign 'parentKeyID' and 'index' + // config.parentKeyID = this.id; + // config.index = indexOverride ?? this.size; + // // Parse config to full data object + // return BladesClock.ApplySchemaDefaults( + // BladesClock.ParseConfigToData(config as BladesClock.Config) + // ); + // } + // #endregion + // #region HTML INTERACTION ~ + // #region Get Elements$ ~ + getElemFromDisplayContext(displayContext) { + let elem$; + const DOM$ = $(".vtt.game.system-eunos-blades"); + switch (displayContext) { + case ClockDisplayContext.overlay: { + elem$ = DOM$.find(`#blades-overlay #${this.id}`); + break; + } + case ClockDisplayContext.pcSheet: { + elem$ = DOM$.find(`.actor.sheet .pc #${this.id}`); + break; + } + case ClockDisplayContext.factionSheet: { + elem$ = DOM$.find(`.actor.sheet .faction #${this.id}`); + break; + } + case ClockDisplayContext.projectSheet: { + elem$ = DOM$.find(`.item.sheet .project #${this.id}`); + break; + } + case ClockDisplayContext.scoreSheet: { + elem$ = DOM$.find(`.item.sheet .score #${this.id}`); + break; + } + case ClockDisplayContext.rollCollab: { + elem$ = DOM$.find(`.roll-collab-sheet #${this.id}`); + break; + } + case ClockDisplayContext.chatMessage: { + elem$ = DOM$.find(`#chat #${this.id}`); + break; + } } - const clock = key.getClockByIndex(index); - if (!clock) { - return; + if (!elem$.length) { + throw new Error(`[BladesClockKey.getElemFromDisplayContext] Error elem$ not found for key '${this.id}' for display context '${displayContext}'.`); } - clock.unhighlight_Animation(clock.getElements$(displayContext)); - } - getRotationOfSegment(segment) { - const stepSize = 360 / this.max; - return stepSize * (segment - 1); + return elem$; } - initOneSegments(clockElems$, segmentNums, isReversing) { - if (segmentNums.length > 3) { - throw new Error(`Too many segments: [${segmentNums.join(", ")}]`); + getElements$(displayContext) { + let elem$; + if (typeof displayContext === "string") { + displayContext = this.getElemFromDisplayContext(displayContext); } - const oneSegs = [...clockElems$.oneSegments$]; - const oneSegsToAnimate = Array.from(clockElems$.oneSegments$).slice(0, segmentNums.length); - for (const segmentNum of segmentNums) { - const oneSegment = oneSegs.shift(); - U.gsap.set(oneSegment, { - rotation: this.getRotationOfSegment(segmentNum), - autoAlpha: isReversing ? 1 : 0 - }); + elem$ = $(displayContext).find(`#${this.id}`); + if (!elem$.length) { + elem$ = $(displayContext).closest(`#${this.id}`); } - if (isReversing) { - clockElems$.clockElem$.attr("data-value", U.getLast(segmentNums) - 1); + if (!(elem$ == null ? void 0 : elem$.length)) { + throw new Error(`[BladesClockKey.getElements$] Cannot find elements for display context '${displayContext}' of clockKey '${this.id}'.`); } - return oneSegsToAnimate; - } - changeSegments_Animation(clockElems$, startVal, endVal, callback) { - startVal = U.gsap.utils.clamp(0, this.max, startVal); - endVal = U.gsap.utils.clamp(0, this.max, endVal); - let delta = endVal - startVal; - if (delta === 0) { - return; + const keyElems$ = { + elem$ + }; + if (!elem$.length) { + throw new Error(`[BladesClockKey.renderClockKey] Error '.clock-key-container' not found for key '${this.id}'.`); } - const segmentNums = []; - if (delta < 0) { - while (Math.abs(delta) > startVal) { - delta++; - } - for (let i = startVal; i > endVal; i--) { - segmentNums.push(i); - } - } else { - while (endVal > this.max) { - delta--; - } - for (let i = startVal + 1; i <= endVal; i++) { - segmentNums.push(i); - } + keyElems$.container$ = elem$.closest(".clock-key-container"); + const imgContainer$ = elem$.find(".key-image-container"); + if (!imgContainer$.length) { + throw new Error(`[BladesClockKey.renderClockKey] Error '.key-image-container' not found for key '${this.id}'.`); } - const segmentsToAnimate = this.initOneSegments(clockElems$, segmentNums, startVal > endVal); - eLog.checkLog3("BladesClock", "changeSegments_Animation", { clockElems$, delta, segmentNums, startVal, endVal, segmentsToAnimate }); - const tl = U.gsap.timeline(); - if (delta > 0) { - tl.fromTo(segmentsToAnimate, { - autoAlpha: 0, - scale: 2 - }, { - autoAlpha: 1, - scale: 1, - duration: 0.5, - stagger: 0.2, - ease: "power2", - callbackScope: this, - onComplete() { - clockElems$.clockElem$.attr("data-value", endVal); - U.gsap.to(segmentsToAnimate, { - autoAlpha: 0, - duration: 0.5, - stagger: 0.2 - // onComplete() { - // // Return clock key to original size and focus - // clockFocusTimeline.reverse(); - // } - }); - } - }); - } else { - tl.fromTo(segmentsToAnimate, { - autoAlpha: 1, - scale: 1 - }, { - autoAlpha: 0, - scale: 2, - duration: 0.5, - stagger: 0.2, - ease: "power2" - // onComplete() { - // // Return clock key to original size and focus - // clockFocusTimeline.reverse(); - // } - }); + keyElems$.imgContainer$ = imgContainer$; + const label$ = elem$.find(".key-label"); + if (!label$.length) { + throw new Error(`[BladesClockKey.renderClockKey] Error label$ not found for key '${this.id}'.`); } - return tl; - } - async changeSegments_SocketCall(displayContext, startVal, endVal) { - if (!game.user.isGM) { - return; + keyElems$.label$ = label$; + const factionLabel$ = elem$.find(".faction-label"); + if (factionLabel$.length) { + keyElems$.factionLabel$ = factionLabel$; } - startVal = U.gsap.utils.clamp(0, this.max, startVal); - endVal = U.gsap.utils.clamp(0, this.max, endVal); - socketlib.system.executeForEveryone("changeSegments_SocketCall", displayContext, this.parentKey.id, this.index, startVal, endVal); - } - static changeSegments_SocketResponse(displayContext, keyID, index, startVal, endVal) { - const key = game.eunoblades.ClockKeys.get(keyID); - if (!(key == null ? void 0 : key.isVisible)) { - return; + const projectLabel$ = elem$.find(".project-label"); + if (projectLabel$.length) { + keyElems$.projectLabel$ = projectLabel$; } - const clock = key.getClockByIndex(index); - if (!clock) { - return; + const scoreLabel$ = elem$.find(".score-label"); + if (scoreLabel$.length) { + keyElems$.scoreLabel$ = scoreLabel$; } - clock.changeSegments_Animation(clock.getElements$(displayContext), startVal, endVal); + this.clocks.forEach((clock) => { + keyElems$.clocks ?? (keyElems$.clocks = {}); + keyElems$.clocks[clock.id] = clock.getElements$(displayContext); + }); + eLog.checkLog3("BladesClockKey", "Clock Key Elements", keyElems$); + return keyElems$; } // #endregion - // #region Adding/Removing Clock Segments ~ - // Returns number of segments beyond max (or 0, if max not met) - async fillSegments(count, isSilent = false) { - const clockOverflow = Math.max(0, this.value + count - this.max); - count = Math.min(this.value + count, this.max) - this.value; - if (count === 0) { - return clockOverflow; - } - await this.updateTarget("value", this.value + count); - if (!isSilent) { - this.parentKey.renderTargetAndKeeper(); + // #region Initial Rendering ~ + async renderTo(parentElem) { + const parent$ = $(parentElem); + if (!parent$.length) { + throw new Error(`[BladesClockKey.renderClockKeyTo] Error parent element not provided for key '${this.id}'.`); } - return clockOverflow; + const clockKeyHTML = await renderTemplate( + "systems/eunos-blades/templates/components/clock-key.hbs", + this + ); + $(clockKeyHTML).appendTo(parent$); } - // Returns (positive) number of segments removed - // in excess of the number of segments in the clock - async clearSegments(count, isSilent = false) { - const clockOverflow = Math.max(0, count - this.value); - count = Math.min(this.value, count); - if (count === 0) { - return clockOverflow; + /** + * This function generates a partial GSAP.TweenVars object that will display the key in a given mode within the bounds of a provided container. + * + * @param {ClockKeyDisplayMode | number} [displayMode="full"] - The display mode. Options include: + * - "full" - displays the entire clock key + * - "clocks" - zooms in to display only the clocks + * - "activeClocks" - zooms in to the active clocks + * - "presentN" (where N is a clock index number) - zooms in to the clock at index N, and presents whichever side has the next available segment towards the camera. + * - A clock index number - zooms in to the clock at index N + * + * @param {HTMLElement | JQuery | {x: number, y: number, width: number, height: number}} [container$] - The container within which the key will be displayed. + * This can be: + * - An HTMLElement + * - A JQuery + * - A {x, y, width, height} position definition + * If not provided, it defaults to the clock key's container element (only if the key is already rendered in the DOM). + * + * @returns {gsap.TweenVars} - A partial GSAP.TweenVars object that describes how to display the key in the given mode within the bounds of the provided container. The returned object may include the following properties: + * - 'scale' (number): A multiple to be applied to scale at "full" display mode. + * - 'top' (number): A delta vertical shift from "full" display mode position. + * - 'left' (number): A delta horizontal shift from "full" display mode position. + * - 'transformOrigin': An absolute value. + * - 'rotationZ': An absolute value for the keySwing axis. + * - 'rotationY': An absolute value for rotation in/out of the screen. + * Any variables left undefined default to "full" display mode. + */ + getVarsForDisplayMode(keyElems$, displayMode = ClockKeyDisplayMode.full, container$) { + const keyTweenVars = {}; + const keyImgContTweenVars = {}; + container$ ?? (container$ = keyElems$.container$); + let targetPosData; + if (container$ instanceof HTMLElement || container$ instanceof jQuery) { + const containerPosData = U.gsap.getProperty($(container$)[0]); + targetPosData = { + x: containerPosData("x"), + y: containerPosData("y"), + width: containerPosData("width"), + height: containerPosData("height") + }; + } else if (isElemPosData(container$)) { + targetPosData = container$; + } else { + throw new Error(`[BladesClockKey.getVarsForDisplayMode] Error container$ '${container$}' is not a valid type.`); + } + let presentingClock; + let focusPosData; + switch (displayMode) { + case ClockKeyDisplayMode.full: { + focusPosData = { + x: this.svgData.width / 2, + y: this.svgData.height / 2, + width: this.svgData.width, + height: this.svgData.height + }; + break; + } + case ClockKeyDisplayMode.clocks: { + focusPosData = this.getClocksBoundingBox(Array.from(this.clocks)); + break; + } + case ClockKeyDisplayMode.activeClocks: { + focusPosData = this.getClocksBoundingBox(this.getClocksIn(this.activeClocks, this.visibleClocks)); + break; + } + case ClockKeyDisplayMode.presentCurrentClock: { + presentingClock = this.currentClock; + displayMode = presentingClock.index; + } + default: { + if (typeof displayMode === "string" && displayMode.startsWith("present")) { + displayMode = U.pInt(displayMode.toString().slice(7)); + presentingClock = this.getClockByIndex(displayMode); + } + if (!U.isInt(displayMode) || displayMode < 0 || displayMode >= this.size) { + throw new Error(`[BladesClockKey.getVarsForDisplayMode] Error display mode '${displayMode}' is not a valid clock index for key '${this.id}'.`); + } + const focusClockData = this.svgData.clocks[displayMode]; + focusPosData = { + x: focusClockData.x, + y: focusClockData.y, + width: this.svgData.clocks.size, + height: this.svgData.clocks.size + }; + break; + } } - await this.updateTarget("value", this.value - count); - if (!isSilent) { - this.parentKey.renderTargetAndKeeper(); + keyTweenVars.scale = Math.min( + targetPosData.height / focusPosData.height, + targetPosData.width / focusPosData.width + ); + keyImgContTweenVars.top = 0.5 * C.ClockKeySquareSize - focusPosData.y; + keyImgContTweenVars.left = 0.5 * C.ClockKeySquareSize - focusPosData.x; + keyImgContTweenVars.transformOrigin = `${focusPosData.x}px ${focusPosData.y}px`; + keyImgContTweenVars.rotateY = 0; + if (presentingClock) { + keyTweenVars.scale *= 2; + if (presentingClock.getActiveSide() === "left") { + keyImgContTweenVars.rotateY = 30; + keyImgContTweenVars.left += this.size === 1 ? 45 : 25; + } else if (presentingClock.getActiveSide() === "right") { + keyImgContTweenVars.rotateY = -30; + keyImgContTweenVars.left -= this.size === 1 ? 45 : 25; + } } - return clockOverflow; - } - async delete() { - const { parentKey } = this; - await super.delete(false); - parentKey.updateClockIndices(); - } - // #endregion -} -const _BladesDirector = class _BladesDirector { - constructor() { - __publicField(this, "_id"); - // #endregion - // #endregion - // #region OVERLAY ~ - // #region >> Overlay Elements$ ~ - __publicField(this, "_overlayContainer"); - __publicField(this, "_overlayContainer$"); - // - As with notifications: placeholder animation until something more final can be coded. - // #endregion - // #region TOOLTIPS ~ - __publicField(this, "_tooltipObserver"); - __publicField(this, "_tooltipElems", /* @__PURE__ */ new Map()); - __publicField(this, "_displayedTooltipID"); - this._id = randomID(); - } - static getInstance() { - return _BladesDirector.instance ?? (_BladesDirector.instance = new _BladesDirector()); + return { keyTweenVars, keyImgContTweenVars }; } - // #endregion - static async Initialize() { - Hooks.on("renderApplication", async () => { - game.eunoblades.Director.initClockKeySection(true); - if (game.user.isGM) { - await game.eunoblades.ClockKeeper.update({ "system.targetScene": game.scenes.current.id }); - game.eunoblades.ClockKeeper.render(); - } + // public fitKeyToContainer( + // keyElems$: ClockKeyElems$, + // posOverrides?: Partial + // ) { + // const {container$, elem$, imgContainer$} = keyElems$; + // // Get position data for the container$ element (x, y, width, height) + // const keyPosition: ElemPosData = { + // x: U.gsap.getProperty(container$[0], "x") as number, + // y: U.gsap.getProperty(container$[0], "y") as number, + // width: U.gsap.getProperty(container$[0], "width") as number, + // height: U.gsap.getProperty(container$[0], "height") as number + // }; + // const {xShift, yShift, scaleMult, ...focusPosOverrides} = posOverrides ?? {}; + // const focusPosition: ElemPosData = { + // ...this.fullDisplayPosData, + // ...focusPosOverrides + // }; + // eLog.checkLog3("BladesClockKey", "[BladesClockKey] Key Positions", { + // keyPosition, + // focusPosition, + // widthScale: keyPosition.width / focusPosition.width, + // heightScale: keyPosition.height / focusPosition.height + // }); + // // Apply scale factor to elem$ to fit default key position inside container$ + // U.gsap.set(elem$, { + // scale: Math.min( + // keyPosition.width / focusPosition.width, + // keyPosition.height / focusPosition.height + // ) * (scaleMult ?? 1) + // }); + // // Apply top, left and transformOrigin value to keyImgContainer, accounting for x/yPercent -50 + // U.gsap.set(imgContainer$, { + // top: (0.5 * C.ClockKeySquareSize) - focusPosition.y + (yShift ?? 0), + // left: (0.5 * C.ClockKeySquareSize) - focusPosition.x + (xShift ?? 0), + // transformOrigin: `${focusPosition.x + (xShift ?? 0)}px ${focusPosition.y + (yShift ?? 0)}px` + // }); + // } + formatLabels(keyElems$) { + const { label$, clocks, factionLabel$, projectLabel$, scoreLabel$ } = keyElems$; + [ + [label$, 2, 4], + factionLabel$ ? [factionLabel$, 2, 2] : void 0, + projectLabel$ ? [projectLabel$, 2, 2] : void 0, + scoreLabel$ ? [scoreLabel$, 2, 2] : void 0, + ...this.clocks.map((clock) => [clocks[clock.id].clockLabel$, 2.5, 3]) + ].filter(Boolean).forEach(([labelElem$, aspectRatio, maxLines]) => { + U.adjustTextContainerAspectRatio(labelElem$, aspectRatio, maxLines); }); - return loadTemplates([ - "systems/eunos-blades/templates/overlay/blades-overlay.hbs", - "systems/eunos-blades/templates/overlay/location.hbs", - "systems/eunos-blades/templates/overlay/score-panel.hbs", - "systems/eunos-blades/templates/overlay/npc-portrait.hbs", - "systems/eunos-blades/templates/overlay/pc-portrait.hbs", - "systems/eunos-blades/templates/overlay/cohort-portrait.hbs", - "systems/eunos-blades/templates/overlay/crew-status-bar.hbs", - "systems/eunos-blades/templates/overlay/game-phase-bar.hbs", - "systems/eunos-blades/templates/overlay/notices/push.hbs" - ]); - } - // #region >> Sockets ~ - static InitSockets() { - const director = _BladesDirector.getInstance(); - socketlib.system.register("renderOverlay_SocketCall", director.renderOverlay_SocketResponse.bind(director)); - director.initClockSockets(); - director.initScorePanelSockets(); - director.initLocationSockets(); - director.initNPCSockets(); - director.initPCSockets(); - director.initCohortSockets(); - director.initCrewSockets(); - director.initNotificationSockets(); - director.initTransitionSockets(); } - get overlayContainer() { - if (!this._overlayContainer) { - [this._overlayContainer] = $("#blades-overlay"); - } - if (!this._overlayContainer) { - $("body.vtt").append('
'); - [this._overlayContainer] = $("#blades-overlay"); + setToDisplayMode(keyElems$, displayMode, isUpdatingTarget = true) { + const { keyTweenVars, keyImgContTweenVars } = this.getVarsForDisplayMode(keyElems$, displayMode); + U.gsap.set(keyElems$.elem$, keyTweenVars); + U.gsap.set(keyElems$.imgContainer$, keyImgContTweenVars); + if (isUpdatingTarget && displayMode !== this.displayMode) { + this.updateTarget("displayMode", displayMode); } - return this._overlayContainer; } - get overlayContainer$() { - if (!this._overlayContainer$) { - this._overlayContainer$ = $(this.overlayContainer); + initElementsInContext(html, displayMode, isUpdatingTarget = true) { + const keyElems$ = this.getElements$(html); + displayMode ?? (displayMode = this.displayMode); + this.setToDisplayMode(keyElems$, displayMode, isUpdatingTarget); + this.formatLabels(keyElems$); + if (displayMode.toString().startsWith("present") || Number.isInteger(displayMode)) { + U.gsap.to(keyElems$.container$.find(".clock-label, .clock-key-label"), { autoAlpha: 0, duration: 0 }); } - return this._overlayContainer$; - } - get clockKeySection$() { - return this.overlayContainer$.find(".overlay-section-clock-keys"); - } - get locationSection$() { - return this.overlayContainer$.find(".overlay-section-location"); - } - get scorePanelSection$() { - return this.overlayContainer$.find(".overlay-section-score-panel"); - } - get npcSection$() { - return this.overlayContainer$.find(".overlay-section-npcs"); - } - get playerSection$() { - return this.overlayContainer$.find(".overlay-section-players"); - } - get crewSection$() { - return this.overlayContainer$.find(".overlay-section-crew"); - } - get notificationSection$() { - return this.overlayContainer$.find(".overlay-section-notifications"); - } - get transitionSection$() { - return this.overlayContainer$.find(".overlay-section-transitions"); - } - get tooltipSection$() { - return this.overlayContainer$.find(".overlay-section-tooltips"); - } - get svgData() { - return ClockKey_SVGDATA; + return keyElems$; } // #endregion - // #region >> Rendering ~ - renderOverlay_SocketCall() { - if (!game.user.isGM) { + async addToScene(sceneID = game.scenes.current.id) { + if (this.isInScene(sceneID)) { return; } - if (!this.overlayContainer) { + const { sceneIDs } = this; + sceneIDs.push(sceneID); + await this.updateTarget({ + isVisible: false, + sceneIDs + }); + this.renderTargetAndKeeper(); + } + async removeFromScene(sceneID = game.scenes.current.id) { + if (!this.isInScene(sceneID)) { return; } - socketlib.system.executeForEveryone("renderOverlay_SocketCall"); + const { sceneIDs } = this; + U.remove(sceneIDs, sceneID); + await this.updateTarget("sceneIDs", sceneIDs); + this.renderTargetAndKeeper(); } - async renderOverlay_SocketResponse() { - const overlayContent = await renderTemplate( - "systems/eunos-blades/templates/overlay/blades-overlay.hbs", - this - ); - this.overlayContainer$.empty().append(overlayContent); - this.initClockKeySection(); - this.initTooltipSection(); + closeClockKey({ container$ }) { + container$.remove(); } - // #endregion - // #endregion - // #region CLOCKS & CLOCK KEYS ~ - // #region >> INITIALIZATION ~ - initClockKeySection(isResetting = false) { - if (isResetting) { - this.clockKeySection$.empty(); - } - const visibleSceneKeys = U.shuffle(this.sceneKeys.filter((key) => key.isVisible)); - let staggerDelay = 0; - while (visibleSceneKeys.length) { - const key = visibleSceneKeys.shift(); - if (key) { - setTimeout(() => this.renderClockKey(key), staggerDelay * 1e3); - staggerDelay += 0.5; - } + get svgData() { + if (this.size === 0) { + throw new Error("[BladesClockKey.svgData] Error size is 0."); } - setTimeout(() => { - }, staggerDelay * 1e3); + const keyData = ClockKey_SVGDATA[this.size]; + let path; + if (this.size === 1 && keyData.paths) { + path = keyData.paths[this.oneKeyIndex]; + } else if (keyData.path) { + path = keyData.path; + } else { + throw new Error("[BladesClockKey.svgData] Error path is not defined."); + } + return { + width: keyData.width, + height: keyData.height, + path, + clocks: keyData.clocks + }; } - initClockSockets() { - socketlib.system.register("renderClockKey_SocketCall", _BladesDirector.renderClockKey_SocketResponse.bind(_BladesDirector)); - socketlib.system.register("pullKey_SocketCall", _BladesDirector.pullKey_SocketResponse.bind(_BladesDirector)); - socketlib.system.register("fadeInName_SocketCall", BladesClockKey.fadeInName_SocketResponse.bind(BladesClockKey)); - socketlib.system.register("fadeOutName_SocketCall", BladesClockKey.fadeOutName_SocketResponse.bind(BladesClockKey)); - socketlib.system.register("reveal_SocketCall", BladesClock.reveal_SocketResponse.bind(BladesClock)); - socketlib.system.register("hide_SocketCall", BladesClock.hide_SocketResponse.bind(BladesClock)); - socketlib.system.register("activate_SocketCall", BladesClock.activate_SocketResponse.bind(BladesClock)); - socketlib.system.register("deactivate_SocketCall", BladesClock.deactivate_SocketResponse.bind(BladesClock)); - socketlib.system.register("fadeInClockName_SocketCall", BladesClock.fadeInClockName_SocketResponse.bind(BladesClock)); - socketlib.system.register("fadeOutClockName_SocketCall", BladesClock.fadeOutClockName_SocketResponse.bind(BladesClock)); - socketlib.system.register("highlight_SocketCall", BladesClock.highlight_SocketResponse.bind(BladesClock)); - socketlib.system.register("unhighlight_SocketCall", BladesClock.unhighlight_SocketResponse.bind(BladesClock)); - socketlib.system.register("changeSegments_SocketCall", BladesClock.changeSegments_SocketResponse.bind(BladesClock)); + isInOverlay(elem) { + return $(elem).hasClass(".overlay-section") || $(elem).closest(".overlay-section").length > 0; } - // #endregion - get sceneKeys() { - return game.eunoblades.ClockKeeper.getSceneKeys(game.scenes.current.id); + get keyHeight() { + return this.svgData.height; } - // #region >> Rendering (Dropping) Clock Keys ~ - dropKey_Animation(key, keyElems$) { - const { - container$, - label$, - imgContainer$, - clocks - } = keyElems$ ?? key.getElements$(game.eunoblades.Director.clockKeySection$); - const keySwingTimeline = imgContainer$.data("keySwingTimeline"); - const tl = U.gsap.timeline().call(() => { - keySwingTimeline.seek("NEUTRAL").play(); - }).from(container$, { - y: -800, - ease: "bounce", - duration: 1 - }, 0).to(container$, { autoAlpha: 1, duration: 0.5, ease: "power2" }, 0); - key.visibleClocks.forEach((clock, i) => { - tl.add( - () => { - clock.reveal_Animation(clocks[clock.id]); - }, - i === 0 ? ">" : "<+0.15" - ); - }); - if (key.name && key.isNameVisible) { - tl.blurReveal(label$, { - ignoreMargin: true, - duration: 0.75 - }, "<+0.05"); - } + get keyWidth() { + return this.svgData.width; } - prepareClockKeyTimelines(key, keyElems$) { - const { container$, imgContainer$, elem$, label$, clocks } = keyElems$; - U.gsap.set(container$, { pointerEvents: "auto" }); - U.gsap.set(elem$, { filter: "brightness(1)" }); - U.gsap.set(imgContainer$, { transformOrigin: "50% 10%" }); - const keyElemScale = U.gsap.getProperty(container$[0], "scale"); - imgContainer$.data( - "keySwingTimeline", - U.gsap.timeline({ paused: true, repeat: -1, yoyo: true }).fromTo(imgContainer$, { rotateZ: -1 }, { rotateZ: 1, duration: 3, ease: "sine.inOut" }).addLabel("NEUTRAL", 1.5).seek("NEUTRAL") - ); - container$.data( - "hoverOverTimeline", - U.gsap.timeline({ - paused: true, - data: { key, imgContainer$, label$, isNameRevealed: false }, - onStart() { - this.data.imgContainer$.data("keySwingTimeline").tweenTo("NEUTRAL", { - duration: 0.25, - ease: "back.out(1.5)" - }); - if (this.data.key.name && !this.data.key.isNameVisible) { - this.data.isNameRevealed = true; - U.gsap.effects.blurReveal(this.data.label$, { - ignoreMargin: true, - duration: 0.5 - }); - } - }, - onReverseComplete() { - this.data.imgContainer$.data("keySwingTimeline").seek("NEUTRAL").play(); - if (this.data.isNameRevealed) { - this.data.isNameRevealed = false; - U.gsap.effects.blurRemove(this.data.label$, { - ignoreMargin: true, - duration: 0.5 - }); - } - } - }).to(elem$, { filter: "brightness(1.5)", scale: keyElemScale * 1.25, duration: 0.5, ease: "sine" }) - ); - key.clocks.forEach((clock) => { - const { clockContainer$, clockLabel$, clockElem$ } = clocks[clock.id]; - if (!(clockContainer$ == null ? void 0 : clockContainer$.length)) { - throw new Error(`[BladesDirector.prepareClockKeyTimelines] Error clockContainer$ not found for clock '${clock.id}' of key '${key.id}'.`); - } - U.gsap.set(clockContainer$, { pointerEvents: "auto" }); - clockContainer$.data( - "hoverOverTimeline", - U.gsap.timeline({ - paused: true, - data: { clock, clockLabel$, isNameRevealed: false }, - onStart() { - if (this.data.clock.name && !this.data.clock.isNameVisible) { - this.data.isNameRevealed = true; - U.gsap.effects.blurReveal(this.data.clockLabel$, { - ignoreMargin: true, - duration: 0.5 - }); - } - }, - onReverseComplete() { - if (this.data.isNameRevealed) { - this.data.isNameRevealed = false; - U.gsap.effects.blurRemove(this.data.clockLabel$, { - ignoreMargin: true, - duration: 0.5 - }); - } - } - }).to(clockElem$, { filter: "brightness(1.5)", scale: 1.25, duration: 0.25, ease: "sine" }) - ); - }); + get keyViewbox() { + return `0 0 ${this.svgData.width} ${this.svgData.height}`; } - async activateClockKeyListeners(key, keyElems$) { - const { container$, clocks } = keyElems$; - if (game.user.isGM) { - container$.on("dblclick", async () => { - var _a; - (_a = game.eunoblades.ClockKeeper.sheet) == null ? void 0 : _a.render(true); - }); - container$.on("contextmenu", async () => { - this.pullKey_SocketCall(key.id); - key.updateTarget("isVisible", false); - }); - } else { - container$.on("mouseenter", () => { - container$.data("hoverOverTimeline").play(); - }).on("mouseleave", () => { - container$.data("hoverOverTimeline").reverse(); - }); - key.clocks.forEach((clock) => { - const { clockContainer$ } = clocks[clock.id]; - clockContainer$.on("mouseenter", () => { - if (clock.isVisible) { - clockContainer$.data("hoverOverTimeline").play(); - } - }).on("mouseleave", () => { - if (clock.isVisible) { - clockContainer$.data("hoverOverTimeline").reverse(); - } - }); - }); + get keyPath() { + return this.svgData.path; + } + get clockSize() { + return this.svgData.clocks.size; + } + getClockPosition(clockIndex = 0) { + if (clockIndex > this.size) { + throw new Error(`[BladesClockKey.getClockPosition] Error clockIndex '${clockIndex}' is greater than key size '${this.size}'.`); + } + if (clockIndex < 0) { + throw new Error(`[BladesClockKey.getClockPosition] Error clockIndex '${clockIndex}' is less than 0.`); } + return this.svgData.clocks[clockIndex]; } - async renderClockKey(key) { - await key.renderTo(this.clockKeySection$); - if (key.positionDragger) { - key.removePositionDragger(); + removePositionDragger() { + var _a, _b; + (_a = this.positionDragger) == null ? void 0 : _a.target.remove(); + (_b = this.positionDragger) == null ? void 0 : _b.kill(); + delete this.positionDragger; + } + spawnPositionDragger(containerElem$ = game.eunoblades.Director.clockKeySection$) { + const self2 = this; + if (this.positionDragger) { + this.removePositionDragger(); } - const keyElems$ = key.initElementsInContext(this.clockKeySection$, ClockKeyDisplayMode.full); - if (key.overlayPosition) { - U.gsap.set(keyElems$.container$, { - left: key.overlayPosition.x, - top: key.overlayPosition.y + const dragElem$ = $(`
`).appendTo(containerElem$); + if (this.overlayPosition) { + dragElem$.css({ + left: this.overlayPosition.x, + top: this.overlayPosition.y }); } - this.prepareClockKeyTimelines(key, keyElems$); - this.activateClockKeyListeners(key, keyElems$); - this.dropKey_Animation(key, keyElems$); + this.positionDragger = new Draggable(dragElem$, { + type: "top,left", + onDragStart() { + $(this.target).css("background", "rgba(255, 255, 0, 0.25)"); + $(this.target).css("outlineColor", "rgba(255, 255, 0, 1)"); + }, + onDragEnd() { + $(this.target).css("background", "rgba(255, 0, 255, 0.25)"); + $(this.target).css("outlineColor", "rgba(255, 0, 255, 1)"); + self2.overlayPosition = { x: this.endX, y: this.endY }; + } + }); + } + switchToMode(keyElems$, displayMode, extendKeyVars = {}, extendKeyContainerVars = {}, isUpdatingTarget = true, callback) { + const { elem$, imgContainer$ } = keyElems$; + const { keyTweenVars, keyImgContTweenVars } = this.getVarsForDisplayMode(keyElems$, displayMode); + const currentDisplayMode = this.displayMode; + const randomID2 = U.gsap.utils.random(1, 1e3, 1); + return U.gsap.timeline({ + callbackScope: this, + paused: true, + onStart() { + eLog.checkLog2("BladesClockKey", `switchToMode #${randomID2} - START`, { key: this, keyElems$, displayMode }); + }, + onComplete() { + eLog.checkLog3("BladesClockKey", `switchToMode #${randomID2} - COMPLETE`, { key: this, keyElems$, displayMode }); + if (isUpdatingTarget && displayMode !== this.currentDisplayMode) { + this.updateTarget("displayMode", displayMode).then(() => callback == null ? void 0 : callback()); + } else { + callback == null ? void 0 : callback(); + } + }, + onReverseComplete() { + eLog.checkLog3("BladesClockKey", `switchToMode #${randomID2} - REVERSE COMPLETE`, { key: this, keyElems$, displayMode }); + if (isUpdatingTarget) { + this.updateTarget("displayMode", currentDisplayMode); + } + } + }).to(elem$, { ...keyTweenVars, ...extendKeyVars }, 0).to(imgContainer$, { ...keyImgContTweenVars, ...extendKeyContainerVars }, 0); + } + // #endregion + // #region ANIMATED UPDATES (Both GM-Only AND Socket Calls) + // #region > SOCKET CALLS: _SocketCall / static _SocketResponse / _Animation + fadeInName_Animation(keyElems$) { + if (!this.name) { + return void 0; + } + return U.gsap.effects.blurReveal(keyElems$.label$, { + ignoreMargin: true, + duration: 0.75 + }); } - async renderClockKey_SocketCall(keyID) { + async fadeInName_SocketCall(displayContext) { if (!game.user.isGM) { return; } - socketlib.system.executeForEveryone("renderClockKey_SocketCall", keyID); + socketlib.system.executeForEveryone("fadeInName_SocketCall", displayContext, this.id); } - static async renderClockKey_SocketResponse(keyID) { + static fadeInName_SocketResponse(displayContext, keyID) { const key = game.eunoblades.ClockKeys.get(keyID); if (!key) { return; } - game.eunoblades.Director.renderClockKey(key); + key.fadeInName_Animation(key.getElements$(displayContext)); } - // #endregion - // #region >> Un-Rendering (Pulling) Clock Keys ~ - pullKey_Animation(key) { - const { container$ } = key.getElements$(game.eunoblades.Director.clockKeySection$); - U.gsap.timeline().to(container$, { - y: -800, - ease: "back.in(1)", + fadeOutName_Animation(keyElems$) { + if (!this.name) { + return void 0; + } + return U.gsap.effects.blurRemove(keyElems$.label$, { + ignoreMargin: true, duration: 0.75 - }).to(container$, { - opacity: 0, - ease: "power2.out", - duration: 0.25 - }, 0.75).call(() => { - container$.remove(); }); } - async pullKey_SocketCall(keyID) { + async fadeOutName_SocketCall(displayContext) { if (!game.user.isGM) { return; } - socketlib.system.executeForEveryone("pullKey_SocketCall", keyID); + this.fadeOutName_Animation(this.getElements$(displayContext)); + socketlib.system.executeForOthers("fadeOutName_SocketCall", displayContext, this.id); } - static pullKey_SocketResponse(keyID) { + static fadeOutName_SocketResponse(displayContext, keyID) { const key = game.eunoblades.ClockKeys.get(keyID); if (!key) { return; } - game.eunoblades.Director.pullKey_Animation(key); + key.fadeOutName_Animation(key.getElements$(displayContext)); } + // #endregion // #endregion - // #endregion - // #region SCORE PANEL ~ - // #region >> INITIALIZATION ~ - initScorePanelSockets() { + // #region Adding & Removing Clocks ~ + async updateClockIndices() { + await this.updateTarget("clocksData", Object.fromEntries( + Object.entries(this.clocksData).map(([id, data], index) => [id, { ...data, index }]) + )); + return this.clocks; } - // #endregion - // ## Score Details - // - Small panel overlapping corner of Location - // - Engagement roll result - // - Plan & Detail - // - Target tier - activateScorePanelListeners() { + async addClock(clockSchema = {}) { + const cData = BladesClock.ParseConfigToData({ + ...BladesClock.ApplySchemaDefaults(clockSchema), + index: this.size, + targetID: this.targetID, + targetKey: `${this.targetKeyPrefix}.clocksData`, + isScopingById: true + }); + await this.updateTarget(`clocksData.${cData.id}`, cData); + void this.clocks; + this.renderTargetAndKeeper(); + } + async deleteClock(clockID) { + var _a, _b; + if (this.size <= 1) { + throw new Error("[BladesClockKey.deleteClock()] Cannot reduce number of clocks below 1!"); + } + clockID ?? (clockID = (_a = Array.from(this.clocks).pop()) == null ? void 0 : _a.id); + if (!clockID) { + return; + } + await ((_b = this.getClockByID(clockID)) == null ? void 0 : _b.delete()); + await this.updateClockIndices(); + void this.clocks; } // #endregion - // #region LOCATIONS ~ - // #region >> INITIALIZATION ~ - initLocationSockets() { + // #region OVERRIDES: Async Update Methods + renderTargetAndKeeper() { + var _a; + this.renderTarget(); + (_a = game.eunoblades.ClockKeeper.sheet) == null ? void 0 : _a.render(); + } + renderTarget() { + var _a; + (_a = this.target.sheet) == null ? void 0 : _a.render(); } // #endregion - // ## Locations - // - District wrapper/header - // - Faction wrapper/footer - // - Location main - // - Slide-scroll of sublocations - activateLocationListeners() { +} +class BladesClock extends BladesTargetLink { + // #region STATIC METHODS ~ + static ApplySchemaDefaults(schemaData) { + const namedValueMax = { + name: schemaData.name ?? "", + value: schemaData.value ?? 0, + max: schemaData.max ?? 8 + }; + return { + index: 0, + color: ClockColor.white, + isVisible: !U.isInt(schemaData.index) || schemaData.index === 0, + isNameVisible: false, + isHighlighted: false, + isActive: !U.isInt(schemaData.index) || schemaData.index === 0, + ...schemaData, + ...namedValueMax + }; } // #endregion - // #region NPCs ~ - // #region >> INITIALIZATION ~ - initNPCSockets() { + // #region GETTERS & SETTERS ~ + get canEdit() { + console.log("NOTE: All Clocks currently Editable; see line 71 of BladesClock.ts"); + return this.isVisible && this.isActive; } - // #endregion// ## NPCs - // - Linked to a location: When location is displayed, so are they. *(Can be linked to District wrapper, main Location, or sublocations)* - // - Portrait images close to the central location display, hover-over popups provide more detailed information from sheet or `BladesScore` instance - activateNPCListeners() { + get data() { + return this.linkData; } - // #endregion - // #region PCs, COHORTs, CREW ~ - // #region >> INITIALIZATION ~ - initPCSockets() { + get name() { + return this.data.name; } - initCohortSockets() { + set name(val) { + this.updateTarget("name", val).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); } - initCrewSockets() { + get value() { + return U.pInt(this.data.value); } - // #endregion - // ## PCs - // - Display panels along bottom - // - Signal lights - activatePCListeners() { + set value(val) { + this.updateTarget("value", U.pInt(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); } - // ## Cohorts - // - Smaller panels alongside the PCs - activateCohortListeners() { + get max() { + return U.pInt(this.data.max); + } + set max(val) { + this.updateTarget("max", U.pInt(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get color() { + return this.data.color ?? ClockColor.white; + } + set color(val) { + this.updateTarget("color", val).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get isActive() { + return U.pBool(this.data.isActive); + } + set isActive(val) { + this.updateTarget("isActive", U.pBool(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get parentKey() { + const pKey = game.eunoblades.ClockKeys.get(this.data.parentKeyID); + if (!pKey) { + throw new Error(`[BladesClockKey.parentKey] No parent key found for clock ${this.id}`); + } + return pKey; + } + get isNameVisible() { + return U.pBool(this.data.isNameVisible); + } + set isNameVisible(val) { + this.updateTarget("isNameVisible", U.pBool(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get isVisible() { + return U.pBool(this.data.isVisible); + } + set isVisible(val) { + this.updateTarget("isVisible", U.pBool(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get isHighlighted() { + return U.pBool(this.data.isHighlighted); + } + set isHighlighted(val) { + this.updateTarget("isHighlighted", U.pBool(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get index() { + return U.pInt(this.data.index); + } + set index(val) { + this.updateTarget("index", U.pInt(val)).then(() => { + this.parentKey.renderTargetAndKeeper(); + }); + } + get isEmpty() { + return this.value === 0; + } + get isComplete() { + return this.value >= this.max; + } + get rollOppClock() { + return this; + } + get rollOppName() { + return this.name; + } + get rollOppType() { + return "clock"; + } + get colorSelectOptions() { + return [ + { value: ClockColor.white, display: "🔘" }, + { value: ClockColor.yellow, display: "📀" }, + { value: ClockColor.cyan, display: "🔵" }, + { value: ClockColor.red, display: "🔴" } + ]; + } + get maxSelectOptions() { + return [ + { value: 2, display: 2 }, + { value: 3, display: 3 }, + { value: 4, display: 4 }, + { value: 5, display: 5 }, + { value: 6, display: 6 }, + { value: 8, display: 8 }, + { value: 10, display: 10 }, + { value: 12, display: 12 } + ]; } - // ## Crew - // - Limited information displayed, maybe bar beneath PCs showing Heat, Wanted Level… - activateCrewListeners() { + get valueSelectOptions() { + const returnVals = []; + for (let i = 0; i <= this.max; i++) { + returnVals.push({ value: i, display: i }); + } + return returnVals; } - // #endregion - // #region NOTIFICATIONS ~ - // #region >> INITIALIZATION ~ - initNotificationSockets() { - socketlib.system.register("pushNotice_SocketCall", _BladesDirector.pushNotice_SocketResponse.bind(_BladesDirector)); + // Returns which hemisphere of the clock will show the final change if segmentDelta segments are added/removed. + getActiveSide(segmentDelta = 0) { + const finalClockValue = Math.min(this.max, Math.max(0, this.value + segmentDelta)); + const halfClockValue = this.max / 2; + if (segmentDelta === 0) { + return finalClockValue >= halfClockValue ? "left" : "right"; + } + return finalClockValue > halfClockValue ? "left" : "right"; } // #endregion - pushNotice_SocketCall(targets, config) { - const pushID = randomID(); - if (typeof targets === "string") { - if (targets === "ALL") { - return socketlib.system.executeForEveryone("pushNotice_SocketCall", pushID, config); - } else if (targets === "GM") { - return socketlib.system.executeForAllGMs("pushNotice_SocketCall", pushID, config); - } else { - targets = game.users.filter( - (user) => { - var _a, _b; - return user.id === targets || user.name === targets || ((_a = user.character) == null ? void 0 : _a.id) === targets || ((_b = user.character) == null ? void 0 : _b.name) === targets || game.user.isGM; - } - ).map((user) => user.id); + // #region HTML INTERACTION ~ + getElemFromDisplayContext(displayContext) { + let elem$; + const DOM$ = $(".vtt.game.system-eunos-blades"); + switch (displayContext) { + case ClockDisplayContext.overlay: { + elem$ = DOM$.find(`#blades-overlay #${this.id}`); + break; } - } - if (targets.length > 0) { - return socketlib.system.executeForUsers("pushNotice_SocketCall", targets, pushID, config); - } - return void 0; - } - static async pushNotice_SocketResponse(pushID, config) { - const director = game.eunoblades.Director; - const pushElem$ = $(await renderTemplate("systems/eunos-blades/templates/overlay/notices/push.hbs", { - id: pushID, - ...config - })).appendTo(director.notificationSection$).on("click", (event) => { - director.$removePush(event.currentTarget); - }).on("contextmenu", (event) => { - director.$removeAndClear(event.currentTarget); - }); - U.gsap.fromTo( - pushElem$, - { - x: 200, - skewX: 20, - autoAlpha: 0, - filter: "blur(10px)" - }, - { - x: 0, - skewX: 0, - autoAlpha: 1, - filter: "blur(0px)", - duration: 0.5, - ease: "back" + case ClockDisplayContext.pcSheet: { + elem$ = DOM$.find(`.actor.sheet .pc #${this.id}`); + break; } - ); - } - async $removePush(target) { - U.gsap.to( - target, - { - x: "+=200", - autoAlpha: 0, - ease: "power2", - duration: 0.5, - onComplete: function() { - $(target).remove(); - } + case ClockDisplayContext.factionSheet: { + elem$ = DOM$.find(`.actor.sheet .faction #${this.id}`); + break; } - ); - } - async $removeAndClear(target) { - const targets = $(target).prevAll().get().reverse(); - targets.unshift(target); - U.gsap.to( - targets, - { - x: "+=200", - autoAlpha: 0, - ease: "power2", - duration: 0.5, - stagger: { - each: 0.5, - from: "start", - ease: "power1.inOut" - }, - onComplete: function() { - targets.forEach((targ) => $(targ).remove()); - } + case ClockDisplayContext.projectSheet: { + elem$ = DOM$.find(`.item.sheet .project #${this.id}`); + break; } - ); - } - // #endregion - // #region TRANSITIONS ~ - // #region >> INITIALIZATION ~ - initTransitionSockets() { - } - // #endregion - // ## Transitions - async advanceGamePhase(phase) { - var _a; - U.gsap.utils.wrap( - Object.values(BladesPhase), - Object.values(BladesPhase).indexOf(phase ?? ((_a = game.eunoblades.Tracker) == null ? void 0 : _a.phase) ?? BladesPhase.Freeplay) + 1 - ); + case ClockDisplayContext.scoreSheet: { + elem$ = DOM$.find(`.item.sheet .score #${this.id}`); + break; + } + case ClockDisplayContext.rollCollab: { + elem$ = DOM$.find(`.roll-collab-sheet #${this.id}`); + break; + } + case ClockDisplayContext.chatMessage: { + elem$ = DOM$.find(`#chat #${this.id}`); + break; + } + } + if (!elem$.length) { + throw new Error(`[BladesClockKey.getElemFromDisplayContext] Error elem$ not found for key '${this.id}' for display context '${displayContext}'.`); + } + return elem$; } - /** - * Adjusts the tooltip's position to ensure it remains within its parent container using jQuery methods. - * @param tooltip - The tooltip element, which can be either an HTMLElement or a JQuery. - */ - adjustTooltipPosition(tooltip$) { - if (tooltip$.css("position") !== "absolute") { - throw new Error("Tooltip position must be 'absolute'."); + getElements$(displayContext) { + let elem$; + if (typeof displayContext === "string") { + displayContext = this.getElemFromDisplayContext(displayContext); } - const tooltipRect = tooltip$[0].getBoundingClientRect(); - const containerRect = this.tooltipSection$[0].getBoundingClientRect(); - const currentTop = tooltip$.position().top; - const currentLeft = tooltip$.position().left; - if (tooltipRect.right > containerRect.right) { - const xShift = containerRect.right - tooltipRect.right; - tooltip$.css("left", `${currentLeft + xShift}px`); - } else if (tooltipRect.left < containerRect.left) { - const xShift = containerRect.left - tooltipRect.left; - tooltip$.css("left", `${currentLeft + xShift}px`); + elem$ = $(displayContext).find(`#${this.id}`); + if (!elem$.length) { + elem$ = $(displayContext).closest(`#${this.id}`); } - if (tooltipRect.bottom > containerRect.bottom) { - const yShift = containerRect.bottom - tooltipRect.bottom; - tooltip$.css("top", `${currentTop + yShift}px`); - } else if (tooltipRect.top < containerRect.top) { - const yShift = containerRect.top - tooltipRect.top; - tooltip$.css("top", `${currentTop + yShift}px`); + if (!(elem$ == null ? void 0 : elem$.length)) { + throw new Error(`[BladesClock.getElements$] Cannot find elements for display context '${displayContext}' of clock '${this.id}' of key '${this.parentKey.id}'.`); + } + const clockElems$ = { + clockElem$: elem$ + }; + const container$ = elem$.closest(".clock-container"); + if (!container$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-container' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.clockContainer$ = container$; + const label$ = elem$.find(".clock-label"); + if (!label$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-label' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.clockLabel$ = label$; + const bg$ = elem$.find(".clock-bg"); + if (!bg$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-bg' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.bg$ = bg$; + const frame$ = elem$.find(".clock-frame"); + if (!frame$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-frame' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.frame$ = frame$; + const fill$ = elem$.find(".clock-fill"); + if (!fill$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-fill' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.fill$ = fill$; + const glow$ = elem$.find(".clock-glow"); + if (!glow$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-glow' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); } + clockElems$.glow$ = glow$; + const cover$ = elem$.find(".clock-cover"); + if (!cover$.length) { + throw new Error(`[BladesClock.getElements$] Error '.clock-cover' not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.cover$ = cover$; + const oneSegments$ = elem$.find(".clock-one-segment"); + if (oneSegments$.length !== 3) { + throw new Error(`[BladesClock.getElements$] Error '.clock-one-segment' elements not found for clock '${this.id}' of key '${this.parentKey.id}'.`); + } + clockElems$.oneSegments$ = oneSegments$; + return clockElems$; } - displayTooltip(tooltip) { - var _a, _b; - if (!tooltip.id) { - throw new Error("Tooltip must have an ID to be cloned to the overlay."); + // #endregion + // #region ANIMATED UPDATES (Both GM-Only AND Socket Calls) + reveal_Animation(clockElems$, callback) { + const fadeInElements = [ + clockElems$.frame$, + clockElems$.fill$ + ].filter((el$) => el$ !== void 0); + const tl = U.gsap.timeline({ + callbackScope: this, + onComplete() { + callback == null ? void 0 : callback(); + } + }); + tl.to(clockElems$.cover$, { scale: 2, autoAlpha: 0, duration: 0.5, ease: "power2" }); + tl.fromTo(fadeInElements, { + autoAlpha: 0, + scale: 2 + }, { + autoAlpha: 1, + scale: 1, + duration: 0.5, + stagger: 0.2, + ease: "power2" + }); + if (this.name && this.isNameVisible) { + tl.blurReveal(clockElems$.clockLabel$, { + ignoreMargin: true, + duration: 0.75 + }, "<+0.05"); + } + if (this.isHighlighted) { + tl.scaleUpReveal(clockElems$.glow$, { + scale: 3, + duration: 0.5 + }, "<+0.05"); } - this._displayedTooltipID = tooltip.id; - const self = this; - game.eunoblades.Director.clearTooltips(); - if (!this._tooltipElems.has(tooltip.id)) { - const ttClone$ = $(U.changeContainer( - tooltip, - game.eunoblades.Director.tooltipSection$[0], - true - )); - this.adjustTooltipPosition(ttClone$); - const revealTimeline = U.gsap.effects.blurRevealTooltip( - ttClone$[0], - { - onReverseComplete() { - if (ttClone$.attr("id") === self._displayedTooltipID) { - delete self._displayedTooltipID; - } - game.eunoblades.Director._tooltipElems.delete(ttClone$.attr("id")); - game.eunoblades.Director.tooltipSection$.find(`#${ttClone$.attr("id")}`).remove(); - game.eunoblades.Director.tooltipSection$.children("[style*='opacity: 0'], [style*='opacity:0']").each(function() { - const id = this.id; - if (id === self._displayedTooltipID) { - return; - } - if (id) { - game.eunoblades.Director._tooltipElems.delete(id); - } - $(this).remove(); - }); - } - } - ); - ttClone$.data("revealTimeline", revealTimeline); - this._tooltipElems.set(tooltip.id, ttClone$); + if (this.isActive) { + tl.add(() => this.activate_Animation(clockElems$), "<+0.05"); + } else { + tl.add(() => this.deactivate_Animation(clockElems$), "<+0.05"); } - (_b = (_a = this._tooltipElems.get(tooltip.id)) == null ? void 0 : _a.data("revealTimeline")) == null ? void 0 : _b.play(); + return tl; } - clearTooltip(tooltipID, isClearingIfTweening = true) { - if (tooltipID === this._displayedTooltipID) { - delete this._displayedTooltipID; + async reveal_SocketCall(displayContext) { + if (!game.user.isGM) { + return; } - const ttElem = game.eunoblades.Director._tooltipElems.get(tooltipID); - if (!ttElem) { + socketlib.system.executeForEveryone("reveal_SocketCall", displayContext, this.parentKey.id, this.index); + } + static reveal_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { return; } - const ttTimeline = ttElem.data("revealTimeline"); - if (ttTimeline.isActive() && !isClearingIfTweening) { + const clock = key.getClockByIndex(index); + if (!clock) { return; } - ttTimeline.reverse(); + const clockElems$ = clock.getElements$(displayContext); + clock.reveal_Animation(clockElems$); } - clearTooltips() { - eLog.checkLog3("Observer", "Observer Triggered!"); - game.eunoblades.Director._tooltipElems.forEach((ttElem) => { - if (ttElem.attr("id") === this._displayedTooltipID) { - return; + hide_Animation(clockElems$, callback) { + const fadeOutElements = [ + clockElems$.frame$, + clockElems$.fill$ + ].filter((el$) => el$ !== void 0); + const tl = U.gsap.timeline({ + callbackScope: this, + onComplete() { + callback == null ? void 0 : callback(); } - game.eunoblades.Director.clearTooltip(ttElem.attr("id"), true); }); - } - initTooltipSection() { - var _a; - const self = this; - this.clearTooltips(); - (_a = this._tooltipObserver) == null ? void 0 : _a.kill(); - this._tooltipObserver = Observer.create({ - type: "touch,pointer", - // onMove: throttledOnMove, - onClick() { - self.clearTooltips(); - } + tl.to(fadeOutElements, { + autoAlpha: 0, + scale: 2, + duration: 0.5, + stagger: 0.2, + ease: "power2" }); - } - // #endregion -}; -// #region INITIALIZATION ~ -// #region >> Single-Instance Factory Construction ~ -__publicField(_BladesDirector, "instance"); -let BladesDirector = _BladesDirector; -class BladesItem extends Item { - constructor() { - super(...arguments); - __publicField(this, "dialogCSSClasses", ""); - } - // #region Static Overrides: Create ~ - static async create(data, options = {}) { - if (Array.isArray(data)) { - data = data[0]; - } - data.system = data.system ?? {}; - eLog.checkLog2("item", "BladesItem.create(data,options)", { data, options }); - data.system.world_name = data.system.world_name ?? data.name.replace(/[^A-Za-z_0-9 ]/g, "").trim().replace(/ /g, "_"); - return super.create(data, options); - } - // #endregion - // #region BladesDocument Implementation - static get All() { - return game.items; - } - static Get(itemRef) { - if (itemRef instanceof BladesItem) { - return itemRef; + if (this.name && this.isNameVisible) { + tl.blurRemove(clockElems$.clockLabel$, { + ignoreMargin: true, + duration: 0.75 + }, "<+0.05"); } - if (U.isDocID(itemRef)) { - return BladesItem.All.get(itemRef); + if (this.isHighlighted) { + tl.scaleDownRemove(clockElems$.glow$, { + scale: 3, + duration: 0.5 + }, "<+0.05"); } - return BladesItem.All.find((a) => a.system.world_name === itemRef) || BladesItem.All.find((a) => a.name === itemRef); + tl.to(clockElems$.cover$, { scale: 1, autoAlpha: 1, duration: 0.5, ease: "power2" }); + return tl; } - static GetTypeWithTags(docType, ...tags) { - if (Array.isArray(docType)) { - return docType.map((dType) => BladesItem.All.filter((item) => item.type === dType)).flat(); + async hide_SocketCall(displayContext) { + if (!game.user.isGM) { + return; } - return BladesItem.All.filter((item) => item.type === docType).filter((item) => item.hasTag(...tags)); - } - static IsType(doc, ...types) { - const typeSet = new Set(types); - return doc instanceof BladesItem && typeSet.has(doc.type); - } - get tags() { - return this.system.tags ?? []; + socketlib.system.executeForEveryone("hide_SocketCall", displayContext, this.parentKey.id, this.index); } - hasTag(...tags) { - return tags.every((tag) => this.tags.includes(tag)); + static hide_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + const clockElems$ = clock.getElements$(displayContext); + clock.hide_Animation(clockElems$); } - async addTag(...tags) { - const curTags = this.tags; - tags.forEach((tag) => { - if (curTags.includes(tag)) { - return; - } - curTags.push(tag); + activate_Animation(clockElems$, callback) { + U.gsap.to(clockElems$.bg$, { autoAlpha: 1, duration: 0.5, ease: "power2" }); + U.gsap.to(clockElems$.frame$, { + filter: "brightness(0.5)", + duration: 0.5, + ease: "power2", + onComplete: callback }); - await this.update({ "system.tags": curTags }); - } - async remTag(...tags) { - const curTags = this.tags.filter((tag) => !tags.includes(tag)); - await this.update({ "system.tags": curTags }); } - get tooltip() { - const tooltipText = [ - this.system.concept, - this.system.rules, - this.system.notes - ].filter(Boolean).join(""); - if (tooltipText) { - return new Handlebars.SafeString(tooltipText).toString(); + async activate_SocketCall(displayContext) { + if (!game.user.isGM) { + return; } - return void 0; + socketlib.system.executeForEveryone("activate_SocketCall", displayContext, this.parentKey.id, this.index); } - getFactorTotal(factor) { - var _a, _b, _c; - switch (factor) { - case Factor.tier: { - if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { - return this.system.tier.value + (((_a = this.parent) == null ? void 0 : _a.getFactorTotal(Factor.tier)) ?? 0); - } - if (BladesItem.IsType(this, BladesItemType.cohort_expert)) { - return this.system.tier.value + (((_b = this.parent) == null ? void 0 : _b.getFactorTotal(Factor.tier)) ?? 0); - } - if (BladesItem.IsType(this, BladesItemType.gear)) { - return this.system.tier.value + (((_c = this.parent) == null ? void 0 : _c.getFactorTotal(Factor.tier)) ?? 0); - } - return this.system.tier.value; - } - case Factor.quality: { - if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { - return this.getFactorTotal(Factor.tier) + (this.system.quality_bonus ?? 0); - } - if (BladesItem.IsType(this, BladesItemType.cohort_expert)) { - return this.getFactorTotal(Factor.tier) + (this.system.quality_bonus ?? 0) + 1; - } - if (BladesItem.IsType(this, BladesItemType.gear)) { - let thisQuality = this.getFactorTotal(Factor.tier) + (this.hasTag("Fine") ? 1 : 0); - if (BladesPC$1.IsType(this.parent)) { - thisQuality += this.parent.getTaggedItemBonuses(this.tags); - } - return thisQuality; - } - if (BladesItem.IsType(this, BladesItemType.design)) { - return this.system.min_quality; - } - return this.getFactorTotal(Factor.tier); - } - case Factor.scale: { - if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { - return this.getFactorTotal(Factor.tier) + (this.system.scale_bonus ?? 0); - } - if (BladesItem.IsType(this, BladesItemType.cohort_expert)) { - return 0 + (this.system.scale_bonus ?? 0); - } - return 0; - } - case Factor.magnitude: { - if (BladesItem.IsType(this, BladesItemType.ritual)) { - return this.system.magnitude.value; - } - return 0; - } - default: - return 0; + static activate_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.activate_Animation(clock.getElements$(displayContext)); + } + deactivate_Animation(clockElems$, callback) { + U.gsap.to(clockElems$.bg$, { autoAlpha: 0, duration: 0.5, ease: "power2" }); + U.gsap.to(clockElems$.frame$, { + filter: "brightness(1) blur(5px)", + duration: 0.5, + ease: "power2", + onComplete: callback + }); + } + async deactivate_SocketCall(displayContext) { + if (!game.user.isGM) { + return; } + socketlib.system.executeForEveryone("deactivate_SocketCall", displayContext, this.parentKey.id, this.index); } - // #endregion - // #region BladesItemDocument Implementation - async archive() { - await this.addTag(Tag.System.Archived); - return this; + static deactivate_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.deactivate_Animation(clock.getElements$(displayContext)); } - async unarchive() { - await this.remTag(Tag.System.Archived); - return this; + fadeInClockName_Animation(clockElems$) { + U.gsap.effects.blurReveal(clockElems$.clockLabel$, { + ignoreMargin: true, + duration: 0.75 + }); } - // #endregion - // #region BladesRoll Implementation - get rollFactors() { - const factorsMap = { - [BladesItemType.cohort_gang]: [Factor.quality, Factor.scale], - [BladesItemType.cohort_expert]: [Factor.quality, Factor.scale], - [BladesItemType.gear]: [Factor.quality], - [BladesItemType.project]: [Factor.quality], - [BladesItemType.ritual]: [Factor.magnitude], - [BladesItemType.design]: [Factor.quality] - }; - if (!factorsMap[this.type]) { - return {}; + async fadeInClockName_SocketCall(displayContext) { + if (!game.user.isGM) { + return; } - const factors = factorsMap[this.type]; - const factorData = {}; - (factors ?? []).forEach((factor, i) => { - const factorTotal = this.getFactorTotal(factor); - factorData[factor] = { - name: factor, - value: factorTotal, - max: factorTotal, - baseVal: factorTotal, - display: [Factor.tier, Factor.quality].includes(factor) ? U.romanizeNum(factorTotal) : `${factorTotal}`, - isActive: i === 0, - isPrimary: i === 0, - isDominant: false, - highFavorsPC: true, - cssClasses: `factor-gold${i === 0 ? " factor-main" : ""}` - }; + socketlib.system.executeForEveryone("fadeInClockName_SocketCall", displayContext, this.parentKey.id, this.index); + } + static fadeInClockName_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.fadeInClockName_Animation(clock.getElements$(displayContext)); + } + fadeOutClockName_Animation(clockElems$) { + U.gsap.effects.blurRemove(clockElems$.clockLabel$, { + ignoreMargin: true, + duration: 0.75 }); - return factorData; } - // #region BladesRoll.PrimaryDoc Implementation - get rollPrimaryID() { - return this.id; + async fadeOutClockName_SocketCall(displayContext) { + if (!game.user.isGM) { + return; + } + socketlib.system.executeForEveryone("fadeOutClockName_SocketCall", displayContext, this.parentKey.id, this.index); } - get rollPrimaryDoc() { - return this; + static fadeOutClockName_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.fadeOutClockName_Animation(clock.getElements$(displayContext)); } - get rollPrimaryName() { - return this.name; + highlight_Animation(clockElems$) { + U.gsap.effects.scaleUpReveal(clockElems$.glow$, { + duration: 0.5, + scale: 3 + }); } - get rollPrimaryType() { - if (![ - BladesItemType.cohort_gang, - BladesItemType.cohort_expert, - BladesItemType.gm_tracker, - BladesItemType.score - ].includes(this.type)) { - throw new Error(`BladesItem of type '${this.type}' ("${this.name}") cannot be RollPrimary.`); + async highlight_SocketCall(displayContext) { + if (!game.user.isGM) { + return; } - return this.type; + socketlib.system.executeForEveryone("highlight_SocketCall", displayContext, this.parentKey.id, this.index); } - get rollPrimaryImg() { - return this.img; + static highlight_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.highlight_Animation(clock.getElements$(displayContext)); } - get rollPrimaryModsSchemaSet() { - return BladesRollMod.ParseDocModsToSchemaSet(this); + unhighlight_Animation(clockElems$) { + U.gsap.effects.scaleDownRemove(clockElems$.glow$, { + duration: 0.5, + scale: 3 + }); } - async applyHarm(amount, _name2) { - if (BladesItem.IsType(this, BladesItemType.cohort_expert, BladesItemType.cohort_gang)) { - const curHarm = this.system.harm.value; - let newHarm; - if (amount > curHarm) { - newHarm = amount; - } else { - newHarm = curHarm + 1; + async unhighlight_SocketCall(displayContext) { + if (!game.user.isGM) { + return; + } + socketlib.system.executeForEveryone("unhighlight_SocketCall", displayContext, this.parentKey.id, this.index); + } + static unhighlight_SocketResponse(displayContext, keyID, index) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.unhighlight_Animation(clock.getElements$(displayContext)); + } + getRotationOfSegment(segment) { + const stepSize = 360 / this.max; + return stepSize * (segment - 1); + } + initOneSegments(clockElems$, segmentNums, isReversing) { + if (segmentNums.length > 3) { + throw new Error(`Too many segments: [${segmentNums.join(", ")}]`); + } + const oneSegs = [...clockElems$.oneSegments$]; + const oneSegsToAnimate = Array.from(clockElems$.oneSegments$).slice(0, segmentNums.length); + for (const segmentNum of segmentNums) { + const oneSegment = oneSegs.shift(); + U.gsap.set(oneSegment, { + rotation: this.getRotationOfSegment(segmentNum), + autoAlpha: isReversing ? 1 : 0 + }); + } + if (isReversing) { + clockElems$.clockElem$.attr("data-value", U.getLast(segmentNums) - 1); + } + return oneSegsToAnimate; + } + changeSegments_Animation(clockElems$, startVal, endVal, callback) { + startVal = U.gsap.utils.clamp(0, this.max, startVal); + endVal = U.gsap.utils.clamp(0, this.max, endVal); + let delta = endVal - startVal; + if (delta === 0) { + return; + } + const segmentNums = []; + if (delta < 0) { + while (Math.abs(delta) > startVal) { + delta++; } - const harmVerb = ["is Weakened", "is Impaired", "has been Broken", "has been Killed!"]; - const harmEffect = [ - "They act with Reduced Effect.", - "They act with Reduced Effect and suffer -1d to all rolls.", - "They cannot do anything until they recover.", - "You may replace them during Downtime." - ]; - BladesDirector.getInstance().pushNotice_SocketCall( - "ALL", - { - title: `${this.name} ${harmVerb[newHarm - 1]}`, - body: harmEffect[newHarm - 1], - type: BladesNoticeType.push, - cssClasses: "harm-alert" + for (let i = startVal; i > endVal; i--) { + segmentNums.push(i); + } + } else { + while (endVal > this.max) { + delta--; + } + for (let i = startVal + 1; i <= endVal; i++) { + segmentNums.push(i); + } + } + const segmentsToAnimate = this.initOneSegments(clockElems$, segmentNums, startVal > endVal); + eLog.checkLog3("BladesClock", "changeSegments_Animation", { clockElems$, delta, segmentNums, startVal, endVal, segmentsToAnimate }); + const tl = U.gsap.timeline(); + if (delta > 0) { + tl.fromTo(segmentsToAnimate, { + autoAlpha: 0, + scale: 2 + }, { + autoAlpha: 1, + scale: 1, + duration: 0.5, + stagger: 0.2, + ease: "power2", + callbackScope: this, + onComplete() { + clockElems$.clockElem$.attr("data-value", endVal); + U.gsap.to(segmentsToAnimate, { + autoAlpha: 0, + duration: 0.5, + stagger: 0.2 + // onComplete() { + // // Return clock key to original size and focus + // clockFocusTimeline.reverse(); + // } + }); } - ); - await this.update({ "system.harm": amount }); + }); + } else { + tl.fromTo(segmentsToAnimate, { + autoAlpha: 1, + scale: 1 + }, { + autoAlpha: 0, + scale: 2, + duration: 0.5, + stagger: 0.2, + ease: "power2" + // onComplete() { + // // Return clock key to original size and focus + // clockFocusTimeline.reverse(); + // } + }); } + return tl; } - async applyWorsePosition() { - if (BladesItem.IsType(this, BladesItemType.cohort_expert, BladesItemType.cohort_gang)) { - this.setFlag("eunos-blades", "isWorsePosition", true); + async changeSegments_SocketCall(displayContext, startVal, endVal) { + if (!game.user.isGM) { + return; } + startVal = U.gsap.utils.clamp(0, this.max, startVal); + endVal = U.gsap.utils.clamp(0, this.max, endVal); + socketlib.system.executeForEveryone("changeSegments_SocketCall", displayContext, this.parentKey.id, this.index, startVal, endVal); } - // #endregion - // #region BladesRoll.OppositionDoc Implementation - get rollOppID() { - return this.id; - } - get rollOppDoc() { - return this; - } - get rollOppImg() { - return this.img; - } - get rollOppName() { - return this.name; + static changeSegments_SocketResponse(displayContext, keyID, index, startVal, endVal) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!(key == null ? void 0 : key.isVisible)) { + return; + } + const clock = key.getClockByIndex(index); + if (!clock) { + return; + } + clock.changeSegments_Animation(clock.getElements$(displayContext), startVal, endVal); } - get rollOppSubName() { - return ""; + // #endregion + // #region Adding/Removing Clock Segments ~ + // Returns number of segments beyond max (or 0, if max not met) + async fillSegments(count, isSilent = false) { + const clockOverflow = Math.max(0, this.value + count - this.max); + count = Math.min(this.value + count, this.max) - this.value; + if (count === 0) { + return clockOverflow; + } + await this.updateTarget("value", this.value + count); + if (!isSilent) { + this.parentKey.renderTargetAndKeeper(); + } + return clockOverflow; } - get rollOppType() { - if (![ - BladesItemType.cohort_gang, - BladesItemType.cohort_expert, - BladesItemType.gm_tracker, - BladesItemType.score, - BladesItemType.location, - BladesItemType.project, - BladesItemType.design, - BladesItemType.ritual - ].includes(this.type)) { - throw new Error(`BladesItem of type '${this.type}' ("${this.name}") cannot be RollOpposition.`); + // Returns (positive) number of segments removed + // in excess of the number of segments in the clock + async clearSegments(count, isSilent = false) { + const clockOverflow = Math.max(0, count - this.value); + count = Math.min(this.value, count); + if (count === 0) { + return clockOverflow; } - return this.type; + await this.updateTarget("value", this.value - count); + if (!isSilent) { + this.parentKey.renderTargetAndKeeper(); + } + return clockOverflow; } - get rollOppModsSchemaSet() { - return []; + async delete() { + const { parentKey } = this; + await super.delete(false); + parentKey.updateClockIndices(); } // #endregion - // #region BladesRoll.ParticipantDoc Implementation - get rollParticipantID() { - return this.id; - } - get rollParticipantDoc() { - return this; - } - get rollParticipantIcon() { - return this.img; +} +const _BladesDirector = class _BladesDirector { + constructor() { + __publicField(this, "_id"); + // #endregion + // #endregion + // #region OVERLAY ~ + // #region >> Overlay Elements$ ~ + __publicField(this, "_overlayContainer"); + __publicField(this, "_overlayContainer$"); + // - As with notifications: placeholder animation until something more final can be coded. + // #endregion + // #region TOOLTIPS ~ + __publicField(this, "_tooltipObserver"); + __publicField(this, "_tooltipElems", /* @__PURE__ */ new Map()); + __publicField(this, "_displayedTooltipID"); + this._id = randomID(); } - get rollParticipantName() { - return this.name; + static getInstance() { + return _BladesDirector.instance ?? (_BladesDirector.instance = new _BladesDirector()); } - get rollParticipantType() { - if (![ - BladesItemType.cohort_gang, - BladesItemType.cohort_expert, - BladesItemType.gm_tracker - ].includes(this.type)) { - throw new Error(`BladesItem of type '${this.type}' ("${this.name}") cannot be RollParticipant.`); - } - return this.type; + // #endregion + static async Initialize() { + Hooks.on("renderApplication", async () => { + game.eunoblades.Director.initClockKeySection(true); + if (game.user.isGM) { + await game.eunoblades.ClockKeeper.update({ "system.targetScene": game.scenes.current.id }); + game.eunoblades.ClockKeeper.render(); + } + }); + return loadTemplates([ + "systems/eunos-blades/templates/overlay/blades-overlay.hbs", + "systems/eunos-blades/templates/overlay/location.hbs", + "systems/eunos-blades/templates/overlay/score-panel.hbs", + "systems/eunos-blades/templates/overlay/npc-portrait.hbs", + "systems/eunos-blades/templates/overlay/pc-portrait.hbs", + "systems/eunos-blades/templates/overlay/cohort-portrait.hbs", + "systems/eunos-blades/templates/overlay/crew-status-bar.hbs", + "systems/eunos-blades/templates/overlay/game-phase-bar.hbs", + "systems/eunos-blades/templates/overlay/notices/push.hbs" + ]); } - get rollParticipantModsSchemaSet() { - return []; + // #region >> Sockets ~ + static InitSockets() { + const director = _BladesDirector.getInstance(); + socketlib.system.register("renderOverlay_SocketCall", director.renderOverlay_SocketResponse.bind(director)); + director.initClockSockets(); + director.initScorePanelSockets(); + director.initLocationSockets(); + director.initNPCSockets(); + director.initPCSockets(); + director.initCohortSockets(); + director.initCrewSockets(); + director.initNotificationSockets(); + director.initTransitionSockets(); } - // #endregion - // #endregion - // #region PREPARING DERIVED DATA - prepareDerivedData() { - super.prepareDerivedData(); - if (BladesItem.IsType(this, BladesItemType.cohort_gang, BladesItemType.cohort_expert)) { - this._prepareCohortData(this.system); - } - if (BladesItem.IsType(this, BladesItemType.crew_playbook)) { - this._preparePlaybookData(this.system); - } - if (BladesItem.IsType(this, BladesItemType.gear)) { - this._prepareGearData(this.system); + get overlayContainer() { + if (!this._overlayContainer) { + [this._overlayContainer] = $("#blades-overlay"); } - if (BladesItem.IsType(this, BladesItemType.playbook)) { - this._preparePlaybookData(this.system); + if (!this._overlayContainer) { + $("body.vtt").append('
'); + [this._overlayContainer] = $("#blades-overlay"); } + return this._overlayContainer; } - _prepareCohortData(system) { - if (!BladesItem.IsType(this, BladesItemType.cohort_gang, BladesItemType.cohort_expert)) { - return; - } - system.tier.name = "Quality"; - const subtypes = U.unique(Object.values(system.subtypes).map((subtype) => subtype.trim()).filter((subtype) => /[A-Za-z]/.test(subtype))); - const eliteSubtypes = [ - ...Object.values(system.elite_subtypes) - ]; - if (BladesCrew$1.IsType(this.parent)) { - eliteSubtypes.push( - ...this.parent.upgrades.filter((upgrade) => (upgrade.name ?? "").startsWith("Elite")).map((upgrade) => (upgrade.name ?? "").trim().replace(/^Elite /, "")) - ); - } - system.subtypes = Object.fromEntries(subtypes.map((subtype, i) => [`${i + 1}`, subtype])); - system.elite_subtypes = Object.fromEntries( - U.unique( - eliteSubtypes.map((subtype) => subtype.trim()).filter((subtype) => /[A-Za-z]/.test(subtype) && subtypes.includes(subtype)) - ).map((subtype, i) => [`${i + 1}`, subtype]) - ); - system.edges = Object.fromEntries(Object.values(system.edges ?? []).filter((edge) => /[A-Za-z]/.test(edge)).map((edge, i) => [`${i + 1}`, edge.trim()])); - system.flaws = Object.fromEntries(Object.values(system.flaws ?? []).filter((flaw) => /[A-Za-z]/.test(flaw)).map((flaw, i) => [`${i + 1}`, flaw.trim()])); - system.quality = this.getFactorTotal(Factor.quality); - if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { - if ([...subtypes, ...eliteSubtypes].includes(Tag.GangType.Vehicle)) { - system.scale = this.getFactorTotal(Factor.scale); - system.scaleExample = "(1 vehicle)"; - } else { - system.scale = this.getFactorTotal(Factor.scale); - const scaleIndex = Math.min(6, system.scale); - system.scaleExample = C.ScaleExamples[scaleIndex]; - system.subtitle = C.ScaleSizes[scaleIndex]; - } - if (subtypes.length + eliteSubtypes.length === 0) { - system.subtitle = system.subtitle.replace(/\s+of\b/g, "").trim(); - } - } else { - system.scale = 0; - system.scaleExample = [...subtypes, ...eliteSubtypes].includes("Pet") ? "(1 animal)" : "(1 person)"; - system.subtitle = "An Expert"; - } - if (subtypes.length + eliteSubtypes.length > 0) { - if ([...subtypes, ...eliteSubtypes].includes(Tag.GangType.Vehicle)) { - system.subtitle = C.VehicleDescriptors[Math.min(6, this.getFactorTotal(Factor.tier))]; - } else { - system.subtitle += ` ${U.oxfordize([ - ...subtypes.filter((subtype) => !eliteSubtypes.includes(subtype)), - ...eliteSubtypes.map((subtype) => `Elite ${subtype}`) - ], false, "&")}`; - } + get overlayContainer$() { + if (!this._overlayContainer$) { + this._overlayContainer$ = $(this.overlayContainer); } + return this._overlayContainer$; + } + get clockKeySection$() { + return this.overlayContainer$.find(".overlay-section-clock-keys"); + } + get locationSection$() { + return this.overlayContainer$.find(".overlay-section-location"); + } + get scorePanelSection$() { + return this.overlayContainer$.find(".overlay-section-score-panel"); + } + get npcSection$() { + return this.overlayContainer$.find(".overlay-section-npcs"); } - _prepareGearData(system) { - if (!BladesItem.IsType(this, BladesItemType.gear)) { - return; - } - system.tier.name = "Quality"; + get playerSection$() { + return this.overlayContainer$.find(".overlay-section-players"); } - _preparePlaybookData(system) { - if (!BladesItem.IsType(this, BladesItemType.playbook, BladesItemType.crew_playbook)) { - return; - } - const expClueData = {}; - [...Object.values(system.experience_clues).filter((clue) => /[A-Za-z]/.test(clue)), " "].forEach((clue, i) => { - expClueData[(i + 1).toString()] = clue; - }); - system.experience_clues = expClueData; - if (BladesItem.IsType(this, BladesItemType.playbook)) { - const gatherInfoData = {}; - [...Object.values(system.gather_info_questions).filter((question) => /[A-Za-z]/.test(question)), " "].forEach((question, i) => { - gatherInfoData[(i + 1).toString()] = question; - }); - system.gather_info_questions = gatherInfoData; - } + get crewSection$() { + return this.overlayContainer$.find(".overlay-section-crew"); } - // #endregion - // Unlock lower-level update method for subclasses - async callOnUpdate(...args) { - await this._onUpdate(...args); + get notificationSection$() { + return this.overlayContainer$.find(".overlay-section-notifications"); } -} -const BladesItem$1 = BladesItem; -const FUNCQUEUE = {}; -const CUSTOMFUNCS = { - addItem: async (actor, funcData, _, isReversing = false) => { - eLog.checkLog("activeEffects", "addItem", { actor, funcData, isReversing }); - if (actor.hasActiveSubItemOf(funcData)) { - if (isReversing) { - return actor.remSubItem(funcData); - } - } else if (!isReversing) { - return actor.addSubItem(funcData); - } - return void 0; - }, - addIfChargen: async (actor, funcData, _, isReversing = false) => { - var _a; - eLog.checkLog("activeEffects", "addIfChargen", { actor, funcData, isReversing }); - if (!isReversing && ((_a = game.eunoblades.Tracker) == null ? void 0 : _a.system.phase) !== BladesPhase.CharGen) { - return; - } - const [target, qty] = funcData.split(/:/); - if (isReversing) { - await actor.update({ [target]: U.pInt(getProperty(actor, target)) - U.pInt(qty) }); + get transitionSection$() { + return this.overlayContainer$.find(".overlay-section-transitions"); + } + get tooltipSection$() { + return this.overlayContainer$.find(".overlay-section-tooltips"); + } + get svgData() { + return ClockKey_SVGDATA; + } + // #endregion + // #region >> Rendering ~ + renderOverlay_SocketCall() { + if (!game.user.isGM) { return; } - await actor.update({ [target]: U.pInt(getProperty(actor, target)) + U.pInt(qty) }); - }, - upgradeIfChargen: async (actor, funcData, _, isReversing = false) => { - var _a; - eLog.checkLog("activeEffects", "upgradeIfChargen", { actor, funcData, isReversing }); - if (!isReversing && ((_a = game.eunoblades.Tracker) == null ? void 0 : _a.system.phase) !== BladesPhase.CharGen) { + if (!this.overlayContainer) { return; } - const [target, qty] = funcData.split(/:/); - if (getProperty(actor, target) < U.pInt(qty)) { - await actor.update({ [target]: U.pInt(qty) }); - } - }, - APPLYTOMEMBERS: async () => void 0, - APPLYTOCOHORTS: async () => void 0, - remItem: async (actor, funcData, _, isReversing = false) => { - function testString(targetString, testDef) { - if (testDef.startsWith("rX")) { - const pat = new RegExp(testDef.replace(/^rX:\/(.*?)\//, "$1")); - return pat.test(targetString); - } - return targetString === testDef; + socketlib.system.executeForEveryone("renderOverlay_SocketCall"); + } + async renderOverlay_SocketResponse() { + const overlayContent = await renderTemplate( + "systems/eunos-blades/templates/overlay/blades-overlay.hbs", + this + ); + this.overlayContainer$.empty().append(overlayContent); + this.initClockKeySection(); + this.initTooltipSection(); + } + // #endregion + // #endregion + // #region CLOCKS & CLOCK KEYS ~ + // #region >> INITIALIZATION ~ + initClockKeySection(isResetting = false) { + if (isResetting) { + this.clockKeySection$.empty(); } - if (funcData.startsWith("{")) { - if (isReversing) { - console.error("Cannot reverse a 'remItem' custom effect that was defined with a JSON object."); - return void 0; - } - const { type, tags, name } = JSON.parse(funcData); - let activeSubItems = actor.activeSubItems; - if (activeSubItems.length === 0) { - return void 0; - } - if (name) { - activeSubItems = activeSubItems.filter((item) => testString(item.name, name)); - } - if (activeSubItems.length === 0) { - return void 0; - } - if (type) { - activeSubItems = activeSubItems.filter((item) => testString(item.type, type)); - } - if (activeSubItems.length === 0) { - return void 0; - } - if (tags) { - activeSubItems = activeSubItems.filter((item) => item.hasTag(...tags)); - } - if (activeSubItems.length === 0) { - return void 0; + const visibleSceneKeys = U.shuffle(this.sceneKeys.filter((key) => key.isVisible)); + let staggerDelay = 0; + while (visibleSceneKeys.length) { + const key = visibleSceneKeys.shift(); + if (key) { + setTimeout(() => this.renderClockKey(key), staggerDelay * 1e3); + staggerDelay += 0.5; } - eLog.checkLog("activeEffects", "remItem - JSON OBJECT", { actor, funcData: JSON.parse(funcData), isReversing, activeSubItems }); - activeSubItems.forEach((item) => actor.remSubItem(item)); - } - eLog.checkLog("activeEffects", "remItem", { actor, funcData, isReversing }); - if (actor.hasActiveSubItemOf(funcData)) { - return actor.remSubItem(funcData); } - if (isReversing) { - return actor.addSubItem(funcData); + setTimeout(() => { + }, staggerDelay * 1e3); + } + initClockSockets() { + socketlib.system.register("renderClockKey_SocketCall", _BladesDirector.renderClockKey_SocketResponse.bind(_BladesDirector)); + socketlib.system.register("pullKey_SocketCall", _BladesDirector.pullKey_SocketResponse.bind(_BladesDirector)); + socketlib.system.register("fadeInName_SocketCall", BladesClockKey.fadeInName_SocketResponse.bind(BladesClockKey)); + socketlib.system.register("fadeOutName_SocketCall", BladesClockKey.fadeOutName_SocketResponse.bind(BladesClockKey)); + socketlib.system.register("reveal_SocketCall", BladesClock.reveal_SocketResponse.bind(BladesClock)); + socketlib.system.register("hide_SocketCall", BladesClock.hide_SocketResponse.bind(BladesClock)); + socketlib.system.register("activate_SocketCall", BladesClock.activate_SocketResponse.bind(BladesClock)); + socketlib.system.register("deactivate_SocketCall", BladesClock.deactivate_SocketResponse.bind(BladesClock)); + socketlib.system.register("fadeInClockName_SocketCall", BladesClock.fadeInClockName_SocketResponse.bind(BladesClock)); + socketlib.system.register("fadeOutClockName_SocketCall", BladesClock.fadeOutClockName_SocketResponse.bind(BladesClock)); + socketlib.system.register("highlight_SocketCall", BladesClock.highlight_SocketResponse.bind(BladesClock)); + socketlib.system.register("unhighlight_SocketCall", BladesClock.unhighlight_SocketResponse.bind(BladesClock)); + socketlib.system.register("changeSegments_SocketCall", BladesClock.changeSegments_SocketResponse.bind(BladesClock)); + } + // #endregion + get sceneKeys() { + return game.eunoblades.ClockKeeper.getSceneKeys(game.scenes.current.id); + } + // #region >> Rendering (Dropping) Clock Keys ~ + dropKey_Animation(key, keyElems$) { + const { + container$, + label$, + imgContainer$, + clocks + } = keyElems$ ?? key.getElements$(game.eunoblades.Director.clockKeySection$); + const keySwingTimeline = imgContainer$.data("keySwingTimeline"); + const tl = U.gsap.timeline().call(() => { + keySwingTimeline.seek("NEUTRAL").play(); + }).from(container$, { + y: -800, + ease: "bounce", + duration: 1 + }, 0).to(container$, { autoAlpha: 1, duration: 0.5, ease: "power2" }, 0); + key.visibleClocks.forEach((clock, i) => { + tl.add( + () => { + clock.reveal_Animation(clocks[clock.id]); + }, + i === 0 ? ">" : "<+0.15" + ); + }); + if (key.name && key.isNameVisible) { + tl.blurReveal(label$, { + ignoreMargin: true, + duration: 0.75 + }, "<+0.05"); } - return void 0; } -}; -class BladesActiveEffect extends ActiveEffect { - static Initialize() { - CONFIG.ActiveEffect.documentClass = BladesActiveEffect; - Hooks.on("preCreateActiveEffect", async (effect) => { - var _a; - eLog.checkLog3("effect", "PRECREATE ActiveEffect", { effect, parent: (_a = effect.parent) == null ? void 0 : _a.name }); - if (!(effect.parent instanceof BladesActor$1)) { - return; - } - if (effect.changes.some((change) => change.key === "APPLYTOMEMBERS")) { - if (BladesActor$1.IsType(effect.parent, BladesActorType.pc) && BladesActor$1.IsType(effect.parent.crew, BladesActorType.crew)) { - const otherMembers = effect.parent.crew.members.filter((member) => { - var _a2; - return member.id !== ((_a2 = effect.parent) == null ? void 0 : _a2.id); + prepareClockKeyTimelines(key, keyElems$) { + const { container$, imgContainer$, elem$, label$, clocks } = keyElems$; + U.gsap.set(container$, { pointerEvents: "auto" }); + U.gsap.set(elem$, { filter: "brightness(1)" }); + U.gsap.set(imgContainer$, { transformOrigin: "50% 10%" }); + const keyElemScale = U.gsap.getProperty(container$[0], "scale"); + imgContainer$.data( + "keySwingTimeline", + U.gsap.timeline({ paused: true, repeat: -1, yoyo: true }).fromTo(imgContainer$, { rotateZ: -1 }, { rotateZ: 1, duration: 3, ease: "sine.inOut" }).addLabel("NEUTRAL", 1.5).seek("NEUTRAL") + ); + container$.data( + "hoverOverTimeline", + U.gsap.timeline({ + paused: true, + data: { key, imgContainer$, label$, isNameRevealed: false }, + onStart() { + this.data.imgContainer$.data("keySwingTimeline").tweenTo("NEUTRAL", { + duration: 0.25, + ease: "back.out(1.5)" }); - if (otherMembers.length > 0) { - effect.changes = effect.changes.filter((change) => change.key !== "APPLYTOMEMBERS"); - await Promise.all(otherMembers.map(async (member) => member.createEmbeddedDocuments("ActiveEffect", [effect.toJSON()]))); - await effect.parent.setFlag("eunos-blades", `memberEffects.${effect.id}`, { - appliedTo: otherMembers.map((member) => member.id), - effect: effect.toJSON() + if (this.data.key.name && !this.data.key.isNameVisible) { + this.data.isNameRevealed = true; + U.gsap.effects.blurReveal(this.data.label$, { + ignoreMargin: true, + duration: 0.5 + }); + } + }, + onReverseComplete() { + this.data.imgContainer$.data("keySwingTimeline").seek("NEUTRAL").play(); + if (this.data.isNameRevealed) { + this.data.isNameRevealed = false; + U.gsap.effects.blurRemove(this.data.label$, { + ignoreMargin: true, + duration: 0.5 }); } - } else if (BladesActor$1.IsType(effect.parent, BladesActorType.crew)) { - const changeKey = U.pullElement(effect.changes, (change) => change.key === "APPLYTOMEMBERS"); - if (!changeKey) { - return; - } - if (effect.parent.members.length > 0) { - await Promise.all(effect.parent.members.map(async (member) => member.createEmbeddedDocuments("ActiveEffect", [effect.toJSON()]))); - } - await effect.parent.setFlag("eunos-blades", `memberEffects.${effect.id}`, { - appliedTo: effect.parent.members.map((member) => member.id), - effect - }); - await effect.updateSource({ changes: [changeKey] }); - } - } else if (effect.changes.some((change) => change.key === "APPLYTOCOHORTS") && (BladesActor$1.IsType(effect.parent, BladesActorType.pc) || BladesActor$1.IsType(effect.parent, BladesActorType.crew))) { - if (effect.parent.cohorts.length > 0) { - await Promise.all(effect.parent.cohorts.map(async (cohort) => cohort.createEmbeddedDocuments("ActiveEffect", [effect.toJSON()]))); - } - await effect.parent.setFlag("eunos-blades", `cohortEffects.${effect.id}`, { - appliedTo: effect.parent.cohorts.map((cohort) => cohort.id), - effect - }); - await effect.updateSource({ changes: effect.changes.filter((change) => change.key === "APPLYTOCOHORTS") }); - } - const [permChanges, changes] = U.partition(effect.changes, (change) => change.key.startsWith("perm")); - await effect.updateSource({ changes }); - for (const permChange of permChanges) { - const { key, value } = permChange; - const permFuncName = key.replace(/^perm/, ""); - if (permFuncName in CUSTOMFUNCS) { - const funcData = { - funcName: permFuncName, - funcData: value, - isReversing: false, - effect - }; - BladesActiveEffect.ThrottleCustomFunc(effect.parent, funcData); - } else if (permFuncName === "Add") { - const [target, qty] = value.split(/:/); - effect.parent.update({ [target]: U.pInt(getProperty(effect.parent, target)) + U.pInt(qty) }); } + }).to(elem$, { filter: "brightness(1.5)", scale: keyElemScale * 1.25, duration: 0.5, ease: "sine" }) + ); + key.clocks.forEach((clock) => { + const { clockContainer$, clockLabel$, clockElem$ } = clocks[clock.id]; + if (!(clockContainer$ == null ? void 0 : clockContainer$.length)) { + throw new Error(`[BladesDirector.prepareClockKeyTimelines] Error clockContainer$ not found for clock '${clock.id}' of key '${key.id}'.`); } + U.gsap.set(clockContainer$, { pointerEvents: "auto" }); + clockContainer$.data( + "hoverOverTimeline", + U.gsap.timeline({ + paused: true, + data: { clock, clockLabel$, isNameRevealed: false }, + onStart() { + if (this.data.clock.name && !this.data.clock.isNameVisible) { + this.data.isNameRevealed = true; + U.gsap.effects.blurReveal(this.data.clockLabel$, { + ignoreMargin: true, + duration: 0.5 + }); + } + }, + onReverseComplete() { + if (this.data.isNameRevealed) { + this.data.isNameRevealed = false; + U.gsap.effects.blurRemove(this.data.clockLabel$, { + ignoreMargin: true, + duration: 0.5 + }); + } + } + }).to(clockElem$, { filter: "brightness(1.5)", scale: 1.25, duration: 0.25, ease: "sine" }) + ); }); - Hooks.on("applyActiveEffect", (actor, changeData) => { - if (!(actor instanceof BladesActor$1)) { - return; - } - if (changeData.key in CUSTOMFUNCS) { - const funcData = { - funcName: changeData.key, - funcData: changeData.value, - isReversing: false, - effect: changeData.effect - }; - BladesActiveEffect.ThrottleCustomFunc(actor, funcData); - } - }); - Hooks.on("updateActiveEffect", (effect, { disabled }) => { - if (!(effect.parent instanceof BladesActor$1)) { - return; - } - const customEffects = effect.changes.filter((changes) => changes.mode === 0); - customEffects.forEach(({ key, value }) => { - const funcData = { - funcName: key, - funcData: value, - isReversing: disabled, - effect - }; - BladesActiveEffect.ThrottleCustomFunc(effect.parent, funcData); + } + async activateClockKeyListeners(key, keyElems$) { + const { container$, clocks } = keyElems$; + if (game.user.isGM) { + container$.on("dblclick", async () => { + var _a; + (_a = game.eunoblades.ClockKeeper.sheet) == null ? void 0 : _a.render(true); }); - }); - Hooks.on("deleteActiveEffect", async (effect) => { - if (!(effect.parent instanceof BladesActor$1)) { - return; - } - if (effect.changes.some((change) => change.key === "APPLYTOMEMBERS")) { - if (BladesActor$1.IsType(effect.parent, BladesActorType.pc) && BladesActor$1.IsType(effect.parent.crew, BladesActorType.crew)) { - const otherMembers = effect.parent.crew.members.filter((member) => { - var _a; - return member.id !== ((_a = effect.parent) == null ? void 0 : _a.id); - }); - if (otherMembers.length > 0) { - await Promise.all(otherMembers.map(async (member) => Promise.all(member.effects.filter((e) => e.name === effect.name).map(async (e) => e.delete())))); + container$.on("contextmenu", async () => { + this.pullKey_SocketCall(key.id); + key.updateTarget("isVisible", false); + }); + } else { + container$.on("mouseenter", () => { + container$.data("hoverOverTimeline").play(); + }).on("mouseleave", () => { + container$.data("hoverOverTimeline").reverse(); + }); + key.clocks.forEach((clock) => { + const { clockContainer$ } = clocks[clock.id]; + clockContainer$.on("mouseenter", () => { + if (clock.isVisible) { + clockContainer$.data("hoverOverTimeline").play(); } - await effect.parent.unsetFlag("eunos-blades", `memberEffects.${effect.id}`); - } else if (BladesActor$1.IsType(effect.parent, BladesActorType.crew)) { - if (effect.parent.members.length > 0) { - await Promise.all(effect.parent.members.map(async (member) => Promise.all(member.effects.filter((e) => e.name === effect.name).map(async (e) => e.delete())))); + }).on("mouseleave", () => { + if (clock.isVisible) { + clockContainer$.data("hoverOverTimeline").reverse(); } - await effect.parent.unsetFlag("eunos-blades", `memberEffects.${effect.id}`); - } - } else if (effect.changes.some((change) => change.key === "APPLYTOCOHORTS") && BladesActor$1.IsType(effect.parent, BladesActorType.pc, BladesActorType.crew)) { - if (effect.parent.cohorts.length > 0) { - await Promise.all(effect.parent.cohorts.map(async (cohort) => Promise.all(cohort.effects.filter((e) => e.name === effect.name).map(async (e) => e.delete())))); - } - await effect.parent.unsetFlag("eunos-blades", `cohortEffects.${effect.id}`); - } - const customEffects = effect.changes.filter((changes) => changes.mode === 0); - customEffects.forEach(({ key, value }) => { - const funcData = { - funcName: key, - funcData: value, - isReversing: true, - effect - }; - BladesActiveEffect.ThrottleCustomFunc(effect.parent, funcData); + }); }); - }); - } - static async AddActiveEffect(doc, name, eChanges, icon = "systems/eunos-blades/assets/icons/effect-icons/default.png") { - const changes = [eChanges].flat(); - await doc.createEmbeddedDocuments("ActiveEffect", [{ name, icon, changes }]); + } } - static ThrottleCustomFunc(actor, data) { - const { funcName, funcData, isReversing, effect } = data; - if (!actor.id) { - return; + async renderClockKey(key) { + await key.renderTo(this.clockKeySection$); + if (key.positionDragger) { + key.removePositionDragger(); } - eLog.checkLog3("activeEffect", `Throttling Func: ${funcName}(${funcData}, ${isReversing})`); - if (actor.id && actor.id in FUNCQUEUE) { - const matchingQueue = FUNCQUEUE[actor.id].queue.find((fData) => JSON.stringify(fData) === JSON.stringify(data)); - eLog.checkLog("activeEffects", "... Checking Queue", { data, FUNCQUEUE: FUNCQUEUE[actor.id], matchingQueue }); - if (matchingQueue) { - eLog.error("... Function ALREADY QUEUED, SKIPPING"); - return; - } - FUNCQUEUE[actor.id].queue.push(data); - return; + const keyElems$ = key.initElementsInContext(this.clockKeySection$, ClockKeyDisplayMode.full); + if (key.overlayPosition) { + U.gsap.set(keyElems$.container$, { + left: key.overlayPosition.x, + top: key.overlayPosition.y + }); } - eLog.checkLog3("activeEffect", "... Creating New FUNCQUEUE, RUNNING:"); - FUNCQUEUE[actor.id] = { - curFunc: BladesActiveEffect.RunCustomFunc(actor, CUSTOMFUNCS[funcName](actor, funcData, effect, isReversing)), - queue: [] - }; + this.prepareClockKeyTimelines(key, keyElems$); + this.activateClockKeyListeners(key, keyElems$); + this.dropKey_Animation(key, keyElems$); } - static async RunCustomFunc(actor, funcPromise) { - if (!actor.id) { + async renderClockKey_SocketCall(keyID) { + if (!game.user.isGM) { return; } - eLog.checkLog("activeEffects", "... Running Func ..."); - await funcPromise; - eLog.checkLog("activeEffects", "... Function Complete!"); - if (FUNCQUEUE[actor.id].queue.length) { - const { funcName, funcData, isReversing, effect } = FUNCQUEUE[actor.id].queue.shift() ?? {}; - if (!funcName || !(funcName in CUSTOMFUNCS)) { - return; - } - if (!funcData) { - return; - } - eLog.checkLog3("activeEffect", `Progressing Queue: ${funcName}(${funcData}, ${isReversing}) -- ${FUNCQUEUE[actor.id].queue.length} remaining funcs.`); - FUNCQUEUE[actor.id].curFunc = BladesActiveEffect.RunCustomFunc( - actor, - CUSTOMFUNCS[funcName](actor, funcData, effect, isReversing) - ); - } else { - eLog.checkLog3("activeEffect", "Function Queue Complete! Deleting."); - delete FUNCQUEUE[actor.id]; - } + socketlib.system.executeForEveryone("renderClockKey_SocketCall", keyID); } - /** - * Manage Active Effect instances through the Actor Sheet via effect control buttons. - * @param {MouseEvent} event The left-click event on the effect control - * @param {Actor|Item} owner The owning entity which manages this effect - */ - static onManageActiveEffect(event, owner) { - var _a; - event.preventDefault(); - const a = event.currentTarget; - if (a.dataset.action === "create") { - return owner.createEmbeddedDocuments("ActiveEffect", [{ - name: owner.name, - icon: owner.img, - origin: owner.uuid - }]); - } - const selector = a.closest("tr"); - if (selector === null) { - return null; - } - const effect = selector.dataset.effectId ? owner.effects.get(selector.dataset.effectId) : null; - if (!effect) { - return null; - } - switch (a.dataset.action) { - case "edit": - return (_a = effect.sheet) == null ? void 0 : _a.render(true); - case "delete": - eLog.checkLog("activeEffects", "delete effect"); - return effect.delete(); - case "toggle": - return effect.update({ disabled: !effect.disabled }); - default: - return null; + static async renderClockKey_SocketResponse(keyID) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!key) { + return; } + game.eunoblades.Director.renderClockKey(key); } - async _preCreate(data, options, user) { - eLog.checkLog3("effect", "ActiveEffect._preCreate()", { data, options, user }); - await super._preCreate(data, options, user); + // #endregion + // #region >> Un-Rendering (Pulling) Clock Keys ~ + pullKey_Animation(key) { + const { container$ } = key.getElements$(game.eunoblades.Director.clockKeySection$); + U.gsap.timeline().to(container$, { + y: -800, + ease: "back.in(1)", + duration: 0.75 + }).to(container$, { + opacity: 0, + ease: "power2.out", + duration: 0.25 + }, 0.75).call(() => { + container$.remove(); + }); } - _onDelete(options, userID) { - eLog.checkLog3("effect", "ActiveEffect._onDelete()", { options, userID }); - super._onDelete(options, userID); + async pullKey_SocketCall(keyID) { + if (!game.user.isGM) { + return; + } + socketlib.system.executeForEveryone("pullKey_SocketCall", keyID); } - get isSuppressed() { - if (!/Actor.*Item/.test(this.origin)) { - return super.isSuppressed; + static pullKey_SocketResponse(keyID) { + const key = game.eunoblades.ClockKeys.get(keyID); + if (!key) { + return; } - const [actorID, itemID] = this.origin.replace(/Actor\.|Item\./g, "").split("."); - const actor = game.actors.get(actorID); - const item = actor.items.get(itemID); - return super.isSuppressed || (item == null ? void 0 : item.hasTag(Tag.System.Archived)); + game.eunoblades.Director.pullKey_Animation(key); } -} -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys.push.apply(keys, symbols); - } - return keys; -} -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys(Object(source), true).forEach(function(key) { - _defineProperty(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); + // #endregion + // #endregion + // #region SCORE PANEL ~ + // #region >> INITIALIZATION ~ + initScorePanelSockets() { } - return target; -} -function _defineProperty(obj, key, value) { - key = _toPropertyKey(key); - if (key in obj) { - Object.defineProperty(obj, key, { - value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; + // #endregion + // ## Score Details + // - Small panel overlapping corner of Location + // - Engagement roll result + // - Plan & Detail + // - Target tier + activateScorePanelListeners() { } - return obj; -} -function _toPrimitive(input, hint) { - if (typeof input !== "object" || input === null) - return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint || "default"); - if (typeof res !== "object") - return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -function _toPropertyKey(arg) { - var key = _toPrimitive(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -const sameStr = (s1, s2, caseSensitive, trim) => { - s1 = "" + s1; - s2 = "" + s2; - if (trim) { - s1 = s1.trim(); - s2 = s2.trim(); - } - return caseSensitive ? s1 == s2 : s1.toLowerCase() == s2.toLowerCase(); -}; -const removeCollectionProp = (collection, unwantedProps) => collection && Array.isArray(collection) && collection.map((v) => omit(v, unwantedProps)); -function omit(obj, props) { - var newObj = {}, p; - for (p in obj) - if (props.indexOf(p) < 0) - newObj[p] = obj[p]; - return newObj; -} -function decode(s) { - var el = document.createElement("div"); - return s.replace(/\&#?[0-9a-z]+;/gi, function(enc) { - el.innerHTML = enc; - return el.innerText; - }); -} -function parseHTML(s) { - var parser = new DOMParser(), node = parser.parseFromString(s.trim(), "text/html"); - return node.body.firstElementChild; -} -function minify(s) { - return s ? s.replace(/\>[\r\n ]+\<").replace(/(<.*?>)|\s+/g, (m, $1) => $1 ? $1 : " ") : ""; -} -function removeTextChildNodes(elm) { - var iter = document.createNodeIterator(elm, NodeFilter.SHOW_TEXT, null, false), textnode; - while (textnode = iter.nextNode()) { - if (!textnode.textContent.trim()) - textnode.parentNode.removeChild(textnode); + // #endregion + // #region LOCATIONS ~ + // #region >> INITIALIZATION ~ + initLocationSockets() { } -} -function getfirstTextNode(elm, action) { - action = action || "previous"; - while (elm = elm[action + "Sibling"]) - if (elm.nodeType == 3) - return elm; -} -function escapeHTML(s) { - return typeof s == "string" ? s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/`|'/g, "'") : s; -} -function isObject(obj) { - var type = Object.prototype.toString.call(obj).split(" ")[1].slice(0, -1); - return obj === Object(obj) && type != "Array" && type != "Function" && type != "RegExp" && type != "HTMLUnknownElement"; -} -function extend(o, o1, o2) { - if (!(o instanceof Object)) - o = {}; - copy(o, o1); - if (o2) - copy(o, o2); - function copy(a, b) { - for (var key in b) - if (b.hasOwnProperty(key)) { - if (isObject(b[key])) { - if (!isObject(a[key])) - a[key] = Object.assign({}, b[key]); - else - copy(a[key], b[key]); - continue; - } - if (Array.isArray(b[key])) { - a[key] = Object.assign([], b[key]); - continue; - } - a[key] = b[key]; - } - } - return o; -} -function concatWithoutDups() { - const newArr = [], existingObj = {}; - for (let arr of arguments) { - for (let item of arr) { - if (isObject(item)) { - if (!existingObj[item.value]) { - newArr.push(item); - existingObj[item.value] = 1; - } - } else if (!newArr.includes(item)) - newArr.push(item); - } + // #endregion + // ## Locations + // - District wrapper/header + // - Faction wrapper/footer + // - Location main + // - Slide-scroll of sublocations + activateLocationListeners() { } - return newArr; -} -function unaccent(s) { - if (!String.prototype.normalize) - return s; - if (typeof s === "string") - return s.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); -} -function getNodeHeight(node) { - var height, clone = node.cloneNode(true); - clone.style.cssText = "position:fixed; top:-9999px; opacity:0"; - document.body.appendChild(clone); - height = clone.clientHeight; - clone.parentNode.removeChild(clone); - return height; -} -var isChromeAndroidBrowser = () => /(?=.*chrome)(?=.*android)/i.test(navigator.userAgent); -function getUID() { - return ("10000000-1000-4000-8000" + -1e11).replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)); -} -function isNodeTag(node) { - return node && node.classList && node.classList.contains(this.settings.classNames.tag); -} -function getCaretGlobalPosition() { - const sel = document.getSelection(); - if (sel.rangeCount) { - const r = sel.getRangeAt(0); - const node = r.startContainer; - const offset = r.startOffset; - let rect, r2; - if (offset > 0) { - r2 = document.createRange(); - r2.setStart(node, offset - 1); - r2.setEnd(node, offset); - rect = r2.getBoundingClientRect(); - return { - left: rect.right, - top: rect.top, - bottom: rect.bottom - }; - } - if (node.getBoundingClientRect) - return node.getBoundingClientRect(); + // #endregion + // #region NPCs ~ + // #region >> INITIALIZATION ~ + initNPCSockets() { } - return { - left: -9999, - top: -9999 - }; -} -function injectAtCaret(content, range) { - var selection = window.getSelection(); - range = range || selection.getRangeAt(0); - if (typeof content == "string") - content = document.createTextNode(content); - if (range) { - range.deleteContents(); - range.insertNode(content); - } - return content; -} -function getSetTagData(tagElm, data, override) { - if (!tagElm) { - console.warn("tag element doesn't exist", tagElm, data); - return data; + // #endregion// ## NPCs + // - Linked to a location: When location is displayed, so are they. *(Can be linked to District wrapper, main Location, or sublocations)* + // - Portrait images close to the central location display, hover-over popups provide more detailed information from sheet or `BladesScore` instance + activateNPCListeners() { } - if (data) - tagElm.__tagifyTagData = override ? data : extend({}, tagElm.__tagifyTagData || {}, data); - return tagElm.__tagifyTagData; -} -var DEFAULTS = { - delimiters: ",", - // [RegEx] split tags by any of these delimiters ("null" to cancel) Example: ",| |." - pattern: null, - // RegEx pattern to validate input by. Ex: /[1-9]/ - tagTextProp: "value", - // tag data Object property which will be displayed as the tag's text - maxTags: Infinity, - // Maximum number of tags - callbacks: {}, - // Exposed callbacks object to be triggered on certain events - addTagOnBlur: true, - // automatically adds the text which was inputed as a tag when blur event happens - onChangeAfterBlur: true, - // By default, the native way of inputs' onChange events is kept, and it only fires when the field is blured. - duplicates: false, - // "true" - allow duplicate tags - whitelist: [], - // Array of tags to suggest as the user types (can be used along with "enforceWhitelist" setting) - blacklist: [], - // A list of non-allowed tags - enforceWhitelist: false, - // Only allow tags from the whitelist - userInput: true, - // disable manually typing/pasting/editing tags (tags may only be added from the whitelist) - keepInvalidTags: false, - // if true, do not remove tags which did not pass validation - createInvalidTags: true, - // if false, do not create invalid tags from invalid user input - mixTagsAllowedAfter: /,|\.|\:|\s/, - // RegEx - Define conditions in which mix-tags content allows a tag to be added after - mixTagsInterpolator: ["[[", "]]"], - // Interpolation for mix mode. Everything between these will become a tag, if is a valid Object - backspace: true, - // false / true / "edit" - skipInvalid: false, - // If `true`, do not add invalid, temporary, tags before automatically removing them - pasteAsTags: true, - // automatically converts pasted text into tags. if "false", allows for further text editing - editTags: { - clicks: 2, - // clicks to enter "edit-mode": 1 for single click. any other value is considered as double-click - keepInvalid: true - // keeps invalid edits as-is until `esc` is pressed while in focus - }, - // 1 or 2 clicks to edit a tag. false/null for not allowing editing - transformTag: () => { - }, - // Takes a tag input string as argument and returns a transformed value - trim: true, - // whether or not the value provided should be trimmed, before being added as a tag - a11y: { - focusableTags: false - }, - mixMode: { - insertAfterTag: " " - // String/Node to inject after a tag has been added (see #588) - }, - autoComplete: { - enabled: true, - // Tries to suggest the input's value while typing (match from whitelist) by adding the rest of term as grayed-out text - rightKey: false - // If `true`, when Right key is pressed, use the suggested value to create a tag, else just auto-completes the input. in mixed-mode this is set to "true" - }, - classNames: { - namespace: "tagify", - mixMode: "tagify--mix", - selectMode: "tagify--select", - input: "tagify__input", - focus: "tagify--focus", - tagNoAnimation: "tagify--noAnim", - tagInvalid: "tagify--invalid", - tagNotAllowed: "tagify--notAllowed", - scopeLoading: "tagify--loading", - hasMaxTags: "tagify--hasMaxTags", - hasNoTags: "tagify--noTags", - empty: "tagify--empty", - inputInvalid: "tagify__input--invalid", - dropdown: "tagify__dropdown", - dropdownWrapper: "tagify__dropdown__wrapper", - dropdownHeader: "tagify__dropdown__header", - dropdownFooter: "tagify__dropdown__footer", - dropdownItem: "tagify__dropdown__item", - dropdownItemActive: "tagify__dropdown__item--active", - dropdownItemHidden: "tagify__dropdown__item--hidden", - dropdownInital: "tagify__dropdown--initial", - tag: "tagify__tag", - tagText: "tagify__tag-text", - tagX: "tagify__tag__removeBtn", - tagLoading: "tagify__tag--loading", - tagEditing: "tagify__tag--editable", - tagFlash: "tagify__tag--flash", - tagHide: "tagify__tag--hide" - }, - dropdown: { - classname: "", - enabled: 2, - // minimum input characters to be typed for the suggestions dropdown to show - maxItems: 10, - searchKeys: ["value", "searchBy"], - fuzzySearch: true, - caseSensitive: false, - accentedSearch: true, - includeSelectedTags: false, - // Should the suggestions list Include already-selected tags (after filtering) - highlightFirst: false, - // highlights first-matched item in the list - closeOnSelect: true, - // closes the dropdown after selecting an item, if `enabled:0` (which means always show dropdown) - clearOnSelect: true, - // after selecting a suggetion, should the typed text input remain or be cleared - position: "all", - // 'manual' / 'text' / 'all' - appendTarget: null - // defaults to document.body once DOM has been loaded - }, - hooks: { - beforeRemoveTag: () => Promise.resolve(), - beforePaste: () => Promise.resolve(), - suggestionClick: () => Promise.resolve() + // #endregion + // #region PCs, COHORTs, CREW ~ + // #region >> INITIALIZATION ~ + initPCSockets() { } -}; -function initDropdown() { - this.dropdown = {}; - for (let p in this._dropdown) - this.dropdown[p] = typeof this._dropdown[p] === "function" ? this._dropdown[p].bind(this) : this._dropdown[p]; - this.dropdown.refs(); -} -var _dropdown = { - refs() { - this.DOM.dropdown = this.parseTemplate("dropdown", [this.settings]); - this.DOM.dropdown.content = this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-wrapper']"); - }, - getHeaderRef() { - return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-header']"); - }, - getFooterRef() { - return this.DOM.dropdown.querySelector("[data-selector='tagify-suggestions-footer']"); - }, - getAllSuggestionsRefs() { - return [...this.DOM.dropdown.content.querySelectorAll(this.settings.classNames.dropdownItemSelector)]; - }, - /** - * shows the suggestions select box - * @param {String} value [optional, filter the whitelist by this value] - */ - show(value) { - var _s = this.settings, firstListItem, firstListItemValue, allowNewTags = _s.mode == "mix" && !_s.enforceWhitelist, noWhitelist = !_s.whitelist || !_s.whitelist.length, noMatchListItem, isManual = _s.dropdown.position == "manual"; - value = value === void 0 ? this.state.inputText : value; - if (noWhitelist && !allowNewTags && !_s.templates.dropdownItemNoMatch || _s.dropdown.enable === false || this.state.isLoading || this.settings.readonly) - return; - clearTimeout(this.dropdownHide__bindEventsTimeout); - this.suggestedListItems = this.dropdown.filterListItems(value); - if (value && !this.suggestedListItems.length) { - this.trigger("dropdown:noMatch", value); - if (_s.templates.dropdownItemNoMatch) - noMatchListItem = _s.templates.dropdownItemNoMatch.call(this, { - value - }); - } - if (!noMatchListItem) { - if (this.suggestedListItems.length) { - if (value && allowNewTags && !this.state.editing.scope && !sameStr(this.suggestedListItems[0].value, value)) - this.suggestedListItems.unshift({ - value - }); + initCohortSockets() { + } + initCrewSockets() { + } + // #endregion + // ## PCs + // - Display panels along bottom + // - Signal lights + activatePCListeners() { + } + // ## Cohorts + // - Smaller panels alongside the PCs + activateCohortListeners() { + } + // ## Crew + // - Limited information displayed, maybe bar beneath PCs showing Heat, Wanted Level… + activateCrewListeners() { + } + // #endregion + // #region NOTIFICATIONS ~ + // #region >> INITIALIZATION ~ + initNotificationSockets() { + socketlib.system.register("pushNotice_SocketCall", _BladesDirector.pushNotice_SocketResponse.bind(_BladesDirector)); + } + // #endregion + pushNotice_SocketCall(targets, config3) { + const pushID = randomID(); + if (typeof targets === "string") { + if (targets === "ALL") { + return socketlib.system.executeForEveryone("pushNotice_SocketCall", pushID, config3); + } else if (targets === "GM") { + return socketlib.system.executeForAllGMs("pushNotice_SocketCall", pushID, config3); } else { - if (value && allowNewTags && !this.state.editing.scope) { - this.suggestedListItems = [{ - value - }]; - } else { - this.input.autocomplete.suggest.call(this); - this.dropdown.hide(); - return; - } - } - firstListItem = this.suggestedListItems[0]; - firstListItemValue = "" + (isObject(firstListItem) ? firstListItem.value : firstListItem); - if (_s.autoComplete && firstListItemValue) { - if (firstListItemValue.indexOf(value) == 0) - this.input.autocomplete.suggest.call(this, firstListItem); + targets = game.users.filter( + (user) => { + var _a, _b; + return user.id === targets || user.name === targets || ((_a = user.character) == null ? void 0 : _a.id) === targets || ((_b = user.character) == null ? void 0 : _b.name) === targets || game.user.isGM; + } + ).map((user) => user.id); } } - this.dropdown.fill(noMatchListItem); - if (_s.dropdown.highlightFirst) { - this.dropdown.highlightOption(this.DOM.dropdown.content.querySelector(_s.classNames.dropdownItemSelector)); - } - if (!this.state.dropdown.visible) - setTimeout(this.dropdown.events.binding.bind(this)); - this.state.dropdown.visible = value || true; - this.state.dropdown.query = value; - this.setStateSelection(); - if (!isManual) { - setTimeout(() => { - this.dropdown.position(); - this.dropdown.render(); - }); + if (targets.length > 0) { + return socketlib.system.executeForUsers("pushNotice_SocketCall", targets, pushID, config3); } - setTimeout(() => { - this.trigger("dropdown:show", this.DOM.dropdown); + return void 0; + } + static async pushNotice_SocketResponse(pushID, config3) { + const director = game.eunoblades.Director; + const pushElem$ = $(await renderTemplate("systems/eunos-blades/templates/overlay/notices/push.hbs", { + id: pushID, + ...config3 + })).appendTo(director.notificationSection$).on("click", (event) => { + director.$removePush(event.currentTarget); + }).on("contextmenu", (event) => { + director.$removeAndClear(event.currentTarget); }); - }, + U.gsap.fromTo( + pushElem$, + { + x: 200, + skewX: 20, + autoAlpha: 0, + filter: "blur(10px)" + }, + { + x: 0, + skewX: 0, + autoAlpha: 1, + filter: "blur(0px)", + duration: 0.5, + ease: "back" + } + ); + } + async $removePush(target) { + U.gsap.to( + target, + { + x: "+=200", + autoAlpha: 0, + ease: "power2", + duration: 0.5, + onComplete: function() { + $(target).remove(); + } + } + ); + } + async $removeAndClear(target) { + const targets = $(target).prevAll().get().reverse(); + targets.unshift(target); + U.gsap.to( + targets, + { + x: "+=200", + autoAlpha: 0, + ease: "power2", + duration: 0.5, + stagger: { + each: 0.5, + from: "start", + ease: "power1.inOut" + }, + onComplete: function() { + targets.forEach((targ) => $(targ).remove()); + } + } + ); + } + // #endregion + // #region TRANSITIONS ~ + // #region >> INITIALIZATION ~ + initTransitionSockets() { + } + // #endregion + // ## Transitions + async advanceGamePhase(phase) { + var _a; + U.gsap.utils.wrap( + Object.values(BladesPhase), + Object.values(BladesPhase).indexOf(phase ?? ((_a = game.eunoblades.Tracker) == null ? void 0 : _a.phase) ?? BladesPhase.Freeplay) + 1 + ); + } /** - * Hides the dropdown (if it's not managed manually by the developer) - * @param {Boolean} overrideManual + * Adjusts the tooltip's position to ensure it remains within its parent container using jQuery methods. + * @param tooltip - The tooltip element, which can be either an HTMLElement or a JQuery. */ - hide(overrideManual) { - var _this$DOM = this.DOM, scope = _this$DOM.scope, dropdown = _this$DOM.dropdown, isManual = this.settings.dropdown.position == "manual" && !overrideManual; - if (!dropdown || !document.body.contains(dropdown) || isManual) - return; - window.removeEventListener("resize", this.dropdown.position); - this.dropdown.events.binding.call(this, false); - scope.setAttribute("aria-expanded", false); - dropdown.parentNode.removeChild(dropdown); - setTimeout(() => { - this.state.dropdown.visible = false; - }, 100); - this.state.dropdown.query = this.state.ddItemData = this.state.ddItemElm = this.state.selection = null; - if (this.state.tag && this.state.tag.value.length) { - this.state.flaggedTags[this.state.tag.baseOffset] = this.state.tag; + adjustTooltipPosition(tooltip$) { + if (tooltip$.css("position") !== "absolute") { + throw new Error("Tooltip position must be 'absolute'."); } - this.trigger("dropdown:hide", dropdown); - return this; - }, - /** - * Toggles dropdown show/hide - * @param {Boolean} show forces the dropdown to show - */ - toggle(show) { - this.dropdown[this.state.dropdown.visible && !show ? "hide" : "show"](); - }, - render() { - var ddHeight = getNodeHeight(this.DOM.dropdown), _s = this.settings, enabled = typeof _s.dropdown.enabled == "number" && _s.dropdown.enabled >= 0; - if (!enabled) - return this; - this.DOM.scope.setAttribute("aria-expanded", true); - if (!document.body.contains(this.DOM.dropdown)) { - this.DOM.dropdown.classList.add(_s.classNames.dropdownInital); - this.dropdown.position(ddHeight); - _s.dropdown.appendTarget.appendChild(this.DOM.dropdown); - setTimeout(() => this.DOM.dropdown.classList.remove(_s.classNames.dropdownInital)); + const tooltipRect = tooltip$[0].getBoundingClientRect(); + const containerRect = this.tooltipSection$[0].getBoundingClientRect(); + const currentTop = tooltip$.position().top; + const currentLeft = tooltip$.position().left; + if (tooltipRect.right > containerRect.right) { + const xShift = containerRect.right - tooltipRect.right; + tooltip$.css("left", `${currentLeft + xShift}px`); + } else if (tooltipRect.left < containerRect.left) { + const xShift = containerRect.left - tooltipRect.left; + tooltip$.css("left", `${currentLeft + xShift}px`); } - return this; - }, - /** - * re-renders the dropdown content element (see "dropdownContent" in templates file) - * @param {String/Array} HTMLContent - optional - */ - fill(HTMLContent) { - HTMLContent = typeof HTMLContent == "string" ? HTMLContent : this.dropdown.createListHTML(HTMLContent || this.suggestedListItems); - var dropdownContent = this.settings.templates.dropdownContent.call(this, HTMLContent); - this.DOM.dropdown.content.innerHTML = minify(dropdownContent); - }, - /** - * Re-renders only the header & footer. - * Used when selecting a suggestion and it is wanted that the suggestions dropdown stays open. - * Since the list of sugegstions is not being re-rendered completely every time a suggestion is selected (the item is transitioned-out) - * then the header & footer should be kept in sync with the suggestions data change - */ - fillHeaderFooter() { - var suggestions = this.dropdown.filterListItems(this.state.dropdown.query), newHeaderElem = this.parseTemplate("dropdownHeader", [suggestions]), newFooterElem = this.parseTemplate("dropdownFooter", [suggestions]), headerRef = this.dropdown.getHeaderRef(), footerRef = this.dropdown.getFooterRef(); - newHeaderElem && (headerRef == null ? void 0 : headerRef.parentNode.replaceChild(newHeaderElem, headerRef)); - newFooterElem && (footerRef == null ? void 0 : footerRef.parentNode.replaceChild(newFooterElem, footerRef)); - }, - /** - * fill data into the suggestions list - * (mainly used to update the list when removing tags while the suggestions dropdown is visible, so they will be re-added to the list. not efficient) - */ - refilter(value) { - value = value || this.state.dropdown.query || ""; - this.suggestedListItems = this.dropdown.filterListItems(value); - this.dropdown.fill(); - if (!this.suggestedListItems.length) - this.dropdown.hide(); - this.trigger("dropdown:updated", this.DOM.dropdown); - }, - position(ddHeight) { - var _sd = this.settings.dropdown; - if (_sd.position == "manual") - return; - var rect, top, bottom, left, width, parentsPositions, ddElm = this.DOM.dropdown, placeAbove = _sd.placeAbove, isDefaultAppendTarget = _sd.appendTarget === document.body, appendTargetScrollTop = isDefaultAppendTarget ? window.pageYOffset : _sd.appendTarget.scrollTop, root = document.fullscreenElement || document.webkitFullscreenElement || document.documentElement, viewportHeight = root.clientHeight, viewportWidth = Math.max(root.clientWidth || 0, window.innerWidth || 0), positionTo = viewportWidth > 480 ? _sd.position : "all", ddTarget = this.DOM[positionTo == "input" ? "input" : "scope"]; - ddHeight = ddHeight || ddElm.clientHeight; - function getParentsPositions(p) { - var left2 = 0, top2 = 0; - while (p && p != root) { - left2 += p.offsetLeft || 0; - top2 += p.offsetTop || 0; - p = p.parentNode; - } - return { - left: left2, - top: top2 - }; + if (tooltipRect.bottom > containerRect.bottom) { + const yShift = containerRect.bottom - tooltipRect.bottom; + tooltip$.css("top", `${currentTop + yShift}px`); + } else if (tooltipRect.top < containerRect.top) { + const yShift = containerRect.top - tooltipRect.top; + tooltip$.css("top", `${currentTop + yShift}px`); } - function getAccumulatedAncestorsScrollTop() { - var scrollTop = 0, p = _sd.appendTarget.parentNode; - while (p) { - scrollTop += p.scrollTop || 0; - p = p.parentNode; - } - return scrollTop; + } + displayTooltip(tooltip) { + var _a, _b; + if (!tooltip.id) { + throw new Error("Tooltip must have an ID to be cloned to the overlay."); } - if (!this.state.dropdown.visible) - return; - if (positionTo == "text") { - rect = getCaretGlobalPosition(); - bottom = rect.bottom; - top = rect.top; - left = rect.left; - width = "auto"; - } else { - parentsPositions = getParentsPositions(_sd.appendTarget); - rect = ddTarget.getBoundingClientRect(); - top = rect.top - parentsPositions.top; - bottom = rect.bottom - 1 - parentsPositions.top; - left = rect.left - parentsPositions.left; - width = rect.width + "px"; - } - if (!isDefaultAppendTarget) { - let accumulatedAncestorsScrollTop = getAccumulatedAncestorsScrollTop(); - top += accumulatedAncestorsScrollTop; - bottom += accumulatedAncestorsScrollTop; - } - top = Math.floor(top); - bottom = Math.ceil(bottom); - placeAbove = placeAbove === void 0 ? viewportHeight - rect.bottom < ddHeight : placeAbove; - ddElm.style.cssText = "left:" + (left + window.pageXOffset) + "px; width:" + width + ";" + (placeAbove ? "top: " + (top + appendTargetScrollTop) + "px" : "top: " + (bottom + appendTargetScrollTop) + "px"); - ddElm.setAttribute("placement", placeAbove ? "top" : "bottom"); - ddElm.setAttribute("position", positionTo); - }, - events: { - /** - * Events should only be binded when the dropdown is rendered and removed when isn't - * because there might be multiple Tagify instances on a certain page - * @param {Boolean} bindUnbind [optional. true when wanting to unbind all the events] - */ - binding() { - let bindUnbind = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true; - var _CB = this.dropdown.events.callbacks, _CBR = this.listeners.dropdown = this.listeners.dropdown || { - position: this.dropdown.position.bind(this, null), - onKeyDown: _CB.onKeyDown.bind(this), - onMouseOver: _CB.onMouseOver.bind(this), - onMouseLeave: _CB.onMouseLeave.bind(this), - onClick: _CB.onClick.bind(this), - onScroll: _CB.onScroll.bind(this) - }, action = bindUnbind ? "addEventListener" : "removeEventListener"; - if (this.settings.dropdown.position != "manual") { - document[action]("scroll", _CBR.position, true); - window[action]("resize", _CBR.position); - window[action]("keydown", _CBR.onKeyDown); - } - this.DOM.dropdown[action]("mouseover", _CBR.onMouseOver); - this.DOM.dropdown[action]("mouseleave", _CBR.onMouseLeave); - this.DOM.dropdown[action]("mousedown", _CBR.onClick); - this.DOM.dropdown.content[action]("scroll", _CBR.onScroll); - }, - callbacks: { - onKeyDown(e) { - if (!this.state.hasFocus || this.state.composing) - return; - var selectedElm = this.DOM.dropdown.querySelector(this.settings.classNames.dropdownItemActiveSelector), selectedElmData = this.dropdown.getSuggestionDataByNode(selectedElm); - switch (e.key) { - case "ArrowDown": - case "ArrowUp": - case "Down": - case "Up": { - e.preventDefault(); - var dropdownItems = this.dropdown.getAllSuggestionsRefs(), actionUp = e.key == "ArrowUp" || e.key == "Up"; - if (selectedElm) { - selectedElm = this.dropdown.getNextOrPrevOption(selectedElm, !actionUp); - } - if (!selectedElm || !selectedElm.matches(this.settings.classNames.dropdownItemSelector)) { - selectedElm = dropdownItems[actionUp ? dropdownItems.length - 1 : 0]; - } - this.dropdown.highlightOption(selectedElm, true); - break; - } - case "Escape": - case "Esc": - this.dropdown.hide(); - break; - case "ArrowRight": - if (this.state.actions.ArrowLeft) - return; - case "Tab": { - if (this.settings.mode != "mix" && selectedElm && !this.settings.autoComplete.rightKey && !this.state.editing) { - e.preventDefault(); - var value = this.dropdown.getMappedValue(selectedElmData); - this.input.autocomplete.set.call(this, value); - return false; + this._displayedTooltipID = tooltip.id; + const self2 = this; + game.eunoblades.Director.clearTooltips(); + if (!this._tooltipElems.has(tooltip.id)) { + const ttClone$ = $(U.changeContainer( + tooltip, + game.eunoblades.Director.tooltipSection$[0], + true + )); + this.adjustTooltipPosition(ttClone$); + const revealTimeline = U.gsap.effects.blurRevealTooltip( + ttClone$[0], + { + onReverseComplete() { + if (ttClone$.attr("id") === self2._displayedTooltipID) { + delete self2._displayedTooltipID; } - return true; - } - case "Enter": { - e.preventDefault(); - this.settings.hooks.suggestionClick(e, { - tagify: this, - tagData: selectedElmData, - suggestionElm: selectedElm - }).then(() => { - if (selectedElm) { - this.dropdown.selectOption(selectedElm); - selectedElm = this.dropdown.getNextOrPrevOption(selectedElm, !actionUp); - this.dropdown.highlightOption(selectedElm); + game.eunoblades.Director._tooltipElems.delete(ttClone$.attr("id")); + game.eunoblades.Director.tooltipSection$.find(`#${ttClone$.attr("id")}`).remove(); + game.eunoblades.Director.tooltipSection$.children("[style*='opacity: 0'], [style*='opacity:0']").each(function() { + const id = this.id; + if (id === self2._displayedTooltipID) { return; - } else - this.dropdown.hide(); - if (this.settings.mode != "mix") - this.addTags(this.state.inputText.trim(), true); - }).catch((err) => err); - break; - } - case "Backspace": { - if (this.settings.mode == "mix" || this.state.editing.scope) - return; - const value2 = this.input.raw.call(this); - if (value2 == "" || value2.charCodeAt(0) == 8203) { - if (this.settings.backspace === true) - this.removeTags(); - else if (this.settings.backspace == "edit") - setTimeout(this.editTag.bind(this), 0); - } + } + if (id) { + game.eunoblades.Director._tooltipElems.delete(id); + } + $(this).remove(); + }); } } - }, - onMouseOver(e) { - var ddItem = e.target.closest(this.settings.classNames.dropdownItemSelector); - ddItem && this.dropdown.highlightOption(ddItem); - }, - onMouseLeave(e) { - this.dropdown.highlightOption(); - }, - onClick(e) { - if (e.button != 0 || e.target == this.DOM.dropdown || e.target == this.DOM.dropdown.content) - return; - var selectedElm = e.target.closest(this.settings.classNames.dropdownItemSelector), selectedElmData = this.dropdown.getSuggestionDataByNode(selectedElm); - this.state.actions.selectOption = true; - setTimeout(() => this.state.actions.selectOption = false, 50); - this.settings.hooks.suggestionClick(e, { - tagify: this, - tagData: selectedElmData, - suggestionElm: selectedElm - }).then(() => { - if (selectedElm) - this.dropdown.selectOption(selectedElm, e); - else - this.dropdown.hide(); - }).catch((err) => console.warn(err)); - }, - onScroll(e) { - var elm = e.target, pos = elm.scrollTop / (elm.scrollHeight - elm.parentNode.clientHeight) * 100; - this.trigger("dropdown:scroll", { - percentage: Math.round(pos) - }); - } - } - }, - /** - * Given a suggestion-item, return the data associated with it - * @param {HTMLElement} tagElm - * @returns Object - */ - getSuggestionDataByNode(tagElm) { - var value = tagElm && tagElm.getAttribute("value"); - return this.suggestedListItems.find((item) => item.value == value) || null; - }, - getNextOrPrevOption(selected) { - let next = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; - var dropdownItems = this.dropdown.getAllSuggestionsRefs(), selectedIdx = dropdownItems.findIndex((item) => item === selected); - return next ? dropdownItems[selectedIdx + 1] : dropdownItems[selectedIdx - 1]; - }, - /** - * mark the currently active suggestion option - * @param {Object} elm option DOM node - * @param {Boolean} adjustScroll when navigation with keyboard arrows (up/down), aut-scroll to always show the highlighted element - */ - highlightOption(elm, adjustScroll) { - var className = this.settings.classNames.dropdownItemActive, itemData; - if (this.state.ddItemElm) { - this.state.ddItemElm.classList.remove(className); - this.state.ddItemElm.removeAttribute("aria-selected"); - } - if (!elm) { - this.state.ddItemData = null; - this.state.ddItemElm = null; - this.input.autocomplete.suggest.call(this); - return; + ); + ttClone$.data("revealTimeline", revealTimeline); + this._tooltipElems.set(tooltip.id, ttClone$); } - itemData = this.dropdown.getSuggestionDataByNode(elm); - this.state.ddItemData = itemData; - this.state.ddItemElm = elm; - elm.classList.add(className); - elm.setAttribute("aria-selected", true); - if (adjustScroll) - elm.parentNode.scrollTop = elm.clientHeight + elm.offsetTop - elm.parentNode.clientHeight; - if (this.settings.autoComplete) { - this.input.autocomplete.suggest.call(this, itemData); - this.dropdown.position(); + (_b = (_a = this._tooltipElems.get(tooltip.id)) == null ? void 0 : _a.data("revealTimeline")) == null ? void 0 : _b.play(); + } + clearTooltip(tooltipID, isClearingIfTweening = true) { + if (tooltipID === this._displayedTooltipID) { + delete this._displayedTooltipID; } - }, - /** - * Create a tag from the currently active suggestion option - * @param {Object} elm DOM node to select - * @param {Object} event The original Click event, if available (since keyboard ENTER key also triggers this method) - */ - selectOption(elm, event) { - var _this$settings$dropdo = this.settings.dropdown, clearOnSelect = _this$settings$dropdo.clearOnSelect, closeOnSelect = _this$settings$dropdo.closeOnSelect; - if (!elm) { - this.addTags(this.state.inputText, true); - closeOnSelect && this.dropdown.hide(); + const ttElem = game.eunoblades.Director._tooltipElems.get(tooltipID); + if (!ttElem) { return; } - event = event || {}; - var value = elm.getAttribute("value"), isNoMatch = value == "noMatch", tagData = this.suggestedListItems.find((item) => (item.value ?? item) == value); - this.trigger("dropdown:select", { - data: tagData, - elm, - event - }); - if (!value || !tagData && !isNoMatch) { - closeOnSelect && setTimeout(this.dropdown.hide.bind(this)); + const ttTimeline = ttElem.data("revealTimeline"); + if (ttTimeline.isActive() && !isClearingIfTweening) { return; } - if (this.state.editing) { - this.onEditTagDone(null, extend({ - __isValid: true - }, this.normalizeTags([tagData])[0])); - } else { - this[this.settings.mode == "mix" ? "addMixTags" : "addTags"]([tagData || this.input.raw.call(this)], clearOnSelect); - } - if (!this.DOM.input.parentNode) - return; - setTimeout(() => { - this.DOM.input.focus(); - this.toggleFocusClass(true); - }); - closeOnSelect && setTimeout(this.dropdown.hide.bind(this)); - elm.addEventListener("transitionend", () => { - this.dropdown.fillHeaderFooter(); - setTimeout(() => elm.remove(), 100); - }, { - once: true + ttTimeline.reverse(); + } + clearTooltips() { + eLog.checkLog3("Observer", "Observer Triggered!"); + game.eunoblades.Director._tooltipElems.forEach((ttElem) => { + if (ttElem.attr("id") === this._displayedTooltipID) { + return; + } + game.eunoblades.Director.clearTooltip(ttElem.attr("id"), true); }); - elm.classList.add(this.settings.classNames.dropdownItemHidden); - }, - // adds all the suggested items, including the ones which are not currently rendered, - // unless specified otherwise (by the "onlyRendered" argument) - selectAll(onlyRendered) { - this.suggestedListItems.length = 0; - this.dropdown.hide(); - this.dropdown.filterListItems(""); - var tagsToAdd = this.dropdown.filterListItems(""); - if (!onlyRendered) - tagsToAdd = this.state.dropdown.suggestions; - this.addTags(tagsToAdd, true); - return this; - }, - /** - * returns an HTML string of the suggestions' list items - * @param {String} value string to filter the whitelist by - * @param {Object} options "exact" - for exact complete match - * @return {Array} list of filtered whitelist items according to the settings provided and current value - */ - filterListItems(value, options) { - var _s = this.settings, _sd = _s.dropdown, options = options || {}, list = [], exactMatchesList = [], whitelist = _s.whitelist, suggestionsCount = _sd.maxItems >= 0 ? _sd.maxItems : Infinity, searchKeys = _sd.searchKeys, whitelistItem, valueIsInWhitelist, searchBy, isDuplicate, niddle, i = 0; - value = _s.mode == "select" && this.value.length && this.value[0][_s.tagTextProp] == value ? "" : value; - if (!value || !searchKeys.length) { - list = _sd.includeSelectedTags ? whitelist : whitelist.filter((item) => !this.isTagDuplicate(isObject(item) ? item.value : item)); - this.state.dropdown.suggestions = list; - return list.slice(0, suggestionsCount); - } - niddle = _sd.caseSensitive ? "" + value : ("" + value).toLowerCase(); - function stringHasAll(s, query) { - return query.toLowerCase().split(" ").every((q) => s.includes(q.toLowerCase())); - } - for (; i < whitelist.length; i++) { - let startsWithMatch, exactMatch; - whitelistItem = whitelist[i] instanceof Object ? whitelist[i] : { - value: whitelist[i] - }; - let itemWithoutSearchKeys = !Object.keys(whitelistItem).some((k) => searchKeys.includes(k)), _searchKeys = itemWithoutSearchKeys ? ["value"] : searchKeys; - if (_sd.fuzzySearch && !options.exact) { - searchBy = _searchKeys.reduce((values, k) => values + " " + (whitelistItem[k] || ""), "").toLowerCase().trim(); - if (_sd.accentedSearch) { - searchBy = unaccent(searchBy); - niddle = unaccent(niddle); - } - startsWithMatch = searchBy.indexOf(niddle) == 0; - exactMatch = searchBy === niddle; - valueIsInWhitelist = stringHasAll(searchBy, niddle); - } else { - startsWithMatch = true; - valueIsInWhitelist = _searchKeys.some((k) => { - var v = "" + (whitelistItem[k] || ""); - if (_sd.accentedSearch) { - v = unaccent(v); - niddle = unaccent(niddle); - } - if (!_sd.caseSensitive) - v = v.toLowerCase(); - exactMatch = v === niddle; - return options.exact ? v === niddle : v.indexOf(niddle) == 0; - }); + } + initTooltipSection() { + var _a; + const self2 = this; + this.clearTooltips(); + (_a = this._tooltipObserver) == null ? void 0 : _a.kill(); + this._tooltipObserver = Observer.create({ + type: "touch,pointer", + // onMove: throttledOnMove, + onClick() { + self2.clearTooltips(); } - isDuplicate = !_sd.includeSelectedTags && this.isTagDuplicate(isObject(whitelistItem) ? whitelistItem.value : whitelistItem); - if (valueIsInWhitelist && !isDuplicate) - if (exactMatch && startsWithMatch) - exactMatchesList.push(whitelistItem); - else if (_sd.sortby == "startsWith" && startsWithMatch) - list.unshift(whitelistItem); - else - list.push(whitelistItem); - } - this.state.dropdown.suggestions = exactMatchesList.concat(list); - return typeof _sd.sortby == "function" ? _sd.sortby(exactMatchesList.concat(list), niddle) : exactMatchesList.concat(list).slice(0, suggestionsCount); - }, - /** - * Returns the final value of a tag data (object) with regards to the "mapValueTo" dropdown setting - * @param {Object} tagData - * @returns - */ - getMappedValue(tagData) { - var mapValueTo = this.settings.dropdown.mapValueTo, value = mapValueTo ? typeof mapValueTo == "function" ? mapValueTo(tagData) : tagData[mapValueTo] || tagData.value : tagData.value; - return value; - }, - /** - * Creates the dropdown items' HTML - * @param {Array} sugegstionsList [Array of Objects] - * @return {String} - */ - createListHTML(sugegstionsList) { - return extend([], sugegstionsList).map((suggestion, idx) => { - if (typeof suggestion == "string" || typeof suggestion == "number") - suggestion = { - value: suggestion - }; - var mappedValue = this.dropdown.getMappedValue(suggestion); - mappedValue = typeof mappedValue == "string" ? escapeHTML(mappedValue) : mappedValue; - return this.settings.templates.dropdownItem.apply(this, [_objectSpread2(_objectSpread2({}, suggestion), {}, { - mappedValue - }), this]); - }).join(""); + }); } + // #endregion }; -const VERSION = 1; -const STORE_KEY = "@yaireo/tagify/"; -const getPersistedData = (id) => (key) => { - let customKey = "/" + key, persistedData, versionMatch = localStorage.getItem(STORE_KEY + id + "/v", VERSION) == VERSION; - if (versionMatch) { - try { - persistedData = JSON.parse(localStorage[STORE_KEY + id + customKey]); - } catch (err) { +// #region INITIALIZATION ~ +// #region >> Single-Instance Factory Construction ~ +__publicField(_BladesDirector, "instance"); +let BladesDirector = _BladesDirector; +class BladesItem extends Item { + constructor() { + super(...arguments); + __publicField(this, "dialogCSSClasses", ""); + } + // #region Static Overrides: Create ~ + static async create(data, options = {}) { + if (Array.isArray(data)) { + data = data[0]; } + data.system = data.system ?? {}; + eLog.checkLog2("item", "BladesItem.create(data,options)", { data, options }); + data.system.world_name = data.system.world_name ?? data.name.replace(/[^A-Za-z_0-9 ]/g, "").trim().replace(/ /g, "_"); + return super.create(data, options); } - return persistedData; -}; -const setPersistedData = (id) => { - if (!id) - return () => { - }; - localStorage.setItem(STORE_KEY + id + "/v", VERSION); - return (data, key) => { - let customKey = "/" + key, persistedData = JSON.stringify(data); - if (data && key) { - localStorage.setItem(STORE_KEY + id + customKey, persistedData); - dispatchEvent(new Event("storage")); + // #endregion + // #region BladesDocument Implementation + static get All() { + return game.items; + } + static Get(itemRef) { + if (itemRef instanceof BladesItem) { + return itemRef; } - }; -}; -const clearPersistedData = (id) => (key) => { - const base = STORE_KEY + "/" + id + "/"; - if (key) - localStorage.removeItem(base + key); - else { - for (let k in localStorage) - if (k.includes(base)) - localStorage.removeItem(k); + if (U.isDocID(itemRef)) { + return BladesItem.All.get(itemRef); + } + return BladesItem.All.find((a) => a.system.world_name === itemRef) || BladesItem.All.find((a) => a.name === itemRef); } -}; -var TEXTS = { - empty: "empty", - exceed: "number of tags exceeded", - pattern: "pattern mismatch", - duplicate: "already exists", - notAllowed: "not allowed" -}; -var templates = { - /** - * - * @param {DOM Object} input Original input DOm element - * @param {Object} settings Tagify instance settings Object - */ - wrapper(input, _s) { - return ` - - ​ - `; - }, - tag(tagData, _ref) { - let _s = _ref.settings; - return ` - -
- ${tagData[_s.tagTextProp] || tagData.value} -
-
`; - }, - dropdown(settings) { - var _sd = settings.dropdown, isManual = _sd.position == "manual", className = `${settings.classNames.dropdown}`; - return `
-
-
`; - }, - dropdownContent(HTMLContent) { - var _s = this.settings, suggestions = this.state.dropdown.suggestions; - return ` - ${_s.templates.dropdownHeader.call(this, suggestions)} - ${HTMLContent} - ${_s.templates.dropdownFooter.call(this, suggestions)} - `; - }, - dropdownItem(item) { - return `
${item.mappedValue || item.value}
`; - }, - /** - * @param {Array} suggestions An array of all the matched suggested items, including those which were sliced away due to the "dropdown.maxItems" setting - */ - dropdownHeader(suggestions) { - return `
`; - }, - dropdownFooter(suggestions) { - var hasMore = suggestions.length - this.settings.dropdown.maxItems; - return hasMore > 0 ? `
- ${hasMore} more items. Refine your search. -
` : ""; - }, - dropdownItemNoMatch: null -}; -function EventDispatcher(instance) { - var target = document.createTextNode(""); - function addRemove(op, events2, cb) { - if (cb) - events2.split(/\s+/g).forEach((name) => target[op + "EventListener"].call(target, name, cb)); + static GetTypeWithTags(docType, ...tags) { + if (Array.isArray(docType)) { + return docType.map((dType) => BladesItem.All.filter((item) => item.type === dType)).flat(); + } + return BladesItem.All.filter((item) => item.type === docType).filter((item) => item.hasTag(...tags)); } - return { - off(events2, cb) { - addRemove("remove", events2, cb); - return this; - }, - on(events2, cb) { - if (cb && typeof cb == "function") - addRemove("add", events2, cb); - return this; - }, - trigger(eventName, data, opts) { - var e; - opts = opts || { - cloneData: true - }; - if (!eventName) + static IsType(doc, ...types) { + const typeSet = new Set(types); + return doc instanceof BladesItem && typeSet.has(doc.type); + } + get tags() { + return this.system.tags ?? []; + } + hasTag(...tags) { + return tags.every((tag) => this.tags.includes(tag)); + } + async addTag(...tags) { + const curTags = this.tags; + tags.forEach((tag) => { + if (curTags.includes(tag)) { return; - if (instance.settings.isJQueryPlugin) { - if (eventName == "remove") - eventName = "removeTag"; - jQuery(instance.DOM.originalInput).triggerHandler(eventName, [data]); - } else { - try { - var eventData = typeof data === "object" ? data : { - value: data - }; - eventData = opts.cloneData ? extend({}, eventData) : eventData; - eventData.tagify = this; - if (data.event) - eventData.event = this.cloneEvent(data.event); - if (data instanceof Object) { - for (var prop in data) - if (data[prop] instanceof HTMLElement) - eventData[prop] = data[prop]; - } - e = new CustomEvent(eventName, { - "detail": eventData - }); - } catch (err) { - console.warn(err); - } - target.dispatchEvent(e); } - } - }; -} -var deleteBackspaceTimeout; -function triggerChangeEvent() { - if (this.settings.mixMode.integrated) - return; - var inputElm = this.DOM.originalInput, changed = this.state.lastOriginalValueReported !== inputElm.value, event = new CustomEvent("change", { - bubbles: true - }); - if (!changed) - return; - this.state.lastOriginalValueReported = inputElm.value; - event.simulated = true; - if (inputElm._valueTracker) - inputElm._valueTracker.setValue(Math.random()); - inputElm.dispatchEvent(event); - this.trigger("change", this.state.lastOriginalValueReported); - inputElm.value = this.state.lastOriginalValueReported; -} -var events = { - // bind custom events which were passed in the settings - customBinding() { - this.customEventsList.forEach((name) => { - this.on(name, this.settings.callbacks[name]); + curTags.push(tag); }); - }, - binding() { - let bindUnbind = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : true; - var _CB = this.events.callbacks, _CBR, action = bindUnbind ? "addEventListener" : "removeEventListener"; - if (this.state.mainEvents && bindUnbind) - return; - this.state.mainEvents = bindUnbind; - if (bindUnbind && !this.listeners.main) { - this.events.bindGlobal.call(this); - if (this.settings.isJQueryPlugin) - jQuery(this.DOM.originalInput).on("tagify.removeAllTags", this.removeAllTags.bind(this)); - } - _CBR = this.listeners.main = this.listeners.main || { - focus: ["input", _CB.onFocusBlur.bind(this)], - keydown: ["input", _CB.onKeydown.bind(this)], - click: ["scope", _CB.onClickScope.bind(this)], - dblclick: ["scope", _CB.onDoubleClickScope.bind(this)], - paste: ["input", _CB.onPaste.bind(this)], - drop: ["input", _CB.onDrop.bind(this)], - compositionstart: ["input", _CB.onCompositionStart.bind(this)], - compositionend: ["input", _CB.onCompositionEnd.bind(this)] - }; - for (var eventName in _CBR) { - this.DOM[_CBR[eventName][0]][action](eventName, _CBR[eventName][1]); - } - clearInterval(this.listeners.main.originalInputValueObserverInterval); - this.listeners.main.originalInputValueObserverInterval = setInterval(_CB.observeOriginalInputValue.bind(this), 500); - var inputMutationObserver = this.listeners.main.inputMutationObserver || new MutationObserver(_CB.onInputDOMChange.bind(this)); - inputMutationObserver.disconnect(); - if (this.settings.mode == "mix") - inputMutationObserver.observe(this.DOM.input, { - childList: true - }); - }, - bindGlobal(unbind) { - var _CB = this.events.callbacks, action = unbind ? "removeEventListener" : "addEventListener", e; - if (!this.listeners || !unbind && this.listeners.global) - return; - this.listeners.global = this.listeners.global || [{ - type: this.isIE ? "keydown" : "input", - // IE cannot register "input" events on contenteditable elements, so the "keydown" should be used instead.. - target: this.DOM.input, - cb: _CB[this.isIE ? "onInputIE" : "onInput"].bind(this) - }, { - type: "keydown", - target: window, - cb: _CB.onWindowKeyDown.bind(this) - }, { - type: "blur", - target: this.DOM.input, - cb: _CB.onFocusBlur.bind(this) - }, { - type: "click", - target: document, - cb: _CB.onClickAnywhere.bind(this) - }]; - for (e of this.listeners.global) - e.target[action](e.type, e.cb); - }, - unbindGlobal() { - this.events.bindGlobal.call(this, true); - }, - /** - * DOM events callbacks - */ - callbacks: { - onFocusBlur(e) { - var _a, _b; - var _s = this.settings, text = e.target ? this.trim(e.target.textContent) : "", currentDisplayValue = (_b = (_a = this.value) == null ? void 0 : _a[0]) == null ? void 0 : _b[_s.tagTextProp], type = e.type, ddEnabled = _s.dropdown.enabled >= 0, eventData = { - relatedTarget: e.relatedTarget - }, isTargetSelectOption = this.state.actions.selectOption && (ddEnabled || !_s.dropdown.closeOnSelect), isTargetAddNewBtn = this.state.actions.addNew && ddEnabled, isRelatedTargetX = e.relatedTarget && isNodeTag.call(this, e.relatedTarget) && this.DOM.scope.contains(e.relatedTarget), shouldAddTags; - if (type == "blur") { - if (e.relatedTarget === this.DOM.scope) { - this.dropdown.hide(); - this.DOM.input.focus(); - return; - } - this.postUpdate(); - _s.onChangeAfterBlur && this.triggerChangeEvent(); - } - if (isTargetSelectOption || isTargetAddNewBtn) - return; - this.state.hasFocus = type == "focus" ? +/* @__PURE__ */ new Date() : false; - this.toggleFocusClass(this.state.hasFocus); - if (_s.mode == "mix") { - if (type == "focus") { - this.trigger("focus", eventData); - } else if (e.type == "blur") { - this.trigger("blur", eventData); - this.loading(false); - this.dropdown.hide(); - this.state.dropdown.visible = void 0; - this.setStateSelection(); + await this.update({ "system.tags": curTags }); + } + async remTag(...tags) { + const curTags = this.tags.filter((tag) => !tags.includes(tag)); + await this.update({ "system.tags": curTags }); + } + get tooltip() { + const tooltipText = [ + this.system.concept, + this.system.rules, + this.system.notes + ].filter(Boolean).join(""); + if (tooltipText) { + return new Handlebars.SafeString(tooltipText).toString(); + } + return void 0; + } + getFactorTotal(factor) { + var _a, _b, _c; + switch (factor) { + case Factor.tier: { + if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { + return this.system.tier.value + (((_a = this.parent) == null ? void 0 : _a.getFactorTotal(Factor.tier)) ?? 0); } - return; - } - if (type == "focus") { - this.trigger("focus", eventData); - if (_s.dropdown.enabled === 0 || !_s.userInput) { - this.dropdown.show(this.value.length ? "" : void 0); + if (BladesItem.IsType(this, BladesItemType.cohort_expert)) { + return this.system.tier.value + (((_b = this.parent) == null ? void 0 : _b.getFactorTotal(Factor.tier)) ?? 0); } - return; - } else if (type == "blur") { - this.trigger("blur", eventData); - this.loading(false); - if (_s.mode == "select") { - if (isRelatedTargetX) { - this.removeTags(); - text = ""; - } - if (currentDisplayValue === text) - text = ""; + if (BladesItem.IsType(this, BladesItemType.gear)) { + return this.system.tier.value + (((_c = this.parent) == null ? void 0 : _c.getFactorTotal(Factor.tier)) ?? 0); } - shouldAddTags = text && !this.state.actions.selectOption && _s.addTagOnBlur; - shouldAddTags && this.addTags(text, true); + return this.system.tier.value; } - this.DOM.input.removeAttribute("style"); - this.dropdown.hide(); - }, - onCompositionStart(e) { - this.state.composing = true; - }, - onCompositionEnd(e) { - this.state.composing = false; - }, - onWindowKeyDown(e) { - var focusedElm = document.activeElement, isTag = isNodeTag.call(this, focusedElm), isBelong = isTag && this.DOM.scope.contains(document.activeElement), isReadyOnlyTag = isBelong && focusedElm.hasAttribute("readonly"), nextTag; - if (!isBelong || isReadyOnlyTag) - return; - nextTag = focusedElm.nextElementSibling; - switch (e.key) { - case "Backspace": { - if (!this.settings.readonly) { - this.removeTags(focusedElm); - (nextTag ? nextTag : this.DOM.input).focus(); - } - break; - } - case "Enter": { - setTimeout(this.editTag.bind(this), 0, focusedElm); - break; + case Factor.quality: { + if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { + return this.getFactorTotal(Factor.tier) + (this.system.quality_bonus ?? 0); } - } - }, - onKeydown(e) { - var _s = this.settings; - if (this.state.composing || !_s.userInput) - return; - if (_s.mode == "select" && _s.enforceWhitelist && this.value.length && e.key != "Tab") { - e.preventDefault(); - } - var s = this.trim(e.target.textContent); - this.trigger("keydown", { - event: e - }); - if (_s.mode == "mix") { - switch (e.key) { - case "Left": - case "ArrowLeft": { - this.state.actions.ArrowLeft = true; - break; - } - case "Delete": - case "Backspace": { - if (this.state.editing) - return; - var sel = document.getSelection(), deleteKeyTagDetected = e.key == "Delete" && sel.anchorOffset == (sel.anchorNode.length || 0), prevAnchorSibling = sel.anchorNode.previousSibling, isCaretAfterTag = sel.anchorNode.nodeType == 1 || !sel.anchorOffset && prevAnchorSibling && prevAnchorSibling.nodeType == 1 && sel.anchorNode.previousSibling; - decode(this.DOM.input.innerHTML); - var lastTagElems = this.getTagElms(), tagBeforeCaret, tagElmToBeDeleted, firstTextNodeBeforeTag; - if (_s.backspace == "edit" && isCaretAfterTag) { - tagBeforeCaret = sel.anchorNode.nodeType == 1 ? null : sel.anchorNode.previousElementSibling; - setTimeout(this.editTag.bind(this), 0, tagBeforeCaret); - e.preventDefault(); - return; - } - if (isChromeAndroidBrowser() && isCaretAfterTag instanceof Element) { - firstTextNodeBeforeTag = getfirstTextNode(isCaretAfterTag); - if (!isCaretAfterTag.hasAttribute("readonly")) - isCaretAfterTag.remove(); - this.DOM.input.focus(); - setTimeout(() => { - this.placeCaretAfterNode(firstTextNodeBeforeTag); - this.DOM.input.click(); - }); - return; - } - if (sel.anchorNode.nodeName == "BR") - return; - if ((deleteKeyTagDetected || isCaretAfterTag) && sel.anchorNode.nodeType == 1) { - if (sel.anchorOffset == 0) - tagElmToBeDeleted = deleteKeyTagDetected ? lastTagElems[0] : null; - else - tagElmToBeDeleted = lastTagElems[Math.min(lastTagElems.length, sel.anchorOffset) - 1]; - } else if (deleteKeyTagDetected) - tagElmToBeDeleted = sel.anchorNode.nextElementSibling; - else if (isCaretAfterTag instanceof Element) - tagElmToBeDeleted = isCaretAfterTag; - if (sel.anchorNode.nodeType == 3 && // node at caret location is a Text node - !sel.anchorNode.nodeValue && // has some text - sel.anchorNode.previousElementSibling) - e.preventDefault(); - if ((isCaretAfterTag || deleteKeyTagDetected) && !_s.backspace) { - e.preventDefault(); - return; - } - if (sel.type != "Range" && !sel.anchorOffset && sel.anchorNode == this.DOM.input && e.key != "Delete") { - e.preventDefault(); - return; - } - if (sel.type != "Range" && tagElmToBeDeleted && tagElmToBeDeleted.hasAttribute("readonly")) { - this.placeCaretAfterNode(getfirstTextNode(tagElmToBeDeleted)); - return; - } - clearTimeout(deleteBackspaceTimeout); - deleteBackspaceTimeout = setTimeout(() => { - var sel2 = document.getSelection(); - decode(this.DOM.input.innerHTML); - !deleteKeyTagDetected && sel2.anchorNode.previousSibling; - this.value = [].map.call(lastTagElems, (node, nodeIdx) => { - var tagData = getSetTagData(node); - if (node.parentNode || tagData.readonly) - return tagData; - else - this.trigger("remove", { - tag: node, - index: nodeIdx, - data: tagData - }); - }).filter((n) => n); - }, 20); - break; - } + if (BladesItem.IsType(this, BladesItemType.cohort_expert)) { + return this.getFactorTotal(Factor.tier) + (this.system.quality_bonus ?? 0) + 1; } - return true; - } - switch (e.key) { - case "Backspace": - if (_s.mode == "select" && _s.enforceWhitelist && this.value.length) - this.removeTags(); - else if (!this.state.dropdown.visible || _s.dropdown.position == "manual") { - if (e.target.textContent == "" || s.charCodeAt(0) == 8203) { - if (_s.backspace === true) - this.removeTags(); - else if (_s.backspace == "edit") - setTimeout(this.editTag.bind(this), 0); - } - } - break; - case "Esc": - case "Escape": - if (this.state.dropdown.visible) - return; - e.target.blur(); - break; - case "Down": - case "ArrowDown": - if (!this.state.dropdown.visible) - this.dropdown.show(); - break; - case "ArrowRight": { - let tagData = this.state.inputSuggestion || this.state.ddItemData; - if (tagData && _s.autoComplete.rightKey) { - this.addTags([tagData], true); - return; + if (BladesItem.IsType(this, BladesItemType.gear)) { + let thisQuality = this.getFactorTotal(Factor.tier) + (this.hasTag("Fine") ? 1 : 0); + if (BladesPC$1.IsType(this.parent)) { + thisQuality += this.parent.getTaggedItemBonuses(this.tags); } - break; - } - case "Tab": { - let selectMode = _s.mode == "select"; - if (s && !selectMode) - e.preventDefault(); - else - return true; - } - case "Enter": - if (this.state.dropdown.visible && _s.dropdown.position != "manual") - return; - e.preventDefault(); - setTimeout(() => { - if (this.state.dropdown.visible || this.state.actions.selectOption) - return; - this.addTags(s, true); - }); - } - }, - onInput(e) { - this.postUpdate(); - var _s = this.settings; - if (_s.mode == "mix") - return this.events.callbacks.onMixTagsInput.call(this, e); - var value = this.input.normalize.call(this), showSuggestions = value.length >= _s.dropdown.enabled, eventData = { - value, - inputElm: this.DOM.input - }, validation = this.validateTag({ - value - }); - if (_s.mode == "select") { - this.toggleScopeValidation(validation); - } - eventData.isValid = validation; - if (this.state.inputText == value) - return; - this.input.set.call(this, value, false); - if (value.search(_s.delimiters) != -1) { - if (this.addTags(value)) { - this.input.set.call(this); + return thisQuality; } - } else if (_s.dropdown.enabled >= 0) { - this.dropdown[showSuggestions ? "show" : "hide"](value); - } - this.trigger("input", eventData); - }, - onMixTagsInput(e) { - var rangeText, match, matchedPatternCount, tag, showSuggestions, selection, _s = this.settings, lastTagsCount = this.value.length, matchFlaggedTag, matchDelimiters, tagsElems = this.getTagElms(), fragment = document.createDocumentFragment(), range = window.getSelection().getRangeAt(0), remainingTagsValues = [].map.call(tagsElems, (node) => getSetTagData(node).value); - if (e.inputType == "deleteContentBackward" && isChromeAndroidBrowser()) { - this.events.callbacks.onKeydown.call(this, { - target: e.target, - key: "Backspace" - }); - } - this.value.slice().forEach((item) => { - if (item.readonly && !remainingTagsValues.includes(item.value)) - fragment.appendChild(this.createTagElem(item)); - }); - if (fragment.childNodes.length) { - range.insertNode(fragment); - this.setRangeAtStartEnd(false, fragment.lastChild); - } - if (tagsElems.length != lastTagsCount) { - this.value = [].map.call(this.getTagElms(), (node) => getSetTagData(node)); - this.update({ - withoutChangeEvent: true - }); - return; - } - if (this.hasMaxTags()) - return true; - if (window.getSelection) { - selection = window.getSelection(); - if (selection.rangeCount > 0 && selection.anchorNode.nodeType == 3) { - range = selection.getRangeAt(0).cloneRange(); - range.collapse(true); - range.setStart(selection.focusNode, 0); - rangeText = range.toString().slice(0, range.endOffset); - matchedPatternCount = rangeText.split(_s.pattern).length - 1; - match = rangeText.match(_s.pattern); - if (match) - tag = rangeText.slice(rangeText.lastIndexOf(match[match.length - 1])); - if (tag) { - this.state.actions.ArrowLeft = false; - this.state.tag = { - prefix: tag.match(_s.pattern)[0], - value: tag.replace(_s.pattern, "") - // get rid of the prefix - }; - this.state.tag.baseOffset = selection.baseOffset - this.state.tag.value.length; - matchDelimiters = this.state.tag.value.match(_s.delimiters); - if (matchDelimiters) { - this.state.tag.value = this.state.tag.value.replace(_s.delimiters, ""); - this.state.tag.delimiters = matchDelimiters[0]; - this.addTags(this.state.tag.value, _s.dropdown.clearOnSelect); - this.dropdown.hide(); - return; - } - showSuggestions = this.state.tag.value.length >= _s.dropdown.enabled; - try { - matchFlaggedTag = this.state.flaggedTags[this.state.tag.baseOffset]; - matchFlaggedTag = matchFlaggedTag.prefix == this.state.tag.prefix && matchFlaggedTag.value[0] == this.state.tag.value[0]; - if (this.state.flaggedTags[this.state.tag.baseOffset] && !this.state.tag.value) - delete this.state.flaggedTags[this.state.tag.baseOffset]; - } catch (err) { - } - if (matchFlaggedTag || matchedPatternCount < this.state.mixMode.matchedPatternCount) - showSuggestions = false; - } else { - this.state.flaggedTags = {}; - } - this.state.mixMode.matchedPatternCount = matchedPatternCount; + if (BladesItem.IsType(this, BladesItemType.design)) { + return this.system.min_quality; } + return this.getFactorTotal(Factor.tier); } - setTimeout(() => { - this.update({ - withoutChangeEvent: true - }); - this.trigger("input", extend({}, this.state.tag, { - textContent: this.DOM.input.textContent - })); - if (this.state.tag) - this.dropdown[showSuggestions ? "show" : "hide"](this.state.tag.value); - }, 10); - }, - onInputIE(e) { - var _this = this; - setTimeout(function() { - _this.events.callbacks.onInput.call(_this, e); - }); - }, - observeOriginalInputValue() { - if (!this.DOM.originalInput.parentNode) - this.destroy(); - if (this.DOM.originalInput.value != this.DOM.originalInput.tagifyValue) - this.loadOriginalValues(); - }, - onClickAnywhere(e) { - if (e.target != this.DOM.scope && !this.DOM.scope.contains(e.target)) { - this.toggleFocusClass(false); - this.state.hasFocus = false; - } - }, - onClickScope(e) { - var _s = this.settings, tagElm = e.target.closest("." + _s.classNames.tag), timeDiffFocus = +/* @__PURE__ */ new Date() - this.state.hasFocus; - if (e.target == this.DOM.scope) { - this.DOM.input.focus(); - return; - } else if (e.target.classList.contains(_s.classNames.tagX)) { - this.removeTags(e.target.parentNode); - return; - } else if (tagElm) { - this.trigger("click", { - tag: tagElm, - index: this.getNodeIndex(tagElm), - data: getSetTagData(tagElm), - event: e - }); - if (_s.editTags === 1 || _s.editTags.clicks === 1) - this.events.callbacks.onDoubleClickScope.call(this, e); - return; - } else if (e.target == this.DOM.input) { - if (_s.mode == "mix") { - this.fixFirefoxLastTagNoCaret(); - } - if (timeDiffFocus > 500) { - if (this.state.dropdown.visible) - this.dropdown.hide(); - else if (_s.dropdown.enabled === 0 && _s.mode != "mix") - this.dropdown.show(this.value.length ? "" : void 0); - return; + case Factor.scale: { + if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { + return this.getFactorTotal(Factor.tier) + (this.system.scale_bonus ?? 0); } - } - if (_s.mode == "select" && _s.dropdown.enabled === 0 && !this.state.dropdown.visible) - this.dropdown.show(); - }, - // special proccess is needed for pasted content in order to "clean" it - onPaste(e) { - e.preventDefault(); - var _s = this.settings, selectModeWithoutInput = _s.mode == "select" && _s.enforceWhitelist; - if (selectModeWithoutInput || !_s.userInput) { - return false; - } - var clipboardData, pastedText; - if (_s.readonly) - return; - clipboardData = e.clipboardData || window.clipboardData; - pastedText = clipboardData.getData("Text"); - _s.hooks.beforePaste(e, { - tagify: this, - pastedText, - clipboardData - }).then((result) => { - if (result === void 0) - result = pastedText; - if (result) { - this.injectAtCaret(result, window.getSelection().getRangeAt(0)); - if (this.settings.mode == "mix") { - this.events.callbacks.onMixTagsInput.call(this, e); - } else if (this.settings.pasteAsTags) { - this.addTags(this.state.inputText + result, true); - } else - this.state.inputText = result; + if (BladesItem.IsType(this, BladesItemType.cohort_expert)) { + return 0 + (this.system.scale_bonus ?? 0); } - }).catch((err) => err); - }, - onDrop(e) { - e.preventDefault(); - }, - onEditTagInput(editableElm, e) { - var tagElm = editableElm.closest("." + this.settings.classNames.tag), tagElmIdx = this.getNodeIndex(tagElm), tagData = getSetTagData(tagElm), textValue = this.input.normalize.call(this, editableElm), dataForChangedProp = { - [this.settings.tagTextProp]: textValue, - __tagId: tagData.__tagId - }, isValid = this.validateTag(dataForChangedProp), hasChanged = this.editTagChangeDetected(extend(tagData, dataForChangedProp)); - if (!hasChanged && editableElm.originalIsValid === true) - isValid = true; - tagElm.classList.toggle(this.settings.classNames.tagInvalid, isValid !== true); - tagData.__isValid = isValid; - tagElm.title = isValid === true ? tagData.title || tagData.value : isValid; - if (textValue.length >= this.settings.dropdown.enabled) { - if (this.state.editing) - this.state.editing.value = textValue; - this.dropdown.show(textValue); - } - this.trigger("edit:input", { - tag: tagElm, - index: tagElmIdx, - data: extend({}, this.value[tagElmIdx], { - newValue: textValue - }), - event: e - }); - }, - onEditTagPaste(tagElm, e) { - var clipboardData = e.clipboardData || window.clipboardData, pastedText = clipboardData.getData("Text"); - e.preventDefault(); - var newNode = injectAtCaret(pastedText); - this.setRangeAtStartEnd(false, newNode); - }, - onEditTagFocus(tagElm) { - this.state.editing = { - scope: tagElm, - input: tagElm.querySelector("[contenteditable]") - }; - }, - onEditTagBlur(editableElm) { - if (!this.state.hasFocus) - this.toggleFocusClass(); - if (!this.DOM.scope.contains(editableElm)) - return; - var _s = this.settings, tagElm = editableElm.closest("." + _s.classNames.tag), tagData = getSetTagData(tagElm), textValue = this.input.normalize.call(this, editableElm), dataForChangedProp = { - [_s.tagTextProp]: textValue, - __tagId: tagData.__tagId - }, originalData = tagData.__originalData, hasChanged = this.editTagChangeDetected(extend(tagData, dataForChangedProp)), isValid = this.validateTag(dataForChangedProp), hasMaxTags, newTagData; - if (!textValue) { - this.onEditTagDone(tagElm); - return; - } - if (!hasChanged) { - this.onEditTagDone(tagElm, originalData); - return; - } - hasMaxTags = this.hasMaxTags(); - newTagData = extend({}, originalData, { - [_s.tagTextProp]: this.trim(textValue), - __isValid: isValid - }); - _s.transformTag.call(this, newTagData, originalData); - isValid = (!hasMaxTags || originalData.__isValid === true) && this.validateTag(newTagData); - if (isValid !== true) { - this.trigger("invalid", { - data: newTagData, - tag: tagElm, - message: isValid - }); - if (_s.editTags.keepInvalid) - return; - if (_s.keepInvalidTags) - newTagData.__isValid = isValid; - else - newTagData = originalData; - } else if (_s.keepInvalidTags) { - delete newTagData.title; - delete newTagData["aria-invalid"]; - delete newTagData.class; + return 0; } - this.onEditTagDone(tagElm, newTagData); - }, - onEditTagkeydown(e, tagElm) { - if (this.state.composing) - return; - this.trigger("edit:keydown", { - event: e - }); - switch (e.key) { - case "Esc": - case "Escape": { - tagElm.parentNode.replaceChild(tagElm.__tagifyTagData.__originalHTML, tagElm); - this.state.editing = false; + case Factor.magnitude: { + if (BladesItem.IsType(this, BladesItemType.ritual)) { + return this.system.magnitude.value; } - case "Enter": - case "Tab": - e.preventDefault(); - e.target.blur(); - } - }, - onDoubleClickScope(e) { - var tagElm = e.target.closest("." + this.settings.classNames.tag), tagData = getSetTagData(tagElm), _s = this.settings, isEditingTag, isReadyOnlyTag; - if (!tagElm || !_s.userInput || tagData.editable === false) - return; - isEditingTag = tagElm.classList.contains(this.settings.classNames.tagEditing); - isReadyOnlyTag = tagElm.hasAttribute("readonly"); - if (_s.mode != "select" && !_s.readonly && !isEditingTag && !isReadyOnlyTag && this.settings.editTags) - this.editTag(tagElm); - this.toggleFocusClass(true); - this.trigger("dblclick", { - tag: tagElm, - index: this.getNodeIndex(tagElm), - data: getSetTagData(tagElm) - }); - }, - /** - * - * @param {Object} m an object representing the observed DOM changes - */ - onInputDOMChange(m) { - m.forEach((record) => { - record.addedNodes.forEach((addedNode) => { - var _a; - if (addedNode.outerHTML == "

") { - addedNode.replaceWith(document.createElement("br")); - } else if (addedNode.nodeType == 1 && addedNode.querySelector(this.settings.classNames.tagSelector)) { - let newlineText = document.createTextNode(""); - if (addedNode.childNodes[0].nodeType == 3 && addedNode.previousSibling.nodeName != "BR") - newlineText = document.createTextNode("\n"); - addedNode.replaceWith(...[newlineText, ...[...addedNode.childNodes].slice(0, -1)]); - this.placeCaretAfterNode(newlineText); - } else if (isNodeTag.call(this, addedNode)) { - if (((_a = addedNode.previousSibling) == null ? void 0 : _a.nodeType) == 3 && !addedNode.previousSibling.textContent) - addedNode.previousSibling.remove(); - if (addedNode.previousSibling && addedNode.previousSibling.nodeName == "BR") { - addedNode.previousSibling.replaceWith("\n​"); - let nextNode = addedNode.nextSibling, anythingAfterNode = ""; - while (nextNode) { - anythingAfterNode += nextNode.textContent; - nextNode = nextNode.nextSibling; - } - anythingAfterNode.trim() && this.placeCaretAfterNode(addedNode.previousSibling); - } - } - }); - record.removedNodes.forEach((removedNode) => { - if (removedNode && removedNode.nodeName == "BR" && isNodeTag.call(this, lastInputChild)) { - this.removeTags(lastInputChild); - this.fixFirefoxLastTagNoCaret(); - } - }); - }); - var lastInputChild = this.DOM.input.lastChild; - if (lastInputChild && lastInputChild.nodeValue == "") - lastInputChild.remove(); - if (!lastInputChild || lastInputChild.nodeName != "BR") { - this.DOM.input.appendChild(document.createElement("br")); + return 0; } + default: + return 0; + } + } + // #endregion + // #region BladesItemDocument Implementation + async archive() { + await this.addTag(Tag.System.Archived); + return this; + } + async unarchive() { + await this.remTag(Tag.System.Archived); + return this; + } + // #endregion + // #region BladesRoll Implementation + get rollFactors() { + const factorsMap = { + [BladesItemType.cohort_gang]: [Factor.quality, Factor.scale], + [BladesItemType.cohort_expert]: [Factor.quality, Factor.scale], + [BladesItemType.gear]: [Factor.quality], + [BladesItemType.project]: [Factor.quality], + [BladesItemType.ritual]: [Factor.magnitude], + [BladesItemType.design]: [Factor.quality] + }; + if (!factorsMap[this.type]) { + return {}; + } + const factors = factorsMap[this.type]; + const factorData = {}; + (factors ?? []).forEach((factor, i) => { + const factorTotal = this.getFactorTotal(factor); + factorData[factor] = { + name: factor, + value: factorTotal, + max: factorTotal, + baseVal: factorTotal, + display: [Factor.tier, Factor.quality].includes(factor) ? U.romanizeNum(factorTotal) : `${factorTotal}`, + isActive: i === 0, + isPrimary: i === 0, + isDominant: false, + highFavorsPC: true, + cssClasses: `factor-gold${i === 0 ? " factor-main" : ""}` + }; + }); + return factorData; + } + // #region BladesRoll.PrimaryDoc Implementation + get rollPrimaryID() { + return this.id; + } + get rollPrimaryDoc() { + return this; + } + get rollPrimaryName() { + return this.name; + } + get rollPrimaryType() { + if (![ + BladesItemType.cohort_gang, + BladesItemType.cohort_expert, + BladesItemType.gm_tracker, + BladesItemType.score + ].includes(this.type)) { + throw new Error(`BladesItem of type '${this.type}' ("${this.name}") cannot be RollPrimary.`); } + return this.type; } -}; -function Tagify(input, settings) { - if (!input) { - console.warn("Tagify:", "input element not found", input); - const mockInstance = new Proxy(this, { - get() { - return () => mockInstance; + get rollPrimaryImg() { + return this.img; + } + get rollPrimaryModsSchemaSet() { + return BladesRollMod.ParseDocModsToSchemaSet(this); + } + async applyHarm(amount, _name2) { + if (BladesItem.IsType(this, BladesItemType.cohort_expert, BladesItemType.cohort_gang)) { + const curHarm = this.system.harm.value; + let newHarm; + if (amount > curHarm) { + newHarm = amount; + } else { + newHarm = curHarm + 1; } - }); - return mockInstance; - } - if (input.__tagify) { - console.warn("Tagify: ", "input element is already Tagified - Same instance is returned.", input); - return input.__tagify; - } - extend(this, EventDispatcher(this)); - this.isFirefox = /firefox|fxios/i.test(navigator.userAgent) && !/seamonkey/i.test(navigator.userAgent); - this.isIE = window.document.documentMode; - settings = settings || {}; - this.getPersistedData = getPersistedData(settings.id); - this.setPersistedData = setPersistedData(settings.id); - this.clearPersistedData = clearPersistedData(settings.id); - this.applySettings(input, settings); - this.state = { - inputText: "", - editing: false, - composing: false, - actions: {}, - // UI actions for state-locking - mixMode: {}, - dropdown: {}, - flaggedTags: {} - // in mix-mode, when a string is detetced as potential tag, and the user has chocen to close the suggestions dropdown, keep the record of the tasg here - }; - this.value = []; - this.listeners = {}; - this.DOM = {}; - this.build(input); - initDropdown.call(this); - this.getCSSVars(); - this.loadOriginalValues(); - this.events.customBinding.call(this); - this.events.binding.call(this); - input.autofocus && this.DOM.input.focus(); - input.__tagify = this; -} -Tagify.prototype = { - _dropdown, - getSetTagData, - helpers: { - sameStr, - removeCollectionProp, - omit, - isObject, - parseHTML, - escapeHTML, - extend, - concatWithoutDups, - getUID, - isNodeTag - }, - customEventsList: ["change", "add", "remove", "invalid", "input", "click", "keydown", "focus", "blur", "edit:input", "edit:beforeUpdate", "edit:updated", "edit:start", "edit:keydown", "dropdown:show", "dropdown:hide", "dropdown:select", "dropdown:updated", "dropdown:noMatch", "dropdown:scroll"], - dataProps: ["__isValid", "__removed", "__originalData", "__originalHTML", "__tagId"], - // internal-uasge props - trim(text) { - return this.settings.trim && text && typeof text == "string" ? text.trim() : text; - }, - // expose this handy utility function - parseHTML, - templates, - parseTemplate(template, data) { - template = this.settings.templates[template] || template; - return parseHTML(template.apply(this, data)); - }, - set whitelist(arr) { - const isArray2 = arr && Array.isArray(arr); - this.settings.whitelist = isArray2 ? arr : []; - this.setPersistedData(isArray2 ? arr : [], "whitelist"); - }, - get whitelist() { - return this.settings.whitelist; - }, - generateClassSelectors(classNames) { - for (let name in classNames) { - let currentName = name; - Object.defineProperty(classNames, currentName + "Selector", { - get() { - return "." + this[currentName].split(" ")[0]; + const harmVerb = ["is Weakened", "is Impaired", "has been Broken", "has been Killed!"]; + const harmEffect = [ + "They act with Reduced Effect.", + "They act with Reduced Effect and suffer -1d to all rolls.", + "They cannot do anything until they recover.", + "You may replace them during Downtime." + ]; + BladesDirector.getInstance().pushNotice_SocketCall( + "ALL", + { + title: `${this.name} ${harmVerb[newHarm - 1]}`, + body: harmEffect[newHarm - 1], + type: BladesNoticeType.push, + cssClasses: "harm-alert" } - }); + ); + await this.update({ "system.harm": amount }); } - }, - applySettings(input, settings) { - var _a, _b; - DEFAULTS.templates = this.templates; - var mixModeDefaults = { - dropdown: { - position: "text" - } - }; - var mergedDefaults = extend({}, DEFAULTS, settings.mode == "mix" ? mixModeDefaults : {}); - var _s = this.settings = extend({}, mergedDefaults, settings); - _s.disabled = input.hasAttribute("disabled"); - _s.readonly = _s.readonly || input.hasAttribute("readonly"); - _s.placeholder = escapeHTML(input.getAttribute("placeholder") || _s.placeholder || ""); - _s.required = input.hasAttribute("required"); - this.generateClassSelectors(_s.classNames); - if (_s.dropdown.includeSelectedTags === void 0) - _s.dropdown.includeSelectedTags = _s.duplicates; - if (this.isIE) - _s.autoComplete = false; - ["whitelist", "blacklist"].forEach((name) => { - var attrVal = input.getAttribute("data-" + name); - if (attrVal) { - attrVal = attrVal.split(_s.delimiters); - if (attrVal instanceof Array) - _s[name] = attrVal; - } - }); - if ("autoComplete" in settings && !isObject(settings.autoComplete)) { - _s.autoComplete = DEFAULTS.autoComplete; - _s.autoComplete.enabled = settings.autoComplete; - } - if (_s.mode == "mix") { - _s.pattern = _s.pattern || /@/; - _s.autoComplete.rightKey = true; - _s.delimiters = settings.delimiters || null; - if (_s.tagTextProp && !_s.dropdown.searchKeys.includes(_s.tagTextProp)) - _s.dropdown.searchKeys.push(_s.tagTextProp); - } - if (input.pattern) - try { - _s.pattern = new RegExp(input.pattern); - } catch (e) { - } - if (_s.delimiters) { - _s._delimiters = _s.delimiters; - try { - _s.delimiters = new RegExp(this.settings.delimiters, "g"); - } catch (e) { - } + } + async applyWorsePosition() { + if (BladesItem.IsType(this, BladesItemType.cohort_expert, BladesItemType.cohort_gang)) { + this.setFlag("eunos-blades", "isWorsePosition", true); } - if (_s.disabled) - _s.userInput = false; - this.TEXTS = _objectSpread2(_objectSpread2({}, TEXTS), _s.texts || {}); - if (_s.mode == "select" && !((_a = settings.dropdown) == null ? void 0 : _a.enabled) || !_s.userInput) { - _s.dropdown.enabled = 0; + } + // #endregion + // #region BladesRoll.OppositionDoc Implementation + get rollOppID() { + return this.id; + } + get rollOppDoc() { + return this; + } + get rollOppImg() { + return this.img; + } + get rollOppName() { + return this.name; + } + get rollOppSubName() { + return ""; + } + get rollOppType() { + if (![ + BladesItemType.cohort_gang, + BladesItemType.cohort_expert, + BladesItemType.gm_tracker, + BladesItemType.score, + BladesItemType.location, + BladesItemType.project, + BladesItemType.design, + BladesItemType.ritual + ].includes(this.type)) { + throw new Error(`BladesItem of type '${this.type}' ("${this.name}") cannot be RollOpposition.`); } - _s.dropdown.appendTarget = ((_b = settings.dropdown) == null ? void 0 : _b.appendTarget) || document.body; - let persistedWhitelist = this.getPersistedData("whitelist"); - if (Array.isArray(persistedWhitelist)) - this.whitelist = Array.isArray(_s.whitelist) ? concatWithoutDups(_s.whitelist, persistedWhitelist) : persistedWhitelist; - }, - /** - * Returns a string of HTML element attributes - * @param {Object} data [Tag data] - */ - getAttributes(data) { - var attrs = this.getCustomAttributes(data), s = "", k; - for (k in attrs) - s += " " + k + (data[k] !== void 0 ? `="${attrs[k]}"` : ""); - return s; - }, - /** - * Returns an object of attributes to be used for the templates - */ - getCustomAttributes(data) { - if (!isObject(data)) - return ""; - var output = {}, propName; - for (propName in data) { - if (propName.slice(0, 2) != "__" && propName != "class" && data.hasOwnProperty(propName) && data[propName] !== void 0) - output[propName] = escapeHTML(data[propName]); + return this.type; + } + get rollOppModsSchemaSet() { + return []; + } + // #endregion + // #region BladesRoll.ParticipantDoc Implementation + get rollParticipantID() { + return this.id; + } + get rollParticipantDoc() { + return this; + } + get rollParticipantIcon() { + return this.img; + } + get rollParticipantName() { + return this.name; + } + get rollParticipantType() { + if (![ + BladesItemType.cohort_gang, + BladesItemType.cohort_expert, + BladesItemType.gm_tracker + ].includes(this.type)) { + throw new Error(`BladesItem of type '${this.type}' ("${this.name}") cannot be RollParticipant.`); } - return output; - }, - setStateSelection() { - var selection = window.getSelection(); - var sel = { - anchorOffset: selection.anchorOffset, - anchorNode: selection.anchorNode, - range: selection.getRangeAt && selection.rangeCount && selection.getRangeAt(0) - }; - this.state.selection = sel; - return sel; - }, - /** - * Get specific CSS variables which are relevant to this script and parse them as needed. - * The result is saved on the instance in "this.CSSVars" - */ - getCSSVars() { - var compStyle = getComputedStyle(this.DOM.scope, null); - const getProp = (name) => compStyle.getPropertyValue("--" + name); - function seprateUnitFromValue(a) { - if (!a) - return {}; - a = a.trim().split(" ")[0]; - var unit = a.split(/\d+/g).filter((n) => n).pop().trim(), value = +a.split(unit).filter((n) => n)[0].trim(); - return { - value, - unit - }; + return this.type; + } + get rollParticipantModsSchemaSet() { + return []; + } + // #endregion + // #endregion + // #region PREPARING DERIVED DATA + prepareDerivedData() { + super.prepareDerivedData(); + if (BladesItem.IsType(this, BladesItemType.cohort_gang, BladesItemType.cohort_expert)) { + this._prepareCohortData(this.system); } - this.CSSVars = { - tagHideTransition: ((_ref) => { - let value = _ref.value, unit = _ref.unit; - return unit == "s" ? value * 1e3 : value; - })(seprateUnitFromValue(getProp("tag-hide-transition"))) - }; - }, - /** - * builds the HTML of this component - * @param {Object} input [DOM element which would be "transformed" into "Tags"] - */ - build(input) { - var DOM = this.DOM; - if (this.settings.mixMode.integrated) { - DOM.originalInput = null; - DOM.scope = input; - DOM.input = input; - } else { - DOM.originalInput = input; - DOM.originalInput_tabIndex = input.tabIndex; - DOM.scope = this.parseTemplate("wrapper", [input, this.settings]); - DOM.input = DOM.scope.querySelector(this.settings.classNames.inputSelector); - input.parentNode.insertBefore(DOM.scope, input); - input.tabIndex = -1; + if (BladesItem.IsType(this, BladesItemType.crew_playbook)) { + this._preparePlaybookData(this.system); } - }, - /** - * revert any changes made by this component - */ - destroy() { - this.events.unbindGlobal.call(this); - this.DOM.scope.parentNode.removeChild(this.DOM.scope); - this.DOM.originalInput.tabIndex = this.DOM.originalInput_tabIndex; - delete this.DOM.originalInput.__tagify; - this.dropdown.hide(true); - clearTimeout(this.dropdownHide__bindEventsTimeout); - clearInterval(this.listeners.main.originalInputValueObserverInterval); - }, - /** - * if the original input has any values, add them as tags - */ - loadOriginalValues(value) { - var lastChild, _s = this.settings; - this.state.blockChangeEvent = true; - if (value === void 0) { - const persistedOriginalValue = this.getPersistedData("value"); - if (persistedOriginalValue && !this.DOM.originalInput.value) - value = persistedOriginalValue; - else - value = _s.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value; - } - this.removeAllTags(); - if (value) { - if (_s.mode == "mix") { - this.parseMixTags(value); - lastChild = this.DOM.input.lastChild; - if (!lastChild || lastChild.tagName != "BR") - this.DOM.input.insertAdjacentHTML("beforeend", "
"); + if (BladesItem.IsType(this, BladesItemType.gear)) { + this._prepareGearData(this.system); + } + if (BladesItem.IsType(this, BladesItemType.playbook)) { + this._preparePlaybookData(this.system); + } + } + _prepareCohortData(system) { + if (!BladesItem.IsType(this, BladesItemType.cohort_gang, BladesItemType.cohort_expert)) { + return; + } + system.tier.name = "Quality"; + const subtypes = U.unique(Object.values(system.subtypes).map((subtype) => subtype.trim()).filter((subtype) => /[A-Za-z]/.test(subtype))); + const eliteSubtypes = [ + ...Object.values(system.elite_subtypes) + ]; + if (BladesCrew$1.IsType(this.parent)) { + eliteSubtypes.push( + ...this.parent.upgrades.filter((upgrade) => (upgrade.name ?? "").startsWith("Elite")).map((upgrade) => (upgrade.name ?? "").trim().replace(/^Elite /, "")) + ); + } + system.subtypes = Object.fromEntries(subtypes.map((subtype, i) => [`${i + 1}`, subtype])); + system.elite_subtypes = Object.fromEntries( + U.unique( + eliteSubtypes.map((subtype) => subtype.trim()).filter((subtype) => /[A-Za-z]/.test(subtype) && subtypes.includes(subtype)) + ).map((subtype, i) => [`${i + 1}`, subtype]) + ); + system.edges = Object.fromEntries(Object.values(system.edges ?? []).filter((edge) => /[A-Za-z]/.test(edge)).map((edge, i) => [`${i + 1}`, edge.trim()])); + system.flaws = Object.fromEntries(Object.values(system.flaws ?? []).filter((flaw) => /[A-Za-z]/.test(flaw)).map((flaw, i) => [`${i + 1}`, flaw.trim()])); + system.quality = this.getFactorTotal(Factor.quality); + if (BladesItem.IsType(this, BladesItemType.cohort_gang)) { + if ([...subtypes, ...eliteSubtypes].includes(Tag.GangType.Vehicle)) { + system.scale = this.getFactorTotal(Factor.scale); + system.scaleExample = "(1 vehicle)"; } else { - try { - if (JSON.parse(value) instanceof Array) - value = JSON.parse(value); - } catch (err) { - } - this.addTags(value, true).forEach((tag) => tag && tag.classList.add(_s.classNames.tagNoAnimation)); + system.scale = this.getFactorTotal(Factor.scale); + const scaleIndex = Math.min(6, system.scale); + system.scaleExample = C.ScaleExamples[scaleIndex]; + system.subtitle = C.ScaleSizes[scaleIndex]; } - } else - this.postUpdate(); - this.state.lastOriginalValueReported = _s.mixMode.integrated ? "" : this.DOM.originalInput.value; - }, - cloneEvent(e) { - var clonedEvent = {}; - for (var v in e) - if (v != "path") - clonedEvent[v] = e[v]; - return clonedEvent; - }, - /** - * Toogle global loading state on/off - * Useful when fetching async whitelist while user is typing - * @param {Boolean} isLoading - */ - loading(isLoading) { - this.state.isLoading = isLoading; - this.DOM.scope.classList[isLoading ? "add" : "remove"](this.settings.classNames.scopeLoading); - return this; - }, - /** - * Toogle a tag loading state on/off - * @param {Boolean} isLoading - */ - tagLoading(tagElm, isLoading) { - if (tagElm) - tagElm.classList[isLoading ? "add" : "remove"](this.settings.classNames.tagLoading); - return this; - }, - /** - * Toggles class on the main tagify container ("scope") - * @param {String} className - * @param {Boolean} force - */ - toggleClass(className, force) { - if (typeof className == "string") - this.DOM.scope.classList.toggle(className, force); - }, - toggleScopeValidation(validation) { - var isValid = validation === true || validation === void 0; - if (!this.settings.required && validation && validation === this.TEXTS.empty) - isValid = true; - this.toggleClass(this.settings.classNames.tagInvalid, !isValid); - this.DOM.scope.title = isValid ? "" : validation; - }, - toggleFocusClass(force) { - this.toggleClass(this.settings.classNames.focus, !!force); - }, - triggerChangeEvent, - events, - fixFirefoxLastTagNoCaret() { - return; - }, - /** https://stackoverflow.com/a/59156872/104380 - * @param {Boolean} start indicating where to place it (start or end of the node) - * @param {Object} node DOM node to place the caret at - */ - setRangeAtStartEnd(start, node) { - if (!node) - return; - start = typeof start == "number" ? start : !!start; - node = node.lastChild || node; - var sel = document.getSelection(); - if (sel.focusNode instanceof Element && !this.DOM.input.contains(sel.focusNode)) { - return true; + if (subtypes.length + eliteSubtypes.length === 0) { + system.subtitle = system.subtitle.replace(/\s+of\b/g, "").trim(); + } + } else { + system.scale = 0; + system.scaleExample = [...subtypes, ...eliteSubtypes].includes("Pet") ? "(1 animal)" : "(1 person)"; + system.subtitle = "An Expert"; } - try { - if (sel.rangeCount >= 1) { - ["Start", "End"].forEach((pos) => sel.getRangeAt(0)["set" + pos](node, start ? start : node.length)); + if (subtypes.length + eliteSubtypes.length > 0) { + if ([...subtypes, ...eliteSubtypes].includes(Tag.GangType.Vehicle)) { + system.subtitle = C.VehicleDescriptors[Math.min(6, this.getFactorTotal(Factor.tier))]; + } else { + system.subtitle += ` ${U.oxfordize([ + ...subtypes.filter((subtype) => !eliteSubtypes.includes(subtype)), + ...eliteSubtypes.map((subtype) => `Elite ${subtype}`) + ], false, "&")}`; } - } catch (err) { } - }, - placeCaretAfterNode(node) { - if (!node || !node.parentNode) + } + _prepareGearData(system) { + if (!BladesItem.IsType(this, BladesItemType.gear)) { return; - var nextSibling = node, sel = window.getSelection(), range = sel.getRangeAt(0); - if (sel.rangeCount) { - range.setStartAfter(nextSibling); - range.collapse(true); - sel.removeAllRanges(); - sel.addRange(range); } - }, - insertAfterTag(tagElm, newNode) { - newNode = newNode || this.settings.mixMode.insertAfterTag; - if (!tagElm || !tagElm.parentNode || !newNode) + system.tier.name = "Quality"; + } + _preparePlaybookData(system) { + if (!BladesItem.IsType(this, BladesItemType.playbook, BladesItemType.crew_playbook)) { return; - newNode = typeof newNode == "string" ? document.createTextNode(newNode) : newNode; - tagElm.parentNode.insertBefore(newNode, tagElm.nextSibling); - return newNode; - }, - // compares all "__originalData" property values with the current "tagData" properties - // and returns "true" if something changed. - editTagChangeDetected(tagData) { - var originalData = tagData.__originalData; - for (var prop in originalData) - if (!this.dataProps.includes(prop) && tagData[prop] != originalData[prop]) - return true; - return false; - }, - // returns the node which has the actual tag's content - getTagTextNode(tagElm) { - return tagElm.querySelector(this.settings.classNames.tagTextSelector); - }, - // sets the text of a tag - setTagTextNode(tagElm, HTML) { - this.getTagTextNode(tagElm).innerHTML = escapeHTML(HTML); + } + const expClueData = {}; + [...Object.values(system.experience_clues).filter((clue) => /[A-Za-z]/.test(clue)), " "].forEach((clue, i) => { + expClueData[(i + 1).toString()] = clue; + }); + system.experience_clues = expClueData; + if (BladesItem.IsType(this, BladesItemType.playbook)) { + const gatherInfoData = {}; + [...Object.values(system.gather_info_questions).filter((question) => /[A-Za-z]/.test(question)), " "].forEach((question, i) => { + gatherInfoData[(i + 1).toString()] = question; + }); + system.gather_info_questions = gatherInfoData; + } + } + // #endregion + // Unlock lower-level update method for subclasses + async callOnUpdate(...args) { + await this._onUpdate(...args); + } +} +const BladesItem$1 = BladesItem; +const FUNCQUEUE = {}; +const CUSTOMFUNCS = { + addItem: async (actor, funcData, _, isReversing = false) => { + eLog.checkLog("activeEffects", "addItem", { actor, funcData, isReversing }); + if (actor.hasActiveSubItemOf(funcData)) { + if (isReversing) { + return actor.remSubItem(funcData); + } + } else if (!isReversing) { + return actor.addSubItem(funcData); + } + return void 0; }, - /** - * Enters a tag into "edit" mode - * @param {Node} tagElm the tag element to edit. if nothing specified, use last last - */ - editTag(tagElm, opts) { - tagElm = tagElm || this.getLastTag(); - opts = opts || {}; - this.dropdown.hide(); - var _s = this.settings, editableElm = this.getTagTextNode(tagElm), tagIdx = this.getNodeIndex(tagElm), tagData = getSetTagData(tagElm), _CB = this.events.callbacks, that = this, isValid = true, delayed_onEditTagBlur = function() { - setTimeout(() => _CB.onEditTagBlur.call(that, that.getTagTextNode(tagElm))); - }; - if (!editableElm) { - console.warn("Cannot find element in Tag template: .", _s.classNames.tagTextSelector); + addIfChargen: async (actor, funcData, _, isReversing = false) => { + var _a; + eLog.checkLog("activeEffects", "addIfChargen", { actor, funcData, isReversing }); + if (!isReversing && ((_a = game.eunoblades.Tracker) == null ? void 0 : _a.system.phase) !== BladesPhase.CharGen) { return; } - if (tagData instanceof Object && "editable" in tagData && !tagData.editable) + const [target, qty] = funcData.split(/:/); + if (isReversing) { + await actor.update({ [target]: U.pInt(getProperty(actor, target)) - U.pInt(qty) }); return; - tagData = getSetTagData(tagElm, { - __originalData: extend({}, tagData), - __originalHTML: tagElm.cloneNode(true) - }); - getSetTagData(tagData.__originalHTML, tagData.__originalData); - editableElm.setAttribute("contenteditable", true); - tagElm.classList.add(_s.classNames.tagEditing); - editableElm.addEventListener("focus", _CB.onEditTagFocus.bind(this, tagElm)); - editableElm.addEventListener("blur", delayed_onEditTagBlur); - editableElm.addEventListener("input", _CB.onEditTagInput.bind(this, editableElm)); - editableElm.addEventListener("paste", _CB.onEditTagPaste.bind(this, editableElm)); - editableElm.addEventListener("keydown", (e) => _CB.onEditTagkeydown.call(this, e, tagElm)); - editableElm.addEventListener("compositionstart", _CB.onCompositionStart.bind(this)); - editableElm.addEventListener("compositionend", _CB.onCompositionEnd.bind(this)); - if (!opts.skipValidation) - isValid = this.editTagToggleValidity(tagElm); - editableElm.originalIsValid = isValid; - this.trigger("edit:start", { - tag: tagElm, - index: tagIdx, - data: tagData, - isValid - }); - editableElm.focus(); - this.setRangeAtStartEnd(false, editableElm); - return this; + } + await actor.update({ [target]: U.pInt(getProperty(actor, target)) + U.pInt(qty) }); }, - /** - * If a tag is invalid, for any reason, set its class to "not allowed" (see defaults file) - * @param {Node} tagElm required - * @param {Object} tagData optional - * @returns true if valid, a string (reason) if not - */ - editTagToggleValidity(tagElm, tagData) { - var tagData = tagData || getSetTagData(tagElm), isValid; - if (!tagData) { - console.warn("tag has no data: ", tagElm, tagData); + upgradeIfChargen: async (actor, funcData, _, isReversing = false) => { + var _a; + eLog.checkLog("activeEffects", "upgradeIfChargen", { actor, funcData, isReversing }); + if (!isReversing && ((_a = game.eunoblades.Tracker) == null ? void 0 : _a.system.phase) !== BladesPhase.CharGen) { return; } - isValid = !("__isValid" in tagData) || tagData.__isValid === true; - if (!isValid) { - this.removeTagsFromValue(tagElm); + const [target, qty] = funcData.split(/:/); + if (getProperty(actor, target) < U.pInt(qty)) { + await actor.update({ [target]: U.pInt(qty) }); } - this.update(); - tagElm.classList.toggle(this.settings.classNames.tagNotAllowed, !isValid); - return tagData.__isValid; }, - onEditTagDone(tagElm, tagData) { - tagElm = tagElm || this.state.editing.scope; - tagData = tagData || {}; - var eventData = { - tag: tagElm, - index: this.getNodeIndex(tagElm), - previousData: getSetTagData(tagElm), - data: tagData - }; - this.trigger("edit:beforeUpdate", eventData, { - cloneData: false + APPLYTOMEMBERS: async () => void 0, + APPLYTOCOHORTS: async () => void 0, + remItem: async (actor, funcData, _, isReversing = false) => { + function testString(targetString, testDef) { + if (testDef.startsWith("rX")) { + const pat = new RegExp(testDef.replace(/^rX:\/(.*?)\//, "$1")); + return pat.test(targetString); + } + return targetString === testDef; + } + if (funcData.startsWith("{")) { + if (isReversing) { + console.error("Cannot reverse a 'remItem' custom effect that was defined with a JSON object."); + return void 0; + } + const { type, tags, name } = JSON.parse(funcData); + let activeSubItems = actor.activeSubItems; + if (activeSubItems.length === 0) { + return void 0; + } + if (name) { + activeSubItems = activeSubItems.filter((item) => testString(item.name, name)); + } + if (activeSubItems.length === 0) { + return void 0; + } + if (type) { + activeSubItems = activeSubItems.filter((item) => testString(item.type, type)); + } + if (activeSubItems.length === 0) { + return void 0; + } + if (tags) { + activeSubItems = activeSubItems.filter((item) => item.hasTag(...tags)); + } + if (activeSubItems.length === 0) { + return void 0; + } + eLog.checkLog("activeEffects", "remItem - JSON OBJECT", { actor, funcData: JSON.parse(funcData), isReversing, activeSubItems }); + activeSubItems.forEach((item) => actor.remSubItem(item)); + } + eLog.checkLog("activeEffects", "remItem", { actor, funcData, isReversing }); + if (actor.hasActiveSubItemOf(funcData)) { + return actor.remSubItem(funcData); + } + if (isReversing) { + return actor.addSubItem(funcData); + } + return void 0; + } +}; +class BladesActiveEffect extends ActiveEffect { + static Initialize() { + CONFIG.ActiveEffect.documentClass = BladesActiveEffect; + Hooks.on("preCreateActiveEffect", async (effect) => { + var _a; + eLog.checkLog3("effect", "PRECREATE ActiveEffect", { effect, parent: (_a = effect.parent) == null ? void 0 : _a.name }); + if (!(effect.parent instanceof BladesActor$1)) { + return; + } + if (effect.changes.some((change) => change.key === "APPLYTOMEMBERS")) { + if (BladesActor$1.IsType(effect.parent, BladesActorType.pc) && BladesActor$1.IsType(effect.parent.crew, BladesActorType.crew)) { + const otherMembers = effect.parent.crew.members.filter((member) => { + var _a2; + return member.id !== ((_a2 = effect.parent) == null ? void 0 : _a2.id); + }); + if (otherMembers.length > 0) { + effect.changes = effect.changes.filter((change) => change.key !== "APPLYTOMEMBERS"); + await Promise.all(otherMembers.map(async (member) => member.createEmbeddedDocuments("ActiveEffect", [effect.toJSON()]))); + await effect.parent.setFlag("eunos-blades", `memberEffects.${effect.id}`, { + appliedTo: otherMembers.map((member) => member.id), + effect: effect.toJSON() + }); + } + } else if (BladesActor$1.IsType(effect.parent, BladesActorType.crew)) { + const changeKey = U.pullElement(effect.changes, (change) => change.key === "APPLYTOMEMBERS"); + if (!changeKey) { + return; + } + if (effect.parent.members.length > 0) { + await Promise.all(effect.parent.members.map(async (member) => member.createEmbeddedDocuments("ActiveEffect", [effect.toJSON()]))); + } + await effect.parent.setFlag("eunos-blades", `memberEffects.${effect.id}`, { + appliedTo: effect.parent.members.map((member) => member.id), + effect + }); + await effect.updateSource({ changes: [changeKey] }); + } + } else if (effect.changes.some((change) => change.key === "APPLYTOCOHORTS") && (BladesActor$1.IsType(effect.parent, BladesActorType.pc) || BladesActor$1.IsType(effect.parent, BladesActorType.crew))) { + if (effect.parent.cohorts.length > 0) { + await Promise.all(effect.parent.cohorts.map(async (cohort) => cohort.createEmbeddedDocuments("ActiveEffect", [effect.toJSON()]))); + } + await effect.parent.setFlag("eunos-blades", `cohortEffects.${effect.id}`, { + appliedTo: effect.parent.cohorts.map((cohort) => cohort.id), + effect + }); + await effect.updateSource({ changes: effect.changes.filter((change) => change.key === "APPLYTOCOHORTS") }); + } + const [permChanges, changes] = U.partition(effect.changes, (change) => change.key.startsWith("perm")); + await effect.updateSource({ changes }); + for (const permChange of permChanges) { + const { key, value } = permChange; + const permFuncName = key.replace(/^perm/, ""); + if (permFuncName in CUSTOMFUNCS) { + const funcData = { + funcName: permFuncName, + funcData: value, + isReversing: false, + effect + }; + BladesActiveEffect.ThrottleCustomFunc(effect.parent, funcData); + } else if (permFuncName === "Add") { + const [target, qty] = value.split(/:/); + effect.parent.update({ [target]: U.pInt(getProperty(effect.parent, target)) + U.pInt(qty) }); + } + } }); - this.state.editing = false; - delete tagData.__originalData; - delete tagData.__originalHTML; - if (tagElm && tagData[this.settings.tagTextProp]) { - tagElm = this.replaceTag(tagElm, tagData); - this.editTagToggleValidity(tagElm, tagData); - if (this.settings.a11y.focusableTags) - tagElm.focus(); - else - this.placeCaretAfterNode(tagElm); - } else if (tagElm) - this.removeTags(tagElm); - this.trigger("edit:updated", eventData); - this.dropdown.hide(); - if (this.settings.keepInvalidTags) - this.reCheckInvalidTags(); - }, - /** - * Replaces an exisitng tag with a new one. Used for updating a tag's data - * @param {Object} tagElm [DOM node to replace] - * @param {Object} tagData [data to create new tag from] - */ - replaceTag(tagElm, tagData) { - if (!tagData || !tagData.value) - tagData = tagElm.__tagifyTagData; - if (tagData.__isValid && tagData.__isValid != true) - extend(tagData, this.getInvalidTagAttrs(tagData, tagData.__isValid)); - var newTagElm = this.createTagElem(tagData); - tagElm.parentNode.replaceChild(newTagElm, tagElm); - this.updateValueByDOMTags(); - return newTagElm; - }, - /** - * update "value" (Array of Objects) by traversing all valid tags - */ - updateValueByDOMTags() { - this.value.length = 0; - [].forEach.call(this.getTagElms(), (node) => { - if (node.classList.contains(this.settings.classNames.tagNotAllowed.split(" ")[0])) + Hooks.on("applyActiveEffect", (actor, changeData) => { + if (!(actor instanceof BladesActor$1)) { return; - this.value.push(getSetTagData(node)); + } + if (changeData.key in CUSTOMFUNCS) { + const funcData = { + funcName: changeData.key, + funcData: changeData.value, + isReversing: false, + effect: changeData.effect + }; + BladesActiveEffect.ThrottleCustomFunc(actor, funcData); + } }); - this.update(); - }, - /** - * injects nodes/text at caret position, which is saved on the "state" when "blur" event gets triggered - * @param {Node} injectedNode [the node to inject at the caret position] - * @param {Object} selection [optional range Object. must have "anchorNode" & "anchorOffset"] - */ - injectAtCaret(injectedNode, range) { - var _a; - range = range || ((_a = this.state.selection) == null ? void 0 : _a.range); - if (!range && injectedNode) { - this.appendMixTags(injectedNode); - return this; - } - injectAtCaret(injectedNode, range); - this.setRangeAtStartEnd(false, injectedNode); - this.updateValueByDOMTags(); - this.update(); - return this; - }, - /** - * input bridge for accessing & setting - * @type {Object} - */ - input: { - set() { - let s = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; - let updateDOM = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; - var hideDropdown = this.settings.dropdown.closeOnSelect; - this.state.inputText = s; - if (updateDOM) - this.DOM.input.innerHTML = escapeHTML("" + s); - if (!s && hideDropdown) - this.dropdown.hide.bind(this); - this.input.autocomplete.suggest.call(this); - this.input.validate.call(this); - }, - raw() { - return this.DOM.input.textContent; - }, - /** - * Marks the tagify's input as "invalid" if the value did not pass "validateTag()" - */ - validate() { - var isValid = !this.state.inputText || this.validateTag({ - value: this.state.inputText - }) === true; - this.DOM.input.classList.toggle(this.settings.classNames.inputInvalid, !isValid); - return isValid; - }, - // remove any child DOM elements that aren't of type TEXT (like
) - normalize(node) { - var clone = node || this.DOM.input, v = []; - clone.childNodes.forEach((n) => n.nodeType == 3 && v.push(n.nodeValue)); - v = v.join("\n"); - try { - v = v.replace(/(?:\r\n|\r|\n)/g, this.settings.delimiters.source.charAt(0)); - } catch (err) { + Hooks.on("updateActiveEffect", (effect, { disabled }) => { + if (!(effect.parent instanceof BladesActor$1)) { + return; } - v = v.replace(/\s/g, " "); - return this.trim(v); - }, - /** - * suggest the rest of the input's value (via CSS "::after" using "content:attr(...)") - * @param {String} s [description] - */ - autocomplete: { - suggest(data) { - if (!this.settings.autoComplete.enabled) - return; - data = data || { - value: "" + const customEffects = effect.changes.filter((changes) => changes.mode === 0); + customEffects.forEach(({ key, value }) => { + const funcData = { + funcName: key, + funcData: value, + isReversing: disabled, + effect }; - if (typeof data == "string") - data = { - value: data - }; - var suggestedText = this.dropdown.getMappedValue(data); - if (typeof suggestedText === "number") - return; - var suggestionStart = suggestedText.substr(0, this.state.inputText.length).toLowerCase(), suggestionTrimmed = suggestedText.substring(this.state.inputText.length); - if (!suggestedText || !this.state.inputText || suggestionStart != this.state.inputText.toLowerCase()) { - this.DOM.input.removeAttribute("data-suggest"); - delete this.state.inputSuggestion; - } else { - this.DOM.input.setAttribute("data-suggest", suggestionTrimmed); - this.state.inputSuggestion = data; - } - }, - /** - * sets the suggested text as the input's value & cleanup the suggestion autocomplete. - * @param {String} s [text] - */ - set(s) { - var dataSuggest = this.DOM.input.getAttribute("data-suggest"), suggestion = s || (dataSuggest ? this.state.inputText + dataSuggest : null); - if (suggestion) { - if (this.settings.mode == "mix") { - this.replaceTextWithNode(document.createTextNode(this.state.tag.prefix + suggestion)); - } else { - this.input.set.call(this, suggestion); - this.setRangeAtStartEnd(false, this.DOM.input); + BladesActiveEffect.ThrottleCustomFunc(effect.parent, funcData); + }); + }); + Hooks.on("deleteActiveEffect", async (effect) => { + if (!(effect.parent instanceof BladesActor$1)) { + return; + } + if (effect.changes.some((change) => change.key === "APPLYTOMEMBERS")) { + if (BladesActor$1.IsType(effect.parent, BladesActorType.pc) && BladesActor$1.IsType(effect.parent.crew, BladesActorType.crew)) { + const otherMembers = effect.parent.crew.members.filter((member) => { + var _a; + return member.id !== ((_a = effect.parent) == null ? void 0 : _a.id); + }); + if (otherMembers.length > 0) { + await Promise.all(otherMembers.map(async (member) => Promise.all(member.effects.filter((e) => e.name === effect.name).map(async (e) => e.delete())))); } - this.input.autocomplete.suggest.call(this); - this.dropdown.hide(); - return true; + await effect.parent.unsetFlag("eunos-blades", `memberEffects.${effect.id}`); + } else if (BladesActor$1.IsType(effect.parent, BladesActorType.crew)) { + if (effect.parent.members.length > 0) { + await Promise.all(effect.parent.members.map(async (member) => Promise.all(member.effects.filter((e) => e.name === effect.name).map(async (e) => e.delete())))); + } + await effect.parent.unsetFlag("eunos-blades", `memberEffects.${effect.id}`); } - return false; + } else if (effect.changes.some((change) => change.key === "APPLYTOCOHORTS") && BladesActor$1.IsType(effect.parent, BladesActorType.pc, BladesActorType.crew)) { + if (effect.parent.cohorts.length > 0) { + await Promise.all(effect.parent.cohorts.map(async (cohort) => Promise.all(cohort.effects.filter((e) => e.name === effect.name).map(async (e) => e.delete())))); + } + await effect.parent.unsetFlag("eunos-blades", `cohortEffects.${effect.id}`); } - } - }, - /** - * returns the index of the the tagData within the "this.value" array collection. - * since values should be unique, it is suffice to only search by "value" property - * @param {Object} tagData - */ - getTagIdx(tagData) { - return this.value.findIndex((item) => item.__tagId == (tagData || {}).__tagId); - }, - getNodeIndex(node) { - var index = 0; - if (node) - while (node = node.previousElementSibling) - index++; - return index; - }, - getTagElms() { - for (var _len = arguments.length, classess = new Array(_len), _key = 0; _key < _len; _key++) { - classess[_key] = arguments[_key]; - } - var classname = "." + [...this.settings.classNames.tag.split(" "), ...classess].join("."); - return [].slice.call(this.DOM.scope.querySelectorAll(classname)); - }, - /** - * gets the last non-readonly, not-in-the-proccess-of-removal tag - */ - getLastTag() { - var lastTag = this.DOM.scope.querySelectorAll(`${this.settings.classNames.tagSelector}:not(.${this.settings.classNames.tagHide}):not([readonly])`); - return lastTag[lastTag.length - 1]; - }, - /** - * Searches if any tag with a certain value already exis - * @param {String/Object} value [text value / tag data object] - * @param {Boolean} caseSensitive - * @return {Number} - */ - isTagDuplicate(value, caseSensitive, tagId) { - var dupsCount = 0, _s = this.settings; - if (_s.mode == "select") - return false; - for (let item of this.value) { - let isSameStr = sameStr(this.trim("" + value), item.value, caseSensitive); - if (isSameStr && tagId != item.__tagId) - dupsCount++; - } - return dupsCount; - }, - getTagIndexByValue(value) { - var indices = []; - this.getTagElms().forEach((tagElm, i) => { - if (sameStr(this.trim(tagElm.textContent), value, this.settings.dropdown.caseSensitive)) - indices.push(i); + const customEffects = effect.changes.filter((changes) => changes.mode === 0); + customEffects.forEach(({ key, value }) => { + const funcData = { + funcName: key, + funcData: value, + isReversing: true, + effect + }; + BladesActiveEffect.ThrottleCustomFunc(effect.parent, funcData); + }); }); - return indices; - }, - getTagElmByValue(value) { - var tagIdx = this.getTagIndexByValue(value)[0]; - return this.getTagElms()[tagIdx]; - }, - /** - * Temporarily marks a tag element (by value or Node argument) - * @param {Object} tagElm [a specific "tag" element to compare to the other tag elements siblings] - */ - flashTag(tagElm) { - if (tagElm) { - tagElm.classList.add(this.settings.classNames.tagFlash); - setTimeout(() => { - tagElm.classList.remove(this.settings.classNames.tagFlash); - }, 100); + } + static async AddActiveEffect(doc, name, eChanges, icon = "systems/eunos-blades/assets/icons/effect-icons/default.png") { + const changes = [eChanges].flat(); + await doc.createEmbeddedDocuments("ActiveEffect", [{ name, icon, changes }]); + } + static ThrottleCustomFunc(actor, data) { + const { funcName, funcData, isReversing, effect } = data; + if (!actor.id) { + return; } - }, - /** - * checks if text is in the blacklist - */ - isTagBlacklisted(v) { - v = this.trim(v.toLowerCase()); - return this.settings.blacklist.filter((x) => ("" + x).toLowerCase() == v).length; - }, - /** - * checks if text is in the whitelist - */ - isTagWhitelisted(v) { - return !!this.getWhitelistItem(v); - }, - /** - * Returns the first whitelist item matched, by value (if match found) - * @param {String} value [text to match by] - */ - getWhitelistItem(value, prop, whitelist) { - var result, prop = prop || "value", _s = this.settings, whitelist = whitelist || _s.whitelist; - whitelist.some((_wi) => { - var _wiv = typeof _wi == "string" ? _wi : _wi[prop] || _wi.value, isSameStr = sameStr(_wiv, value, _s.dropdown.caseSensitive, _s.trim); - if (isSameStr) { - result = typeof _wi == "string" ? { - value: _wi - } : _wi; - return true; + eLog.checkLog3("activeEffect", `Throttling Func: ${funcName}(${funcData}, ${isReversing})`); + if (actor.id && actor.id in FUNCQUEUE) { + const matchingQueue = FUNCQUEUE[actor.id].queue.find((fData) => JSON.stringify(fData) === JSON.stringify(data)); + eLog.checkLog("activeEffects", "... Checking Queue", { data, FUNCQUEUE: FUNCQUEUE[actor.id], matchingQueue }); + if (matchingQueue) { + eLog.error("... Function ALREADY QUEUED, SKIPPING"); + return; } - }); - if (!result && prop == "value" && _s.tagTextProp != "value") { - result = this.getWhitelistItem(value, _s.tagTextProp, whitelist); + FUNCQUEUE[actor.id].queue.push(data); + return; } - return result; - }, - /** - * validate a tag object BEFORE the actual tag will be created & appeneded - * @param {String} s - * @param {String} uid [unique ID, to not inclue own tag when cheking for duplicates] - * @return {Boolean/String} ["true" if validation has passed, String for a fail] - */ - validateTag(tagData) { - var _s = this.settings, prop = "value" in tagData ? "value" : _s.tagTextProp, v = this.trim(tagData[prop] + ""); - if (!(tagData[prop] + "").trim()) - return this.TEXTS.empty; - if (_s.pattern && _s.pattern instanceof RegExp && !_s.pattern.test(v)) - return this.TEXTS.pattern; - if (!_s.duplicates && this.isTagDuplicate(v, _s.dropdown.caseSensitive, tagData.__tagId)) - return this.TEXTS.duplicate; - if (this.isTagBlacklisted(v) || _s.enforceWhitelist && !this.isTagWhitelisted(v)) - return this.TEXTS.notAllowed; - if (_s.validate) - return _s.validate(tagData); - return true; - }, - getInvalidTagAttrs(tagData, validation) { - return { - "aria-invalid": true, - "class": `${tagData.class || ""} ${this.settings.classNames.tagNotAllowed}`.trim(), - "title": validation + eLog.checkLog3("activeEffect", "... Creating New FUNCQUEUE, RUNNING:"); + FUNCQUEUE[actor.id] = { + curFunc: BladesActiveEffect.RunCustomFunc(actor, CUSTOMFUNCS[funcName](actor, funcData, effect, isReversing)), + queue: [] }; - }, - hasMaxTags() { - return this.value.length >= this.settings.maxTags ? this.TEXTS.exceed : false; - }, - setReadonly(toggle, attrribute) { - var _s = this.settings; - document.activeElement.blur(); - _s[attrribute || "readonly"] = toggle; - this.DOM.scope[(toggle ? "set" : "remove") + "Attribute"](attrribute || "readonly", true); - this.setContentEditable(!toggle); - }, - setContentEditable(state) { - if (!this.settings.userInput) + } + static async RunCustomFunc(actor, funcPromise) { + if (!actor.id) { return; - this.DOM.input.contentEditable = state; - this.DOM.input.tabIndex = !!state ? 0 : -1; - }, - setDisabled(isDisabled) { - this.setReadonly(isDisabled, "disabled"); - }, - /** - * pre-proccess the tagsItems, which can be a complex tagsItems like an Array of Objects or a string comprised of multiple words - * so each item should be iterated on and a tag created for. - * @return {Array} [Array of Objects] - */ - normalizeTags(tagsItems) { - var _this$settings = this.settings, whitelist = _this$settings.whitelist, delimiters = _this$settings.delimiters, mode = _this$settings.mode, tagTextProp = _this$settings.tagTextProp, whitelistMatches = [], whitelistWithProps = whitelist ? whitelist[0] instanceof Object : false, isArray2 = Array.isArray(tagsItems), isCollection = isArray2 && tagsItems[0].value, mapStringToCollection = (s) => (s + "").split(delimiters).filter((n) => n).map((v) => ({ - [tagTextProp]: this.trim(v), - value: this.trim(v) - })); - if (typeof tagsItems == "number") - tagsItems = tagsItems.toString(); - if (typeof tagsItems == "string") { - if (!tagsItems.trim()) - return []; - tagsItems = mapStringToCollection(tagsItems); - } else if (isArray2) { - tagsItems = [].concat(...tagsItems.map((item) => item.value != void 0 ? item : mapStringToCollection(item))); - } - if (whitelistWithProps && !isCollection) { - tagsItems.forEach((item) => { - var whitelistMatchesValues = whitelistMatches.map((a) => a.value); - var filteredList = this.dropdown.filterListItems.call(this, item[tagTextProp], { - exact: true - }); - if (!this.settings.duplicates) - filteredList = filteredList.filter((filteredItem) => !whitelistMatchesValues.includes(filteredItem.value)); - var matchObj = filteredList.length > 1 ? this.getWhitelistItem(item[tagTextProp], tagTextProp, filteredList) : filteredList[0]; - if (matchObj && matchObj instanceof Object) { - whitelistMatches.push(matchObj); - } else if (mode != "mix") { - if (item.value == void 0) - item.value = item[tagTextProp]; - whitelistMatches.push(item); - } - }); - if (whitelistMatches.length) - tagsItems = whitelistMatches; } - return tagsItems; - }, - /** - * Parse the initial value of a textarea (or input) element and generate mixed text w/ tags - * https://stackoverflow.com/a/57598892/104380 - * @param {String} s - */ - parseMixTags(s) { - var _this$settings2 = this.settings, mixTagsInterpolator = _this$settings2.mixTagsInterpolator, duplicates = _this$settings2.duplicates, transformTag = _this$settings2.transformTag, enforceWhitelist = _this$settings2.enforceWhitelist, maxTags = _this$settings2.maxTags, tagTextProp = _this$settings2.tagTextProp, tagsDataSet = []; - s = s.split(mixTagsInterpolator[0]).map((s1, i) => { - var s2 = s1.split(mixTagsInterpolator[1]), preInterpolated = s2[0], maxTagsReached = tagsDataSet.length == maxTags, textProp, tagData, tagElm; - try { - if (preInterpolated == +preInterpolated) - throw Error; - tagData = JSON.parse(preInterpolated); - } catch (err) { - tagData = this.normalizeTags(preInterpolated)[0] || { - value: preInterpolated - }; - } - transformTag.call(this, tagData); - if (!maxTagsReached && s2.length > 1 && (!enforceWhitelist || this.isTagWhitelisted(tagData.value)) && !(!duplicates && this.isTagDuplicate(tagData.value))) { - textProp = tagData[tagTextProp] ? tagTextProp : "value"; - tagData[textProp] = this.trim(tagData[textProp]); - tagElm = this.createTagElem(tagData); - tagsDataSet.push(tagData); - tagElm.classList.add(this.settings.classNames.tagNoAnimation); - s2[0] = tagElm.outerHTML; - this.value.push(tagData); - } else if (s1) - return i ? mixTagsInterpolator[0] + s1 : s1; - return s2.join(""); - }).join(""); - this.DOM.input.innerHTML = s; - this.DOM.input.appendChild(document.createTextNode("")); - this.DOM.input.normalize(); - this.getTagElms().forEach((elm, idx) => getSetTagData(elm, tagsDataSet[idx])); - this.update({ - withoutChangeEvent: true - }); - return s; - }, - /** - * For mixed-mode: replaces a text starting with a prefix with a wrapper element (tag or something) - * First there *has* to be a "this.state.tag" which is a string that was just typed and is staring with a prefix - */ - replaceTextWithNode(newWrapperNode, strToReplace) { - if (!this.state.tag && !strToReplace) - return; - strToReplace = strToReplace || this.state.tag.prefix + this.state.tag.value; - var idx, nodeToReplace, selection = this.state.selection || window.getSelection(), nodeAtCaret = selection.anchorNode, firstSplitOffset = this.state.tag.delimiters ? this.state.tag.delimiters.length : 0; - nodeAtCaret.splitText(selection.anchorOffset - firstSplitOffset); - idx = nodeAtCaret.nodeValue.lastIndexOf(strToReplace); - if (idx == -1) - return true; - nodeToReplace = nodeAtCaret.splitText(idx); - newWrapperNode && nodeAtCaret.parentNode.replaceChild(newWrapperNode, nodeToReplace); - return true; - }, - /** - * For selecting a single option (not used for multiple tags, but for "mode:select" only) - * @param {Object} tagElm Tag DOM node - * @param {Object} tagData Tag data - */ - selectTag(tagElm, tagData) { - var _s = this.settings; - if (_s.enforceWhitelist && !this.isTagWhitelisted(tagData.value)) - return; - this.input.set.call(this, tagData[_s.tagTextProp] || tagData.value, true); - if (this.state.actions.selectOption) - setTimeout(() => this.setRangeAtStartEnd(false, this.DOM.input)); - var lastTagElm = this.getLastTag(); - if (lastTagElm) - this.replaceTag(lastTagElm, tagData); - else - this.appendTag(tagElm); - this.value[0] = tagData; - this.update(); - this.trigger("add", { - tag: tagElm, - data: tagData - }); - return [tagElm]; - }, - /** - * add an empty "tag" element in an editable state - */ - addEmptyTag(initialData) { - var tagData = extend({ - value: "" - }, initialData || {}), tagElm = this.createTagElem(tagData); - getSetTagData(tagElm, tagData); - this.appendTag(tagElm); - this.editTag(tagElm, { - skipValidation: true - }); - }, - /** - * add a "tag" element to the "tags" component - * @param {String/Array} tagsItems [A string (single or multiple values with a delimiter), or an Array of Objects or just Array of Strings] - * @param {Boolean} clearInput [flag if the input's value should be cleared after adding tags] - * @param {Boolean} skipInvalid [do not add, mark & remove invalid tags] - * @return {Array} Array of DOM elements (tags) - */ - addTags(tagsItems, clearInput, skipInvalid) { - var tagElems = [], _s = this.settings, aggregatedinvalidInput = [], frag = document.createDocumentFragment(); - skipInvalid = skipInvalid || _s.skipInvalid; - if (!tagsItems || tagsItems.length == 0) { - return tagElems; - } - tagsItems = this.normalizeTags(tagsItems); - switch (_s.mode) { - case "mix": - return this.addMixTags(tagsItems); - case "select": { - clearInput = false; - this.removeAllTags(); - } - } - this.DOM.input.removeAttribute("style"); - tagsItems.forEach((tagData) => { - var tagElm, tagElmParams = {}, originalData = Object.assign({}, tagData, { - value: tagData.value + "" - }); - tagData = Object.assign({}, originalData); - _s.transformTag.call(this, tagData); - tagData.__isValid = this.hasMaxTags() || this.validateTag(tagData); - if (tagData.__isValid !== true) { - if (skipInvalid) - return; - extend(tagElmParams, this.getInvalidTagAttrs(tagData, tagData.__isValid), { - __preInvalidData: originalData - }); - if (tagData.__isValid == this.TEXTS.duplicate) - this.flashTag(this.getTagElmByValue(tagData.value)); - if (!_s.createInvalidTags) { - aggregatedinvalidInput.push(tagData.value); - return; - } + eLog.checkLog("activeEffects", "... Running Func ..."); + await funcPromise; + eLog.checkLog("activeEffects", "... Function Complete!"); + if (FUNCQUEUE[actor.id].queue.length) { + const { funcName, funcData, isReversing, effect } = FUNCQUEUE[actor.id].queue.shift() ?? {}; + if (!funcName || !(funcName in CUSTOMFUNCS)) { + return; } - if ("readonly" in tagData) { - if (tagData.readonly) - tagElmParams["aria-readonly"] = true; - else - delete tagData.readonly; - } - tagElm = this.createTagElem(tagData, tagElmParams); - tagElems.push(tagElm); - if (_s.mode == "select") { - return this.selectTag(tagElm, tagData); - } - frag.appendChild(tagElm); - if (tagData.__isValid && tagData.__isValid === true) { - this.value.push(tagData); - this.trigger("add", { - tag: tagElm, - index: this.value.length - 1, - data: tagData - }); - } else { - this.trigger("invalid", { - data: tagData, - index: this.value.length, - tag: tagElm, - message: tagData.__isValid - }); - if (!_s.keepInvalidTags) - setTimeout(() => this.removeTags(tagElm, true), 1e3); + if (!funcData) { + return; } - this.dropdown.position(); - }); - this.appendTag(frag); - this.update(); - if (tagsItems.length && clearInput) { - this.input.set.call(this, _s.createInvalidTags ? "" : aggregatedinvalidInput.join(_s._delimiters)); - this.setRangeAtStartEnd(false, this.DOM.input); - } - _s.dropdown.enabled && this.dropdown.refilter(); - return tagElems; - }, - /** - * Adds a mix-content tag - * @param {String/Array} tagData A string (single or multiple values with a delimiter), or an Array of Objects or just Array of Strings - */ - addMixTags(tagsData) { - tagsData = this.normalizeTags(tagsData); - if (tagsData[0].prefix || this.state.tag) { - return this.prefixedTextToTag(tagsData[0]); - } - var frag = document.createDocumentFragment(); - tagsData.forEach((tagData) => { - var tagElm = this.createTagElem(tagData); - frag.appendChild(tagElm); - }); - this.appendMixTags(frag); - return frag; - }, - appendMixTags(node) { - var selection = !!this.state.selection; - if (selection) { - this.injectAtCaret(node); + eLog.checkLog3("activeEffect", `Progressing Queue: ${funcName}(${funcData}, ${isReversing}) -- ${FUNCQUEUE[actor.id].queue.length} remaining funcs.`); + FUNCQUEUE[actor.id].curFunc = BladesActiveEffect.RunCustomFunc( + actor, + CUSTOMFUNCS[funcName](actor, funcData, effect, isReversing) + ); } else { - this.DOM.input.focus(); - selection = this.setStateSelection(); - selection.range.setStart(this.DOM.input, selection.range.endOffset); - selection.range.setEnd(this.DOM.input, selection.range.endOffset); - this.DOM.input.appendChild(node); - this.updateValueByDOMTags(); - this.update(); + eLog.checkLog3("activeEffect", "Function Queue Complete! Deleting."); + delete FUNCQUEUE[actor.id]; } - }, - /** - * Adds a tag which was activly typed by the user - * @param {String/Array} tagItem [A string (single or multiple values with a delimiter), or an Array of Objects or just Array of Strings] - */ - prefixedTextToTag(tagItem) { - var _s = this.settings, tagElm, createdFromDelimiters = this.state.tag.delimiters; - _s.transformTag.call(this, tagItem); - tagItem.prefix = tagItem.prefix || this.state.tag ? this.state.tag.prefix : (_s.pattern.source || _s.pattern)[0]; - tagElm = this.createTagElem(tagItem); - if (!this.replaceTextWithNode(tagElm)) { - this.DOM.input.appendChild(tagElm); - } - setTimeout(() => tagElm.classList.add(this.settings.classNames.tagNoAnimation), 300); - this.value.push(tagItem); - this.update(); - if (!createdFromDelimiters) { - var elm = this.insertAfterTag(tagElm) || tagElm; - setTimeout(this.placeCaretAfterNode, 0, elm); - } - this.state.tag = null; - this.trigger("add", extend({}, { - tag: tagElm - }, { - data: tagItem - })); - return tagElm; - }, - /** - * appened (validated) tag to the component's DOM scope - */ - appendTag(tagElm) { - var DOM = this.DOM, insertBeforeNode = DOM.input; - DOM.scope.insertBefore(tagElm, insertBeforeNode); - }, - /** - * creates a DOM tag element and injects it into the component (this.DOM.scope) - * @param {Object} tagData [text value & properties for the created tag] - * @param {Object} extraData [properties which are for the HTML template only] - * @return {Object} [DOM element] - */ - createTagElem(tagData, extraData) { - tagData.__tagId = getUID(); - var tagElm, templateData = extend({}, tagData, _objectSpread2({ - value: escapeHTML(tagData.value + "") - }, extraData)); - tagElm = this.parseTemplate("tag", [templateData, this]); - removeTextChildNodes(tagElm); - getSetTagData(tagElm, tagData); - return tagElm; - }, - /** - * re-check all invalid tags. - * called after a tag was edited or removed - */ - reCheckInvalidTags() { - var _s = this.settings; - this.getTagElms(_s.classNames.tagNotAllowed).forEach((tagElm, i) => { - var tagData = getSetTagData(tagElm), hasMaxTags = this.hasMaxTags(), tagValidation = this.validateTag(tagData), isValid = tagValidation === true && !hasMaxTags; - if (_s.mode == "select") - this.toggleScopeValidation(tagValidation); - if (isValid) { - tagData = tagData.__preInvalidData ? tagData.__preInvalidData : { - value: tagData.value - }; - return this.replaceTag(tagElm, tagData); - } - tagElm.title = hasMaxTags || tagValidation; - }); - }, - /** - * Removes a tag - * @param {Array|Node|String} tagElms [DOM element(s) or a String value. if undefined or null, remove last added tag] - * @param {Boolean} silent [A flag, which when turned on, does not remove any value and does not update the original input value but simply removes the tag from tagify] - * @param {Number} tranDuration [Transition duration in MS] - * TODO: Allow multiple tags to be removed at-once - */ - removeTags(tagElms, silent, tranDuration) { - var tagsToRemove, _s = this.settings; - tagElms = tagElms && tagElms instanceof HTMLElement ? [tagElms] : tagElms instanceof Array ? tagElms : tagElms ? [tagElms] : [this.getLastTag()]; - tagsToRemove = tagElms.reduce((elms, tagElm) => { - if (tagElm && typeof tagElm == "string") - tagElm = this.getTagElmByValue(tagElm); - var tagData = getSetTagData(tagElm); - if (tagElm && tagData && !tagData.readonly) - elms.push({ - node: tagElm, - idx: this.getTagIdx(tagData), - // this.getNodeIndex(tagElm); // this.getTagIndexByValue(tagElm.textContent) - data: getSetTagData(tagElm, { - "__removed": true - }) - }); - return elms; - }, []); - tranDuration = typeof tranDuration == "number" ? tranDuration : this.CSSVars.tagHideTransition; - if (_s.mode == "select") { - tranDuration = 0; - this.input.set.call(this); - } - if (tagsToRemove.length == 1 && _s.mode != "select") { - if (tagsToRemove[0].node.classList.contains(_s.classNames.tagNotAllowed)) - silent = true; - } - if (!tagsToRemove.length) - return; - return _s.hooks.beforeRemoveTag(tagsToRemove, { - tagify: this - }).then(() => { - function removeNode(tag) { - if (!tag.node.parentNode) - return; - tag.node.parentNode.removeChild(tag.node); - if (!silent) { - this.trigger("remove", { - tag: tag.node, - index: tag.idx, - data: tag.data - }); - this.dropdown.refilter(); - this.dropdown.position(); - this.DOM.input.normalize(); - if (_s.keepInvalidTags) - this.reCheckInvalidTags(); - } else if (_s.keepInvalidTags) - this.trigger("remove", { - tag: tag.node, - index: tag.idx - }); - } - function animation(tag) { - tag.node.style.width = parseFloat(window.getComputedStyle(tag.node).width) + "px"; - document.body.clientTop; - tag.node.classList.add(_s.classNames.tagHide); - setTimeout(removeNode.bind(this), tranDuration, tag); - } - if (tranDuration && tranDuration > 10 && tagsToRemove.length == 1) - animation.call(this, tagsToRemove[0]); - else - tagsToRemove.forEach(removeNode.bind(this)); - if (!silent) { - this.removeTagsFromValue(tagsToRemove.map((tag) => tag.node)); - this.update(); - if (_s.mode == "select") - this.setContentEditable(true); - } - }).catch((reason) => { - }); - }, - removeTagsFromDOM() { - [].slice.call(this.getTagElms()).forEach((elm) => elm.parentNode.removeChild(elm)); - }, + } /** - * @param {Array/Node} tags to be removed from the this.value array + * Manage Active Effect instances through the Actor Sheet via effect control buttons. + * @param {MouseEvent} event The left-click event on the effect control + * @param {Actor|Item} owner The owning entity which manages this effect */ - removeTagsFromValue(tags) { - tags = Array.isArray(tags) ? tags : [tags]; - tags.forEach((tag) => { - var tagData = getSetTagData(tag), tagIdx = this.getTagIdx(tagData); - if (tagIdx > -1) - this.value.splice(tagIdx, 1); - }); - }, - removeAllTags(opts) { - opts = opts || {}; - this.value = []; - if (this.settings.mode == "mix") - this.DOM.input.innerHTML = ""; - else - this.removeTagsFromDOM(); - this.dropdown.refilter(); - this.dropdown.position(); - if (this.state.dropdown.visible) - setTimeout(() => { - this.DOM.input.focus(); - }); - if (this.settings.mode == "select") { - this.input.set.call(this); - this.setContentEditable(true); + static onManageActiveEffect(event, owner) { + var _a; + event.preventDefault(); + const a = event.currentTarget; + if (a.dataset.action === "create") { + return owner.createEmbeddedDocuments("ActiveEffect", [{ + name: owner.name, + icon: owner.img, + origin: owner.uuid + }]); } - this.update(opts); - }, - postUpdate() { - var _a, _b; - this.state.blockChangeEvent = false; - var _s = this.settings, classNames = _s.classNames, hasValue = _s.mode == "mix" ? _s.mixMode.integrated ? this.DOM.input.textContent : this.DOM.originalInput.value.trim() : this.value.length + this.input.raw.call(this).length; - this.toggleClass(classNames.hasMaxTags, this.value.length >= _s.maxTags); - this.toggleClass(classNames.hasNoTags, !this.value.length); - this.toggleClass(classNames.empty, !hasValue); - if (_s.mode == "select") { - this.toggleScopeValidation((_b = (_a = this.value) == null ? void 0 : _a[0]) == null ? void 0 : _b.__isValid); + const selector3 = a.closest("tr"); + if (selector3 === null) { + return null; } - }, - setOriginalInputValue(v) { - var inputElm = this.DOM.originalInput; - if (!this.settings.mixMode.integrated) { - inputElm.value = v; - inputElm.tagifyValue = inputElm.value; - this.setPersistedData(v, "value"); + const effect = selector3.dataset.effectId ? owner.effects.get(selector3.dataset.effectId) : null; + if (!effect) { + return null; } - }, - /** - * update the origianl (hidden) input field's value - * see - https://stackoverflow.com/q/50957841/104380 - */ - update(args) { - const UPDATE_DELAY = 100; - clearTimeout(this.debouncedUpdateTimeout); - this.debouncedUpdateTimeout = setTimeout(reallyUpdate.bind(this), UPDATE_DELAY); - function reallyUpdate() { - var inputValue = this.getInputValue(); - this.setOriginalInputValue(inputValue); - if ((!this.settings.onChangeAfterBlur || !(args || {}).withoutChangeEvent) && !this.state.blockChangeEvent) - this.triggerChangeEvent(); - this.postUpdate(); + switch (a.dataset.action) { + case "edit": + return (_a = effect.sheet) == null ? void 0 : _a.render(true); + case "delete": + eLog.checkLog("activeEffects", "delete effect"); + return effect.delete(); + case "toggle": + return effect.update({ disabled: !effect.disabled }); + default: + return null; } - }, - getInputValue() { - var value = this.getCleanValue(); - return this.settings.mode == "mix" ? this.getMixedTagsAsString(value) : value.length ? this.settings.originalInputValueFormat ? this.settings.originalInputValueFormat(value) : JSON.stringify(value) : ""; - }, - /** - * removes properties from `this.value` which are only used internally - */ - getCleanValue(v) { - return removeCollectionProp(v || this.value, this.dataProps); - }, - getMixedTagsAsString() { - var result = "", that = this, _s = this.settings, originalInputValueFormat = _s.originalInputValueFormat || JSON.stringify, _interpolator = _s.mixTagsInterpolator; - function iterateChildren(rootNode) { - rootNode.childNodes.forEach((node) => { - if (node.nodeType == 1) { - const tagData = getSetTagData(node); - if (node.tagName == "BR") { - result += "\r\n"; - } - if (tagData && isNodeTag.call(that, node)) { - if (tagData.__removed) - return; - else - result += _interpolator[0] + originalInputValueFormat(omit(tagData, that.dataProps)) + _interpolator[1]; - } else if (node.getAttribute("style") || ["B", "I", "U"].includes(node.tagName)) - result += node.textContent; - else if (node.tagName == "DIV" || node.tagName == "P") { - result += "\r\n"; - iterateChildren(node); - } - } else - result += node.textContent; - }); + } + async _preCreate(data, options, user) { + eLog.checkLog3("effect", "ActiveEffect._preCreate()", { data, options, user }); + await super._preCreate(data, options, user); + } + _onDelete(options, userID) { + eLog.checkLog3("effect", "ActiveEffect._onDelete()", { options, userID }); + super._onDelete(options, userID); + } + get isSuppressed() { + if (!/Actor.*Item/.test(this.origin)) { + return super.isSuppressed; } - iterateChildren(this.DOM.input); - return result; + const [actorID, itemID] = this.origin.replace(/Actor\.|Item\./g, "").split("."); + const actor = game.actors.get(actorID); + const item = actor.items.get(itemID); + return super.isSuppressed || (item == null ? void 0 : item.hasTag(Tag.System.Archived)); } -}; -Tagify.prototype.removeTag = Tagify.prototype.removeTags; +} const _onTagifyChange = (event, doc, targetKey) => { const tagString = event.target.value; if (tagString) { @@ -14729,7 +21902,7 @@ const Tags = { }); tagify.dropdown.createListHTML = (optionsArr) => { const map = {}; - return structuredClone(optionsArr).map((suggestion, idx) => { + return structuredClone(optionsArr).map((suggestion) => { const value = tagify.dropdown.getMappedValue.call( tagify, suggestion @@ -14748,7 +21921,7 @@ const Tags = { suggestion.value = value && typeof value === "string" ? U.escapeHTML(value) : value; tagHTMLString += tagify.settings.templates.dropdownItem.apply( tagify, - [suggestion, idx] + [suggestion] ); return tagHTMLString; }).join(""); @@ -14804,27 +21977,27 @@ class BladesItemSheet extends ItemSheet { constructor() { super(...arguments); __publicField(this, "_getTypedItemData", { - [BladesItemType.ability]: (context) => { + [BladesItemType.ability]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.ability)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.background]: (context) => { + [BladesItemType.background]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.background)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.clock_keeper]: (context) => { + [BladesItemType.clock_keeper]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.clock_keeper)) { return void 0; } @@ -14832,18 +22005,18 @@ class BladesItemSheet extends ItemSheet { phases: Object.values(BladesPhase) }; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.cohort_gang]: (context) => { + [BladesItemType.cohort_gang]: (context3) => { var _a, _b; if (!BladesItem$1.IsType(this.item, BladesItemType.cohort_gang, BladesItemType.cohort_expert)) { return void 0; } - context.tierTotal = this.item.system.quality > 0 ? U.romanizeNum(this.item.system.quality) : "0"; - (_a = context.system).subtypes ?? (_a.subtypes = {}); - (_b = context.system).elite_subtypes ?? (_b.elite_subtypes = {}); + context3.tierTotal = this.item.system.quality > 0 ? U.romanizeNum(this.item.system.quality) : "0"; + (_a = context3.system).subtypes ?? (_a.subtypes = {}); + (_b = context3.system).elite_subtypes ?? (_b.elite_subtypes = {}); const sheetData = { tierData: { class: "comp-tier comp-vertical comp-teeth", @@ -14857,78 +22030,78 @@ class BladesItemSheet extends ItemSheet { } } }; - sheetData.edgeData = Object.fromEntries(Object.values(context.system.edges ?? []).filter((edge) => /[A-Za-z]/.test(edge)).map((edge) => [edge.trim(), C.EdgeTooltips[edge]])); - sheetData.flawData = Object.fromEntries(Object.values(context.system.flaws ?? []).filter((flaw) => /[A-Za-z]/.test(flaw)).map((flaw) => [flaw.trim(), C.FlawTooltips[flaw]])); + sheetData.edgeData = Object.fromEntries(Object.values(context3.system.edges ?? []).filter((edge) => /[A-Za-z]/.test(edge)).map((edge) => [edge.trim(), C.EdgeTooltips[edge]])); + sheetData.flawData = Object.fromEntries(Object.values(context3.system.flaws ?? []).filter((flaw) => /[A-Za-z]/.test(flaw)).map((flaw) => [flaw.trim(), C.FlawTooltips[flaw]])); return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.cohort_expert]: (context) => { + [BladesItemType.cohort_expert]: (context3) => { const typedItemData = this._getTypedItemData[BladesItemType.cohort_gang]; if (!typedItemData) { throw new Error(`No data for type ${this.item.type}`); } - return typedItemData(context); + return typedItemData(context3); }, - [BladesItemType.crew_ability]: (context) => { + [BladesItemType.crew_ability]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.crew_ability)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.crew_reputation]: (context) => { + [BladesItemType.crew_reputation]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.crew_reputation)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.crew_playbook]: (context) => { + [BladesItemType.crew_playbook]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.crew_playbook)) { return void 0; } - if (context.isGM) { + if (context3.isGM) { const expClueData = {}; - [...Object.values(context.system.experience_clues ?? []).filter((clue) => /[A-Za-z]/.test(clue)), " "].forEach((clue, i) => { + [...Object.values(context3.system.experience_clues ?? []).filter((clue) => /[A-Za-z]/.test(clue)), " "].forEach((clue, i) => { expClueData[(i + 1).toString()] = clue; }); - context.system.experience_clues = expClueData; + context3.system.experience_clues = expClueData; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.crew_upgrade]: (context) => { + [BladesItemType.crew_upgrade]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.crew_upgrade)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.feature]: (context) => { + [BladesItemType.feature]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.feature)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.gm_tracker]: (context) => { + [BladesItemType.gm_tracker]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.gm_tracker)) { return void 0; } @@ -14937,21 +22110,21 @@ class BladesItemSheet extends ItemSheet { phases: Object.values(BladesPhase) }; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.heritage]: (context) => { + [BladesItemType.heritage]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.heritage)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.gear]: (context) => { + [BladesItemType.gear]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.gear)) { return void 0; } @@ -14971,97 +22144,97 @@ class BladesItemSheet extends ItemSheet { } }; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.playbook]: (context) => { + [BladesItemType.playbook]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.playbook)) { return void 0; } - if (context.isGM) { + if (context3.isGM) { const expClueData = {}; - [...Object.values(context.system.experience_clues ?? []).filter((clue) => /[A-Za-z]/.test(clue)), " "].forEach((clue, i) => { + [...Object.values(context3.system.experience_clues ?? []).filter((clue) => /[A-Za-z]/.test(clue)), " "].forEach((clue, i) => { expClueData[(i + 1).toString()] = clue; }); - context.system.experience_clues = expClueData; + context3.system.experience_clues = expClueData; const gatherInfoData = {}; - [...Object.values(context.system.gather_info_questions ?? []).filter((question) => /[A-Za-z]/.test(question)), " "].forEach((question, i) => { + [...Object.values(context3.system.gather_info_questions ?? []).filter((question) => /[A-Za-z]/.test(question)), " "].forEach((question, i) => { gatherInfoData[(i + 1).toString()] = question; }); - context.system.gather_info_questions = gatherInfoData; + context3.system.gather_info_questions = gatherInfoData; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.preferred_op]: (context) => { + [BladesItemType.preferred_op]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.preferred_op)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.stricture]: (context) => { + [BladesItemType.stricture]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.stricture)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.vice]: (context) => { + [BladesItemType.vice]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.vice)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.ritual]: (context) => { + [BladesItemType.ritual]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.ritual)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.design]: (context) => { + [BladesItemType.design]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.design)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.location]: (context) => { + [BladesItemType.location]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.location)) { return void 0; } const sheetData = {}; return { - ...context, + ...context3, ...sheetData }; }, - [BladesItemType.score]: (context) => { + [BladesItemType.score]: (context3) => { if (!BladesItem$1.IsType(this.item, BladesItemType.score)) { return void 0; } - return context; + return context3; } }); } @@ -15081,7 +22254,7 @@ class BladesItemSheet extends ItemSheet { // override async getData() { getData() { var _a; - const context = super.getData(); + const context3 = super.getData(); const sheetData = { cssClass: this.item.type, editable: this.options.editable, @@ -15094,10 +22267,10 @@ class BladesItemSheet extends ItemSheet { }; const typedItemData = this._getTypedItemData[this.item.type]; if (typedItemData) { - return typedItemData({ ...context, ...sheetData }); + return typedItemData({ ...context3, ...sheetData }); } return { - ...context, + ...context3, ...sheetData }; } @@ -15146,7 +22319,7 @@ class BladesItemSheet extends ItemSheet { } async activateListeners(html) { await super.activateListeners(html); - const self = this; + const self2 = this; Tags.InitListeners(html, this.item); ApplyTooltipAnimations(html); if (!this.options.editable) { @@ -15178,11 +22351,11 @@ class BladesItemSheet extends ItemSheet { } html.find(".effect-control").on("click", (ev) => { var _a; - if (self.item.isOwned) { + if (self2.item.isOwned) { (_a = ui.notifications) == null ? void 0 : _a.warn(game.i18n.localize("BITD.EffectWarning")); return; } - BladesActiveEffect.onManageActiveEffect(ev, self.item); + BladesActiveEffect.onManageActiveEffect(ev, self2.item); }); html.find('[data-action="toggle-turf-connection"').on("click", this.toggleTurfConnection.bind(this)); } @@ -15218,11 +22391,11 @@ class BladesProjectSheet extends BladesItemSheet { }); } getData() { - const context = super.getData(); + const context3 = super.getData(); const sheetData = {}; sheetData.presentingClock = this.presentedClock; return { - ...context, + ...context3, ...sheetData }; } @@ -15255,21 +22428,21 @@ class BladesProjectSheet extends BladesItemSheet { } switchToPresentAllClocks(clockKey, keyElems$) { const { clocks } = keyElems$; - const timeline = clockKey.switchToMode(keyElems$, ClockKeyDisplayMode.clocks); + const timeline2 = clockKey.switchToMode(keyElems$, ClockKeyDisplayMode.clocks); if (clockKey.size > 1) { clockKey.visibleClocks.forEach((clock, i) => { const { clockLabel$ } = clocks[clock.id]; - timeline.blurReveal(clockLabel$, i === 0 ? ">" : "<+0.05"); + timeline2.blurReveal(clockLabel$, i === 0 ? ">" : "<+0.05"); }); } - timeline.play().then(() => { + timeline2.play().then(() => { if (this._htmlContext && this.document.currentClock) { this._htmlContext.find(".sheet-subtitle").attr("data-action", "current-clock-name").val(this.document.currentClock.name); } }); } switchToPresentClock(clockRef, clockKey, keyElems$) { - const timeline = clockKey.switchToMode( + const timeline2 = clockKey.switchToMode( keyElems$, clockRef === ClockKeyDisplayMode.presentCurrentClock ? clockRef : `present${clockRef}`, void 0, @@ -15282,8 +22455,8 @@ class BladesProjectSheet extends BladesItemSheet { } } ); - timeline.to(keyElems$.container$.find(".clock-label, .clock-key-label"), { autoAlpha: 0, duration: 0.5, ease: "sine" }, 0); - timeline.play().then(); + timeline2.to(keyElems$.container$.find(".clock-label, .clock-key-label"), { autoAlpha: 0, duration: 0.5, ease: "sine" }, 0); + timeline2.play().then(); } activateClockKeyListeners(clockKey, keyElems$) { eLog.checkLog2("BladesProject", "Clock Key Data", { clockKey, keyElems$ }); @@ -15724,7 +22897,7 @@ class BladesScoreSheet extends BladesItemSheet { await this.document.update({ "system.randomizers": finalRandomData }); } getData() { - const context = super.getData(); + const context3 = super.getData(); const sheetData = {}; sheetData.playerCharacters = BladesActor$1.GetTypeWithTags(BladesActorType.pc, Tag.PC.ActivePC).map((pc) => { return Object.assign( @@ -15745,15 +22918,15 @@ class BladesScoreSheet extends BladesItemSheet { ); }); const validOppositions = {}; - for (const [id, data] of Object.entries(context.system.oppositions)) { + for (const [id, data] of Object.entries(context3.system.oppositions)) { if (!data.rollOppName && !data.rollOppSubName) { continue; } validOppositions[id] = data; } - context.system.oppositions = validOppositions; + context3.system.oppositions = validOppositions; return { - ...context, + ...context3, ...sheetData }; } @@ -16602,10 +23775,10 @@ class BladesDialog extends Dialog { html.find("textarea").on({ change: (event) => this.updateInputText($(event.currentTarget)) }); } activateSelectionListeners(html) { - const self = this; + const self2 = this; html.find(".nav-tabs .tab-selector").on("click", (event) => { const tabIndex = U.pInt($(event.currentTarget).data("tab")); - const numItems = Object.values(self.tabs ?? [])[tabIndex].length; + const numItems = Object.values(self2.tabs ?? [])[tabIndex].length; const width = U.pInt(150 * Math.ceil(Math.sqrt(numItems))); eLog.checkLog3("nav", "Nav Tab Size Recalculation", { tabIndex, numItems, width }); this.render(false, { width }); @@ -16616,15 +23789,15 @@ class BladesDialog extends Dialog { } const docId = $(this).data("itemId"); const docType = $(this).data("docType"); - eLog.checkLog("dialog", "[BladesDialog] on Click", { elem: this, docId, docType, parent: self.parent }); - if (self.parent instanceof BladesActor$1) { + eLog.checkLog("dialog", "[BladesDialog] on Click", { elem: this, docId, docType, parent: self2.parent }); + if (self2.parent instanceof BladesActor$1) { if (docType === "Actor") { - self.parent.addSubActor(docId, self.tags); + self2.parent.addSubActor(docId, self2.tags); } else if (docType === "Item") { - self.parent.addSubItem(docId); + self2.parent.addSubItem(docId); } } - self.close(); + self2.close(); }); } async close() { @@ -17493,7 +24666,7 @@ class BladesActor extends Actor { } }); } - async update(updateData, context, isSkippingSubActorCheck = false) { + async update(updateData, context3, isSkippingSubActorCheck = false) { if (!updateData) { return super.update(updateData); } @@ -17513,7 +24686,7 @@ class BladesActor extends Actor { ); delete diffPlaybookData._id; if (!U.isEmpty(diffPlaybookData)) { - await this.playbook.update(playbookUpdateData, context).then(() => { + await this.playbook.update(playbookUpdateData, context3).then(() => { var _a; return (_a = this.sheet) == null ? void 0 : _a.render(false); }); @@ -17521,7 +24694,7 @@ class BladesActor extends Actor { } else if ((BladesActor.IsType(this, BladesActorType.npc) || BladesActor.IsType(this, BladesActorType.faction)) && this.parentActor && !isSkippingSubActorCheck) { return this.parentActor.updateSubActor(this.id, updateData).then(() => this); } - return super.update(updateData, context); + return super.update(updateData, context3); } // #endregion // #region Rolling Dice ~ @@ -17561,7 +24734,7 @@ class BladesActor extends Actor { } const titleChance = 0.05; const suffixChance = 0.01; - const { persona, secret, random } = this.system; + const { persona, secret, random: random3 } = this.system; function sampleArray(arr, ...curVals) { arr = arr.filter((elem) => !curVals.includes(elem)); if (!arr.length) { @@ -17582,9 +24755,9 @@ class BladesActor extends Actor { Math.random() <= suffixChance ? sampleArray(Randomizers.NPC.name_suffix) : "" ].filter((val) => Boolean(val)).join(" "); }, - background: () => sampleArray(Randomizers.NPC.background, random.background.value), - heritage: () => sampleArray(Randomizers.NPC.heritage, random.heritage.value), - profession: () => sampleArray(Randomizers.NPC.profession, random.profession.value), + background: () => sampleArray(Randomizers.NPC.background, random3.background.value), + heritage: () => sampleArray(Randomizers.NPC.heritage, random3.heritage.value), + profession: () => sampleArray(Randomizers.NPC.profession, random3.profession.value), gender: () => sampleArray(Randomizers.NPC.gender, persona.gender.value), appearance: () => sampleArray(Randomizers.NPC.appearance, persona.appearance.value), goal: () => sampleArray(Randomizers.NPC.goal, persona.goal.value, secret.goal.value), @@ -17609,9 +24782,9 @@ class BladesActor extends Actor { var _a; return !((_a = persona[key]) == null ? void 0 : _a.isLocked); }), - ...Object.keys(random).filter((key) => { + ...Object.keys(random3).filter((key) => { var _a; - return !((_a = random[key]) == null ? void 0 : _a.isLocked); + return !((_a = random3[key]) == null ? void 0 : _a.isLocked); }), ...Object.keys(secret).filter((key) => { var _a; @@ -17629,7 +24802,7 @@ class BladesActor extends Actor { const randomVal = randomGen[key](); updateData[`system.random.${key}`] = { isLocked: false, - value: randomVal || random[key].value + value: randomVal || random3[key].value }; break; } @@ -17743,7 +24916,7 @@ class BladesActorSheet extends ActorSheet { */ getData() { var _a, _b; - const context = super.getData(); + const context3 = super.getData(); const sheetData = { // Basic actor data. cssClass: this.actor.type, @@ -17848,7 +25021,7 @@ class BladesActorSheet extends ActorSheet { }; } return { - ...context, + ...context3, ...sheetData }; } @@ -18121,7 +25294,7 @@ class BladesActorSheet extends ActorSheet { $("#eunos-blades-tooltips").children(".tooltip").remove(); return; } - const config = { + const config3 = { target: this.actor, targetFlagKey: "rollCollab", rollDowntimeAction: downtimeAction @@ -18130,18 +25303,18 @@ class BladesActorSheet extends ActorSheet { case DowntimeAction.AcquireAsset: case DowntimeAction.LongTermProject: case DowntimeAction.ReduceHeat: { - config.rollType = RollType.Action; + config3.rollType = RollType.Action; break; } case DowntimeAction.Recover: { - config.rollType = RollType.Action; + config3.rollType = RollType.Action; if (BladesPC$1.IsType(this.actor) && this.actor.healingClock) { - config.rollClockKey = this.actor.healingClock.id; + config3.rollClockKey = this.actor.healingClock.id; } break; } case DowntimeAction.IndulgeVice: { - config.rollType = RollType.IndulgeVice; + config3.rollType = RollType.IndulgeVice; break; } case DowntimeAction.Train: { @@ -18158,11 +25331,11 @@ class BladesActorSheet extends ActorSheet { "system.downtime_actions_open_submenu": "", "system.downtime_actions.value": (((_c = this.actor.system.downtime_actions) == null ? void 0 : _c.value) ?? 0) + 1 }); - if ("rollType" in config) { + if ("rollType" in config3) { if (downtimeAction === DowntimeAction.IndulgeVice) { - BladesIndulgeViceRoll.New(config); + BladesIndulgeViceRoll.New(config3); } else { - BladesActionRoll.New(config); + BladesActionRoll.New(config3); } } } @@ -18203,11 +25376,11 @@ class BladesPCSheet extends BladesActorSheet { } getData() { var _a, _b, _c, _d; - const context = super.getData(); + const context3 = super.getData(); const { activeSubItems, activeSubActors } = this.actor; const sheetData = {}; sheetData.preparedItems = Object.assign( - context.preparedItems ?? {}, + context3.preparedItems ?? {}, { abilities: activeSubItems.filter((item) => item.type === BladesItemType.ability).map((item) => { if (item.system.uses_per_score.max) { @@ -18252,7 +25425,7 @@ class BladesPCSheet extends BladesActorSheet { }), playbook: this.actor.playbook, projects: activeSubItems.filter((item) => item.type === BladesItemType.project), - cohorts: (_a = context.preparedItems) == null ? void 0 : _a.cohorts + cohorts: (_a = context3.preparedItems) == null ? void 0 : _a.cohorts } ); sheetData.preparedActors = { @@ -18529,8 +25702,8 @@ class BladesPCSheet extends BladesActorSheet { "" ].join("")).toString(); eLog.checkLog("Attribute", "[BladesPCSheet] attributeData", { attributeData: sheetData.attributeData }); - eLog.checkLog("actor", "[BladesPCSheet] getData()", { ...context, ...sheetData }); - return { ...context, ...sheetData }; + eLog.checkLog("actor", "[BladesPCSheet] getData()", { ...context3, ...sheetData }); + return { ...context3, ...sheetData }; } get activeArmor() { return Object.keys(U.objFilter(this.actor.system.armor.active, (val) => val === true)); @@ -18595,24 +25768,24 @@ class BladesPCSheet extends BladesActorSheet { if (!this.options.editable) { return; } - const self = this; + const self2 = this; html.find(".main-armor-control").on({ click() { - const targetArmor = self._getClickArmor(); + const targetArmor = self2._getClickArmor(); if (!targetArmor) { return; } - self.actor.update({ [`system.armor.checked.${targetArmor}`]: true }); + self2.actor.update({ [`system.armor.checked.${targetArmor}`]: true }); }, contextmenu() { - const targetArmor = self._getContextMenuArmor(); + const targetArmor = self2._getContextMenuArmor(); if (!targetArmor) { return; } - self.actor.update({ [`system.armor.checked.${targetArmor}`]: false }); + self2.actor.update({ [`system.armor.checked.${targetArmor}`]: false }); }, mouseenter() { - const targetArmor = self._getHoverArmor(); + const targetArmor = self2._getHoverArmor(); eLog.log4("Mouse Enter", targetArmor, this, $(this), $(this).next()); if (!targetArmor) { return; @@ -18620,7 +25793,7 @@ class BladesPCSheet extends BladesActorSheet { $(this).siblings(`.svg-armor.armor-${targetArmor}`).addClass("hover-over"); }, mouseleave() { - const targetArmor = self._getHoverArmor(); + const targetArmor = self2._getHoverArmor(); if (!targetArmor) { return; } @@ -18629,25 +25802,25 @@ class BladesPCSheet extends BladesActorSheet { }); html.find(".special-control").on({ click() { - if (!self.activeArmor.includes("special")) { + if (!self2.activeArmor.includes("special")) { return; } - self.actor.update({ "system.armor.checked.special": self.uncheckedArmor.includes("special") }); + self2.actor.update({ "system.armor.checked.special": self2.uncheckedArmor.includes("special") }); }, contextmenu() { - if (!self.activeArmor.includes("special")) { + if (!self2.activeArmor.includes("special")) { return; } - self.actor.update({ "system.armor.checked.special": self.uncheckedArmor.includes("special") }); + self2.actor.update({ "system.armor.checked.special": self2.uncheckedArmor.includes("special") }); }, mouseenter() { - if (!self.activeArmor.includes("special") || self.activeArmor.length === 1) { + if (!self2.activeArmor.includes("special") || self2.activeArmor.length === 1) { return; } $(this).siblings(".svg-armor.armor-special").addClass("hover-over"); }, mouseleave() { - if (!self.activeArmor.includes("special") || self.activeArmor.length === 1) { + if (!self2.activeArmor.includes("special") || self2.activeArmor.length === 1) { return; } $(this).siblings(".svg-armor.armor-special").removeClass("hover-over"); @@ -19270,12 +26443,12 @@ class BladesNPCSheet extends BladesActorSheet { }); } getData() { - const context = super.getData(); - context.isSubActor = context.actor.isSubActor; - context.parentActor = context.actor.parentActor; - context.persona = context.actor.system.persona; - context.random = context.actor.system.random; - context.secret = context.actor.system.secret; + const context3 = super.getData(); + context3.isSubActor = context3.actor.isSubActor; + context3.parentActor = context3.actor.parentActor; + context3.persona = context3.actor.system.persona; + context3.random = context3.actor.system.random; + context3.secret = context3.actor.system.secret; const rStatus = { name: { size: 3, label: "Name" }, gender: { size: "half", label: "Gender" }, @@ -19294,17 +26467,17 @@ class BladesNPCSheet extends BladesActorSheet { trait3: { size: "half", label: null } }; for (const cat of ["persona", "random", "secret"]) { - for (const [key] of Object.entries(context[cat])) { + for (const [key] of Object.entries(context3[cat])) { if (key in rStatus) { Object.assign( - context[cat][key], + context3[cat][key], rStatus[key] ); } } } - console.log({ persona: context.persona, random: context.random, secret: context.secret }); - return context; + console.log({ persona: context3.persona, random: context3.random, secret: context3.secret }); + return context3; } activateListeners(html) { super.activateListeners(html); @@ -19436,9 +26609,9 @@ class BladesFactionSheet extends BladesActorSheet { }); } getData() { - const context = super.getData(); + const context3 = super.getData(); if (!BladesActor$1.IsType(this.actor, BladesActorType.faction)) { - return context; + return context3; } const sheetData = { tierData: { @@ -19456,7 +26629,7 @@ class BladesFactionSheet extends BladesActorSheet { clockKeys: this.actor.clocks }; return { - ...context, + ...context3, ...sheetData }; } @@ -19563,12 +26736,12 @@ class BladesCrewSheet extends BladesActorSheet { }); } getData() { - const context = super.getData(); - eLog.checkLog("actor", "[BladesCrewSheet] super.getData()", { ...context }); + const context3 = super.getData(); + eLog.checkLog("actor", "[BladesCrewSheet] super.getData()", { ...context3 }); const { activeSubItems } = this.actor; const sheetData = {}; sheetData.preparedItems = Object.assign( - context.preparedItems ?? {}, + context3.preparedItems ?? {}, { abilities: activeSubItems.filter((item) => item.type === BladesItemType.crew_ability), playbook: this.actor.playbook, @@ -19675,8 +26848,8 @@ class BladesCrewSheet extends BladesActorSheet { svgEmpty: "frame" } }; - eLog.checkLog("actor", "[BladesCrewSheet] return getData()", { ...context, ...sheetData }); - return { ...context, ...sheetData }; + eLog.checkLog("actor", "[BladesCrewSheet] return getData()", { ...context3, ...sheetData }); + return { ...context3, ...sheetData }; } activateListeners(html) { super.activateListeners(html); @@ -19780,15 +26953,15 @@ class BladesCrew extends BladesActor$1 { if (!BladesActor$1.IsType(this, BladesActorType.crew)) { return []; } - const self = this; - return BladesActor$1.GetTypeWithTags(BladesActorType.pc).filter((actor) => actor.isMember(self)); + const self2 = this; + return BladesActor$1.GetTypeWithTags(BladesActorType.pc).filter((actor) => actor.isMember(self2)); } get contacts() { if (!BladesActor$1.IsType(this, BladesActorType.crew) || !this.playbook) { return []; } - const self = this; - return this.activeSubActors.filter((actor) => actor.hasTag(self.playbookName)); + const self2 = this; + return this.activeSubActors.filter((actor) => actor.hasTag(self2.playbookName)); } get claims() { if (!BladesActor$1.IsType(this, BladesActorType.crew) || !this.playbook) { @@ -21078,14 +28251,14 @@ class BladesRollPrimary { rollFactors: doc.rollFactors }; } - static BuildData(config) { - if (BladesRollPrimary.IsValidData(config.rollPrimaryData)) { - return config.rollPrimaryData; + static BuildData(config3) { + if (BladesRollPrimary.IsValidData(config3.rollPrimaryData)) { + return config3.rollPrimaryData; } let rollPrimary; - const rollUser = game.users.get(config.rollUserID ?? game.user.id); - if ("target" in config && BladesRollPrimary.IsDoc(config.target)) { - rollPrimary = config.target; + const rollUser = game.users.get(config3.rollUserID ?? game.user.id); + if ("target" in config3 && BladesRollPrimary.IsDoc(config3.target)) { + rollPrimary = config3.target; } else if (rollUser && BladesRollPrimary.IsDoc(rollUser.character)) { rollPrimary = rollUser.character; } else { @@ -21100,8 +28273,8 @@ class BladesRollPrimary { rollFactors: rollPrimary.rollFactors }; } - static Build(config) { - return new BladesRollPrimary(this.BuildData(config)); + static Build(config3) { + return new BladesRollPrimary(this.BuildData(config3)); } get rollPrimaryDoc() { if (!this._rollPrimaryDoc) { @@ -21650,9 +28823,9 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { // static set Active(val: BladesRoll | undefined) { // BladesRoll._Active = val; // } - static GetUserPermissions(config) { + static GetUserPermissions(config3) { var _a, _b, _c, _d; - if (!config.rollPrimaryData) { + if (!config3.rollPrimaryData) { throw new Error("[BladesRoll.GetUserPermissions()] Missing rollPrimaryData."); } const GMUserID = (_a = game.users.find((user) => user.isGM)) == null ? void 0 : _a.id; @@ -21666,13 +28839,13 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { [RollPermissions.Participant]: [], [RollPermissions.Observer]: [] }; - const { rollPrimaryDoc } = new BladesRollPrimary(config.rollPrimaryData); + const { rollPrimaryDoc } = new BladesRollPrimary(config3.rollPrimaryData); if (BladesPC$1.IsType(rollPrimaryDoc) && U.pullElement(playerUserIDs, (_b = rollPrimaryDoc.primaryUser) == null ? void 0 : _b.id)) { userIDs[RollPermissions.Primary].push((_c = rollPrimaryDoc.primaryUser) == null ? void 0 : _c.id); } else if (BladesCrew$1.IsType(rollPrimaryDoc)) { userIDs[RollPermissions.Primary].push(...playerUserIDs); } else if (BladesItem$1.IsType(rollPrimaryDoc, BladesItemType.cohort_gang, BladesItemType.cohort_expert)) { - if (config.rollUserID === GMUserID) { + if (config3.rollUserID === GMUserID) { userIDs[RollPermissions.Primary].push(...playerUserIDs); } else if (BladesPC$1.IsType(rollPrimaryDoc.parent) && ((_d = rollPrimaryDoc.parent.primaryUser) == null ? void 0 : _d.id)) { userIDs[RollPermissions.Primary].push(rollPrimaryDoc.parent.primaryUser.id); @@ -21680,8 +28853,8 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { } else if (BladesGMTracker.IsType(rollPrimaryDoc)) { userIDs[RollPermissions.Primary].push(GMUserID); } - if (config.rollParticipantData) { - userIDs[RollPermissions.Participant].push(...getParticipantDocUserIDs(config.rollParticipantData, playerUserIDs)); + if (config3.rollParticipantData) { + userIDs[RollPermissions.Participant].push(...getParticipantDocUserIDs(config3.rollParticipantData, playerUserIDs)); } userIDs[RollPermissions.Observer] = playerUserIDs.filter((uID) => !userIDs[RollPermissions.Participant].includes(uID)); const userFlagData = {}; @@ -21719,28 +28892,28 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { }).flat().filter((pUser) => pUser !== null && !userIDs[RollPermissions.Primary].includes(pUser)); } } - static BuildLinkConfig(config) { + static BuildLinkConfig(config3) { const partialLinkConfig = {}; - if ("targetKey" in config && config.targetKey) { - partialLinkConfig.targetKey = config.targetKey; - } else if ("targetFlagKey" in config && config.targetFlagKey) { - partialLinkConfig.targetFlagKey = config.targetFlagKey; - } - if ("target" in config) { - if (U.isDocUUID(config.target)) { - partialLinkConfig.targetID = config.target; - } else if (U.isDocID(config.target)) { - const confTarget = game.actors.get(config.target) ?? game.items.get(config.target) ?? game.messages.get(config.target) ?? game.users.get(config.target); + if ("targetKey" in config3 && config3.targetKey) { + partialLinkConfig.targetKey = config3.targetKey; + } else if ("targetFlagKey" in config3 && config3.targetFlagKey) { + partialLinkConfig.targetFlagKey = config3.targetFlagKey; + } + if ("target" in config3) { + if (U.isDocUUID(config3.target)) { + partialLinkConfig.targetID = config3.target; + } else if (U.isDocID(config3.target)) { + const confTarget = game.actors.get(config3.target) ?? game.items.get(config3.target) ?? game.messages.get(config3.target) ?? game.users.get(config3.target); if (confTarget) { partialLinkConfig.targetID = confTarget.uuid; } else { - throw new Error(`[BladesRoll.BuildLinkConfig] No target found with id ${config.target}.`); + throw new Error(`[BladesRoll.BuildLinkConfig] No target found with id ${config3.target}.`); } } else { - partialLinkConfig.targetID = config.target.uuid; + partialLinkConfig.targetID = config3.target.uuid; } - } else if ("targetID" in config) { - partialLinkConfig.targetID = config.targetID; + } else if ("targetID" in config3) { + partialLinkConfig.targetID = config3.targetID; } else { throw new Error("[BladesRoll.BuildLinkConfig] You must provide a valid target or targetID in the config object."); } @@ -21791,14 +28964,14 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { * - This method is central to the dynamic and flexible creation of roll instances within the * system, allowing for easy extension and customization in subclasses of `BladesRoll`. */ - static async New(config) { - const linkConfig = this.BuildLinkConfig(config); - config.userPermissions = this.GetUserPermissions(config); - if (!config.rollType) { + static async New(config3) { + const linkConfig = this.BuildLinkConfig(config3); + config3.userPermissions = this.GetUserPermissions(config3); + if (!config3.rollType) { throw new Error("rollType must be defined in config"); } - eLog.checkLog3("bladesRoll", "BladesRoll.NewRoll()", { config }); - const rollInst = await this.Create({ ...config, ...linkConfig }); + eLog.checkLog3("bladesRoll", "BladesRoll.NewRoll()", { config: config3 }); + const rollInst = await this.Create({ ...config3, ...linkConfig }); if (!rollInst.isInitPromiseResolved) { eLog.checkLog3("bladesRoll", "BladesRoll Init Promise NOT Resolved After Awaiting Create"); await U.waitFor(rollInst.initPromise); @@ -23350,7 +30523,7 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { } spawnPositionDragger() { var _a; - const self = this; + const self2 = this; if (!this._elem$) { throw new Error(`[BladesRoll.spawnPositionDragger] No elem$ found for roll ${this.id}.`); } @@ -23363,7 +30536,7 @@ const _BladesRoll = class _BladesRoll extends BladesTargetLink { }, onDragEnd() { U.gsap.to(this.target, { opacity: 1, duration: 0.25, ease: "power2" }); - self.overlayPosition = { x: this.endX, y: this.endY }; + self2.overlayPosition = { x: this.endX, y: this.endY }; } }); } @@ -23717,10 +30890,10 @@ class BladesActionRoll extends BladesRoll { * @see {@link BladesRoll.New} for the base method's functionality and the generic creation process * for roll instances. */ - static async New(config) { - const linkConfig = this.BuildLinkConfig(config); + static async New(config3) { + const linkConfig = this.BuildLinkConfig(config3); const parsedConfig = { - ...config, + ...config3, ...linkConfig }; const rollInst = await super.New(parsedConfig); @@ -23820,15 +30993,15 @@ class BladesActionRoll extends BladesRoll { } } class BladesResistanceRoll extends BladesRoll { - static ApplySchemaDefaults(config) { + static ApplySchemaDefaults(config3) { var _a; - if (!config.resistanceData || !BladesConsequence.IsValidConsequenceData((_a = config.resistanceData) == null ? void 0 : _a.consequence)) { - eLog.error("rollCollab", "[PrepareResistanceRoll] Bad Roll Consequence Data.", config); + if (!config3.resistanceData || !BladesConsequence.IsValidConsequenceData((_a = config3.resistanceData) == null ? void 0 : _a.consequence)) { + eLog.error("rollCollab", "[PrepareResistanceRoll] Bad Roll Consequence Data.", config3); throw new Error("[PrepareResistanceRoll()] Bad Consequence Data for Resistance Roll"); } - config.rollTrait = config.resistanceData.consequence.attribute; - eLog.checkLog3("bladesRoll", "BladesRoll.PrepareResistanceRoll() [1]", { config }); - return config; + config3.rollTrait = config3.resistanceData.consequence.attribute; + eLog.checkLog3("bladesRoll", "BladesRoll.PrepareResistanceRoll() [1]", { config: config3 }); + return config3; } /** * Asynchronously creates a new instance of this subclass of `BladesRoll`. @@ -23845,10 +31018,10 @@ class BladesResistanceRoll extends BladesRoll { * @see {@link BladesRoll.New} for the base method's functionality and the generic creation process * for roll instances. */ - static async New(config) { - const linkConfig = this.BuildLinkConfig(config); + static async New(config3) { + const linkConfig = this.BuildLinkConfig(config3); const parsedConfig = { - ...config, + ...config3, ...linkConfig }; const rollInst = await super.New(parsedConfig); @@ -23888,11 +31061,11 @@ class BladesInlineResistanceRoll extends BladesResistanceRoll { } } class BladesFortuneRoll extends BladesRoll { - static ApplySchemaDefaults(config) { - if (!(U.isInt(config.rollTrait) || U.lCase(config.rollTrait) in { ...ActionTrait, ...AttributeTrait, ...Factor })) { - throw new Error(`[PrepareFortuneRoll()] Bad RollTrait for Fortune Roll: ${config.rollTrait}`); + static ApplySchemaDefaults(config3) { + if (!(U.isInt(config3.rollTrait) || U.lCase(config3.rollTrait) in { ...ActionTrait, ...AttributeTrait, ...Factor })) { + throw new Error(`[PrepareFortuneRoll()] Bad RollTrait for Fortune Roll: ${config3.rollTrait}`); } - return config; + return config3; } /** * Asynchronously creates a new instance of this subclass of `BladesRoll`. @@ -23909,10 +31082,10 @@ class BladesFortuneRoll extends BladesRoll { * @see {@link BladesRoll.New} for the base method's functionality and the generic creation process * for roll instances. */ - static async New(config) { - const linkConfig = this.BuildLinkConfig(config); + static async New(config3) { + const linkConfig = this.BuildLinkConfig(config3); const parsedConfig = { - ...config, + ...config3, ...linkConfig }; const rollInst = await super.New(parsedConfig); @@ -23920,19 +31093,19 @@ class BladesFortuneRoll extends BladesRoll { } } class BladesIndulgeViceRoll extends BladesRoll { - static ApplySchemaDefaults(config) { + static ApplySchemaDefaults(config3) { var _a; - const rollPrimaryDoc = BladesRollPrimary.GetDoc((_a = config.rollPrimaryData) == null ? void 0 : _a.rollPrimaryID); + const rollPrimaryDoc = BladesRollPrimary.GetDoc((_a = config3.rollPrimaryData) == null ? void 0 : _a.rollPrimaryID); if (!rollPrimaryDoc || !BladesPC$1.IsType(rollPrimaryDoc)) { throw new Error("[BladesRoll.PrepareIndulgeViceRollConfig] RollPrimary must be a PC for Indulge Vice rolls."); } const { attributes } = rollPrimaryDoc; const minAttrVal = Math.min(...Object.values(attributes)); - config.rollTrait = U.sample( + config3.rollTrait = U.sample( Object.values(AttributeTrait).filter((attr) => attributes[attr] === minAttrVal) )[0]; - config.rollDowntimeAction = DowntimeAction.IndulgeVice; - return config; + config3.rollDowntimeAction = DowntimeAction.IndulgeVice; + return config3; } /** * Asynchronously creates a new instance of this subclass of `BladesRoll`. @@ -23949,10 +31122,10 @@ class BladesIndulgeViceRoll extends BladesRoll { * @see {@link BladesRoll.New} for the base method's functionality and the generic creation process * for roll instances. */ - static async New(config) { - const linkConfig = this.BuildLinkConfig(config); + static async New(config3) { + const linkConfig = this.BuildLinkConfig(config3); const parsedConfig = { - ...config, + ...config3, ...linkConfig }; const rollInst = await super.New(parsedConfig); @@ -24408,14 +31581,14 @@ class BladesScene extends Scene { class AIAssistant { constructor(nameOrID, instructions, model = "gpt-4-1106-preview", { isUsingRetrieval, functionTools, file_ids, metadata } = {}) { __privateAdd(this, _apiKey, void 0); - __privateAdd(this, _id, void 0); + __privateAdd(this, _id2, void 0); __privateAdd(this, _name, void 0); __privateAdd(this, _instructions, void 0); __privateAdd(this, _tools, void 0); __privateAdd(this, _model, void 0); __privateAdd(this, _fileIDs, void 0); __privateAdd(this, _metadata, void 0); - __privateSet(this, _id, ""); + __privateSet(this, _id2, ""); __privateSet(this, _name, ""); __privateSet(this, _instructions, instructions ?? ""); __privateSet(this, _tools, []); @@ -24437,7 +31610,7 @@ class AIAssistant { } this.createAssistant(); } else { - __privateSet(this, _id, nameOrID); + __privateSet(this, _id2, nameOrID); this.retrieveAssistant(); } } @@ -24472,7 +31645,7 @@ class AIAssistant { const data = await response.json(); fetchRequest.body = JSON.parse(fetchRequest.body); eLog.checkLog3("BladesAI", "AI Query", { prompt: fetchRequest, response: data }); - __privateSet(this, _id, data.id); + __privateSet(this, _id2, data.id); } async retrieveAssistant() { const fetchRequest = { @@ -24484,7 +31657,7 @@ class AIAssistant { } }; const response = await fetch( - `https://api.openai.com/v1/assistants/${__privateGet(this, _id)}`, + `https://api.openai.com/v1/assistants/${__privateGet(this, _id2)}`, fetchRequest ); if (!response.ok) { @@ -24501,7 +31674,7 @@ class AIAssistant { } } _apiKey = new WeakMap(); -_id = new WeakMap(); +_id2 = new WeakMap(); _name = new WeakMap(); _instructions = new WeakMap(); _tools = new WeakMap(); @@ -24513,7 +31686,7 @@ class BladesAI { * AI class constructor * @param {BladesAI.Config} [config] Configuration settings for the API */ - constructor(config) { + constructor(config3) { __publicField(this, "apiKey"); __publicField(this, "model"); __publicField(this, "temperature", 0.5); @@ -24534,11 +31707,11 @@ class BladesAI { this.model = 0; } this.apiKey = apiKey; - this.systemMessage = config.systemMessage; - this.examplePrompts = config.examplePrompts; - this.temperature = config.temperature ?? this.temperature; - this.frequency_penalty = config.frequency_penalty ?? this.frequency_penalty; - this.presence_penalty = config.presence_penalty ?? this.presence_penalty; + this.systemMessage = config3.systemMessage; + this.examplePrompts = config3.examplePrompts; + this.temperature = config3.temperature ?? this.temperature; + this.frequency_penalty = config3.frequency_penalty ?? this.frequency_penalty; + this.presence_penalty = config3.presence_penalty ?? this.presence_penalty; } static async GetModels(isVerbose = false) { const apiKey = U.getSetting("openAPIKey"); @@ -24764,7 +31937,7 @@ class BladesClockKeeperSheet extends BladesItemSheet { ]); } getData() { - const context = super.getData(); + const context3 = super.getData(); const sheetData = { currentScene: game.scenes.current.id, targetScene: this.item.targetSceneID, @@ -24773,7 +31946,7 @@ class BladesClockKeeperSheet extends BladesItemSheet { pcsWithProjects: BladesPC$1.All.filter((pc) => pc.projects.length > 0), factions: Array.from(BladesFaction$1.All) }; - return { ...context, ...sheetData }; + return { ...context3, ...sheetData }; } addKey(event) { event.preventDefault(); diff --git a/dist/lib/greensock/CSSPlugin.js b/dist/lib/greensock/CSSPlugin.js new file mode 100644 index 00000000..679888fa --- /dev/null +++ b/dist/lib/greensock/CSSPlugin.js @@ -0,0 +1,1532 @@ +/*! + * CSSPlugin 3.11.0 + * https://greensock.com + * + * Copyright 2008-2022, GreenSock. All rights reserved. + * Subject to the terms at https://greensock.com/standard-license or for + * Club GreenSock members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ + +/* eslint-disable */ +import { gsap, _getProperty, _numExp, _numWithUnitExp, getUnit, _isString, _isUndefined, _renderComplexString, _relExp, _forEachName, _sortPropTweensByPriority, _colorStringFilter, _checkPlugin, _replaceRandom, _plugins, GSCache, PropTween, _config, _ticker, _round, _missingPlugin, _getSetter, _getCache, _colorExp, _parseRelative, _setDefaults, _removeLinkedListItem //for the commented-out className feature. +} from "./gsap-core.js"; + +var _win, + _doc, + _docElement, + _pluginInitted, + _tempDiv, + _tempDivStyler, + _recentSetterPlugin, + _reverting, + _windowExists = function _windowExists() { + return typeof window !== "undefined"; +}, + _transformProps = {}, + _RAD2DEG = 180 / Math.PI, + _DEG2RAD = Math.PI / 180, + _atan2 = Math.atan2, + _bigNum = 1e8, + _capsExp = /([A-Z])/g, + _horizontalExp = /(left|right|width|margin|padding|x)/i, + _complexExp = /[\s,\(]\S/, + _propertyAliases = { + autoAlpha: "opacity,visibility", + scale: "scaleX,scaleY", + alpha: "opacity" +}, + _renderCSSProp = function _renderCSSProp(ratio, data) { + return data.set(data.t, data.p, Math.round((data.s + data.c * ratio) * 10000) / 10000 + data.u, data); +}, + _renderPropWithEnd = function _renderPropWithEnd(ratio, data) { + return data.set(data.t, data.p, ratio === 1 ? data.e : Math.round((data.s + data.c * ratio) * 10000) / 10000 + data.u, data); +}, + _renderCSSPropWithBeginning = function _renderCSSPropWithBeginning(ratio, data) { + return data.set(data.t, data.p, ratio ? Math.round((data.s + data.c * ratio) * 10000) / 10000 + data.u : data.b, data); +}, + //if units change, we need a way to render the original unit/value when the tween goes all the way back to the beginning (ratio:0) +_renderRoundedCSSProp = function _renderRoundedCSSProp(ratio, data) { + var value = data.s + data.c * ratio; + data.set(data.t, data.p, ~~(value + (value < 0 ? -.5 : .5)) + data.u, data); +}, + _renderNonTweeningValue = function _renderNonTweeningValue(ratio, data) { + return data.set(data.t, data.p, ratio ? data.e : data.b, data); +}, + _renderNonTweeningValueOnlyAtEnd = function _renderNonTweeningValueOnlyAtEnd(ratio, data) { + return data.set(data.t, data.p, ratio !== 1 ? data.b : data.e, data); +}, + _setterCSSStyle = function _setterCSSStyle(target, property, value) { + return target.style[property] = value; +}, + _setterCSSProp = function _setterCSSProp(target, property, value) { + return target.style.setProperty(property, value); +}, + _setterTransform = function _setterTransform(target, property, value) { + return target._gsap[property] = value; +}, + _setterScale = function _setterScale(target, property, value) { + return target._gsap.scaleX = target._gsap.scaleY = value; +}, + _setterScaleWithRender = function _setterScaleWithRender(target, property, value, data, ratio) { + var cache = target._gsap; + cache.scaleX = cache.scaleY = value; + cache.renderTransform(ratio, cache); +}, + _setterTransformWithRender = function _setterTransformWithRender(target, property, value, data, ratio) { + var cache = target._gsap; + cache[property] = value; + cache.renderTransform(ratio, cache); +}, + _transformProp = "transform", + _transformOriginProp = _transformProp + "Origin", + _saveStyle = function _saveStyle(property) { + var _this = this; + + var target = this.target, + style = target.style; + + if (property in _transformProps) { + this.tfm = this.tfm || {}; + + if (property !== "transform") { + property = _propertyAliases[property] || property; + ~property.indexOf(",") ? property.split(",").forEach(function (a) { + return _this.tfm[a] = _get(target, a); + }) : this.tfm[property] = target._gsap.x ? target._gsap[property] : _get(target, property); // note: scale would map to "scaleX,scaleY", thus we loop and apply them both. + } + + target._gsap.svg && (this.svg = target.getAttribute(property) || ""); + + if (this.props.indexOf(_transformProp) >= 0) { + return; + } + + property = _transformProp; + } + + style && this.props.push(property, style[property]); +}, + _removeIndependentTransforms = function _removeIndependentTransforms(style) { + if (style.translate) { + style.removeProperty("translate"); + style.removeProperty("scale"); + style.removeProperty("rotate"); + } +}, + _revertStyle = function _revertStyle() { + var props = this.props, + target = this.target, + style = target.style, + cache = target._gsap, + i, + p; + + for (i = 0; i < props.length; i += 2) { + props[i + 1] ? style[props[i]] = props[i + 1] : style.removeProperty(props[i].replace(_capsExp, "-$1").toLowerCase()); + } + + if (this.tfm) { + cache.svg && target.setAttribute("transform", this.svg || ""); + + for (p in this.tfm) { + cache[p] = this.tfm[p]; + } + + i = _reverting(); + + if (i && !i.isStart && !style[_transformProp]) { + _removeIndependentTransforms(style); + + cache.uncache = 1; // if it's a startAt that's being reverted in the _initTween() of the core, we don't need to uncache transforms. This is purely a performance optimization. + } + } +}, + _getStyleSaver = function _getStyleSaver(target, properties) { + var saver = { + target: target, + props: [], + revert: _revertStyle, + save: _saveStyle + }; + properties && properties.split(",").forEach(function (p) { + return saver.save(p); + }); + return saver; +}, + _supports3D, + _createElement = function _createElement(type, ns) { + var e = _doc.createElementNS ? _doc.createElementNS((ns || "http://www.w3.org/1999/xhtml").replace(/^https/, "http"), type) : _doc.createElement(type); //some servers swap in https for http in the namespace which can break things, making "style" inaccessible. + + return e.style ? e : _doc.createElement(type); //some environments won't allow access to the element's style when created with a namespace in which case we default to the standard createElement() to work around the issue. Also note that when GSAP is embedded directly inside an SVG file, createElement() won't allow access to the style object in Firefox (see https://greensock.com/forums/topic/20215-problem-using-tweenmax-in-standalone-self-containing-svg-file-err-cannot-set-property-csstext-of-undefined/). +}, + _getComputedProperty = function _getComputedProperty(target, property, skipPrefixFallback) { + var cs = getComputedStyle(target); + return cs[property] || cs.getPropertyValue(property.replace(_capsExp, "-$1").toLowerCase()) || cs.getPropertyValue(property) || !skipPrefixFallback && _getComputedProperty(target, _checkPropPrefix(property) || property, 1) || ""; //css variables may not need caps swapped out for dashes and lowercase. +}, + _prefixes = "O,Moz,ms,Ms,Webkit".split(","), + _checkPropPrefix = function _checkPropPrefix(property, element, preferPrefix) { + var e = element || _tempDiv, + s = e.style, + i = 5; + + if (property in s && !preferPrefix) { + return property; + } + + property = property.charAt(0).toUpperCase() + property.substr(1); + + while (i-- && !(_prefixes[i] + property in s)) {} + + return i < 0 ? null : (i === 3 ? "ms" : i >= 0 ? _prefixes[i] : "") + property; +}, + _initCore = function _initCore() { + if (_windowExists() && window.document) { + _win = window; + _doc = _win.document; + _docElement = _doc.documentElement; + _tempDiv = _createElement("div") || { + style: {} + }; + _tempDivStyler = _createElement("div"); + _transformProp = _checkPropPrefix(_transformProp); + _transformOriginProp = _transformProp + "Origin"; + _tempDiv.style.cssText = "border-width:0;line-height:0;position:absolute;padding:0"; //make sure to override certain properties that may contaminate measurements, in case the user has overreaching style sheets. + + _supports3D = !!_checkPropPrefix("perspective"); + _reverting = gsap.core.reverting; + _pluginInitted = 1; + } +}, + _getBBoxHack = function _getBBoxHack(swapIfPossible) { + //works around issues in some browsers (like Firefox) that don't correctly report getBBox() on SVG elements inside a element and/or . We try creating an SVG, adding it to the documentElement and toss the element in there so that it's definitely part of the rendering tree, then grab the bbox and if it works, we actually swap out the original getBBox() method for our own that does these extra steps whenever getBBox is needed. This helps ensure that performance is optimal (only do all these extra steps when absolutely necessary...most elements don't need it). + var svg = _createElement("svg", this.ownerSVGElement && this.ownerSVGElement.getAttribute("xmlns") || "http://www.w3.org/2000/svg"), + oldParent = this.parentNode, + oldSibling = this.nextSibling, + oldCSS = this.style.cssText, + bbox; + + _docElement.appendChild(svg); + + svg.appendChild(this); + this.style.display = "block"; + + if (swapIfPossible) { + try { + bbox = this.getBBox(); + this._gsapBBox = this.getBBox; //store the original + + this.getBBox = _getBBoxHack; + } catch (e) {} + } else if (this._gsapBBox) { + bbox = this._gsapBBox(); + } + + if (oldParent) { + if (oldSibling) { + oldParent.insertBefore(this, oldSibling); + } else { + oldParent.appendChild(this); + } + } + + _docElement.removeChild(svg); + + this.style.cssText = oldCSS; + return bbox; +}, + _getAttributeFallbacks = function _getAttributeFallbacks(target, attributesArray) { + var i = attributesArray.length; + + while (i--) { + if (target.hasAttribute(attributesArray[i])) { + return target.getAttribute(attributesArray[i]); + } + } +}, + _getBBox = function _getBBox(target) { + var bounds; + + try { + bounds = target.getBBox(); //Firefox throws errors if you try calling getBBox() on an SVG element that's not rendered (like in a or ). https://bugzilla.mozilla.org/show_bug.cgi?id=612118 + } catch (error) { + bounds = _getBBoxHack.call(target, true); + } + + bounds && (bounds.width || bounds.height) || target.getBBox === _getBBoxHack || (bounds = _getBBoxHack.call(target, true)); //some browsers (like Firefox) misreport the bounds if the element has zero width and height (it just assumes it's at x:0, y:0), thus we need to manually grab the position in that case. + + return bounds && !bounds.width && !bounds.x && !bounds.y ? { + x: +_getAttributeFallbacks(target, ["x", "cx", "x1"]) || 0, + y: +_getAttributeFallbacks(target, ["y", "cy", "y1"]) || 0, + width: 0, + height: 0 + } : bounds; +}, + _isSVG = function _isSVG(e) { + return !!(e.getCTM && (!e.parentNode || e.ownerSVGElement) && _getBBox(e)); +}, + //reports if the element is an SVG on which getBBox() actually works +_removeProperty = function _removeProperty(target, property) { + if (property) { + var style = target.style; + + if (property in _transformProps && property !== _transformOriginProp) { + property = _transformProp; + } + + if (style.removeProperty) { + if (property.substr(0, 2) === "ms" || property.substr(0, 6) === "webkit") { + //Microsoft and some Webkit browsers don't conform to the standard of capitalizing the first prefix character, so we adjust so that when we prefix the caps with a dash, it's correct (otherwise it'd be "ms-transform" instead of "-ms-transform" for IE9, for example) + property = "-" + property; + } + + style.removeProperty(property.replace(_capsExp, "-$1").toLowerCase()); + } else { + //note: old versions of IE use "removeAttribute()" instead of "removeProperty()" + style.removeAttribute(property); + } + } +}, + _addNonTweeningPT = function _addNonTweeningPT(plugin, target, property, beginning, end, onlySetAtEnd) { + var pt = new PropTween(plugin._pt, target, property, 0, 1, onlySetAtEnd ? _renderNonTweeningValueOnlyAtEnd : _renderNonTweeningValue); + plugin._pt = pt; + pt.b = beginning; + pt.e = end; + + plugin._props.push(property); + + return pt; +}, + _nonConvertibleUnits = { + deg: 1, + rad: 1, + turn: 1 +}, + _nonStandardLayouts = { + grid: 1, + flex: 1 +}, + //takes a single value like 20px and converts it to the unit specified, like "%", returning only the numeric amount. +_convertToUnit = function _convertToUnit(target, property, value, unit) { + var curValue = parseFloat(value) || 0, + curUnit = (value + "").trim().substr((curValue + "").length) || "px", + // some browsers leave extra whitespace at the beginning of CSS variables, hence the need to trim() + style = _tempDiv.style, + horizontal = _horizontalExp.test(property), + isRootSVG = target.tagName.toLowerCase() === "svg", + measureProperty = (isRootSVG ? "client" : "offset") + (horizontal ? "Width" : "Height"), + amount = 100, + toPixels = unit === "px", + toPercent = unit === "%", + px, + parent, + cache, + isSVG; + + if (unit === curUnit || !curValue || _nonConvertibleUnits[unit] || _nonConvertibleUnits[curUnit]) { + return curValue; + } + + curUnit !== "px" && !toPixels && (curValue = _convertToUnit(target, property, value, "px")); + isSVG = target.getCTM && _isSVG(target); + + if ((toPercent || curUnit === "%") && (_transformProps[property] || ~property.indexOf("adius"))) { + px = isSVG ? target.getBBox()[horizontal ? "width" : "height"] : target[measureProperty]; + return _round(toPercent ? curValue / px * amount : curValue / 100 * px); + } + + style[horizontal ? "width" : "height"] = amount + (toPixels ? curUnit : unit); + parent = ~property.indexOf("adius") || unit === "em" && target.appendChild && !isRootSVG ? target : target.parentNode; + + if (isSVG) { + parent = (target.ownerSVGElement || {}).parentNode; + } + + if (!parent || parent === _doc || !parent.appendChild) { + parent = _doc.body; + } + + cache = parent._gsap; + + if (cache && toPercent && cache.width && horizontal && cache.time === _ticker.time && !cache.uncache) { + return _round(curValue / cache.width * amount); + } else { + (toPercent || curUnit === "%") && !_nonStandardLayouts[_getComputedProperty(parent, "display")] && (style.position = _getComputedProperty(target, "position")); + parent === target && (style.position = "static"); // like for borderRadius, if it's a % we must have it relative to the target itself but that may not have position: relative or position: absolute in which case it'd go up the chain until it finds its offsetParent (bad). position: static protects against that. + + parent.appendChild(_tempDiv); + px = _tempDiv[measureProperty]; + parent.removeChild(_tempDiv); + style.position = "absolute"; + + if (horizontal && toPercent) { + cache = _getCache(parent); + cache.time = _ticker.time; + cache.width = parent[measureProperty]; + } + } + + return _round(toPixels ? px * curValue / amount : px && curValue ? amount / px * curValue : 0); +}, + _get = function _get(target, property, unit, uncache) { + var value; + _pluginInitted || _initCore(); + + if (property in _propertyAliases && property !== "transform") { + property = _propertyAliases[property]; + + if (~property.indexOf(",")) { + property = property.split(",")[0]; + } + } + + if (_transformProps[property] && property !== "transform") { + value = _parseTransform(target, uncache); + value = property !== "transformOrigin" ? value[property] : value.svg ? value.origin : _firstTwoOnly(_getComputedProperty(target, _transformOriginProp)) + " " + value.zOrigin + "px"; + } else { + value = target.style[property]; + + if (!value || value === "auto" || uncache || ~(value + "").indexOf("calc(")) { + value = _specialProps[property] && _specialProps[property](target, property, unit) || _getComputedProperty(target, property) || _getProperty(target, property) || (property === "opacity" ? 1 : 0); // note: some browsers, like Firefox, don't report borderRadius correctly! Instead, it only reports every corner like borderTopLeftRadius + } + } + + return unit && !~(value + "").trim().indexOf(" ") ? _convertToUnit(target, property, value, unit) + unit : value; +}, + _tweenComplexCSSString = function _tweenComplexCSSString(target, prop, start, end) { + // note: we call _tweenComplexCSSString.call(pluginInstance...) to ensure that it's scoped properly. We may call it from within a plugin too, thus "this" would refer to the plugin. + if (!start || start === "none") { + // some browsers like Safari actually PREFER the prefixed property and mis-report the unprefixed value like clipPath (BUG). In other words, even though clipPath exists in the style ("clipPath" in target.style) and it's set in the CSS properly (along with -webkit-clip-path), Safari reports clipPath as "none" whereas WebkitClipPath reports accurately like "ellipse(100% 0% at 50% 0%)", so in this case we must SWITCH to using the prefixed property instead. See https://greensock.com/forums/topic/18310-clippath-doesnt-work-on-ios/ + var p = _checkPropPrefix(prop, target, 1), + s = p && _getComputedProperty(target, p, 1); + + if (s && s !== start) { + prop = p; + start = s; + } else if (prop === "borderColor") { + start = _getComputedProperty(target, "borderTopColor"); // Firefox bug: always reports "borderColor" as "", so we must fall back to borderTopColor. See https://greensock.com/forums/topic/24583-how-to-return-colors-that-i-had-after-reverse/ + } + } + + var pt = new PropTween(this._pt, target.style, prop, 0, 1, _renderComplexString), + index = 0, + matchIndex = 0, + a, + result, + startValues, + startNum, + color, + startValue, + endValue, + endNum, + chunk, + endUnit, + startUnit, + endValues; + pt.b = start; + pt.e = end; + start += ""; // ensure values are strings + + end += ""; + + if (end === "auto") { + target.style[prop] = end; + end = _getComputedProperty(target, prop) || end; + target.style[prop] = start; + } + + a = [start, end]; + + _colorStringFilter(a); // pass an array with the starting and ending values and let the filter do whatever it needs to the values. If colors are found, it returns true and then we must match where the color shows up order-wise because for things like boxShadow, sometimes the browser provides the computed values with the color FIRST, but the user provides it with the color LAST, so flip them if necessary. Same for drop-shadow(). + + + start = a[0]; + end = a[1]; + startValues = start.match(_numWithUnitExp) || []; + endValues = end.match(_numWithUnitExp) || []; + + if (endValues.length) { + while (result = _numWithUnitExp.exec(end)) { + endValue = result[0]; + chunk = end.substring(index, result.index); + + if (color) { + color = (color + 1) % 5; + } else if (chunk.substr(-5) === "rgba(" || chunk.substr(-5) === "hsla(") { + color = 1; + } + + if (endValue !== (startValue = startValues[matchIndex++] || "")) { + startNum = parseFloat(startValue) || 0; + startUnit = startValue.substr((startNum + "").length); + endValue.charAt(1) === "=" && (endValue = _parseRelative(startNum, endValue) + startUnit); + endNum = parseFloat(endValue); + endUnit = endValue.substr((endNum + "").length); + index = _numWithUnitExp.lastIndex - endUnit.length; + + if (!endUnit) { + //if something like "perspective:300" is passed in and we must add a unit to the end + endUnit = endUnit || _config.units[prop] || startUnit; + + if (index === end.length) { + end += endUnit; + pt.e += endUnit; + } + } + + if (startUnit !== endUnit) { + startNum = _convertToUnit(target, prop, startValue, endUnit) || 0; + } // these nested PropTweens are handled in a special way - we'll never actually call a render or setter method on them. We'll just loop through them in the parent complex string PropTween's render method. + + + pt._pt = { + _next: pt._pt, + p: chunk || matchIndex === 1 ? chunk : ",", + //note: SVG spec allows omission of comma/space when a negative sign is wedged between two numbers, like 2.5-5.3 instead of 2.5,-5.3 but when tweening, the negative value may switch to positive, so we insert the comma just in case. + s: startNum, + c: endNum - startNum, + m: color && color < 4 || prop === "zIndex" ? Math.round : 0 + }; + } + } + + pt.c = index < end.length ? end.substring(index, end.length) : ""; //we use the "c" of the PropTween to store the final part of the string (after the last number) + } else { + pt.r = prop === "display" && end === "none" ? _renderNonTweeningValueOnlyAtEnd : _renderNonTweeningValue; + } + + _relExp.test(end) && (pt.e = 0); //if the end string contains relative values or dynamic random(...) values, delete the end it so that on the final render we don't actually set it to the string with += or -= characters (forces it to use the calculated value). + + this._pt = pt; //start the linked list with this new PropTween. Remember, we call _tweenComplexCSSString.call(pluginInstance...) to ensure that it's scoped properly. We may call it from within another plugin too, thus "this" would refer to the plugin. + + return pt; +}, + _keywordToPercent = { + top: "0%", + bottom: "100%", + left: "0%", + right: "100%", + center: "50%" +}, + _convertKeywordsToPercentages = function _convertKeywordsToPercentages(value) { + var split = value.split(" "), + x = split[0], + y = split[1] || "50%"; + + if (x === "top" || x === "bottom" || y === "left" || y === "right") { + //the user provided them in the wrong order, so flip them + value = x; + x = y; + y = value; + } + + split[0] = _keywordToPercent[x] || x; + split[1] = _keywordToPercent[y] || y; + return split.join(" "); +}, + _renderClearProps = function _renderClearProps(ratio, data) { + if (data.tween && data.tween._time === data.tween._dur) { + var target = data.t, + style = target.style, + props = data.u, + cache = target._gsap, + prop, + clearTransforms, + i; + + if (props === "all" || props === true) { + style.cssText = ""; + clearTransforms = 1; + } else { + props = props.split(","); + i = props.length; + + while (--i > -1) { + prop = props[i]; + + if (_transformProps[prop]) { + clearTransforms = 1; + prop = prop === "transformOrigin" ? _transformOriginProp : _transformProp; + } + + _removeProperty(target, prop); + } + } + + if (clearTransforms) { + _removeProperty(target, _transformProp); + + if (cache) { + cache.svg && target.removeAttribute("transform"); + + _parseTransform(target, 1); // force all the cached values back to "normal"/identity, otherwise if there's another tween that's already set to render transforms on this element, it could display the wrong values. + + + cache.uncache = 1; + + _removeIndependentTransforms(style); + } + } + } +}, + // note: specialProps should return 1 if (and only if) they have a non-zero priority. It indicates we need to sort the linked list. +_specialProps = { + clearProps: function clearProps(plugin, target, property, endValue, tween) { + if (tween.data !== "isFromStart") { + var pt = plugin._pt = new PropTween(plugin._pt, target, property, 0, 0, _renderClearProps); + pt.u = endValue; + pt.pr = -10; + pt.tween = tween; + + plugin._props.push(property); + + return 1; + } + } + /* className feature (about 0.4kb gzipped). + , className(plugin, target, property, endValue, tween) { + let _renderClassName = (ratio, data) => { + data.css.render(ratio, data.css); + if (!ratio || ratio === 1) { + let inline = data.rmv, + target = data.t, + p; + target.setAttribute("class", ratio ? data.e : data.b); + for (p in inline) { + _removeProperty(target, p); + } + } + }, + _getAllStyles = (target) => { + let styles = {}, + computed = getComputedStyle(target), + p; + for (p in computed) { + if (isNaN(p) && p !== "cssText" && p !== "length") { + styles[p] = computed[p]; + } + } + _setDefaults(styles, _parseTransform(target, 1)); + return styles; + }, + startClassList = target.getAttribute("class"), + style = target.style, + cssText = style.cssText, + cache = target._gsap, + classPT = cache.classPT, + inlineToRemoveAtEnd = {}, + data = {t:target, plugin:plugin, rmv:inlineToRemoveAtEnd, b:startClassList, e:(endValue.charAt(1) !== "=") ? endValue : startClassList.replace(new RegExp("(?:\\s|^)" + endValue.substr(2) + "(?![\\w-])"), "") + ((endValue.charAt(0) === "+") ? " " + endValue.substr(2) : "")}, + changingVars = {}, + startVars = _getAllStyles(target), + transformRelated = /(transform|perspective)/i, + endVars, p; + if (classPT) { + classPT.r(1, classPT.d); + _removeLinkedListItem(classPT.d.plugin, classPT, "_pt"); + } + target.setAttribute("class", data.e); + endVars = _getAllStyles(target, true); + target.setAttribute("class", startClassList); + for (p in endVars) { + if (endVars[p] !== startVars[p] && !transformRelated.test(p)) { + changingVars[p] = endVars[p]; + if (!style[p] && style[p] !== "0") { + inlineToRemoveAtEnd[p] = 1; + } + } + } + cache.classPT = plugin._pt = new PropTween(plugin._pt, target, "className", 0, 0, _renderClassName, data, 0, -11); + if (style.cssText !== cssText) { //only apply if things change. Otherwise, in cases like a background-image that's pulled dynamically, it could cause a refresh. See https://greensock.com/forums/topic/20368-possible-gsap-bug-switching-classnames-in-chrome/. + style.cssText = cssText; //we recorded cssText before we swapped classes and ran _getAllStyles() because in cases when a className tween is overwritten, we remove all the related tweening properties from that class change (otherwise class-specific stuff can't override properties we've directly set on the target's style object due to specificity). + } + _parseTransform(target, true); //to clear the caching of transforms + data.css = new gsap.plugins.css(); + data.css.init(target, changingVars, tween); + plugin._props.push(...data.css._props); + return 1; + } + */ + +}, + +/* + * -------------------------------------------------------------------------------------- + * TRANSFORMS + * -------------------------------------------------------------------------------------- + */ +_identity2DMatrix = [1, 0, 0, 1, 0, 0], + _rotationalProperties = {}, + _isNullTransform = function _isNullTransform(value) { + return value === "matrix(1, 0, 0, 1, 0, 0)" || value === "none" || !value; +}, + _getComputedTransformMatrixAsArray = function _getComputedTransformMatrixAsArray(target) { + var matrixString = _getComputedProperty(target, _transformProp); + + return _isNullTransform(matrixString) ? _identity2DMatrix : matrixString.substr(7).match(_numExp).map(_round); +}, + _getMatrix = function _getMatrix(target, force2D) { + var cache = target._gsap || _getCache(target), + style = target.style, + matrix = _getComputedTransformMatrixAsArray(target), + parent, + nextSibling, + temp, + addedToDOM; + + if (cache.svg && target.getAttribute("transform")) { + temp = target.transform.baseVal.consolidate().matrix; //ensures that even complex values like "translate(50,60) rotate(135,0,0)" are parsed because it mashes it into a matrix. + + matrix = [temp.a, temp.b, temp.c, temp.d, temp.e, temp.f]; + return matrix.join(",") === "1,0,0,1,0,0" ? _identity2DMatrix : matrix; + } else if (matrix === _identity2DMatrix && !target.offsetParent && target !== _docElement && !cache.svg) { + //note: if offsetParent is null, that means the element isn't in the normal document flow, like if it has display:none or one of its ancestors has display:none). Firefox returns null for getComputedStyle() if the element is in an iframe that has display:none. https://bugzilla.mozilla.org/show_bug.cgi?id=548397 + //browsers don't report transforms accurately unless the element is in the DOM and has a display value that's not "none". Firefox and Microsoft browsers have a partial bug where they'll report transforms even if display:none BUT not any percentage-based values like translate(-50%, 8px) will be reported as if it's translate(0, 8px). + temp = style.display; + style.display = "block"; + parent = target.parentNode; + + if (!parent || !target.offsetParent) { + // note: in 3.3.0 we switched target.offsetParent to _doc.body.contains(target) to avoid [sometimes unnecessary] MutationObserver calls but that wasn't adequate because there are edge cases where nested position: fixed elements need to get reparented to accurately sense transforms. See https://github.com/greensock/GSAP/issues/388 and https://github.com/greensock/GSAP/issues/375 + addedToDOM = 1; //flag + + nextSibling = target.nextElementSibling; + + _docElement.appendChild(target); //we must add it to the DOM in order to get values properly + + } + + matrix = _getComputedTransformMatrixAsArray(target); + temp ? style.display = temp : _removeProperty(target, "display"); + + if (addedToDOM) { + nextSibling ? parent.insertBefore(target, nextSibling) : parent ? parent.appendChild(target) : _docElement.removeChild(target); + } + } + + return force2D && matrix.length > 6 ? [matrix[0], matrix[1], matrix[4], matrix[5], matrix[12], matrix[13]] : matrix; +}, + _applySVGOrigin = function _applySVGOrigin(target, origin, originIsAbsolute, smooth, matrixArray, pluginToAddPropTweensTo) { + var cache = target._gsap, + matrix = matrixArray || _getMatrix(target, true), + xOriginOld = cache.xOrigin || 0, + yOriginOld = cache.yOrigin || 0, + xOffsetOld = cache.xOffset || 0, + yOffsetOld = cache.yOffset || 0, + a = matrix[0], + b = matrix[1], + c = matrix[2], + d = matrix[3], + tx = matrix[4], + ty = matrix[5], + originSplit = origin.split(" "), + xOrigin = parseFloat(originSplit[0]) || 0, + yOrigin = parseFloat(originSplit[1]) || 0, + bounds, + determinant, + x, + y; + + if (!originIsAbsolute) { + bounds = _getBBox(target); + xOrigin = bounds.x + (~originSplit[0].indexOf("%") ? xOrigin / 100 * bounds.width : xOrigin); + yOrigin = bounds.y + (~(originSplit[1] || originSplit[0]).indexOf("%") ? yOrigin / 100 * bounds.height : yOrigin); + } else if (matrix !== _identity2DMatrix && (determinant = a * d - b * c)) { + //if it's zero (like if scaleX and scaleY are zero), skip it to avoid errors with dividing by zero. + x = xOrigin * (d / determinant) + yOrigin * (-c / determinant) + (c * ty - d * tx) / determinant; + y = xOrigin * (-b / determinant) + yOrigin * (a / determinant) - (a * ty - b * tx) / determinant; + xOrigin = x; + yOrigin = y; + } + + if (smooth || smooth !== false && cache.smooth) { + tx = xOrigin - xOriginOld; + ty = yOrigin - yOriginOld; + cache.xOffset = xOffsetOld + (tx * a + ty * c) - tx; + cache.yOffset = yOffsetOld + (tx * b + ty * d) - ty; + } else { + cache.xOffset = cache.yOffset = 0; + } + + cache.xOrigin = xOrigin; + cache.yOrigin = yOrigin; + cache.smooth = !!smooth; + cache.origin = origin; + cache.originIsAbsolute = !!originIsAbsolute; + target.style[_transformOriginProp] = "0px 0px"; //otherwise, if someone sets an origin via CSS, it will likely interfere with the SVG transform attribute ones (because remember, we're baking the origin into the matrix() value). + + if (pluginToAddPropTweensTo) { + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "xOrigin", xOriginOld, xOrigin); + + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "yOrigin", yOriginOld, yOrigin); + + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "xOffset", xOffsetOld, cache.xOffset); + + _addNonTweeningPT(pluginToAddPropTweensTo, cache, "yOffset", yOffsetOld, cache.yOffset); + } + + target.setAttribute("data-svg-origin", xOrigin + " " + yOrigin); +}, + _parseTransform = function _parseTransform(target, uncache) { + var cache = target._gsap || new GSCache(target); + + if ("x" in cache && !uncache && !cache.uncache) { + return cache; + } + + var style = target.style, + invertedScaleX = cache.scaleX < 0, + px = "px", + deg = "deg", + cs = getComputedStyle(target), + origin = _getComputedProperty(target, _transformOriginProp) || "0", + x, + y, + z, + scaleX, + scaleY, + rotation, + rotationX, + rotationY, + skewX, + skewY, + perspective, + xOrigin, + yOrigin, + matrix, + angle, + cos, + sin, + a, + b, + c, + d, + a12, + a22, + t1, + t2, + t3, + a13, + a23, + a33, + a42, + a43, + a32; + x = y = z = rotation = rotationX = rotationY = skewX = skewY = perspective = 0; + scaleX = scaleY = 1; + cache.svg = !!(target.getCTM && _isSVG(target)); + + if (cs.translate) { + // accommodate independent transforms by combining them into normal ones. + if (cs.translate !== "none" || cs.scale !== "none" || cs.rotate !== "none") { + style[_transformProp] = (cs.translate !== "none" ? "translate3d(" + (cs.translate + " 0 0").split(" ").slice(0, 3).join(", ") + ") " : "") + (cs.rotate !== "none" ? "rotate(" + cs.rotate + ") " : "") + (cs.scale !== "none" ? "scale(" + cs.scale.split(" ").join(",") + ") " : "") + cs[_transformProp]; + } + + style.scale = style.rotate = style.translate = "none"; + } + + matrix = _getMatrix(target, cache.svg); + + if (cache.svg) { + t1 = (!cache.uncache || origin === "0px 0px") && !uncache && target.getAttribute("data-svg-origin"); // if origin is 0,0 and cache.uncache is true, let the recorded data-svg-origin stay. Otherwise, whenever we set cache.uncache to true, we'd need to set element.style.transformOrigin = (cache.xOrigin - bbox.x) + "px " + (cache.yOrigin - bbox.y) + "px". Remember, to work around browser inconsistencies we always force SVG elements' transformOrigin to 0,0 and offset the translation accordingly. + + _applySVGOrigin(target, t1 || origin, !!t1 || cache.originIsAbsolute, cache.smooth !== false, matrix); + } + + xOrigin = cache.xOrigin || 0; + yOrigin = cache.yOrigin || 0; + + if (matrix !== _identity2DMatrix) { + a = matrix[0]; //a11 + + b = matrix[1]; //a21 + + c = matrix[2]; //a31 + + d = matrix[3]; //a41 + + x = a12 = matrix[4]; + y = a22 = matrix[5]; //2D matrix + + if (matrix.length === 6) { + scaleX = Math.sqrt(a * a + b * b); + scaleY = Math.sqrt(d * d + c * c); + rotation = a || b ? _atan2(b, a) * _RAD2DEG : 0; //note: if scaleX is 0, we cannot accurately measure rotation. Same for skewX with a scaleY of 0. Therefore, we default to the previously recorded value (or zero if that doesn't exist). + + skewX = c || d ? _atan2(c, d) * _RAD2DEG + rotation : 0; + skewX && (scaleY *= Math.abs(Math.cos(skewX * _DEG2RAD))); + + if (cache.svg) { + x -= xOrigin - (xOrigin * a + yOrigin * c); + y -= yOrigin - (xOrigin * b + yOrigin * d); + } //3D matrix + + } else { + a32 = matrix[6]; + a42 = matrix[7]; + a13 = matrix[8]; + a23 = matrix[9]; + a33 = matrix[10]; + a43 = matrix[11]; + x = matrix[12]; + y = matrix[13]; + z = matrix[14]; + angle = _atan2(a32, a33); + rotationX = angle * _RAD2DEG; //rotationX + + if (angle) { + cos = Math.cos(-angle); + sin = Math.sin(-angle); + t1 = a12 * cos + a13 * sin; + t2 = a22 * cos + a23 * sin; + t3 = a32 * cos + a33 * sin; + a13 = a12 * -sin + a13 * cos; + a23 = a22 * -sin + a23 * cos; + a33 = a32 * -sin + a33 * cos; + a43 = a42 * -sin + a43 * cos; + a12 = t1; + a22 = t2; + a32 = t3; + } //rotationY + + + angle = _atan2(-c, a33); + rotationY = angle * _RAD2DEG; + + if (angle) { + cos = Math.cos(-angle); + sin = Math.sin(-angle); + t1 = a * cos - a13 * sin; + t2 = b * cos - a23 * sin; + t3 = c * cos - a33 * sin; + a43 = d * sin + a43 * cos; + a = t1; + b = t2; + c = t3; + } //rotationZ + + + angle = _atan2(b, a); + rotation = angle * _RAD2DEG; + + if (angle) { + cos = Math.cos(angle); + sin = Math.sin(angle); + t1 = a * cos + b * sin; + t2 = a12 * cos + a22 * sin; + b = b * cos - a * sin; + a22 = a22 * cos - a12 * sin; + a = t1; + a12 = t2; + } + + if (rotationX && Math.abs(rotationX) + Math.abs(rotation) > 359.9) { + //when rotationY is set, it will often be parsed as 180 degrees different than it should be, and rotationX and rotation both being 180 (it looks the same), so we adjust for that here. + rotationX = rotation = 0; + rotationY = 180 - rotationY; + } + + scaleX = _round(Math.sqrt(a * a + b * b + c * c)); + scaleY = _round(Math.sqrt(a22 * a22 + a32 * a32)); + angle = _atan2(a12, a22); + skewX = Math.abs(angle) > 0.0002 ? angle * _RAD2DEG : 0; + perspective = a43 ? 1 / (a43 < 0 ? -a43 : a43) : 0; + } + + if (cache.svg) { + //sense if there are CSS transforms applied on an SVG element in which case we must overwrite them when rendering. The transform attribute is more reliable cross-browser, but we can't just remove the CSS ones because they may be applied in a CSS rule somewhere (not just inline). + t1 = target.getAttribute("transform"); + cache.forceCSS = target.setAttribute("transform", "") || !_isNullTransform(_getComputedProperty(target, _transformProp)); + t1 && target.setAttribute("transform", t1); + } + } + + if (Math.abs(skewX) > 90 && Math.abs(skewX) < 270) { + if (invertedScaleX) { + scaleX *= -1; + skewX += rotation <= 0 ? 180 : -180; + rotation += rotation <= 0 ? 180 : -180; + } else { + scaleY *= -1; + skewX += skewX <= 0 ? 180 : -180; + } + } + + uncache = uncache || cache.uncache; + cache.x = x - ((cache.xPercent = x && (!uncache && cache.xPercent || (Math.round(target.offsetWidth / 2) === Math.round(-x) ? -50 : 0))) ? target.offsetWidth * cache.xPercent / 100 : 0) + px; + cache.y = y - ((cache.yPercent = y && (!uncache && cache.yPercent || (Math.round(target.offsetHeight / 2) === Math.round(-y) ? -50 : 0))) ? target.offsetHeight * cache.yPercent / 100 : 0) + px; + cache.z = z + px; + cache.scaleX = _round(scaleX); + cache.scaleY = _round(scaleY); + cache.rotation = _round(rotation) + deg; + cache.rotationX = _round(rotationX) + deg; + cache.rotationY = _round(rotationY) + deg; + cache.skewX = skewX + deg; + cache.skewY = skewY + deg; + cache.transformPerspective = perspective + px; + + if (cache.zOrigin = parseFloat(origin.split(" ")[2]) || 0) { + style[_transformOriginProp] = _firstTwoOnly(origin); + } + + cache.xOffset = cache.yOffset = 0; + cache.force3D = _config.force3D; + cache.renderTransform = cache.svg ? _renderSVGTransforms : _supports3D ? _renderCSSTransforms : _renderNon3DTransforms; + cache.uncache = 0; + return cache; +}, + _firstTwoOnly = function _firstTwoOnly(value) { + return (value = value.split(" "))[0] + " " + value[1]; +}, + //for handling transformOrigin values, stripping out the 3rd dimension +_addPxTranslate = function _addPxTranslate(target, start, value) { + var unit = getUnit(start); + return _round(parseFloat(start) + parseFloat(_convertToUnit(target, "x", value + "px", unit))) + unit; +}, + _renderNon3DTransforms = function _renderNon3DTransforms(ratio, cache) { + cache.z = "0px"; + cache.rotationY = cache.rotationX = "0deg"; + cache.force3D = 0; + + _renderCSSTransforms(ratio, cache); +}, + _zeroDeg = "0deg", + _zeroPx = "0px", + _endParenthesis = ") ", + _renderCSSTransforms = function _renderCSSTransforms(ratio, cache) { + var _ref = cache || this, + xPercent = _ref.xPercent, + yPercent = _ref.yPercent, + x = _ref.x, + y = _ref.y, + z = _ref.z, + rotation = _ref.rotation, + rotationY = _ref.rotationY, + rotationX = _ref.rotationX, + skewX = _ref.skewX, + skewY = _ref.skewY, + scaleX = _ref.scaleX, + scaleY = _ref.scaleY, + transformPerspective = _ref.transformPerspective, + force3D = _ref.force3D, + target = _ref.target, + zOrigin = _ref.zOrigin, + transforms = "", + use3D = force3D === "auto" && ratio && ratio !== 1 || force3D === true; // Safari has a bug that causes it not to render 3D transform-origin values properly, so we force the z origin to 0, record it in the cache, and then do the math here to offset the translate values accordingly (basically do the 3D transform-origin part manually) + + + if (zOrigin && (rotationX !== _zeroDeg || rotationY !== _zeroDeg)) { + var angle = parseFloat(rotationY) * _DEG2RAD, + a13 = Math.sin(angle), + a33 = Math.cos(angle), + cos; + + angle = parseFloat(rotationX) * _DEG2RAD; + cos = Math.cos(angle); + x = _addPxTranslate(target, x, a13 * cos * -zOrigin); + y = _addPxTranslate(target, y, -Math.sin(angle) * -zOrigin); + z = _addPxTranslate(target, z, a33 * cos * -zOrigin + zOrigin); + } + + if (transformPerspective !== _zeroPx) { + transforms += "perspective(" + transformPerspective + _endParenthesis; + } + + if (xPercent || yPercent) { + transforms += "translate(" + xPercent + "%, " + yPercent + "%) "; + } + + if (use3D || x !== _zeroPx || y !== _zeroPx || z !== _zeroPx) { + transforms += z !== _zeroPx || use3D ? "translate3d(" + x + ", " + y + ", " + z + ") " : "translate(" + x + ", " + y + _endParenthesis; + } + + if (rotation !== _zeroDeg) { + transforms += "rotate(" + rotation + _endParenthesis; + } + + if (rotationY !== _zeroDeg) { + transforms += "rotateY(" + rotationY + _endParenthesis; + } + + if (rotationX !== _zeroDeg) { + transforms += "rotateX(" + rotationX + _endParenthesis; + } + + if (skewX !== _zeroDeg || skewY !== _zeroDeg) { + transforms += "skew(" + skewX + ", " + skewY + _endParenthesis; + } + + if (scaleX !== 1 || scaleY !== 1) { + transforms += "scale(" + scaleX + ", " + scaleY + _endParenthesis; + } + + target.style[_transformProp] = transforms || "translate(0, 0)"; +}, + _renderSVGTransforms = function _renderSVGTransforms(ratio, cache) { + var _ref2 = cache || this, + xPercent = _ref2.xPercent, + yPercent = _ref2.yPercent, + x = _ref2.x, + y = _ref2.y, + rotation = _ref2.rotation, + skewX = _ref2.skewX, + skewY = _ref2.skewY, + scaleX = _ref2.scaleX, + scaleY = _ref2.scaleY, + target = _ref2.target, + xOrigin = _ref2.xOrigin, + yOrigin = _ref2.yOrigin, + xOffset = _ref2.xOffset, + yOffset = _ref2.yOffset, + forceCSS = _ref2.forceCSS, + tx = parseFloat(x), + ty = parseFloat(y), + a11, + a21, + a12, + a22, + temp; + + rotation = parseFloat(rotation); + skewX = parseFloat(skewX); + skewY = parseFloat(skewY); + + if (skewY) { + //for performance reasons, we combine all skewing into the skewX and rotation values. Remember, a skewY of 10 degrees looks the same as a rotation of 10 degrees plus a skewX of 10 degrees. + skewY = parseFloat(skewY); + skewX += skewY; + rotation += skewY; + } + + if (rotation || skewX) { + rotation *= _DEG2RAD; + skewX *= _DEG2RAD; + a11 = Math.cos(rotation) * scaleX; + a21 = Math.sin(rotation) * scaleX; + a12 = Math.sin(rotation - skewX) * -scaleY; + a22 = Math.cos(rotation - skewX) * scaleY; + + if (skewX) { + skewY *= _DEG2RAD; + temp = Math.tan(skewX - skewY); + temp = Math.sqrt(1 + temp * temp); + a12 *= temp; + a22 *= temp; + + if (skewY) { + temp = Math.tan(skewY); + temp = Math.sqrt(1 + temp * temp); + a11 *= temp; + a21 *= temp; + } + } + + a11 = _round(a11); + a21 = _round(a21); + a12 = _round(a12); + a22 = _round(a22); + } else { + a11 = scaleX; + a22 = scaleY; + a21 = a12 = 0; + } + + if (tx && !~(x + "").indexOf("px") || ty && !~(y + "").indexOf("px")) { + tx = _convertToUnit(target, "x", x, "px"); + ty = _convertToUnit(target, "y", y, "px"); + } + + if (xOrigin || yOrigin || xOffset || yOffset) { + tx = _round(tx + xOrigin - (xOrigin * a11 + yOrigin * a12) + xOffset); + ty = _round(ty + yOrigin - (xOrigin * a21 + yOrigin * a22) + yOffset); + } + + if (xPercent || yPercent) { + //The SVG spec doesn't support percentage-based translation in the "transform" attribute, so we merge it into the translation to simulate it. + temp = target.getBBox(); + tx = _round(tx + xPercent / 100 * temp.width); + ty = _round(ty + yPercent / 100 * temp.height); + } + + temp = "matrix(" + a11 + "," + a21 + "," + a12 + "," + a22 + "," + tx + "," + ty + ")"; + target.setAttribute("transform", temp); + forceCSS && (target.style[_transformProp] = temp); //some browsers prioritize CSS transforms over the transform attribute. When we sense that the user has CSS transforms applied, we must overwrite them this way (otherwise some browser simply won't render the transform attribute changes!) +}, + _addRotationalPropTween = function _addRotationalPropTween(plugin, target, property, startNum, endValue) { + var cap = 360, + isString = _isString(endValue), + endNum = parseFloat(endValue) * (isString && ~endValue.indexOf("rad") ? _RAD2DEG : 1), + change = endNum - startNum, + finalValue = startNum + change + "deg", + direction, + pt; + + if (isString) { + direction = endValue.split("_")[1]; + + if (direction === "short") { + change %= cap; + + if (change !== change % (cap / 2)) { + change += change < 0 ? cap : -cap; + } + } + + if (direction === "cw" && change < 0) { + change = (change + cap * _bigNum) % cap - ~~(change / cap) * cap; + } else if (direction === "ccw" && change > 0) { + change = (change - cap * _bigNum) % cap - ~~(change / cap) * cap; + } + } + + plugin._pt = pt = new PropTween(plugin._pt, target, property, startNum, change, _renderPropWithEnd); + pt.e = finalValue; + pt.u = "deg"; + + plugin._props.push(property); + + return pt; +}, + _assign = function _assign(target, source) { + // Internet Explorer doesn't have Object.assign(), so we recreate it here. + for (var p in source) { + target[p] = source[p]; + } + + return target; +}, + _addRawTransformPTs = function _addRawTransformPTs(plugin, transforms, target) { + //for handling cases where someone passes in a whole transform string, like transform: "scale(2, 3) rotate(20deg) translateY(30em)" + var startCache = _assign({}, target._gsap), + exclude = "perspective,force3D,transformOrigin,svgOrigin", + style = target.style, + endCache, + p, + startValue, + endValue, + startNum, + endNum, + startUnit, + endUnit; + + if (startCache.svg) { + startValue = target.getAttribute("transform"); + target.setAttribute("transform", ""); + style[_transformProp] = transforms; + endCache = _parseTransform(target, 1); + + _removeProperty(target, _transformProp); + + target.setAttribute("transform", startValue); + } else { + startValue = getComputedStyle(target)[_transformProp]; + style[_transformProp] = transforms; + endCache = _parseTransform(target, 1); + style[_transformProp] = startValue; + } + + for (p in _transformProps) { + startValue = startCache[p]; + endValue = endCache[p]; + + if (startValue !== endValue && exclude.indexOf(p) < 0) { + //tweening to no perspective gives very unintuitive results - just keep the same perspective in that case. + startUnit = getUnit(startValue); + endUnit = getUnit(endValue); + startNum = startUnit !== endUnit ? _convertToUnit(target, p, startValue, endUnit) : parseFloat(startValue); + endNum = parseFloat(endValue); + plugin._pt = new PropTween(plugin._pt, endCache, p, startNum, endNum - startNum, _renderCSSProp); + plugin._pt.u = endUnit || 0; + + plugin._props.push(p); + } + } + + _assign(endCache, startCache); +}; // handle splitting apart padding, margin, borderWidth, and borderRadius into their 4 components. Firefox, for example, won't report borderRadius correctly - it will only do borderTopLeftRadius and the other corners. We also want to handle paddingTop, marginLeft, borderRightWidth, etc. + + +_forEachName("padding,margin,Width,Radius", function (name, index) { + var t = "Top", + r = "Right", + b = "Bottom", + l = "Left", + props = (index < 3 ? [t, r, b, l] : [t + l, t + r, b + r, b + l]).map(function (side) { + return index < 2 ? name + side : "border" + side + name; + }); + + _specialProps[index > 1 ? "border" + name : name] = function (plugin, target, property, endValue, tween) { + var a, vars; + + if (arguments.length < 4) { + // getter, passed target, property, and unit (from _get()) + a = props.map(function (prop) { + return _get(plugin, prop, property); + }); + vars = a.join(" "); + return vars.split(a[0]).length === 5 ? a[0] : vars; + } + + a = (endValue + "").split(" "); + vars = {}; + props.forEach(function (prop, i) { + return vars[prop] = a[i] = a[i] || a[(i - 1) / 2 | 0]; + }); + plugin.init(target, vars, tween); + }; +}); + +export var CSSPlugin = { + name: "css", + register: _initCore, + targetTest: function targetTest(target) { + return target.style && target.nodeType; + }, + init: function init(target, vars, tween, index, targets) { + var props = this._props, + style = target.style, + startAt = tween.vars.startAt, + startValue, + endValue, + endNum, + startNum, + type, + specialProp, + p, + startUnit, + endUnit, + relative, + isTransformRelated, + transformPropTween, + cache, + smooth, + hasPriority, + inlineProps; + _pluginInitted || _initCore(); // we may call init() multiple times on the same plugin instance, like when adding special properties, so make sure we don't overwrite the revert data or inlineProps + + this.styles = this.styles || _getStyleSaver(target); + inlineProps = this.styles.props; + this.tween = tween; + + for (p in vars) { + if (p === "autoRound") { + continue; + } + + endValue = vars[p]; + + if (_plugins[p] && _checkPlugin(p, vars, tween, index, target, targets)) { + // plugins + continue; + } + + type = typeof endValue; + specialProp = _specialProps[p]; + + if (type === "function") { + endValue = endValue.call(tween, index, target, targets); + type = typeof endValue; + } + + if (type === "string" && ~endValue.indexOf("random(")) { + endValue = _replaceRandom(endValue); + } + + if (specialProp) { + specialProp(this, target, p, endValue, tween) && (hasPriority = 1); + } else if (p.substr(0, 2) === "--") { + //CSS variable + startValue = (getComputedStyle(target).getPropertyValue(p) + "").trim(); + endValue += ""; + _colorExp.lastIndex = 0; + + if (!_colorExp.test(startValue)) { + // colors don't have units + startUnit = getUnit(startValue); + endUnit = getUnit(endValue); + } + + endUnit ? startUnit !== endUnit && (startValue = _convertToUnit(target, p, startValue, endUnit) + endUnit) : startUnit && (endValue += startUnit); + this.add(style, "setProperty", startValue, endValue, index, targets, 0, 0, p); + props.push(p); + inlineProps.push(p, style[p]); + } else if (type !== "undefined") { + if (startAt && p in startAt) { + // in case someone hard-codes a complex value as the start, like top: "calc(2vh / 2)". Without this, it'd use the computed value (always in px) + startValue = typeof startAt[p] === "function" ? startAt[p].call(tween, index, target, targets) : startAt[p]; + _isString(startValue) && ~startValue.indexOf("random(") && (startValue = _replaceRandom(startValue)); + getUnit(startValue + "") || (startValue += _config.units[p] || getUnit(_get(target, p)) || ""); // for cases when someone passes in a unitless value like {x: 100}; if we try setting translate(100, 0px) it won't work. + + (startValue + "").charAt(1) === "=" && (startValue = _get(target, p)); // can't work with relative values + } else { + startValue = _get(target, p); + } + + startNum = parseFloat(startValue); + relative = type === "string" && endValue.charAt(1) === "=" && endValue.substr(0, 2); + relative && (endValue = endValue.substr(2)); + endNum = parseFloat(endValue); + + if (p in _propertyAliases) { + if (p === "autoAlpha") { + //special case where we control the visibility along with opacity. We still allow the opacity value to pass through and get tweened. + if (startNum === 1 && _get(target, "visibility") === "hidden" && endNum) { + //if visibility is initially set to "hidden", we should interpret that as intent to make opacity 0 (a convenience) + startNum = 0; + } + + inlineProps.push("visibility", style.visibility); + + _addNonTweeningPT(this, style, "visibility", startNum ? "inherit" : "hidden", endNum ? "inherit" : "hidden", !endNum); + } + + if (p !== "scale" && p !== "transform") { + p = _propertyAliases[p]; + ~p.indexOf(",") && (p = p.split(",")[0]); + } + } + + isTransformRelated = p in _transformProps; //--- TRANSFORM-RELATED --- + + if (isTransformRelated) { + this.styles.save(p); + + if (!transformPropTween) { + cache = target._gsap; + cache.renderTransform && !vars.parseTransform || _parseTransform(target, vars.parseTransform); // if, for example, gsap.set(... {transform:"translateX(50vw)"}), the _get() call doesn't parse the transform, thus cache.renderTransform won't be set yet so force the parsing of the transform here. + + smooth = vars.smoothOrigin !== false && cache.smooth; + transformPropTween = this._pt = new PropTween(this._pt, style, _transformProp, 0, 1, cache.renderTransform, cache, 0, -1); //the first time through, create the rendering PropTween so that it runs LAST (in the linked list, we keep adding to the beginning) + + transformPropTween.dep = 1; //flag it as dependent so that if things get killed/overwritten and this is the only PropTween left, we can safely kill the whole tween. + } + + if (p === "scale") { + this._pt = new PropTween(this._pt, cache, "scaleY", cache.scaleY, (relative ? _parseRelative(cache.scaleY, relative + endNum) : endNum) - cache.scaleY || 0, _renderCSSProp); + this._pt.u = 0; + props.push("scaleY", p); + p += "X"; + } else if (p === "transformOrigin") { + inlineProps.push(_transformOriginProp, style[_transformOriginProp]); + endValue = _convertKeywordsToPercentages(endValue); //in case something like "left top" or "bottom right" is passed in. Convert to percentages. + + if (cache.svg) { + _applySVGOrigin(target, endValue, 0, smooth, 0, this); + } else { + endUnit = parseFloat(endValue.split(" ")[2]) || 0; //handle the zOrigin separately! + + endUnit !== cache.zOrigin && _addNonTweeningPT(this, cache, "zOrigin", cache.zOrigin, endUnit); + + _addNonTweeningPT(this, style, p, _firstTwoOnly(startValue), _firstTwoOnly(endValue)); + } + + continue; + } else if (p === "svgOrigin") { + _applySVGOrigin(target, endValue, 1, smooth, 0, this); + + continue; + } else if (p in _rotationalProperties) { + _addRotationalPropTween(this, cache, p, startNum, relative ? _parseRelative(startNum, relative + endValue) : endValue); + + continue; + } else if (p === "smoothOrigin") { + _addNonTweeningPT(this, cache, "smooth", cache.smooth, endValue); + + continue; + } else if (p === "force3D") { + cache[p] = endValue; + continue; + } else if (p === "transform") { + _addRawTransformPTs(this, endValue, target); + + continue; + } + } else if (!(p in style)) { + p = _checkPropPrefix(p) || p; + } + + if (isTransformRelated || (endNum || endNum === 0) && (startNum || startNum === 0) && !_complexExp.test(endValue) && p in style) { + startUnit = (startValue + "").substr((startNum + "").length); + endNum || (endNum = 0); // protect against NaN + + endUnit = getUnit(endValue) || (p in _config.units ? _config.units[p] : startUnit); + startUnit !== endUnit && (startNum = _convertToUnit(target, p, startValue, endUnit)); + this._pt = new PropTween(this._pt, isTransformRelated ? cache : style, p, startNum, (relative ? _parseRelative(startNum, relative + endNum) : endNum) - startNum, !isTransformRelated && (endUnit === "px" || p === "zIndex") && vars.autoRound !== false ? _renderRoundedCSSProp : _renderCSSProp); + this._pt.u = endUnit || 0; + + if (startUnit !== endUnit && endUnit !== "%") { + //when the tween goes all the way back to the beginning, we need to revert it to the OLD/ORIGINAL value (with those units). We record that as a "b" (beginning) property and point to a render method that handles that. (performance optimization) + this._pt.b = startValue; + this._pt.r = _renderCSSPropWithBeginning; + } + } else if (!(p in style)) { + if (p in target) { + //maybe it's not a style - it could be a property added directly to an element in which case we'll try to animate that. + this.add(target, p, startValue || target[p], relative ? relative + endValue : endValue, index, targets); + } else { + _missingPlugin(p, endValue); + + continue; + } + } else { + _tweenComplexCSSString.call(this, target, p, startValue, relative ? relative + endValue : endValue); + } + + isTransformRelated || inlineProps.push(p, style[p]); + props.push(p); + } + } + + hasPriority && _sortPropTweensByPriority(this); + }, + render: function render(ratio, data) { + if (data.tween._time || !_reverting()) { + var pt = data._pt; + + while (pt) { + pt.r(ratio, pt.d); + pt = pt._next; + } + } else { + data.styles.revert(); + } + }, + get: _get, + aliases: _propertyAliases, + getSetter: function getSetter(target, property, plugin) { + //returns a setter function that accepts target, property, value and applies it accordingly. Remember, properties like "x" aren't as simple as target.style.property = value because they've got to be applied to a proxy object and then merged into a transform string in a renderer. + var p = _propertyAliases[property]; + p && p.indexOf(",") < 0 && (property = p); + return property in _transformProps && property !== _transformOriginProp && (target._gsap.x || _get(target, "x")) ? plugin && _recentSetterPlugin === plugin ? property === "scale" ? _setterScale : _setterTransform : (_recentSetterPlugin = plugin || {}) && (property === "scale" ? _setterScaleWithRender : _setterTransformWithRender) : target.style && !_isUndefined(target.style[property]) ? _setterCSSStyle : ~property.indexOf("-") ? _setterCSSProp : _getSetter(target, property); + }, + core: { + _removeProperty: _removeProperty, + _getMatrix: _getMatrix + } +}; +gsap.utils.checkPrefix = _checkPropPrefix; +gsap.core.getStyleSaver = _getStyleSaver; + +(function (positionAndScale, rotation, others, aliases) { + var all = _forEachName(positionAndScale + "," + rotation + "," + others, function (name) { + _transformProps[name] = 1; + }); + + _forEachName(rotation, function (name) { + _config.units[name] = "deg"; + _rotationalProperties[name] = 1; + }); + + _propertyAliases[all[13]] = positionAndScale + "," + rotation; + + _forEachName(aliases, function (name) { + var split = name.split(":"); + _propertyAliases[split[1]] = all[split[0]]; + }); +})("x,y,z,scale,scaleX,scaleY,xPercent,yPercent", "rotation,rotationX,rotationY,skewX,skewY", "transform,transformOrigin,svgOrigin,force3D,smoothOrigin,transformPerspective", "0:translateX,1:translateY,2:translateZ,8:rotate,8:rotationZ,8:rotateZ,9:rotateX,10:rotateY"); + +_forEachName("x,y,z,top,right,bottom,left,width,height,fontSize,padding,margin,perspective", function (name) { + _config.units[name] = "px"; +}); + +gsap.registerPlugin(CSSPlugin); +export { CSSPlugin as default, _getBBox, _createElement, _checkPropPrefix as checkPrefix }; \ No newline at end of file diff --git a/dist/lib/greensock/CSSRulePlugin.js b/dist/lib/greensock/CSSRulePlugin.js new file mode 100644 index 00000000..49413c78 --- /dev/null +++ b/dist/lib/greensock/CSSRulePlugin.js @@ -0,0 +1,134 @@ +/*! + * CSSRulePlugin 3.11.0 + * https://greensock.com + * + * @license Copyright 2008-2022, GreenSock. All rights reserved. + * Subject to the terms at https://greensock.com/standard-license or for + * Club GreenSock members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ + +/* eslint-disable */ +var gsap, + _coreInitted, + _win, + _doc, + CSSPlugin, + _windowExists = function _windowExists() { + return typeof window !== "undefined"; +}, + _getGSAP = function _getGSAP() { + return gsap || _windowExists() && (gsap = window.gsap) && gsap.registerPlugin && gsap; +}, + _checkRegister = function _checkRegister() { + if (!_coreInitted) { + _initCore(); + + if (!CSSPlugin) { + console.warn("Please gsap.registerPlugin(CSSPlugin, CSSRulePlugin)"); + } + } + + return _coreInitted; +}, + _initCore = function _initCore(core) { + gsap = core || _getGSAP(); + + if (_windowExists()) { + _win = window; + _doc = document; + } + + if (gsap) { + CSSPlugin = gsap.plugins.css; + + if (CSSPlugin) { + _coreInitted = 1; + } + } +}; + +export var CSSRulePlugin = { + version: "3.11.0", + name: "cssRule", + init: function init(target, value, tween, index, targets) { + if (!_checkRegister() || typeof target.cssText === "undefined") { + return false; + } + + var div = target._gsProxy = target._gsProxy || _doc.createElement("div"); + + this.ss = target; + this.style = div.style; + div.style.cssText = target.cssText; + CSSPlugin.prototype.init.call(this, div, value, tween, index, targets); //we just offload all the work to the regular CSSPlugin and then copy the cssText back over to the rule in the render() method. This allows us to have all of the updates to CSSPlugin automatically flow through to CSSRulePlugin instead of having to maintain both + }, + render: function render(ratio, data) { + var pt = data._pt, + style = data.style, + ss = data.ss, + i; + + while (pt) { + pt.r(ratio, pt.d); + pt = pt._next; + } + + i = style.length; + + while (--i > -1) { + ss[style[i]] = style[style[i]]; + } + }, + getRule: function getRule(selector) { + _checkRegister(); + + var ruleProp = _doc.all ? "rules" : "cssRules", + styleSheets = _doc.styleSheets, + i = styleSheets.length, + pseudo = selector.charAt(0) === ":", + j, + curSS, + cs, + a; + selector = (pseudo ? "" : ",") + selector.split("::").join(":").toLowerCase() + ","; //note: old versions of IE report tag name selectors as upper case, so we just change everything to lowercase. + + if (pseudo) { + a = []; + } + + while (i--) { + //Firefox may throw insecure operation errors when css is loaded from other domains, so try/catch. + try { + curSS = styleSheets[i][ruleProp]; + + if (!curSS) { + continue; + } + + j = curSS.length; + } catch (e) { + console.warn(e); + continue; + } + + while (--j > -1) { + cs = curSS[j]; + + if (cs.selectorText && ("," + cs.selectorText.split("::").join(":").toLowerCase() + ",").indexOf(selector) !== -1) { + //note: IE adds an extra ":" to pseudo selectors, so .myClass:after becomes .myClass::after, so we need to strip the extra one out. + if (pseudo) { + a.push(cs.style); + } else { + return cs.style; + } + } + } + } + + return a; + }, + register: _initCore +}; +_getGSAP() && gsap.registerPlugin(CSSRulePlugin); +export { CSSRulePlugin as default }; \ No newline at end of file diff --git a/dist/lib/greensock/CustomBounce.js b/dist/lib/greensock/CustomBounce.js new file mode 100644 index 00000000..856d7e14 --- /dev/null +++ b/dist/lib/greensock/CustomBounce.js @@ -0,0 +1,166 @@ +/*! + * CustomBounce 3.11.0 + * https://greensock.com + * + * @license Copyright 2008-2022, GreenSock. All rights reserved. + * Subject to the terms at https://greensock.com/standard-license or for + * Club GreenSock members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ + +/* eslint-disable */ +var gsap, + _coreInitted, + createCustomEase, + _getGSAP = function _getGSAP() { + return gsap || typeof window !== "undefined" && (gsap = window.gsap) && gsap.registerPlugin && gsap; +}, + _initCore = function _initCore(required) { + gsap = _getGSAP(); + createCustomEase = gsap && gsap.parseEase("_CE"); + + if (createCustomEase) { + _coreInitted = 1; + + gsap.parseEase("bounce").config = function (vars) { + return typeof vars === "object" ? _create("", vars) : _create("bounce(" + vars + ")", { + strength: +vars + }); + }; + } else { + required && console.warn("Please gsap.registerPlugin(CustomEase, CustomBounce)"); + } +}, + _normalizeX = function _normalizeX(a) { + //scales all the x values in an array [x, y, x, y...] AND rounds them to the closest hundredth (decimal) + var l = a.length, + s = 1 / a[l - 2], + rnd = 1000, + i; + + for (i = 2; i < l; i += 2) { + a[i] = ~~(a[i] * s * rnd) / rnd; + } + + a[l - 2] = 1; //in case there are any rounding errors. x should always end at 1. +}, + _bonusValidated = 1, + //CustomBounce +_create = function _create(id, vars) { + if (!_coreInitted) { + _initCore(1); + } + + vars = vars || {}; + + if (_bonusValidated) { + var max = 0.999, + decay = Math.min(max, vars.strength || 0.7), + // Math.min(0.999, 1 - 0.3 / (vars.strength || 1)), + decayX = decay, + gap = (vars.squash || 0) / 100, + originalGap = gap, + slope = 1 / 0.03, + w = 0.2, + h = 1, + prevX = 0.1, + path = [0, 0, 0.07, 0, 0.1, 1, 0.1, 1], + squashPath = [0, 0, 0, 0, 0.1, 0, 0.1, 0], + cp1, + cp2, + x, + y, + i, + nextX, + squishMagnitude; + + for (i = 0; i < 200; i++) { + w *= decayX * ((decayX + 1) / 2); + h *= decay * decay; + nextX = prevX + w; + x = prevX + w * 0.49; + y = 1 - h; + cp1 = prevX + h / slope; + cp2 = x + (x - cp1) * 0.8; + + if (gap) { + prevX += gap; + cp1 += gap; + x += gap; + cp2 += gap; + nextX += gap; + squishMagnitude = gap / originalGap; + squashPath.push(prevX - gap, 0, prevX - gap, squishMagnitude, prevX - gap / 2, squishMagnitude, //center peak anchor + prevX, squishMagnitude, prevX, 0, prevX, 0, //base anchor + prevX, squishMagnitude * -0.6, prevX + (nextX - prevX) / 6, 0, nextX, 0); + path.push(prevX - gap, 1, prevX, 1, prevX, 1); + gap *= decay * decay; + } + + path.push(prevX, 1, cp1, y, x, y, cp2, y, nextX, 1, nextX, 1); + decay *= 0.95; + slope = h / (nextX - cp2); + prevX = nextX; + + if (y > max) { + break; + } + } + + if (vars.endAtStart && vars.endAtStart !== "false") { + x = -0.1; + path.unshift(x, 1, x, 1, -0.07, 0); + + if (originalGap) { + gap = originalGap * 2.5; //make the initial anticipation squash longer (more realistic) + + x -= gap; + path.unshift(x, 1, x, 1, x, 1); + squashPath.splice(0, 6); + squashPath.unshift(x, 0, x, 0, x, 1, x + gap / 2, 1, x + gap, 1, x + gap, 0, x + gap, 0, x + gap, -0.6, x + gap + 0.033, 0); + + for (i = 0; i < squashPath.length; i += 2) { + squashPath[i] -= x; + } + } + + for (i = 0; i < path.length; i += 2) { + path[i] -= x; + path[i + 1] = 1 - path[i + 1]; + } + } + + if (gap) { + _normalizeX(squashPath); + + squashPath[2] = "C" + squashPath[2]; + createCustomEase(vars.squashID || id + "-squash", "M" + squashPath.join(",")); + } + + _normalizeX(path); + + path[2] = "C" + path[2]; + return createCustomEase(id, "M" + path.join(",")); + } +}; + +export var CustomBounce = /*#__PURE__*/function () { + function CustomBounce(id, vars) { + this.ease = _create(id, vars); + } + + CustomBounce.create = function create(id, vars) { + return _create(id, vars); + }; + + CustomBounce.register = function register(core) { + gsap = core; + + _initCore(); + }; + + return CustomBounce; +}(); +_getGSAP() && gsap.registerPlugin(CustomBounce); +CustomBounce.version = "3.11.0"; +export { CustomBounce as default }; \ No newline at end of file diff --git a/dist/lib/greensock/CustomEase.js b/dist/lib/greensock/CustomEase.js new file mode 100644 index 00000000..1ea97952 --- /dev/null +++ b/dist/lib/greensock/CustomEase.js @@ -0,0 +1,371 @@ +/*! + * CustomEase 3.11.0 + * https://greensock.com + * + * @license Copyright 2008-2022, GreenSock. All rights reserved. + * Subject to the terms at https://greensock.com/standard-license or for + * Club GreenSock members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ + +/* eslint-disable */ +import { stringToRawPath, rawPathToString, transformRawPath } from "./utils/paths.js"; + +var gsap, + _coreInitted, + _getGSAP = function _getGSAP() { + return gsap || typeof window !== "undefined" && (gsap = window.gsap) && gsap.registerPlugin && gsap; +}, + _initCore = function _initCore() { + gsap = _getGSAP(); + + if (gsap) { + gsap.registerEase("_CE", CustomEase.create); + _coreInitted = 1; + } else { + console.warn("Please gsap.registerPlugin(CustomEase)"); + } +}, + _bigNum = 1e20, + _round = function _round(value) { + return ~~(value * 1000 + (value < 0 ? -.5 : .5)) / 1000; +}, + _bonusValidated = 1, + //CustomEase +_numExp = /[-+=\.]*\d+[\.e\-\+]*\d*[e\-\+]*\d*/gi, + //finds any numbers, including ones that start with += or -=, negative numbers, and ones in scientific notation like 1e-8. +_needsParsingExp = /[cLlsSaAhHvVtTqQ]/g, + _findMinimum = function _findMinimum(values) { + var l = values.length, + min = _bigNum, + i; + + for (i = 1; i < l; i += 6) { + +values[i] < min && (min = +values[i]); + } + + return min; +}, + //takes all the points and translates/scales them so that the x starts at 0 and ends at 1. +_normalize = function _normalize(values, height, originY) { + if (!originY && originY !== 0) { + originY = Math.max(+values[values.length - 1], +values[1]); + } + + var tx = +values[0] * -1, + ty = -originY, + l = values.length, + sx = 1 / (+values[l - 2] + tx), + sy = -height || (Math.abs(+values[l - 1] - +values[1]) < 0.01 * (+values[l - 2] - +values[0]) ? _findMinimum(values) + ty : +values[l - 1] + ty), + i; + + if (sy) { + //typically y ends at 1 (so that the end values are reached) + sy = 1 / sy; + } else { + //in case the ease returns to its beginning value, scale everything proportionally + sy = -sx; + } + + for (i = 0; i < l; i += 2) { + values[i] = (+values[i] + tx) * sx; + values[i + 1] = (+values[i + 1] + ty) * sy; + } +}, + //note that this function returns point objects like {x, y} rather than working with segments which are arrays with alternating x, y values as in the similar function in paths.js +_bezierToPoints = function _bezierToPoints(x1, y1, x2, y2, x3, y3, x4, y4, threshold, points, index) { + var x12 = (x1 + x2) / 2, + y12 = (y1 + y2) / 2, + x23 = (x2 + x3) / 2, + y23 = (y2 + y3) / 2, + x34 = (x3 + x4) / 2, + y34 = (y3 + y4) / 2, + x123 = (x12 + x23) / 2, + y123 = (y12 + y23) / 2, + x234 = (x23 + x34) / 2, + y234 = (y23 + y34) / 2, + x1234 = (x123 + x234) / 2, + y1234 = (y123 + y234) / 2, + dx = x4 - x1, + dy = y4 - y1, + d2 = Math.abs((x2 - x4) * dy - (y2 - y4) * dx), + d3 = Math.abs((x3 - x4) * dy - (y3 - y4) * dx), + length; + + if (!points) { + points = [{ + x: x1, + y: y1 + }, { + x: x4, + y: y4 + }]; + index = 1; + } + + points.splice(index || points.length - 1, 0, { + x: x1234, + y: y1234 + }); + + if ((d2 + d3) * (d2 + d3) > threshold * (dx * dx + dy * dy)) { + length = points.length; + + _bezierToPoints(x1, y1, x12, y12, x123, y123, x1234, y1234, threshold, points, index); + + _bezierToPoints(x1234, y1234, x234, y234, x34, y34, x4, y4, threshold, points, index + 1 + (points.length - length)); + } + + return points; +}; + +export var CustomEase = /*#__PURE__*/function () { + function CustomEase(id, data, config) { + _coreInitted || _initCore(); + this.id = id; + _bonusValidated && this.setData(data, config); + } + + var _proto = CustomEase.prototype; + + _proto.setData = function setData(data, config) { + config = config || {}; + data = data || "0,0,1,1"; + var values = data.match(_numExp), + closest = 1, + points = [], + lookup = [], + precision = config.precision || 1, + fast = precision <= 1, + l, + a1, + a2, + i, + inc, + j, + point, + prevPoint, + p; + this.data = data; + + if (_needsParsingExp.test(data) || ~data.indexOf("M") && data.indexOf("C") < 0) { + values = stringToRawPath(data)[0]; + } + + l = values.length; + + if (l === 4) { + values.unshift(0, 0); + values.push(1, 1); + l = 8; + } else if ((l - 2) % 6) { + throw "Invalid CustomEase"; + } + + if (+values[0] !== 0 || +values[l - 2] !== 1) { + _normalize(values, config.height, config.originY); + } + + this.segment = values; + + for (i = 2; i < l; i += 6) { + a1 = { + x: +values[i - 2], + y: +values[i - 1] + }; + a2 = { + x: +values[i + 4], + y: +values[i + 5] + }; + points.push(a1, a2); + + _bezierToPoints(a1.x, a1.y, +values[i], +values[i + 1], +values[i + 2], +values[i + 3], a2.x, a2.y, 1 / (precision * 200000), points, points.length - 1); + } + + l = points.length; + + for (i = 0; i < l; i++) { + point = points[i]; + prevPoint = points[i - 1] || point; + + if ((point.x > prevPoint.x || prevPoint.y !== point.y && prevPoint.x === point.x || point === prevPoint) && point.x <= 1) { + //if a point goes BACKWARD in time or is a duplicate, just drop it. Also it shouldn't go past 1 on the x axis, as could happen in a string like "M0,0 C0,0 0.12,0.68 0.18,0.788 0.195,0.845 0.308,1 0.32,1 0.403,1.005 0.398,1 0.5,1 0.602,1 0.816,1.005 0.9,1 0.91,1 0.948,0.69 0.962,0.615 1.003,0.376 1,0 1,0". + prevPoint.cx = point.x - prevPoint.x; //change in x between this point and the next point (performance optimization) + + prevPoint.cy = point.y - prevPoint.y; + prevPoint.n = point; + prevPoint.nx = point.x; //next point's x value (performance optimization, making lookups faster in getRatio()). Remember, the lookup will always land on a spot where it's either this point or the very next one (never beyond that) + + if (fast && i > 1 && Math.abs(prevPoint.cy / prevPoint.cx - points[i - 2].cy / points[i - 2].cx) > 2) { + //if there's a sudden change in direction, prioritize accuracy over speed. Like a bounce ease - you don't want to risk the sampling chunks landing on each side of the bounce anchor and having it clipped off. + fast = 0; + } + + if (prevPoint.cx < closest) { + if (!prevPoint.cx) { + prevPoint.cx = 0.001; //avoids math problems in getRatio() (dividing by zero) + + if (i === l - 1) { + //in case the final segment goes vertical RIGHT at the end, make sure we end at the end. + prevPoint.x -= 0.001; + closest = Math.min(closest, 0.001); + fast = 0; + } + } else { + closest = prevPoint.cx; + } + } + } else { + points.splice(i--, 1); + l--; + } + } + + l = 1 / closest + 1 | 0; + inc = 1 / l; + j = 0; + point = points[0]; + + if (fast) { + for (i = 0; i < l; i++) { + //for fastest lookups, we just sample along the path at equal x (time) distance. Uses more memory and is slightly less accurate for anchors that don't land on the sampling points, but for the vast majority of eases it's excellent (and fast). + p = i * inc; + + if (point.nx < p) { + point = points[++j]; + } + + a1 = point.y + (p - point.x) / point.cx * point.cy; + lookup[i] = { + x: p, + cx: inc, + y: a1, + cy: 0, + nx: 9 + }; + + if (i) { + lookup[i - 1].cy = a1 - lookup[i - 1].y; + } + } + + lookup[l - 1].cy = points[points.length - 1].y - a1; + } else { + //this option is more accurate, ensuring that EVERY anchor is hit perfectly. Clipping across a bounce, for example, would never happen. + for (i = 0; i < l; i++) { + //build a lookup table based on the smallest distance so that we can instantly find the appropriate point (well, it'll either be that point or the very next one). We'll look up based on the linear progress. So it's it's 0.5 and the lookup table has 100 elements, it'd be like lookup[Math.floor(0.5 * 100)] + if (point.nx < i * inc) { + point = points[++j]; + } + + lookup[i] = point; + } + + if (j < points.length - 1) { + lookup[i - 1] = points[points.length - 2]; + } + } //this._calcEnd = (points[points.length-1].y !== 1 || points[0].y !== 0); //ensures that we don't run into floating point errors. As long as we're starting at 0 and ending at 1, tell GSAP to skip the final calculation and use 0/1 as the factor. + + + this.ease = function (p) { + var point = lookup[p * l | 0] || lookup[l - 1]; + + if (point.nx < p) { + point = point.n; + } + + return point.y + (p - point.x) / point.cx * point.cy; + }; + + this.ease.custom = this; + this.id && gsap && gsap.registerEase(this.id, this.ease); + return this; + }; + + _proto.getSVGData = function getSVGData(config) { + return CustomEase.getSVGData(this, config); + }; + + CustomEase.create = function create(id, data, config) { + return new CustomEase(id, data, config).ease; + }; + + CustomEase.register = function register(core) { + gsap = core; + + _initCore(); + }; + + CustomEase.get = function get(id) { + return gsap.parseEase(id); + }; + + CustomEase.getSVGData = function getSVGData(ease, config) { + config = config || {}; + var width = config.width || 100, + height = config.height || 100, + x = config.x || 0, + y = (config.y || 0) + height, + e = gsap.utils.toArray(config.path)[0], + a, + slope, + i, + inc, + tx, + ty, + precision, + threshold, + prevX, + prevY; + + if (config.invert) { + height = -height; + y = 0; + } + + if (typeof ease === "string") { + ease = gsap.parseEase(ease); + } + + if (ease.custom) { + ease = ease.custom; + } + + if (ease instanceof CustomEase) { + a = rawPathToString(transformRawPath([ease.segment], width, 0, 0, -height, x, y)); + } else { + a = [x, y]; + precision = Math.max(5, (config.precision || 1) * 200); + inc = 1 / precision; + precision += 2; + threshold = 5 / precision; + prevX = _round(x + inc * width); + prevY = _round(y + ease(inc) * -height); + slope = (prevY - y) / (prevX - x); + + for (i = 2; i < precision; i++) { + tx = _round(x + i * inc * width); + ty = _round(y + ease(i * inc) * -height); + + if (Math.abs((ty - prevY) / (tx - prevX) - slope) > threshold || i === precision - 1) { + //only add points when the slope changes beyond the threshold + a.push(prevX, prevY); + slope = (ty - prevY) / (tx - prevX); + } + + prevX = tx; + prevY = ty; + } + + a = "M" + a.join(","); + } + + e && e.setAttribute("d", a); + return a; + }; + + return CustomEase; +}(); +_getGSAP() && gsap.registerPlugin(CustomEase); +CustomEase.version = "3.11.0"; +export { CustomEase as default }; \ No newline at end of file diff --git a/dist/lib/greensock/CustomWiggle.js b/dist/lib/greensock/CustomWiggle.js new file mode 100644 index 00000000..ee3c56e3 --- /dev/null +++ b/dist/lib/greensock/CustomWiggle.js @@ -0,0 +1,162 @@ +/*! + * CustomWiggle 3.11.0 + * https://greensock.com + * + * @license Copyright 2008-2022, GreenSock. All rights reserved. + * Subject to the terms at https://greensock.com/standard-license or for + * Club GreenSock members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com +*/ + +/* eslint-disable */ +var gsap, + _coreInitted, + createCustomEase, + _getGSAP = function _getGSAP() { + return gsap || typeof window !== "undefined" && (gsap = window.gsap) && gsap.registerPlugin && gsap; +}, + _eases = { + easeOut: "M0,1,C0.7,1,0.6,0,1,0", + easeInOut: "M0,0,C0.1,0,0.24,1,0.444,1,0.644,1,0.6,0,1,0", + anticipate: "M0,0,C0,0.222,0.024,0.386,0,0.4,0.18,0.455,0.65,0.646,0.7,0.67,0.9,0.76,1,0.846,1,1", + uniform: "M0,0,C0,0.95,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0" +}, + _linearEase = function _linearEase(p) { + return p; +}, + _initCore = function _initCore(required) { + if (!_coreInitted) { + gsap = _getGSAP(); + createCustomEase = gsap && gsap.parseEase("_CE"); + + if (createCustomEase) { + for (var p in _eases) { + _eases[p] = createCustomEase("", _eases[p]); + } + + _coreInitted = 1; + + _create("wiggle").config = function (vars) { + return typeof vars === "object" ? _create("", vars) : _create("wiggle(" + vars + ")", { + wiggles: +vars + }); + }; + } else { + required && console.warn("Please gsap.registerPlugin(CustomEase, CustomWiggle)"); + } + } +}, + _parseEase = function _parseEase(ease, invertNonCustomEases) { + if (typeof ease !== "function") { + ease = gsap.parseEase(ease) || createCustomEase("", ease); + } + + return ease.custom || !invertNonCustomEases ? ease : function (p) { + return 1 - ease(p); + }; +}, + _bonusValidated = 1, + //CustomWiggle +_create = function _create(id, vars) { + if (!_coreInitted) { + _initCore(1); + } + + vars = vars || {}; + var wiggles = (vars.wiggles || 10) | 0, + inc = 1 / wiggles, + x = inc / 2, + anticipate = vars.type === "anticipate", + yEase = _eases[vars.type] || _eases.easeOut, + xEase = _linearEase, + rnd = 1000, + nextX, + nextY, + angle, + handleX, + handleY, + easedX, + y, + path, + i; + + if (_bonusValidated) { + if (anticipate) { + //the anticipate ease is actually applied on the x-axis (timing) and uses easeOut for amplitude. + xEase = yEase; + yEase = _eases.easeOut; + } + + if (vars.timingEase) { + xEase = _parseEase(vars.timingEase); + } + + if (vars.amplitudeEase) { + yEase = _parseEase(vars.amplitudeEase, true); + } + + easedX = xEase(x); + y = anticipate ? -yEase(x) : yEase(x); + path = [0, 0, easedX / 4, 0, easedX / 2, y, easedX, y]; + + if (vars.type === "random") { + //if we just select random values on the y-axis and plug them into the "normal" algorithm, since the control points are always straight horizontal, it creates a bit of a slowdown at each anchor which just didn't seem as desirable, so we switched to an algorithm that bends the control points to be more in line with their context. + path.length = 4; + nextX = xEase(inc); + nextY = Math.random() * 2 - 1; + + for (i = 2; i < wiggles; i++) { + x = nextX; + y = nextY; + nextX = xEase(inc * i); + nextY = Math.random() * 2 - 1; + angle = Math.atan2(nextY - path[path.length - 3], nextX - path[path.length - 4]); + handleX = Math.cos(angle) * inc; + handleY = Math.sin(angle) * inc; + path.push(x - handleX, y - handleY, x, y, x + handleX, y + handleY); + } + + path.push(nextX, 0, 1, 0); + } else { + for (i = 1; i < wiggles; i++) { + path.push(xEase(x + inc / 2), y); + x += inc; + y = (y > 0 ? -1 : 1) * yEase(i * inc); + easedX = xEase(x); + path.push(xEase(x - inc / 2), y, easedX, y); + } + + path.push(xEase(x + inc / 4), y, xEase(x + inc / 4), 0, 1, 0); + } + + i = path.length; + + while (--i > -1) { + path[i] = ~~(path[i] * rnd) / rnd; //round values to avoid odd strings for super tiny values + } + + path[2] = "C" + path[2]; + return createCustomEase(id, "M" + path.join(",")); + } +}; + +export var CustomWiggle = /*#__PURE__*/function () { + function CustomWiggle(id, vars) { + this.ease = _create(id, vars); + } + + CustomWiggle.create = function create(id, vars) { + return _create(id, vars); + }; + + CustomWiggle.register = function register(core) { + gsap = core; + + _initCore(); + }; + + return CustomWiggle; +}(); +_getGSAP() && gsap.registerPlugin(CustomWiggle); +CustomWiggle.version = "3.11.0"; +export { CustomWiggle as default }; \ No newline at end of file diff --git a/dist/lib/greensock/Draggable.js b/dist/lib/greensock/Draggable.js new file mode 100644 index 00000000..6826519c --- /dev/null +++ b/dist/lib/greensock/Draggable.js @@ -0,0 +1,2670 @@ +function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } + +function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } + +/*! + * Draggable 3.11.0 + * https://greensock.com + * + * @license Copyright 2008-2022, GreenSock. All rights reserved. + * Subject to the terms at https://greensock.com/standard-license or for + * Club GreenSock members, the agreement issued with that membership. + * @author: Jack Doyle, jack@greensock.com + */ + +/* eslint-disable */ +import { getGlobalMatrix, Matrix2D } from "./utils/matrix.js"; + +var gsap, + _win, + _doc, + _docElement, + _body, + _tempDiv, + _placeholderDiv, + _coreInitted, + _checkPrefix, + _toArray, + _supportsPassive, + _isTouchDevice, + _touchEventLookup, + _dragCount, + _isMultiTouching, + _isAndroid, + InertiaPlugin, + _defaultCursor, + _supportsPointer, + _windowExists = function _windowExists() { + return typeof window !== "undefined"; +}, + _getGSAP = function _getGSAP() { + return gsap || _windowExists() && (gsap = window.gsap) && gsap.registerPlugin && gsap; +}, + _isFunction = function _isFunction(value) { + return typeof value === "function"; +}, + _isObject = function _isObject(value) { + return typeof value === "object"; +}, + _isUndefined = function _isUndefined(value) { + return typeof value === "undefined"; +}, + _emptyFunc = function _emptyFunc() { + return false; +}, + _transformProp = "transform", + _transformOriginProp = "transformOrigin", + _round = function _round(value) { + return Math.round(value * 10000) / 10000; +}, + _isArray = Array.isArray, + _createElement = function _createElement(type, ns) { + var e = _doc.createElementNS ? _doc.createElementNS((ns || "http://www.w3.org/1999/xhtml").replace(/^https/, "http"), type) : _doc.createElement(type); //some servers swap in https for http in the namespace which can break things, making "style" inaccessible. + + return e.style ? e : _doc.createElement(type); //some environments won't allow access to the element's style when created with a namespace in which case we default to the standard createElement() to work around the issue. Also note that when GSAP is embedded directly inside an SVG file, createElement() won't allow access to the style object in Firefox (see https://greensock.com/forums/topic/20215-problem-using-tweenmax-in-standalone-self-containing-svg-file-err-cannot-set-property-csstext-of-undefined/). +}, + _RAD2DEG = 180 / Math.PI, + _bigNum = 1e20, + _identityMatrix = new Matrix2D(), + _getTime = Date.now || function () { + return new Date().getTime(); +}, + _renderQueue = [], + _lookup = {}, + //when a Draggable is created, the target gets a unique _gsDragID property that allows gets associated with the Draggable instance for quick lookups in Draggable.get(). This avoids circular references that could cause gc problems. +_lookupCount = 0, + _clickableTagExp = /^(?:a|input|textarea|button|select)$/i, + _lastDragTime = 0, + _temp1 = {}, + // a simple object we reuse and populate (usually x/y properties) to conserve memory and improve performance. +_windowProxy = {}, + //memory/performance optimization - we reuse this object during autoScroll to store window-related bounds/offsets. +_copy = function _copy(obj, factor) { + var copy = {}, + p; + + for (p in obj) { + copy[p] = factor ? obj[p] * factor : obj[p]; + } + + return copy; +}, + _extend = function _extend(obj, defaults) { + for (var p in defaults) { + if (!(p in obj)) { + obj[p] = defaults[p]; + } + } + + return obj; +}, + _setTouchActionForAllDescendants = function _setTouchActionForAllDescendants(elements, value) { + var i = elements.length, + children; + + while (i--) { + value ? elements[i].style.touchAction = value : elements[i].style.removeProperty("touch-action"); + children = elements[i].children; + children && children.length && _setTouchActionForAllDescendants(children, value); + } +}, + _renderQueueTick = function _renderQueueTick() { + return _renderQueue.forEach(function (func) { + return func(); + }); +}, + _addToRenderQueue = function _addToRenderQueue(func) { + _renderQueue.push(func); + + if (_renderQueue.length === 1) { + gsap.ticker.add(_renderQueueTick); + } +}, + _renderQueueTimeout = function _renderQueueTimeout() { + return !_renderQueue.length && gsap.ticker.remove(_renderQueueTick); +}, + _removeFromRenderQueue = function _removeFromRenderQueue(func) { + var i = _renderQueue.length; + + while (i--) { + if (_renderQueue[i] === func) { + _renderQueue.splice(i, 1); + } + } + + gsap.to(_renderQueueTimeout, { + overwrite: true, + delay: 15, + duration: 0, + onComplete: _renderQueueTimeout, + data: "_draggable" + }); //remove the "tick" listener only after the render queue is empty for 15 seconds (to improve performance). Adding/removing it constantly for every click/touch wouldn't deliver optimal speed, and we also don't want the ticker to keep calling the render method when things are idle for long periods of time (we want to improve battery life on mobile devices). +}, + _setDefaults = function _setDefaults(obj, defaults) { + for (var p in defaults) { + if (!(p in obj)) { + obj[p] = defaults[p]; + } + } + + return obj; +}, + _addListener = function _addListener(element, type, func, capture) { + if (element.addEventListener) { + var touchType = _touchEventLookup[type]; + capture = capture || (_supportsPassive ? { + passive: false + } : null); + element.addEventListener(touchType || type, func, capture); + touchType && type !== touchType && element.addEventListener(type, func, capture); //some browsers actually support both, so must we. But pointer events cover all. + } +}, + _removeListener = function _removeListener(element, type, func) { + if (element.removeEventListener) { + var touchType = _touchEventLookup[type]; + element.removeEventListener(touchType || type, func); + touchType && type !== touchType && element.removeEventListener(type, func); + } +}, + _preventDefault = function _preventDefault(event) { + event.preventDefault && event.preventDefault(); + event.preventManipulation && event.preventManipulation(); //for some Microsoft browsers +}, + _hasTouchID = function _hasTouchID(list, ID) { + var i = list.length; + + while (i--) { + if (list[i].identifier === ID) { + return true; + } + } +}, + _onMultiTouchDocumentEnd = function _onMultiTouchDocumentEnd(event) { + _isMultiTouching = event.touches && _dragCount < event.touches.length; + + _removeListener(event.target, "touchend", _onMultiTouchDocumentEnd); +}, + _onMultiTouchDocument = function _onMultiTouchDocument(event) { + _isMultiTouching = event.touches && _dragCount < event.touches.length; + + _addListener(event.target, "touchend", _onMultiTouchDocumentEnd); +}, + _getDocScrollTop = function _getDocScrollTop(doc) { + return _win.pageYOffset || doc.scrollTop || doc.documentElement.scrollTop || doc.body.scrollTop || 0; +}, + _getDocScrollLeft = function _getDocScrollLeft(doc) { + return _win.pageXOffset || doc.scrollLeft || doc.documentElement.scrollLeft || doc.body.scrollLeft || 0; +}, + _addScrollListener = function _addScrollListener(e, callback) { + _addListener(e, "scroll", callback); + + if (!_isRoot(e.parentNode)) { + _addScrollListener(e.parentNode, callback); + } +}, + _removeScrollListener = function _removeScrollListener(e, callback) { + _removeListener(e, "scroll", callback); + + if (!_isRoot(e.parentNode)) { + _removeScrollListener(e.parentNode, callback); + } +}, + _isRoot = function _isRoot(e) { + return !!(!e || e === _docElement || e.nodeType === 9 || e === _doc.body || e === _win || !e.nodeType || !e.parentNode); +}, + _getMaxScroll = function _getMaxScroll(element, axis) { + var dim = axis === "x" ? "Width" : "Height", + scroll = "scroll" + dim, + client = "client" + dim; + return Math.max(0, _isRoot(element) ? Math.max(_docElement[scroll], _body[scroll]) - (_win["inner" + dim] || _docElement[client] || _body[client]) : element[scroll] - element[client]); +}, + _recordMaxScrolls = function _recordMaxScrolls(e, skipCurrent) { + //records _gsMaxScrollX and _gsMaxScrollY properties for the element and all ancestors up the chain so that we can cap it, otherwise dragging beyond the edges with autoScroll on can endlessly scroll. + var x = _getMaxScroll(e, "x"), + y = _getMaxScroll(e, "y"); + + if (_isRoot(e)) { + e = _windowProxy; + } else { + _recordMaxScrolls(e.parentNode, skipCurrent); + } + + e._gsMaxScrollX = x; + e._gsMaxScrollY = y; + + if (!skipCurrent) { + e._gsScrollX = e.scrollLeft || 0; + e._gsScrollY = e.scrollTop || 0; + } +}, + _setStyle = function _setStyle(element, property, value) { + var style = element.style; + + if (!style) { + return; + } + + if (_isUndefined(style[property])) { + property = _checkPrefix(property, element) || property; + } + + if (value == null) { + style.removeProperty && style.removeProperty(property.replace(/([A-Z])/g, "-$1").toLowerCase()); + } else { + style[property] = value; + } +}, + _getComputedStyle = function _getComputedStyle(element) { + return _win.getComputedStyle(element instanceof Element ? element : element.host || (element.parentNode || {}).host || element); +}, + //the "host" stuff helps to accommodate ShadowDom objects. +_tempRect = {}, + //reuse to reduce garbage collection tasks +_parseRect = function _parseRect(e) { + //accepts a DOM element, a mouse event, or a rectangle object and returns the corresponding rectangle with left, right, width, height, top, and bottom properties + if (e === _win) { + _tempRect.left = _tempRect.top = 0; + _tempRect.width = _tempRect.right = _docElement.clientWidth || e.innerWidth || _body.clientWidth || 0; + _tempRect.height = _tempRect.bottom = (e.innerHeight || 0) - 20 < _docElement.clientHeight ? _docElement.clientHeight : e.innerHeight || _body.clientHeight || 0; + return _tempRect; + } + + var doc = e.ownerDocument || _doc, + r = !_isUndefined(e.pageX) ? { + left: e.pageX - _getDocScrollLeft(doc), + top: e.pageY - _getDocScrollTop(doc), + right: e.pageX - _getDocScrollLeft(doc) + 1, + bottom: e.pageY - _getDocScrollTop(doc) + 1 + } : !e.nodeType && !_isUndefined(e.left) && !_isUndefined(e.top) ? e : _toArray(e)[0].getBoundingClientRect(); + + if (_isUndefined(r.right) && !_isUndefined(r.width)) { + r.right = r.left + r.width; + r.bottom = r.top + r.height; + } else if (_isUndefined(r.width)) { + //some browsers don't include width and height properties. We can't just set them directly on r because some browsers throw errors, so create a new generic object. + r = { + width: r.right - r.left, + height: r.bottom - r.top, + right: r.right, + left: r.left, + bottom: r.bottom, + top: r.top + }; + } + + return r; +}, + _dispatchEvent = function _dispatchEvent(target, type, callbackName) { + var vars = target.vars, + callback = vars[callbackName], + listeners = target._listeners[type], + result; + + if (_isFunction(callback)) { + result = callback.apply(vars.callbackScope || target, vars[callbackName + "Params"] || [target.pointerEvent]); + } + + if (listeners && target.dispatchEvent(type) === false) { + result = false; + } + + return result; +}, + _getBounds = function _getBounds(target, context) { + //accepts any of the following: a DOM element, jQuery object, selector text, or an object defining bounds as {top, left, width, height} or {minX, maxX, minY, maxY}. Returns an object with left, top, width, and height properties. + var e = _toArray(target)[0], + top, + left, + offset; + + if (!e.nodeType && e !== _win) { + if (!_isUndefined(target.left)) { + offset = { + x: 0, + y: 0 + }; //_getOffsetTransformOrigin(context); //the bounds should be relative to the origin + + return { + left: target.left - offset.x, + top: target.top - offset.y, + width: target.width, + height: target.height + }; + } + + left = target.min || target.minX || target.minRotation || 0; + top = target.min || target.minY || 0; + return { + left: left, + top: top, + width: (target.max || target.maxX || target.maxRotation || 0) - left, + height: (target.max || target.maxY || 0) - top + }; + } + + return _getElementBounds(e, context); +}, + _point1 = {}, + //we reuse to minimize garbage collection tasks. +_getElementBounds = function _getElementBounds(element, context) { + context = _toArray(context)[0]; + var isSVG = element.getBBox && element.ownerSVGElement, + doc = element.ownerDocument || _doc, + left, + right, + top, + bottom, + matrix, + p1, + p2, + p3, + p4, + bbox, + width, + height, + cs; + + if (element === _win) { + top = _getDocScrollTop(doc); + left = _getDocScrollLeft(doc); + right = left + (doc.documentElement.clientWidth || element.innerWidth || doc.body.clientWidth || 0); + bottom = top + ((element.innerHeight || 0) - 20 < doc.documentElement.clientHeight ? doc.documentElement.clientHeight : element.innerHeight || doc.body.clientHeight || 0); //some browsers (like Firefox) ignore absolutely positioned elements, and collapse the height of the documentElement, so it could be 8px, for example, if you have just an absolutely positioned div. In that case, we use the innerHeight to resolve this. + } else if (context === _win || _isUndefined(context)) { + return element.getBoundingClientRect(); + } else { + left = top = 0; + + if (isSVG) { + bbox = element.getBBox(); + width = bbox.width; + height = bbox.height; + } else { + if (element.viewBox && (bbox = element.viewBox.baseVal)) { + left = bbox.x || 0; + top = bbox.y || 0; + width = bbox.width; + height = bbox.height; + } + + if (!width) { + cs = _getComputedStyle(element); + bbox = cs.boxSizing === "border-box"; + width = (parseFloat(cs.width) || element.clientWidth || 0) + (bbox ? 0 : parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth)); + height = (parseFloat(cs.height) || element.clientHeight || 0) + (bbox ? 0 : parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth)); + } + } + + right = width; + bottom = height; + } + + if (element === context) { + return { + left: left, + top: top, + width: right - left, + height: bottom - top + }; + } + + matrix = getGlobalMatrix(context, true).multiply(getGlobalMatrix(element)); + p1 = matrix.apply({ + x: left, + y: top + }); + p2 = matrix.apply({ + x: right, + y: top + }); + p3 = matrix.apply({ + x: right, + y: bottom + }); + p4 = matrix.apply({ + x: left, + y: bottom + }); + left = Math.min(p1.x, p2.x, p3.x, p4.x); + top = Math.min(p1.y, p2.y, p3.y, p4.y); + return { + left: left, + top: top, + width: Math.max(p1.x, p2.x, p3.x, p4.x) - left, + height: Math.max(p1.y, p2.y, p3.y, p4.y) - top + }; +}, + _parseInertia = function _parseInertia(draggable, snap, max, min, factor, forceZeroVelocity) { + var vars = {}, + a, + i, + l; + + if (snap) { + if (factor !== 1 && snap instanceof Array) { + //some data must be altered to make sense, like if the user passes in an array of rotational values in degrees, we must convert it to radians. Or for scrollLeft and scrollTop, we invert the values. + vars.end = a = []; + l = snap.length; + + if (_isObject(snap[0])) { + //if the array is populated with objects, like points ({x:100, y:200}), make copies before multiplying by the factor, otherwise we'll mess up the originals and the user may reuse it elsewhere. + for (i = 0; i < l; i++) { + a[i] = _copy(snap[i], factor); + } + } else { + for (i = 0; i < l; i++) { + a[i] = snap[i] * factor; + } + } + + max += 1.1; //allow 1.1 pixels of wiggle room when snapping in order to work around some browser inconsistencies in the way bounds are reported which can make them roughly a pixel off. For example, if "snap:[-$('#menu').width(), 0]" was defined and #menu had a wrapper that was used as the bounds, some browsers would be one pixel off, making the minimum -752 for example when snap was [-753,0], thus instead of snapping to -753, it would snap to 0 since -753 was below the minimum. + + min -= 1.1; + } else if (_isFunction(snap)) { + vars.end = function (value) { + var result = snap.call(draggable, value), + copy, + p; + + if (factor !== 1) { + if (_isObject(result)) { + copy = {}; + + for (p in result) { + copy[p] = result[p] * factor; + } + + result = copy; + } else { + result *= factor; + } + } + + return result; //we need to ensure that we can scope the function call to the Draggable instance itself so that users can access important values like maxX, minX, maxY, minY, x, and y from within that function. + }; + } else { + vars.end = snap; + } + } + + if (max || max === 0) { + vars.max = max; + } + + if (min || min === 0) { + vars.min = min; + } + + if (forceZeroVelocity) { + vars.velocity = 0; + } + + return vars; +}, + _isClickable = function _isClickable(element) { + //sometimes it's convenient to mark an element as clickable by adding a data-clickable="true" attribute (in which case we won't preventDefault() the mouse/touch event). This method checks if the element is an , , or