auto-champion-select 1.8.6 → 1.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +17 -17
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -4,19 +4,19 @@
4
4
  * @name auto-champion-select
5
5
  * @link https://github.com/controlado/auto-champion-select#readme
6
6
  * @description Pick or ban automatically! 🐧
7
- * @version 1.8.6
7
+ * @version 1.8.7
8
8
  * @license GPL-3.0-or-later
9
9
  */
10
- import{request as f,sleep as g,linkEndpoint as N}from"https://cdn.jsdelivr.net/npm/balaclava-utils@latest";const ut="1.8.6",pt={enabled:!1},mt={enabled:!1,force:!1,champions:[432,235],positionsByChampionId:{235:["BOTTOM","UTILITY"],432:["UTILITY"]}},ft={enabled:!1,force:!1,champions:[157,777,238,38]},gt={controladoAutoAccept:pt,controladoPick:mt,controladoBan:ft};function d(i){const t=Number(i);return Number.isSafeInteger(t)&&t>0?t:null}function K(i,t=null){const e=[],n=new Set,o=Ct(t);if(!Array.isArray(i))return e;for(const s of i){const r=d(s);r===null||n.has(r)||o&&!o.has(r)||(e.push(r),n.add(r))}return e}function Ct(i){return i?new Set(Array.from(i,d).filter(t=>t!==null)):null}const E=[{value:"TOP",label:"Top",iconPath:"/fe/lol-parties/icon-position-top.png"},{value:"JUNGLE",label:"Jungle",iconPath:"/fe/lol-parties/icon-position-jungle.png"},{value:"MIDDLE",label:"Mid",iconPath:"/fe/lol-parties/icon-position-middle.png"},{value:"BOTTOM",label:"ADC",iconPath:"/fe/lol-parties/icon-position-bottom.png"},{value:"UTILITY",label:"Support",iconPath:"/fe/lol-parties/icon-position-utility.png"}],wt=new Set(E.map(i=>i.value));function I(i){const t=String(i??"").toUpperCase();return wt.has(t)?t:null}function L(i,t=null){const e={};if(!i||typeof i!="object"||Array.isArray(i))return e;const n=bt(t);for(const[o,s]of Object.entries(i)){const r=d(o),a=String(r);if(r===null||n&&!n.has(a)||!Array.isArray(s))continue;const c=[],p=new Set;for(const ht of s){const P=I(ht);!P||p.has(P)||(c.push(P),p.add(P))}c.length>0&&(e[a]=c)}return e}function bt(i){if(!i)return null;const t=new Set;for(const e of i){const n=d(e);n!==null&&t.add(String(n))}return t}function F(i){return E.find(t=>t.value===i)}function Q(i,t){var n;const e=d(t);return e===null?[]:((n=i==null?void 0:i.positionsByChampionId)==null?void 0:n[String(e)])||[]}function St(i,t,e){const n=Q(i,t);if(n.length===0)return!0;const o=I(e);return o!==null&&n.includes(o)}const $=new Set;function Pt(i,t){return Object.prototype.hasOwnProperty.call(i,t)}function A(i,t){return Pt(i,t)}function M(){if(!globalThis.DataStore)throw new Error("DataStore is not available");return globalThis.DataStore}function yt(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function B(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function Z(i){const t=gt[i];if(!t)throw new Error(`Unknown auto-champion-select config key: ${i}`);return B(t)}function tt(i,t,e={}){const n=Z(i),o=yt(t)?B(t):{},s={...n,...o},r={enabled:s.enabled===!0};return A(n,"force")&&(r.force=s.force===!0),A(n,"champions")&&(r.champions=K(s.champions,e.allowedChampionIds)),A(n,"positionsByChampionId")&&(r.positionsByChampionId=L(s.positionsByChampionId,e.selectedChampionIds||r.champions)),r}function et(i,t,e={}){const n=t===void 0?Z(i):t;return tt(i,n,e)}function C(i,t={}){const n=M().get(i);return et(i,n,t)}function Et(i,t,e={}){const n=M(),o=tt(i,t,e);return n.set(i,o),o}function It(i,t){return JSON.stringify(i)===JSON.stringify(t)}function At(i,t,e){$.has(i)||($.add(i),console.warn(`auto-champion-select: Repaired ${i} in DataStore. The stored value used a different schema; plugins like reynbow/auto-champ-lock write this shape. Saved normalized config.`,{storedConfig:t,normalizedConfig:e}))}function nt(i,t={}){const e=M(),n=e.get(i),o=et(i,n,t);return(n===void 0||!It(n,o))&&(n!==void 0&&At(i,n,o),e.set(i,o)),o}function x(i,t,e={}){const n=C(i,e),o=B(n),s=t(o)||o;return Et(i,s,e)}const h=Object.freeze({readyCheckAccept:"/lol-matchmaking/v1/ready-check/accept",gameflowPhase:"/lol-gameflow/v1/gameflow-phase",wallet:"/lol-inventory/v1/wallet",ownedChampions:"/lol-champions/v1/owned-champions-minimal",championSummary:"/lol-game-data/assets/v1/champion-summary.json",champSelectSession:"/lol-champ-select/v1/session",championIcon(i){return`/lol-game-data/assets/v1/champion-icons/${i}.png`},champSelectAction(i){return`/lol-champ-select/v1/session/actions/${i}`}}),Ot=1e3;function ot(i){let t=null;return function(){return t||(t=Promise.resolve().then(i).finally(()=>{t=null})),t}}function it(i){const t=[],e=new Set;if(!Array.isArray(i))return t;for(const n of i){if(!n||typeof n!="object")continue;const o=d(n.id),s=typeof n.name=="string"?n.name:"";o===null||!s||e.has(s)||(t.push({...n,id:o,name:s,squarePortraitPath:n.squarePortraitPath||h.championIcon(o)}),e.add(s))}return t.sort((n,o)=>n.name.localeCompare(o.name)),t}async function Tt(){let i=await f("GET",h.ownedChampions);for(;!i.ok;)console.debug("auto-champion-select(owned-champions-minimal): Retrying..."),i=await f("GET",h.ownedChampions),await g(Ot);return it(await i.json())}async function kt(){const i=await f("GET",h.championSummary);return it(await i.json())}const _t=ot(Tt),Lt=ot(kt),z=300,m=Object.freeze({APPLIED:"applied",TRY_NEXT_CHAMPION:"try-next-champion",ABORT_ACTION:"abort-action"});function v(i){return Array.isArray(i)?i.flat():[]}function vt(i){return v(i).filter(t=>t.type==="ban"&&t.completed===!0).map(t=>t.championId)}function G(i){return Array.isArray(i)?i:[]}function O(i){const t=new Set;for(const e of i){const n=d(e);n!==null&&t.add(n)}return t}function U(i){return i.type==="pick"?0:1}function Rt(){return{pickConfig:C("controladoPick"),banConfig:C("controladoBan")}}class Mt{constructor(){this.session=null,this.actions=null,this.localPlayerCellId=null,this.teammateIntentChampionIds=new Set,this.localPlayerIntentChampionId=null,this.pickedChampionIds=new Set,this.bannedChampionIds=new Set,this.localPlayerAssignedPosition=null,this.watchTask=null,this.watchVersion=0,this.mounted=!1}mount(){this.mounted||(this.mounted=!0,this.watchVersion+=1,this.watchTask||(this.watchTask=this.watch()))}unmount(){this.mounted&&(this.mounted=!1,this.watchVersion+=1)}async watch(){try{for(;this.mounted;){const t=this.watchVersion;let e=!1;try{await this.refreshSessionState(),e=!0}catch(n){console.debug("auto-champion-select: Failed to update champion select",n)}if(!e||!this.mounted||t!==this.watchVersion){this.mounted&&t===this.watchVersion&&await g(z);continue}try{await this.runAutoSelectCycle()}catch(n){console.debug("auto-champion-select: Failed to run champion select cycle",n)}this.mounted&&t===this.watchVersion&&await g(z)}}finally{this.watchTask=null}}async refreshSessionState(){var s,r;const t=await f("GET",h.champSelectSession);if(!t.ok)throw new Error(`Session request failed with status ${t.status}`);this.session=await t.json(),this.actions=this.session.actions,this.localPlayerCellId=this.session.localPlayerCellId;const e=G(this.session.myTeam),n=G(this.session.theirTeam),o=e.find(a=>a.cellId===this.localPlayerCellId);this.localPlayerAssignedPosition=I(o==null?void 0:o.assignedPosition),this.localPlayerIntentChampionId=d(o==null?void 0:o.championPickIntent),this.pickedChampionIds=O([...e,...n].map(a=>a.championId)),this.bannedChampionIds=O([...((s=this.session.bans)==null?void 0:s.myTeamBans)||[],...((r=this.session.bans)==null?void 0:r.theirTeamBans)||[],...vt(this.actions)]),this.teammateIntentChampionIds=O(e.map(a=>a.championPickIntent))}async runAutoSelectCycle(){const{pickConfig:t,banConfig:e}=Rt();if(!t.enabled&&!e.enabled)return;const n=this.getLocalPlayerActions();if(n.length===0){console.debug("auto-champion-select: No local player sub actions found, skipping..."),this.unmount();return}for(const o of n){if(!this.isActionAvailable(o))continue;const s=this.getConfigForActionType(o.type,{pickConfig:t,banConfig:e});if(s!=null&&s.enabled)for(const r of s.champions){const a=await this.attemptChampionForAction(o,r,s);if(a===m.APPLIED)break;if(a===m.ABORT_ACTION)return}}}getLocalPlayerActions(){return v(this.actions).filter(t=>this.isPendingLocalPlayerAction(t)).sort((t,e)=>U(t)-U(e))}isPendingLocalPlayerAction(t){return t.actorCellId===this.localPlayerCellId&&t.completed===!1}isActionAvailable(t){return t.type==="pick"||t.isInProgress===!0}getConfigForActionType(t,e){return t==="pick"?e.pickConfig:t==="ban"?e.banConfig:null}async attemptChampionForAction(t,e,n){const o=d(e);if(o===null||this.isChampionUnavailableForAction(t,o,n))return m.TRY_NEXT_CHAMPION;if(this.isPickIntentAlreadyApplied(t,o)||(console.debug(`auto-champion-select: Trying to ${t.type} ${o}...`),(await this.selectChampion(t.id,o)).ok))return m.APPLIED;console.debug(`auto-champion-select: Failed to ${t.type} ${o}, refreshing champ select state...`);const r=await this.refreshActionAfterFailedAttempt(t);return!r||!this.isActionAvailable(r)||!this.isChampionUnavailableForAction(r,o,n)?m.ABORT_ACTION:(console.debug(`auto-champion-select: ${o} is unavailable after refresh, trying next ${t.type}...`),m.TRY_NEXT_CHAMPION)}isPickIntentAlreadyApplied(t,e){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId===e||d(t.championId)===e)}async refreshActionAfterFailedAttempt(t){try{await this.refreshSessionState()}catch(e){return console.debug("auto-champion-select: Failed to refresh champion select after select failure",e),null}return v(this.actions).find(e=>e.id===t.id&&e.actorCellId===t.actorCellId&&e.type===t.type&&e.completed===!1)||null}isChampionUnavailableForAction(t,e,n){if(t.type==="pick"&&!St(n,e,this.localPlayerAssignedPosition)){const o=Q(n,e);return this.localPlayerAssignedPosition?console.debug(`auto-champion-select: Picking ${e} but assigned position ${this.localPlayerAssignedPosition} is not in ${o.join(", ")}, skipping...`):console.debug(`auto-champion-select: Picking ${e} but no assigned position is available for ${o.join(", ")} restriction, skipping...`),!0}if(this.bannedChampionIds.has(e))return console.debug(`auto-champion-select: Banning ${e} but it's already banned, skipping...`),!0;if(t.type==="ban"&&this.teammateIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Banning ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Banning ${e} but it's already picked, skipping...`),!0;if(t.type==="pick"&&this.pickedChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Picking ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Picking ${e} but it's already picked, skipping...`),!0;return!1}selectChampion(t,e){const n=h.champSelectAction(t);return f("PATCH",n,{body:{championId:e,completed:!0}})}}const u=Object.freeze({dropdown:"lol-uikit-framed-dropdown",dropdownOption:"lol-uikit-dropdown-option",radioInputOption:"lol-uikit-radio-input-option",scrollable:"lol-uikit-scrollable",socialRosterGroup:"lol-social-roster-group"}),l=Object.freeze({socialRoster:".lol-social-roster",champSelectButtons:".bottom-right-buttons",firstChampSelectSquareButton:"lol-social-chat-toggle-button, .missions-tracker-button-component, .champ-select-voice-button-wrapper",dropdownRoot:".ui-dropdown",dropdownCurrent:".ui-dropdown-current",dropdownCurrentContent:".ui-dropdown-current-content",dropdownOption:u.dropdownOption,dropdownOptionSelected:`${u.dropdownOption}[selected]`,dropdownOptionsContainer:".ui-dropdown-options-container",dropdownOptions:".ui-dropdown-options",dropdownScrollable:u.scrollable,socialRosterGroupArrow:".arrow",socialRosterGroupHeader:".group-header",socialRosterGroupLabel:"span"});function q(){return document.querySelector(l.socialRoster)}function R(){return document.querySelector(l.champSelectButtons)}const Bt=50,xt=100,T=210,W="controlado-placeholder",H="controlado-search",st="controlado-filter-icon",w="controlado-filter-icon--trash",rt="controlado-filter-input",at="controlado-tag",ct="controlado-tag--search",Dt=`
11
- ${l.dropdownRoot} {
10
+ import{request as f,sleep as g,linkEndpoint as $}from"https://cdn.jsdelivr.net/npm/balaclava-utils@latest";const wt="1.8.7",bt={enabled:!1},yt={enabled:!1,force:!1,champions:[432,235],positionsByChampionId:{235:["BOTTOM","UTILITY"],432:["UTILITY"]}},St={enabled:!1,force:!1,champions:[157,777,238,38]},Pt={controladoAutoAccept:bt,controladoPick:yt,controladoBan:St};function d(o){const t=Number(o);return Number.isSafeInteger(t)&&t>0?t:null}function nt(o,t=null){const e=[],n=new Set,i=Et(t);if(!Array.isArray(o))return e;for(const s of o){const r=d(s);r===null||n.has(r)||i&&!i.has(r)||(e.push(r),n.add(r))}return e}function Et(o){return o?new Set(Array.from(o,d).filter(t=>t!==null)):null}const E=[{value:"TOP",label:"Top",iconPath:"/fe/lol-parties/icon-position-top.png"},{value:"JUNGLE",label:"Jungle",iconPath:"/fe/lol-parties/icon-position-jungle.png"},{value:"MIDDLE",label:"Mid",iconPath:"/fe/lol-parties/icon-position-middle.png"},{value:"BOTTOM",label:"ADC",iconPath:"/fe/lol-parties/icon-position-bottom.png"},{value:"UTILITY",label:"Support",iconPath:"/fe/lol-parties/icon-position-utility.png"}],It=new Set(E.map(o=>o.value));function I(o){const t=String(o??"").toUpperCase();return It.has(t)?t:null}function M(o,t=null){const e={};if(!o||typeof o!="object"||Array.isArray(o))return e;const n=At(t);for(const[i,s]of Object.entries(o)){const r=d(i),a=String(r);if(r===null||n&&!n.has(a)||!Array.isArray(s))continue;const l=[],h=new Set;for(const A of s){const S=I(A);!S||h.has(S)||(l.push(S),h.add(S))}l.length>0&&(e[a]=l)}return e}function At(o){if(!o)return null;const t=new Set;for(const e of o){const n=d(e);n!==null&&t.add(String(n))}return t}function z(o){return E.find(t=>t.value===o)}function ot(o,t){var n;const e=d(t);return e===null?[]:((n=o==null?void 0:o.positionsByChampionId)==null?void 0:n[String(e)])||[]}function Ot(o,t,e){const n=ot(o,t);if(n.length===0)return!0;const i=I(e);return i!==null&&n.includes(i)}const U=new Set;function Tt(o,t){return Object.prototype.hasOwnProperty.call(o,t)}function O(o,t){return Tt(o,t)}function D(){if(!globalThis.DataStore)throw new Error("DataStore is not available");return globalThis.DataStore}function _t(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function x(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function it(o){const t=Pt[o];if(!t)throw new Error(`Unknown auto-champion-select config key: ${o}`);return x(t)}function st(o,t,e={}){const n=it(o),i=_t(t)?x(t):{},s={...n,...i},r={enabled:s.enabled===!0};return O(n,"force")&&(r.force=s.force===!0),O(n,"champions")&&(r.champions=nt(s.champions,e.allowedChampionIds)),O(n,"positionsByChampionId")&&(r.positionsByChampionId=M(s.positionsByChampionId,e.selectedChampionIds||r.champions)),r}function rt(o,t,e={}){const n=t===void 0?it(o):t;return st(o,n,e)}function C(o,t={}){const n=D().get(o);return rt(o,n,t)}function kt(o,t,e={}){const n=D(),i=st(o,t,e);return n.set(o,i),i}function vt(o,t){return JSON.stringify(o)===JSON.stringify(t)}function Mt(o,t,e){U.has(o)||(U.add(o),console.warn(`auto-champion-select: Repaired ${o} in DataStore. The stored value used a different schema; plugins like reynbow/auto-champ-lock write this shape. Saved normalized config.`,{storedConfig:t,normalizedConfig:e}))}function at(o,t={}){const e=D(),n=e.get(o),i=rt(o,n,t);return(n===void 0||!vt(n,i))&&(n!==void 0&&Mt(o,n,i),e.set(o,i)),i}function N(o,t,e={}){const n=C(o,e),i=x(n),s=t(i)||i;return kt(o,s,e)}const u=Object.freeze({readyCheckAccept:"/lol-matchmaking/v1/ready-check/accept",gameflowPhase:"/lol-gameflow/v1/gameflow-phase",wallet:"/lol-inventory/v1/wallet",ownedChampions:"/lol-champions/v1/owned-champions-minimal",championSummary:"/lol-game-data/assets/v1/champion-summary.json",champSelectSession:"/lol-champ-select/v1/session",championIcon(o){return`/lol-game-data/assets/v1/champion-icons/${o}.png`},champSelectAction(o){return`/lol-champ-select/v1/session/actions/${o}`}}),Rt=1e3;function lt(o){let t=null;return function(){return t||(t=Promise.resolve().then(o).finally(()=>{t=null})),t}}function ct(o){const t=[],e=new Set;if(!Array.isArray(o))return t;for(const n of o){if(!n||typeof n!="object")continue;const i=d(n.id),s=typeof n.name=="string"?n.name:"";i===null||!s||e.has(s)||(t.push({...n,id:i,name:s,squarePortraitPath:n.squarePortraitPath||u.championIcon(i)}),e.add(s))}return t.sort((n,i)=>n.name.localeCompare(i.name)),t}async function Lt(){let o=await f("GET",u.ownedChampions);for(;!o.ok;)console.debug("auto-champion-select(owned-champions-minimal): Retrying..."),o=await f("GET",u.ownedChampions),await g(Rt);return ct(await o.json())}async function Bt(){const o=await f("GET",u.championSummary);return ct(await o.json())}const Dt=lt(Lt),xt=lt(Bt),G=300,m=Object.freeze({APPLIED:"applied",TRY_NEXT_CHAMPION:"try-next-champion",ABORT_ACTION:"abort-action"});function R(o){return Array.isArray(o)?o.flat():[]}function Nt(o){return R(o).filter(t=>t.type==="ban"&&t.completed===!0).map(t=>t.championId)}function q(o){return Array.isArray(o)?o:[]}function T(o){const t=new Set;for(const e of o){const n=d(e);n!==null&&t.add(n)}return t}function H(o){return o.type==="pick"?0:1}function Ft(){return{pickConfig:C("controladoPick"),banConfig:C("controladoBan")}}class $t{constructor(){this.session=null,this.actions=null,this.localPlayerCellId=null,this.teammateIntentChampionIds=new Set,this.localPlayerIntentChampionId=null,this.pickedChampionIds=new Set,this.bannedChampionIds=new Set,this.localPlayerAssignedPosition=null,this.watchTask=null,this.watchVersion=0,this.mounted=!1}mount(){this.mounted||(this.mounted=!0,this.watchVersion+=1,this.watchTask||(this.watchTask=this.watch()))}unmount(){this.mounted&&(this.mounted=!1,this.watchVersion+=1)}async watch(){try{for(;this.mounted;){const t=this.watchVersion;let e=!1;try{await this.refreshSessionState(),e=!0}catch(n){console.debug("auto-champion-select: Failed to update champion select",n)}if(!e||!this.mounted||t!==this.watchVersion){this.mounted&&t===this.watchVersion&&await g(G);continue}try{await this.runAutoSelectCycle()}catch(n){console.debug("auto-champion-select: Failed to run champion select cycle",n)}this.mounted&&t===this.watchVersion&&await g(G)}}finally{this.watchTask=null}}async refreshSessionState(){var s,r;const t=await f("GET",u.champSelectSession);if(!t.ok)throw new Error(`Session request failed with status ${t.status}`);this.session=await t.json(),this.actions=this.session.actions,this.localPlayerCellId=this.session.localPlayerCellId;const e=q(this.session.myTeam),n=q(this.session.theirTeam),i=e.find(a=>a.cellId===this.localPlayerCellId);this.localPlayerAssignedPosition=I(i==null?void 0:i.assignedPosition),this.localPlayerIntentChampionId=d(i==null?void 0:i.championPickIntent),this.pickedChampionIds=T([...e,...n].map(a=>a.championId)),this.bannedChampionIds=T([...((s=this.session.bans)==null?void 0:s.myTeamBans)||[],...((r=this.session.bans)==null?void 0:r.theirTeamBans)||[],...Nt(this.actions)]),this.teammateIntentChampionIds=T(e.map(a=>a.championPickIntent))}async runAutoSelectCycle(){const{pickConfig:t,banConfig:e}=Ft();if(!t.enabled&&!e.enabled)return;const n=this.getLocalPlayerActions();if(n.length===0){console.debug("auto-champion-select: No local player sub actions found, skipping..."),this.unmount();return}for(const i of n){if(!this.isActionAvailable(i))continue;const s=this.getConfigForActionType(i.type,{pickConfig:t,banConfig:e});if(s!=null&&s.enabled)for(const r of s.champions){const a=await this.attemptChampionForAction(i,r,s);if(a===m.APPLIED)break;if(a===m.ABORT_ACTION)return}}}getLocalPlayerActions(){return R(this.actions).filter(t=>this.isPendingLocalPlayerAction(t)).sort((t,e)=>H(t)-H(e))}isPendingLocalPlayerAction(t){return t.actorCellId===this.localPlayerCellId&&t.completed===!1}isActionAvailable(t){return t.type==="pick"||t.isInProgress===!0}getConfigForActionType(t,e){return t==="pick"?e.pickConfig:t==="ban"?e.banConfig:null}async attemptChampionForAction(t,e,n){const i=d(e);if(i===null||this.isChampionUnavailableForAction(t,i,n))return m.TRY_NEXT_CHAMPION;if(this.isPickIntentAlreadyApplied(t,i)||(console.debug(`auto-champion-select: Trying to ${t.type} ${i}...`),(await this.selectChampion(t.id,i)).ok))return m.APPLIED;console.debug(`auto-champion-select: Failed to ${t.type} ${i}, refreshing champ select state...`);const r=await this.refreshActionAfterFailedAttempt(t);return!r||!this.isActionAvailable(r)||!this.isChampionUnavailableForAction(r,i,n)?m.ABORT_ACTION:(console.debug(`auto-champion-select: ${i} is unavailable after refresh, trying next ${t.type}...`),m.TRY_NEXT_CHAMPION)}isPickIntentAlreadyApplied(t,e){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId===e||d(t.championId)===e)}async refreshActionAfterFailedAttempt(t){try{await this.refreshSessionState()}catch(e){return console.debug("auto-champion-select: Failed to refresh champion select after select failure",e),null}return R(this.actions).find(e=>e.id===t.id&&e.actorCellId===t.actorCellId&&e.type===t.type&&e.completed===!1)||null}isChampionUnavailableForAction(t,e,n){if(t.type==="pick"&&!Ot(n,e,this.localPlayerAssignedPosition)){const i=ot(n,e);return this.localPlayerAssignedPosition?console.debug(`auto-champion-select: Picking ${e} but assigned position ${this.localPlayerAssignedPosition} is not in ${i.join(", ")}, skipping...`):console.debug(`auto-champion-select: Picking ${e} but no assigned position is available for ${i.join(", ")} restriction, skipping...`),!0}if(this.bannedChampionIds.has(e))return console.debug(`auto-champion-select: Banning ${e} but it's already banned, skipping...`),!0;if(t.type==="ban"&&this.teammateIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Banning ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Banning ${e} but it's already picked, skipping...`),!0;if(t.type==="pick"&&this.pickedChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Picking ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Picking ${e} but it's already picked, skipping...`),!0;return!1}selectChampion(t,e){const n=u.champSelectAction(t);return f("PATCH",n,{body:{championId:e,completed:!0}})}}const p=Object.freeze({dropdown:"lol-uikit-framed-dropdown",dropdownOption:"lol-uikit-dropdown-option",radioInputOption:"lol-uikit-radio-input-option",scrollable:"lol-uikit-scrollable",socialRosterGroup:"lol-social-roster-group"}),c=Object.freeze({socialRoster:".lol-social-roster",champSelectButtons:".bottom-right-buttons",firstChampSelectSquareButton:"lol-social-chat-toggle-button, .missions-tracker-button-component, .champ-select-voice-button-wrapper",dropdownRoot:".ui-dropdown",dropdownCurrent:".ui-dropdown-current",dropdownCurrentContent:".ui-dropdown-current-content",dropdownOption:p.dropdownOption,dropdownOptionSelected:`${p.dropdownOption}[selected]`,dropdownOptionsContainer:".ui-dropdown-options-container",dropdownOptions:".ui-dropdown-options",dropdownScrollable:p.scrollable,socialRosterGroupArrow:".arrow",socialRosterGroupHeader:".group-header",socialRosterGroupLabel:"span"});function Y(){return document.querySelector(c.socialRoster)}function L(){return document.querySelector(c.champSelectButtons)}const zt=50,Ut=100,_=210,W="controlado-placeholder",j="controlado-search",dt="controlado-filter-icon",w="controlado-filter-icon--trash",ht="controlado-filter-input",ut="controlado-tag",pt="controlado-tag--search",Gt=`
11
+ ${c.dropdownRoot} {
12
12
  position: relative;
13
13
  }
14
14
 
15
15
  :host {
16
- --framed-dropdown-scrollable-max-height: ${T}px;
16
+ --framed-dropdown-scrollable-max-height: ${_}px;
17
17
  }
18
18
 
19
- :host ${l.dropdownRoot} dt${l.dropdownCurrent} {
19
+ :host ${c.dropdownRoot} dt${c.dropdownCurrent} {
20
20
  display: grid;
21
21
  grid-template-columns: minmax(0, 1fr) max-content;
22
22
  align-items: center;
@@ -24,32 +24,32 @@ import{request as f,sleep as g,linkEndpoint as N}from"https://cdn.jsdelivr.net/n
24
24
  padding: 7px 8px 7px 10px;
25
25
  }
26
26
 
27
- :host ${l.dropdownRoot} dt${l.dropdownCurrent}::after {
27
+ :host ${c.dropdownRoot} dt${c.dropdownCurrent}::after {
28
28
  display: none;
29
29
  }
30
30
 
31
- :host ${l.dropdownRoot} dt${l.dropdownCurrent} ${l.dropdownCurrentContent} {
31
+ :host ${c.dropdownRoot} dt${c.dropdownCurrent} ${c.dropdownCurrentContent} {
32
32
  min-width: 0;
33
33
  padding: 0;
34
34
  text-align: left;
35
35
  }
36
36
 
37
- ${l.dropdownOptionsContainer} {
37
+ ${c.dropdownOptionsContainer} {
38
38
  position: absolute;
39
39
  top: auto;
40
40
  bottom: 100%;
41
- height: ${T}px;
41
+ height: ${_}px;
42
42
  overflow: hidden;
43
43
  transform-origin: bottom;
44
44
  transform: translateY(0);
45
45
  }
46
46
 
47
- ${l.dropdownOptions},
48
- ${l.dropdownScrollable} {
49
- height: ${T}px;
47
+ ${c.dropdownOptions},
48
+ ${c.dropdownScrollable} {
49
+ height: ${_}px;
50
50
  }
51
51
 
52
- .${st} {
52
+ .${dt} {
53
53
  cursor: default;
54
54
  display: inline-block;
55
55
  flex: 0 0 auto;
@@ -69,7 +69,7 @@ import{request as f,sleep as g,linkEndpoint as N}from"https://cdn.jsdelivr.net/n
69
69
  -webkit-mask-size: 12px 12px;
70
70
  }
71
71
 
72
- .${rt} {
72
+ .${ht} {
73
73
  flex: 0 0 auto;
74
74
  min-width: 0;
75
75
  width: auto;
@@ -83,7 +83,7 @@ import{request as f,sleep as g,linkEndpoint as N}from"https://cdn.jsdelivr.net/n
83
83
  font-weight: inherit;
84
84
  }
85
85
 
86
- .${at} {
86
+ .${ut} {
87
87
  cursor: default;
88
88
  display: inline-flex;
89
89
  align-items: center;
@@ -101,7 +101,7 @@ import{request as f,sleep as g,linkEndpoint as N}from"https://cdn.jsdelivr.net/n
101
101
  box-shadow: inset 0 0 8px rgba(15, 30, 45, 0.6);
102
102
  }
103
103
 
104
- .${ct} {
104
+ .${pt} {
105
105
  border-color: #d7b46a;
106
106
  color: #f6e1b2;
107
107
  background: #1a232f;
@@ -113,4 +113,4 @@ import{request as f,sleep as g,linkEndpoint as N}from"https://cdn.jsdelivr.net/n
113
113
  text-transform: none;
114
114
  font-weight: 500;
115
115
  }
116
- `;function Y(i){const t=document.createElement(u.dropdownOption);return t.setAttribute("slot",u.dropdownOption),t.innerText=i,t}class Nt{constructor(t,e,n,o={}){this.dropdownElement=t,this.placeholderText=e,this.searchPlaceholderText=o.searchPlaceholderText||"Search",this.onChampionSelected=n,this.placeholderOption=null}renderOptions(t){this.dropdownElement.replaceChildren(),this.placeholderOption=Y(this.placeholderText),this.placeholderOption.setAttribute("selected","true"),this.hidePlaceholderOption(),this.dropdownElement.appendChild(this.placeholderOption);for(const e of t){const n=this.createChampionOption(e);this.dropdownElement.appendChild(n)}}createChampionOption(t){const e=Y(t.name);return e.addEventListener("click",()=>{this.onChampionSelected(t.id),requestAnimationFrame(()=>this.reset())}),e}async waitForRender(){for(let t=0;t<Bt;t++){const e=this.dropdownElement.shadowRoot;if(this.dropdownElement.isConnected&&(e!=null&&e.querySelector(l.dropdownCurrent)))return e;await g(xt)}return null}ensureSearchPlaceholder(t){if(t.querySelector(`#${W}`))return;const e=t.querySelector(l.dropdownCurrent);e&&e.appendChild(this.createSearchPlaceholder())}createSearchPlaceholder(){const t=document.createElement("div");t.classList.add(at,ct),t.id=W;const e=document.createElement("input");e.classList.add(rt),e.id=H,e.type="text",e.placeholder=this.searchPlaceholderText,e.setAttribute("aria-label",this.searchPlaceholderText),e.size=Math.max(this.searchPlaceholderText.length,1);const n=document.createElement("span");return n.classList.add(st),n.addEventListener("click",()=>{n.classList.contains(w)&&this.clearSearch(e,n)}),e.addEventListener("input",o=>{this.ensureOpen(),this.filterOptions(o.target.value),n.classList.toggle(w,!!o.target.value)}),["pointerdown","click"].forEach(o=>{t.addEventListener(o,s=>s.stopPropagation()),n.addEventListener(o,s=>s.stopPropagation())}),["pointerdown","focusin"].forEach(o=>{e.addEventListener(o,s=>s.stopPropagation(),!0)}),t.appendChild(n),t.appendChild(e),t}clearSearch(t,e){t.value="",this.filterOptions(""),e.classList.toggle(w,!1)}filterOptions(t){const e=t.toLowerCase();this.dropdownElement.querySelectorAll(l.dropdownOption).forEach(o=>{if(o===this.placeholderOption){this.hidePlaceholderOption();return}(o.textContent??"").toLowerCase().includes(e)?o.style.display="":o.style.display="none"})}hidePlaceholderOption(){this.placeholderOption&&(this.placeholderOption.style.display="none")}reset(){var t;this.dropdownElement.querySelectorAll(l.dropdownOptionSelected).forEach(e=>{e.removeAttribute("selected")}),(t=this.placeholderOption)==null||t.setAttribute("selected","true"),this.withShadowRoot(e=>{var s;const n=e.querySelector(`#${H}`),o=e.querySelector(`.${w}`);n&&o?this.clearSearch(n,o):(n&&(n.value="",this.filterOptions("")),o&&o.classList.remove(w)),this.isOpen()&&((s=e.querySelector(l.dropdownCurrent))==null||s.click())})}isOpen(){return this.dropdownElement.classList.contains("active")}ensureOpen(){this.isOpen()||this.withShadowRoot(t=>{const e=t.querySelector(l.dropdownCurrent);e&&e.click()})}patchDropdownShadowDom(){this.withShadowRoot(t=>{this.ensureDropdownOpensUpward(t),this.injectDropdownSearchStyles(t)})}ensureDropdownOpensUpward(t){var e;(e=t.querySelector(l.dropdownRoot))==null||e.classList.add("opens-upward")}injectDropdownSearchStyles(t){if(t.querySelector("style[data-controlado='dropdown-tags']"))return;const e=document.createElement("style");e.dataset.controlado="dropdown-tags",e.textContent=Dt,t.appendChild(e)}withShadowRoot(t){const e=this.dropdownElement.shadowRoot;e&&t(e)}}const Ft=".champion-priority-selector__position-badge",$t=".champion-priority-selector__position-option",zt=".champion-priority-selector__remove",Gt="✕",Ut=0,j=1,y=8,qt=5,Wt=150,Ht="cubic-bezier(0.2, 0, 0, 1)";class V{constructor(t,e,n,o={}){this.element=this.createRootElement(),this.dropdownElement=this.createDropdownElement(),this.championDropdown=new Nt(this.dropdownElement,t,a=>this.addChampion(a),{searchPlaceholderText:o.searchPlaceholderText});const{scrollElement:s,trackElement:r}=this.createSelectedChampionsScroll();this.scrollElement=s,this.trackElement=r,this.enablePositionRestrictions=o.enablePositionRestrictions===!0,this.positionMenuElement=this.enablePositionRestrictions?this.createPositionMenu():null,this.positionMenuChampionId=null,this.positionsByChampionId={},this.emptyElement=this.createEmptyState(t),this.element.append(this.dropdownElement,this.scrollElement),this.positionMenuElement&&this.element.appendChild(this.positionMenuElement),this.config=null,this.configKey=e,this.loadChampions=n,this.champions=[],this.championById=new Map,this.selectedChampionIds=[],this.iconButtons=new Map,this.dragState=null,this.handleWindowPointerMove=a=>this.moveDrag(a),this.handleWindowPointerUp=a=>this.finishDrag(a),this.handleWindowPointerCancel=a=>this.cancelDrag(a),this.handlePositionMenuOutsidePointerDown=a=>this.closePositionMenuOnOutsidePointerDown(a),this.handlePositionMenuKeyDown=a=>this.closePositionMenuOnKeyDown(a),this.setupInFlight=null,this.setupPending=!1}createRootElement(){const t=document.createElement("div");return t.classList.add("champion-priority-selector"),t}createDropdownElement(){const t=document.createElement(u.dropdown);return t.classList.add("dropdown-champions-default","dropdown-drop-up"),t}createSelectedChampionsScroll(){const t=document.createElement(u.scrollable);t.classList.add("champion-priority-selector__scroll"),t.setAttribute("direction","horizontal"),t.setAttribute("overflow-masks","disabled"),t.setAttribute("side-scroll-wheel","true");const e=document.createElement("div");return e.classList.add("champion-priority-selector__track"),t.appendChild(e),{scrollElement:t,trackElement:e}}createEmptyState(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__empty");const n=document.createElement("span");n.innerText="No champions";const o=document.createElement("span"),s=t.replace(/^Add\s+/i,"").toLowerCase();return o.innerText=`Use dropdown to add ${s} option`,e.append(n,o),e}createPositionMenu(){const t=document.createElement("div");t.classList.add("champion-priority-selector__position-menu"),t.hidden=!0;for(const e of E)t.appendChild(this.createPositionOption(e));return t}createPositionOption(t){const e=document.createElement("button");e.classList.add("champion-priority-selector__position-option"),e.type="button",e.dataset.position=t.value,e.title=t.label,e.setAttribute("aria-label",t.label),e.setAttribute("aria-pressed","false"),e.addEventListener("pointerdown",o=>o.stopPropagation()),e.addEventListener("click",o=>{o.stopPropagation(),this.toggleChampionPosition(t.value)});const n=document.createElement("img");return n.src=t.iconPath,n.alt=t.label,n.draggable=!1,e.appendChild(n),e}async setup(){return this.setupPending=!0,this.setupInFlight||(this.setupInFlight=this.runSetupLoop()),this.setupInFlight}refresh(){return this.setup()}async runSetupLoop(){try{for(;this.setupPending;)this.setupPending=!1,await this.performSetup()}finally{this.setupInFlight=null}}async performSetup(){this.champions=await this.loadChampions(),this.championById=new Map(this.champions.map(n=>[n.id,n]));const t=this.getAllowedChampionIds();this.config=nt(this.configKey,{allowedChampionIds:t}),this.selectedChampionIds=K(this.config.champions,t),this.enablePositionRestrictions&&(this.positionsByChampionId=L(this.config.positionsByChampionId,this.selectedChampionIds)),this.championDropdown.renderOptions(this.champions),this.renderSelectedChampions();const e=await this.championDropdown.waitForRender();e&&(this.championDropdown.ensureSearchPlaceholder(e),this.championDropdown.patchDropdownShadowDom())}getAllowedChampionIds(){return new Set(this.championById.keys())}addChampion(t){const e=d(t);e===null||!this.championById.has(e)||this.selectedChampionIds.includes(e)||(this.selectedChampionIds.push(e),this.renderSelectedChampions(),this.saveConfig())}removeChampion(t){const e=d(t),n=this.selectedChampionIds.indexOf(e);e===null||n===-1||(this.selectedChampionIds.splice(n,1),this.positionMenuChampionId===e&&this.closePositionMenu(),this.enablePositionRestrictions&&delete this.positionsByChampionId[String(e)],this.renderSelectedChampions(),this.saveConfig())}moveChampionToIndex(t,e){const n=d(t),o=this.selectedChampionIds.indexOf(n);if(n===null||o===-1)return!1;const[s]=this.selectedChampionIds.splice(o,1),r=Math.max(0,Math.min(e,this.selectedChampionIds.length));return this.selectedChampionIds.splice(r,0,s),o!==r}syncPositionsByChampionId(){this.enablePositionRestrictions&&(this.positionsByChampionId=L(this.positionsByChampionId,this.selectedChampionIds))}saveConfig(){this.syncPositionsByChampionId();const t=this.getAllowedChampionIds();this.config=x(this.configKey,e=>(e.champions=[...this.selectedChampionIds],this.enablePositionRestrictions&&(e.positionsByChampionId={...this.positionsByChampionId}),e),{allowedChampionIds:t,selectedChampionIds:this.selectedChampionIds}),this.enablePositionRestrictions&&(this.positionsByChampionId=this.config.positionsByChampionId||{}),console.debug(this.configKey,this.config)}renderSelectedChampions(t=null,e=null){this.positionMenuChampionId!==null&&this.closePositionMenu();const n=new Set(this.selectedChampionIds);for(const[s,r]of this.iconButtons)n.has(s)||(r.remove(),this.iconButtons.delete(s));if(this.selectedChampionIds.length===0){this.trackElement.replaceChildren(this.emptyElement);return}this.emptyElement.remove();const o=this.selectedChampionIds.map((s,r)=>this.getIconButton(s,r)).filter(Boolean);this.trackElement.append(...o),t&&this.animateReorder(t,e)}getIconButton(t,e){const n=this.championById.get(t);if(!n)return null;let o=this.iconButtons.get(t);o||(o=this.createIconButton(n),this.iconButtons.set(t,o)),o.dataset.rank=String(e+1);const s=this.getChampionPositionTitleSuffix(t);o.title=`${e+1}. ${n.name}${s}`,o.setAttribute("aria-label",`${e+1}. ${n.name}${s}`);const r=o.querySelector("img");r.src=n.squarePortraitPath,r.alt=n.name;const a=o.querySelector(zt);return a.setAttribute("aria-label",`Remove ${n.name}`),a.title=`Remove ${n.name}`,this.renderPositionBadge(o,t),o}createIconButton(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__icon"),e.setAttribute("role","button"),e.tabIndex=0;const n=document.createElement("img");n.draggable=!1;const o=document.createElement("button");return o.classList.add("champion-priority-selector__remove"),o.type="button",o.dataset.icon=Gt,o.addEventListener("pointerdown",s=>s.stopPropagation()),o.addEventListener("click",s=>{s.stopPropagation(),this.removeChampion(t.id)}),e.addEventListener("pointerdown",s=>this.startDrag(s,t.id)),e.addEventListener("auxclick",s=>this.removeChampionOnMiddleClick(s,t.id)),this.enablePositionRestrictions&&e.addEventListener("contextmenu",s=>this.openPositionMenu(s,t.id)),e.append(n,o),e}getChampionAllowedPositions(t){const e=d(t);return e===null?[]:this.positionsByChampionId[String(e)]||[]}getChampionAllowedPositionLabels(t){return this.getChampionAllowedPositions(t).map(e=>{var n;return(n=F(e))==null?void 0:n.label}).filter(Boolean)}getChampionPositionTitleSuffix(t){const e=this.getChampionAllowedPositionLabels(t);return e.length>0?` (${e.join(", ")})`:""}renderPositionBadge(t,e){var o;if((o=t.querySelector(Ft))==null||o.remove(),!this.enablePositionRestrictions)return;const n=this.createPositionBadge(e);n&&t.appendChild(n)}createPositionBadge(t){const e=this.getChampionAllowedPositions(t),n=this.getChampionAllowedPositionLabels(t),o=document.createElement("button");if(o.classList.add("champion-priority-selector__position-badge"),o.type="button",o.title=n.length>0?`${n.join(", ")}. Click to edit positions.`:"Any position. Click to restrict positions.",o.setAttribute("aria-label",o.title),o.addEventListener("pointerdown",a=>a.stopPropagation()),o.addEventListener("click",a=>this.openPositionMenu(a,t,o)),e.length===0)return o.classList.add("champion-priority-selector__position-badge--empty"),o.innerText="+",o;const s=F(e[0]);if(!s)return null;e.length>1&&(o.dataset.count=String(e.length));const r=document.createElement("img");return r.src=s.iconPath,r.alt=s.label,r.draggable=!1,o.appendChild(r),o}openPositionMenu(t,e,n=null){if(!this.enablePositionRestrictions||!this.positionMenuElement)return;const o=d(e);if(o===null||!this.selectedChampionIds.includes(o))return;t.preventDefault(),t.stopPropagation(),this.positionMenuChampionId=o,this.renderPositionMenu(),this.positionMenuElement.hidden=!1,this.positionMenuElement.style.left="0px",this.positionMenuElement.style.top="0px";const{left:s,top:r}=this.getPositionMenuCoordinates(t,n);this.positionMenuElement.style.left=`${s}px`,this.positionMenuElement.style.top=`${r}px`,document.addEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.addEventListener("keydown",this.handlePositionMenuKeyDown,!0)}getPositionMenuCoordinates(t,e=null){const n=this.positionMenuElement.getBoundingClientRect();let o=t.clientX,s=t.clientY;if(e&&t.type==="click"&&t.detail===0){const c=e.getBoundingClientRect();o=c.left+c.width/2,s=c.bottom}const r=Math.min(Math.max(o,y),window.innerWidth-n.width-y),a=Math.min(Math.max(s,y),window.innerHeight-n.height-y);return{left:r,top:a}}renderPositionMenu(){if(!this.positionMenuElement||this.positionMenuChampionId===null)return;const t=new Set(this.getChampionAllowedPositions(this.positionMenuChampionId));this.positionMenuElement.querySelectorAll($t).forEach(e=>{const n=t.has(e.dataset.position);e.classList.toggle("champion-priority-selector__position-option--selected",n),e.setAttribute("aria-pressed",String(n))})}toggleChampionPosition(t){if(!this.enablePositionRestrictions||this.positionMenuChampionId===null)return;const e=I(t);if(!e)return;const n=String(this.positionMenuChampionId),o=new Set(this.positionsByChampionId[n]||[]);o.has(e)?o.delete(e):o.add(e);const s=E.map(c=>c.value).filter(c=>o.has(c));s.length>0?this.positionsByChampionId[n]=s:delete this.positionsByChampionId[n],this.renderPositionMenu();const r=this.iconButtons.get(this.positionMenuChampionId),a=this.selectedChampionIds.indexOf(this.positionMenuChampionId);r&&a!==-1&&this.getIconButton(this.positionMenuChampionId,a),this.saveConfig()}closePositionMenuOnOutsidePointerDown(t){var e;(e=this.positionMenuElement)!=null&&e.contains(t.target)||this.closePositionMenu()}closePositionMenuOnKeyDown(t){t.key==="Escape"&&this.closePositionMenu()}closePositionMenu(){this.positionMenuElement&&(this.positionMenuElement.hidden=!0,this.positionMenuChampionId=null,document.removeEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.removeEventListener("keydown",this.handlePositionMenuKeyDown,!0))}startDrag(t,e){var o;if(t.button===j){t.preventDefault();return}if(t.button!==Ut)return;this.dragState&&this.clearDragState();const n=this.iconButtons.get(e);if(n){this.dragState={championId:e,pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,active:!1,moved:!1};try{(o=n.setPointerCapture)==null||o.call(n,t.pointerId)}catch{}window.addEventListener("pointermove",this.handleWindowPointerMove),window.addEventListener("pointerup",this.handleWindowPointerUp),window.addEventListener("pointercancel",this.handleWindowPointerCancel)}}removeChampionOnMiddleClick(t,e){t.button===j&&(t.preventDefault(),t.stopPropagation(),this.removeChampion(e))}moveDrag(t){var p;if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.championId,n=t.clientX-this.dragState.startX,o=t.clientY-this.dragState.startY,s=Math.hypot(n,o);if(!this.dragState.active){if(s<qt)return;this.dragState.active=!0,(p=this.iconButtons.get(e))==null||p.classList.add("champion-priority-selector__icon--dragging")}t.preventDefault();const r=this.getDropIndex(t.clientX,e),a=this.selectedChampionIds.indexOf(e);if(r===a||r===-1)return;const c=this.getIconPositions();this.moveChampionToIndex(e,r)&&(this.dragState.moved=!0,this.renderSelectedChampions(c,e))}finishDrag(t){if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.active,n=this.dragState.moved;this.clearDragState(),e&&n&&this.saveConfig()}cancelDrag(t){!this.dragState||this.dragState.pointerId!==t.pointerId||this.clearDragState()}clearDragState(){var o;if(!this.dragState)return;const{championId:t,pointerId:e}=this.dragState,n=this.iconButtons.get(t);n==null||n.classList.remove("champion-priority-selector__icon--dragging");try{(o=n==null?void 0:n.releasePointerCapture)==null||o.call(n,e)}catch{}window.removeEventListener("pointermove",this.handleWindowPointerMove),window.removeEventListener("pointerup",this.handleWindowPointerUp),window.removeEventListener("pointercancel",this.handleWindowPointerCancel),this.dragState=null}getDropIndex(t,e){const n=this.selectedChampionIds.filter(o=>o!==e);for(let o=0;o<n.length;o++){const s=this.iconButtons.get(n[o]);if(!s)continue;const r=s.getBoundingClientRect();if(t<r.left+r.width/2)return o}return n.length}getIconPositions(){const t=new Map;for(const e of this.selectedChampionIds){const n=this.iconButtons.get(e);n&&t.set(e,n.getBoundingClientRect())}return t}animateReorder(t,e){for(const n of this.selectedChampionIds){if(n===e)continue;const o=this.iconButtons.get(n),s=t.get(n);if(!o||!s||typeof o.animate!="function")continue;const r=o.getBoundingClientRect(),a=s.left-r.left,c=s.top-r.top;a===0&&c===0||o.animate([{transform:`translate(${a}px, ${c}px)`},{transform:"translate(0, 0)"}],{duration:Wt,easing:Ht})}}}const Yt=200,k="auto-select-champ-select-menu--collapsed",jt="auto-select-champ-select-menu-button-wrapper--open";class _{constructor(t,e){this.element=document.createElement(u.radioInputOption),this.element.classList.add("lol-settings-voice-input-mode-option","auto-select-checkbox"),this.element.innerText=t,this.config=null,this.configKey=e,this.setupComplete=!1}setup(){this.syncFromConfig(),this.setupComplete||(this.element.addEventListener("click",()=>this.toggle()),this.setupComplete=!0)}syncFromConfig(){this.config=nt(this.configKey),this.element.toggleAttribute("selected",this.config.enabled===!0)}toggle(){return console.debug("auto-champion-select: Toggling",this.configKey),this.config=x(this.configKey,t=>(t.enabled=!t.enabled,t)),this.element.toggleAttribute("selected",this.config.enabled===!0),this.config.enabled}}class Vt{constructor(t,e,n){this.element=document.createElement("div"),this.element.classList.add("auto-select-champ-select-menu",k),this.buttonWrapper=document.createElement("div"),this.buttonWrapper.classList.add("auto-select-champ-select-menu-button-wrapper"),this.headerElement=document.createElement("button"),this.headerElement.classList.add("auto-select-champ-select-menu__header"),this.headerElement.type="button",this.headerElement.setAttribute("aria-label",t),this.headerElement.setAttribute("aria-expanded","false"),this.headerElement.addEventListener("click",()=>this.toggle()),this.contentElement=document.createElement("div"),this.contentElement.classList.add("auto-select-champ-select-menu__content"),this.titleElement=document.createElement("div"),this.titleElement.classList.add("auto-select-champ-select-menu__title"),this.titleElement.textContent=t,this.buttonWrapper.append(this.headerElement,this.element),this.contentElement.appendChild(this.titleElement),this.element.appendChild(this.contentElement),this.returnControlsToSocialRoster=e,this.controlElements=n,this.boundCloseOnOutsideInteraction=o=>this.closeOnOutsideInteraction(o),this.buttonObserver=null,this.buttonMountFrame=null,this.buttonMountTask=null,this.hiddenStates=new WeakMap,this.mounted=!1}async mount(){return this.mounted?this.mountButton():(this.mounted=!0,this.controlElements.forEach(t=>{this.hiddenStates.set(t,t.classList.contains("hidden")),t.classList.remove("hidden"),this.contentElement.appendChild(t)}),this.observeButtonContainer(),document.addEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.mountButton())}unmount(){return this.mounted?(this.mounted=!1,this.stopButtonMounting(),document.removeEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.setOpen(!1),this.buttonWrapper.remove(),this.restoreHiddenStates(),this.returnControlsToSocialRoster()):this.returnControlsToSocialRoster()}stopButtonMounting(){var t;(t=this.buttonObserver)==null||t.disconnect(),this.buttonObserver=null,this.buttonMountFrame!==null&&(cancelAnimationFrame(this.buttonMountFrame),this.buttonMountFrame=null),this.buttonMountTask=null}restoreHiddenStates(){this.controlElements.forEach(t=>{t.classList.toggle("hidden",this.hiddenStates.get(t)===!0),this.hiddenStates.delete(t)})}isOpen(){return!this.element.classList.contains(k)}setOpen(t){this.element.classList.toggle(k,!t),this.buttonWrapper.classList.toggle(jt,t),this.headerElement.setAttribute("aria-expanded",String(t))}toggle(){this.setOpen(!this.isOpen())}closeOnOutsideInteraction(t){if(!this.isOpen())return;(typeof t.composedPath=="function"?t.composedPath():[]).includes(this.buttonWrapper)||this.buttonWrapper.contains(t.target)||this.setOpen(!1)}observeButtonContainer(){this.buttonObserver=new MutationObserver(()=>this.scheduleMountButton()),this.buttonObserver.observe(document.body,{childList:!0,subtree:!0})}scheduleMountButton(){this.buttonMountFrame===null&&(this.buttonMountFrame=requestAnimationFrame(()=>{this.buttonMountFrame=null,this.mountButton()}))}mountButton(){return this.buttonMountTask||(this.buttonMountTask=this.appendButtonToContainer().finally(()=>{this.buttonMountTask=null})),this.buttonMountTask}async appendButtonToContainer(){let t=R();for(;this.mounted&&!t;)await g(Yt),t=R();if(!this.mounted||!t)return;const e=t.querySelector(l.firstChampSelectSquareButton);this.buttonWrapper.parentNode===t&&this.buttonWrapper.nextSibling===e||t.insertBefore(this.buttonWrapper,e)}}class Xt{constructor(t,...e){this.element=document.createElement(u.socialRosterGroup),this.element.addEventListener("post-render",()=>this.onPostRender()),this.element.addEventListener("click",()=>this.onClick()),this.label=t,this.collapsibleElements=e,this.waitRender()}waitRender(){new MutationObserver((t,e)=>{if(this.element.querySelector(l.socialRosterGroupLabel)){const n=new Event("post-render");this.element.dispatchEvent(n),e.disconnect()}}).observe(this.element,{childList:!0})}onPostRender(){var t;this.element.querySelector(l.socialRosterGroupLabel).innerText=this.label,(t=this.element.querySelector(l.socialRosterGroupHeader))==null||t.removeAttribute("draggable")}onClick(){var t;this.collapsibleElements.forEach(e=>{e.closest(".auto-select-champ-select-menu")||e.classList.toggle("hidden")}),(t=this.element.querySelector(l.socialRosterGroupArrow))==null||t.toggleAttribute("open")}}const S="Balaclava: Auto Champion Select";function Jt(i){return typeof(i==null?void 0:i.then)=="function"}class D{constructor({id:t,name:e,legend:n,tags:o,group:s,callback:r,toasts:a}){this.id=t,this.name=e,this.legend=n,this.tags=o,this.group=s,this.perform=this.perform.bind(this),this.callback=r,this.toasts=a}perform(){try{const t=this.callback();if(Jt(t))return Toast.promise(t,{loading:this.toasts.loading,success:this.toasts.success,error:this.toasts.error});const e=this.toasts.success||(t?this.toasts.on:this.toasts.off);Toast.success(e)}catch(t){Toast.error(this.toasts.error),console.error(t)}}}class lt extends D{constructor(t,e,n){super({id:`${e}Switch`,name:()=>`Auto ${t} [${C(e).enabled?"ON":"OFF"}]`,legend:()=>C(e).enabled?"Turn OFF":"Turn ON",tags:[S,e,"switch"],group:S,callback:n,toasts:{on:`Auto ${t} is ON!`,off:`Auto ${t} is OFF!`,error:`Failed to toggle Auto ${t}. Check console.`}})}}function Kt(i){return x(i,e=>(e.force=!e.force,e)).force}class dt extends D{constructor(t,e){super({id:`${e}ForceSwitch`,name:()=>`Force ${t} [${C(e).force?"ON":"OFF"}]`,legend:()=>`Ignore team intent and force ${t} the selected champion`,tags:[S,e,"force","switch"],group:S,callback:()=>Kt(e),toasts:{on:`Force ${t} is ON!`,off:`Force ${t} is OFF!`,error:`Failed to toggle Force ${t}. Check console.`}})}}class Qt extends D{constructor(t){super({id:"RefreshDropdowns",name:()=>"Refresh Champions",legend:()=>"Normally champion selectors refresh automatically...",tags:[S,"refresh"],group:S,callback:t,toasts:{success:"Refreshed Champions!",error:"Failed to refresh Champions. Check console."}})}}class Zt extends lt{constructor(t){super("Pick","controladoPick",t)}}class te extends lt{constructor(t){super("Ban","controladoBan",t)}}class ee extends dt{constructor(){super("Pick","controladoPick")}}class ne extends dt{constructor(){super("Ban","controladoBan")}}function oe(i){for(const t of i)CommandBar.addAction(t)}const ie=2e3,se=200,re=6e4,ae=".auto-select-champ-select-menu__header",b=Object.freeze({autoAccept:"controladoAutoAccept",pick:"controladoPick",ban:"controladoBan"});async function ce(){C(b.autoAccept).enabled===!0&&(console.debug("auto-champion-select(auto-accept): Ready check detected, accepting in 2 seconds..."),await g(ie),await le())}async function le(){const i=await f("POST",h.readyCheckAccept);i.ok?console.debug("auto-champion-select(auto-accept): Accepted ready check"):console.error("auto-champion-select(auto-accept): Failed to accept ready check",i)}async function de(i){const t=await f("GET",h.gameflowPhase),e=t.ok?await t.json():null;i.handleGameflowPhase(e)}function he({championSelect:i,champSelectControlsMenu:t,setupChampionSelectors:e}){let n=0;return async function(a){const c=++n;try{await o(a,c)}catch(p){console.error("auto-champion-select: Failed to handle gameflow phase",p)}};async function o(r,a){r==="ReadyCheck"&&ce().catch(c=>console.error("auto-champion-select(auto-accept): Failed to handle ready check",c)),await s(r),a===n&&await e()}async function s(r){r==="ChampSelect"?(i.mount(),await t.mount()):(i.unmount(),await t.unmount())}}function ue(){const i=new Mt,t=new _("Accept",b.autoAccept),e=new _("Pick",b.pick),n=new V("Add pick",b.pick,_t,{enablePositionRestrictions:!0}),o=new _("Ban",b.ban),s=new V("Add ban",b.ban,Lt),r=pe(n,s),a=me(t,e,o),c=new Xt("Auto champion select",r,a);return{championSelect:i,autoAcceptToggle:t,pickToggle:e,banToggle:o,pickChampionSelector:n,banChampionSelector:s,selectorsContainer:r,checkboxesContainer:a,pluginSection:c,championSelectors:[n,s]}}function pe(...i){const t=document.createElement("div");return t.append(...i.map(e=>e.element)),t}function me(...i){const t=document.createElement("div");return t.classList.add("auto-select-checkboxes-div"),t.append(...i.map(e=>e.element)),t}function fe({pluginSection:i,checkboxesContainer:t,selectorsContainer:e}){let n=null,o=0,s=()=>!1;async function r(a){let c=q();for(;!c;){if(s()||a!==o)return;await g(se),c=q()}s()||a!==o||c.append(i.element,t,e)}return{setIsChampSelectControlsMounted(a){s=a},returnControlsToSocialRoster(){if(n)return n;const a=++o;return n=r(a).catch(c=>console.error("auto-champion-select: Failed to return controls to social roster",c)).finally(()=>{n=null}),n}}}function ge({autoAcceptToggle:i,pickToggle:t,banToggle:e}){i.setup(),t.setup(),e.setup()}async function Ce(i){await Promise.all(i.map(t=>t.setup()))}async function we(i){await Promise.all(i.map(t=>t.refresh()))}function be(){const i=ue(),t=fe(i),e=new Vt("Auto Champion Select",t.returnControlsToSocialRoster,[i.checkboxesContainer,i.selectorsContainer]);t.setIsChampSelectControlsMounted(()=>e.mounted);const n={...i,champSelectControlsMenu:e,setupToggles:()=>ge(i),setupChampionSelectors:()=>Ce(i.championSelectors),refreshChampionSelectors:()=>we(i.championSelectors),refreshPickChampionSelector:async()=>{await i.pickChampionSelector.refresh()}};return n.handleGameflowPhase=he(n),n}function Se(i){N(h.gameflowPhase,t=>{i.handleGameflowPhase(t.data)}),N(h.wallet,async t=>{if(t.eventType==="Update"){console.debug("auto-champion-select(wallet): Refreshing champion selectors...");try{await i.refreshPickChampionSelector()}catch(e){console.error("auto-champion-select(wallet): Failed to refresh champion selectors",e)}}})}function Pe({pickToggle:i,banToggle:t,refreshChampionSelectors:e}){oe([new Zt(()=>i.toggle()),new te(()=>t.toggle()),new ee,new ne,new Qt(e)])}function ye(i){let t=null,e=null;function n(){e==null||e.disconnect(),e=null,t!==null&&(cancelAnimationFrame(t),t=null)}const o=setTimeout(()=>{n()},re);function s(){if(!(R()!==null))return;clearTimeout(o),n(),document.querySelector(ae)!==null||i.handleGameflowPhase("ChampSelect")}e=new MutationObserver(()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,s()}))}),e.observe(document.body,{childList:!0,subtree:!0}),s()}async function Ee(){const i=be();i.setupToggles(),Pe(i),Se(i),await de(i),ye(i),console.debug(`auto-champion-select(${ut}): Report bugs to Balaclava#1912`)}let X=!1;function J(){X||(X=!0,Ee().catch(i=>console.error("auto-champion-select: Failed to initialize",i)))}document.readyState==="loading"?window.addEventListener("load",J,{once:!0}):J();export{J as load};
116
+ `;function V(o){const t=document.createElement(p.dropdownOption);return t.setAttribute("slot",p.dropdownOption),t.innerText=o,t}class qt{constructor(t,e,n,i={}){this.dropdownElement=t,this.placeholderText=e,this.searchPlaceholderText=i.searchPlaceholderText||"Search",this.onChampionSelected=n,this.placeholderOption=null}renderOptions(t){this.dropdownElement.replaceChildren(),this.placeholderOption=V(this.placeholderText),this.placeholderOption.setAttribute("selected","true"),this.hidePlaceholderOption(),this.dropdownElement.appendChild(this.placeholderOption);for(const e of t){const n=this.createChampionOption(e);this.dropdownElement.appendChild(n)}}createChampionOption(t){const e=V(t.name);return e.addEventListener("click",()=>{this.onChampionSelected(t.id),requestAnimationFrame(()=>this.reset())}),e}async waitForRender(){for(let t=0;t<zt;t++){const e=this.dropdownElement.shadowRoot;if(this.dropdownElement.isConnected&&(e!=null&&e.querySelector(c.dropdownCurrent)))return e;await g(Ut)}return null}ensureSearchPlaceholder(t){if(t.querySelector(`#${W}`))return;const e=t.querySelector(c.dropdownCurrent);e&&e.appendChild(this.createSearchPlaceholder())}createSearchPlaceholder(){const t=document.createElement("div");t.classList.add(ut,pt),t.id=W;const e=document.createElement("input");e.classList.add(ht),e.id=j,e.type="text",e.placeholder=this.searchPlaceholderText,e.setAttribute("aria-label",this.searchPlaceholderText),e.size=Math.max(this.searchPlaceholderText.length,1);const n=document.createElement("span");return n.classList.add(dt),n.addEventListener("click",()=>{n.classList.contains(w)&&this.clearSearch(e,n)}),e.addEventListener("input",i=>{this.ensureOpen(),this.filterOptions(i.target.value),n.classList.toggle(w,!!i.target.value)}),["pointerdown","click"].forEach(i=>{t.addEventListener(i,s=>s.stopPropagation()),n.addEventListener(i,s=>s.stopPropagation())}),["pointerdown","focusin"].forEach(i=>{e.addEventListener(i,s=>s.stopPropagation(),!0)}),t.appendChild(n),t.appendChild(e),t}clearSearch(t,e){t.value="",this.filterOptions(""),e.classList.toggle(w,!1)}filterOptions(t){const e=t.toLowerCase();this.dropdownElement.querySelectorAll(c.dropdownOption).forEach(i=>{if(i===this.placeholderOption){this.hidePlaceholderOption();return}(i.textContent??"").toLowerCase().includes(e)?i.style.display="":i.style.display="none"})}hidePlaceholderOption(){this.placeholderOption&&(this.placeholderOption.style.display="none")}reset(){var t;this.dropdownElement.querySelectorAll(c.dropdownOptionSelected).forEach(e=>{e.removeAttribute("selected")}),(t=this.placeholderOption)==null||t.setAttribute("selected","true"),this.withShadowRoot(e=>{var s;const n=e.querySelector(`#${j}`),i=e.querySelector(`.${w}`);n&&i?this.clearSearch(n,i):(n&&(n.value="",this.filterOptions("")),i&&i.classList.remove(w)),this.isOpen()&&((s=e.querySelector(c.dropdownCurrent))==null||s.click())})}isOpen(){return this.dropdownElement.classList.contains("active")}ensureOpen(){this.isOpen()||this.withShadowRoot(t=>{const e=t.querySelector(c.dropdownCurrent);e&&e.click()})}patchDropdownShadowDom(){this.withShadowRoot(t=>{this.ensureDropdownOpensUpward(t),this.injectDropdownSearchStyles(t)})}ensureDropdownOpensUpward(t){var e;(e=t.querySelector(c.dropdownRoot))==null||e.classList.add("opens-upward")}injectDropdownSearchStyles(t){if(t.querySelector("style[data-controlado='dropdown-tags']"))return;const e=document.createElement("style");e.dataset.controlado="dropdown-tags",e.textContent=Gt,t.appendChild(e)}withShadowRoot(t){const e=this.dropdownElement.shadowRoot;e&&t(e)}}const Ht=".champion-priority-selector__position-badge",Yt=".champion-priority-selector__position-option",Wt=".champion-priority-selector__remove",jt="✕",Vt=0,X=1,P=8,Xt=5,Kt=150,Jt="cubic-bezier(0.2, 0, 0, 1)";class K{constructor(t,e,n,i={}){this.element=this.createRootElement(),this.dropdownElement=this.createDropdownElement(),this.championDropdown=new qt(this.dropdownElement,t,a=>this.addChampion(a),{searchPlaceholderText:i.searchPlaceholderText});const{scrollElement:s,trackElement:r}=this.createSelectedChampionsScroll();this.scrollElement=s,this.trackElement=r,this.enablePositionRestrictions=i.enablePositionRestrictions===!0,this.positionMenuElement=this.enablePositionRestrictions?this.createPositionMenu():null,this.positionMenuChampionId=null,this.positionsByChampionId={},this.emptyElement=this.createEmptyState(t),this.element.append(this.dropdownElement,this.scrollElement),this.positionMenuElement&&this.element.appendChild(this.positionMenuElement),this.config=null,this.configKey=e,this.loadChampions=n,this.champions=[],this.championById=new Map,this.selectedChampionIds=[],this.iconButtons=new Map,this.dragState=null,this.handleWindowPointerMove=a=>this.moveDrag(a),this.handleWindowPointerUp=a=>this.finishDrag(a),this.handleWindowPointerCancel=a=>this.cancelDrag(a),this.handlePositionMenuOutsidePointerDown=a=>this.closePositionMenuOnOutsidePointerDown(a),this.handlePositionMenuKeyDown=a=>this.closePositionMenuOnKeyDown(a),this.setupInFlight=null,this.setupPending=!1}createRootElement(){const t=document.createElement("div");return t.classList.add("champion-priority-selector"),t}createDropdownElement(){const t=document.createElement(p.dropdown);return t.classList.add("dropdown-champions-default","dropdown-drop-up"),t}createSelectedChampionsScroll(){const t=document.createElement(p.scrollable);t.classList.add("champion-priority-selector__scroll"),t.setAttribute("direction","horizontal"),t.setAttribute("overflow-masks","disabled"),t.setAttribute("side-scroll-wheel","true");const e=document.createElement("div");return e.classList.add("champion-priority-selector__track"),t.appendChild(e),{scrollElement:t,trackElement:e}}createEmptyState(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__empty");const n=document.createElement("span");n.innerText="No champions";const i=document.createElement("span"),s=t.replace(/^Add\s+/i,"").toLowerCase();return i.innerText=`Use dropdown to add ${s} option`,e.append(n,i),e}createPositionMenu(){const t=document.createElement("div");t.classList.add("champion-priority-selector__position-menu"),t.hidden=!0;for(const e of E)t.appendChild(this.createPositionOption(e));return t}createPositionOption(t){const e=document.createElement("button");e.classList.add("champion-priority-selector__position-option"),e.type="button",e.dataset.position=t.value,e.title=t.label,e.setAttribute("aria-label",t.label),e.setAttribute("aria-pressed","false"),e.addEventListener("pointerdown",i=>i.stopPropagation()),e.addEventListener("click",i=>{i.stopPropagation(),this.toggleChampionPosition(t.value)});const n=document.createElement("img");return n.src=t.iconPath,n.alt=t.label,n.draggable=!1,e.appendChild(n),e}async setup(){return this.setupPending=!0,this.setupInFlight||(this.setupInFlight=this.runSetupLoop()),this.setupInFlight}refresh(){return this.setup()}async runSetupLoop(){try{for(;this.setupPending;)this.setupPending=!1,await this.performSetup()}finally{this.setupInFlight=null}}async performSetup(){this.champions=await this.loadChampions(),this.championById=new Map(this.champions.map(n=>[n.id,n]));const t=this.getAllowedChampionIds();this.config=at(this.configKey,{allowedChampionIds:t}),this.selectedChampionIds=nt(this.config.champions,t),this.enablePositionRestrictions&&(this.positionsByChampionId=M(this.config.positionsByChampionId,this.selectedChampionIds)),this.championDropdown.renderOptions(this.champions),this.renderSelectedChampions();const e=await this.championDropdown.waitForRender();e&&(this.championDropdown.ensureSearchPlaceholder(e),this.championDropdown.patchDropdownShadowDom())}getAllowedChampionIds(){return new Set(this.championById.keys())}addChampion(t){const e=d(t);e===null||!this.championById.has(e)||this.selectedChampionIds.includes(e)||(this.selectedChampionIds.push(e),this.renderSelectedChampions(),this.saveConfig())}removeChampion(t){const e=d(t),n=this.selectedChampionIds.indexOf(e);e===null||n===-1||(this.selectedChampionIds.splice(n,1),this.positionMenuChampionId===e&&this.closePositionMenu(),this.enablePositionRestrictions&&delete this.positionsByChampionId[String(e)],this.renderSelectedChampions(),this.saveConfig())}moveChampionToIndex(t,e){const n=d(t),i=this.selectedChampionIds.indexOf(n);if(n===null||i===-1)return!1;const[s]=this.selectedChampionIds.splice(i,1),r=Math.max(0,Math.min(e,this.selectedChampionIds.length));return this.selectedChampionIds.splice(r,0,s),i!==r}syncPositionsByChampionId(){this.enablePositionRestrictions&&(this.positionsByChampionId=M(this.positionsByChampionId,this.selectedChampionIds))}saveConfig(){this.syncPositionsByChampionId();const t=this.getAllowedChampionIds();this.config=N(this.configKey,e=>(e.champions=[...this.selectedChampionIds],this.enablePositionRestrictions&&(e.positionsByChampionId={...this.positionsByChampionId}),e),{allowedChampionIds:t,selectedChampionIds:this.selectedChampionIds}),this.enablePositionRestrictions&&(this.positionsByChampionId=this.config.positionsByChampionId||{}),console.debug(this.configKey,this.config)}renderSelectedChampions(t=null,e=null){this.positionMenuChampionId!==null&&this.closePositionMenu();const n=new Set(this.selectedChampionIds);for(const[s,r]of this.iconButtons)n.has(s)||(r.remove(),this.iconButtons.delete(s));if(this.selectedChampionIds.length===0){this.trackElement.replaceChildren(this.emptyElement);return}this.emptyElement.remove();const i=this.selectedChampionIds.map((s,r)=>this.getIconButton(s,r)).filter(Boolean);this.trackElement.append(...i),t&&this.animateReorder(t,e)}getIconButton(t,e){const n=this.championById.get(t);if(!n)return null;let i=this.iconButtons.get(t);i||(i=this.createIconButton(n),this.iconButtons.set(t,i)),i.dataset.rank=String(e+1);const s=this.getChampionPositionTitleSuffix(t);i.title=`${e+1}. ${n.name}${s}`,i.setAttribute("aria-label",`${e+1}. ${n.name}${s}`);const r=i.querySelector("img");r.src=n.squarePortraitPath,r.alt=n.name;const a=i.querySelector(Wt);return a.setAttribute("aria-label",`Remove ${n.name}`),a.title=`Remove ${n.name}`,this.renderPositionBadge(i,t),i}createIconButton(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__icon"),e.setAttribute("role","button"),e.tabIndex=0;const n=document.createElement("img");n.draggable=!1;const i=document.createElement("button");return i.classList.add("champion-priority-selector__remove"),i.type="button",i.dataset.icon=jt,i.addEventListener("pointerdown",s=>s.stopPropagation()),i.addEventListener("click",s=>{s.stopPropagation(),this.removeChampion(t.id)}),e.addEventListener("pointerdown",s=>this.startDrag(s,t.id)),e.addEventListener("auxclick",s=>this.removeChampionOnMiddleClick(s,t.id)),this.enablePositionRestrictions&&e.addEventListener("contextmenu",s=>this.openPositionMenu(s,t.id)),e.append(n,i),e}getChampionAllowedPositions(t){const e=d(t);return e===null?[]:this.positionsByChampionId[String(e)]||[]}getChampionAllowedPositionLabels(t){return this.getChampionAllowedPositions(t).map(e=>{var n;return(n=z(e))==null?void 0:n.label}).filter(Boolean)}getChampionPositionTitleSuffix(t){const e=this.getChampionAllowedPositionLabels(t);return e.length>0?` (${e.join(", ")})`:""}renderPositionBadge(t,e){var i;if((i=t.querySelector(Ht))==null||i.remove(),!this.enablePositionRestrictions)return;const n=this.createPositionBadge(e);n&&t.appendChild(n)}createPositionBadge(t){const e=this.getChampionAllowedPositions(t),n=this.getChampionAllowedPositionLabels(t),i=document.createElement("button");if(i.classList.add("champion-priority-selector__position-badge"),i.type="button",i.title=n.length>0?`${n.join(", ")}. Click to edit positions.`:"Any position. Click to restrict positions.",i.setAttribute("aria-label",i.title),i.addEventListener("pointerdown",a=>a.stopPropagation()),i.addEventListener("click",a=>this.openPositionMenu(a,t,i)),e.length===0)return i.classList.add("champion-priority-selector__position-badge--empty"),i.innerText="+",i;const s=z(e[0]);if(!s)return null;e.length>1&&(i.dataset.count=String(e.length));const r=document.createElement("img");return r.src=s.iconPath,r.alt=s.label,r.draggable=!1,i.appendChild(r),i}openPositionMenu(t,e,n=null){if(!this.enablePositionRestrictions||!this.positionMenuElement)return;const i=d(e);if(i===null||!this.selectedChampionIds.includes(i))return;t.preventDefault(),t.stopPropagation(),this.positionMenuChampionId=i,this.renderPositionMenu(),this.positionMenuElement.hidden=!1,this.positionMenuElement.style.left="0px",this.positionMenuElement.style.top="0px";const{left:s,top:r}=this.getPositionMenuCoordinates(t,n);this.positionMenuElement.style.left=`${s}px`,this.positionMenuElement.style.top=`${r}px`,document.addEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.addEventListener("keydown",this.handlePositionMenuKeyDown,!0)}getPositionMenuCoordinates(t,e=null){const n=this.positionMenuElement.getBoundingClientRect();let i=t.clientX,s=t.clientY;if(e&&t.type==="click"&&t.detail===0){const l=e.getBoundingClientRect();i=l.left+l.width/2,s=l.bottom}const r=Math.min(Math.max(i,P),window.innerWidth-n.width-P),a=Math.min(Math.max(s,P),window.innerHeight-n.height-P);return{left:r,top:a}}renderPositionMenu(){if(!this.positionMenuElement||this.positionMenuChampionId===null)return;const t=new Set(this.getChampionAllowedPositions(this.positionMenuChampionId));this.positionMenuElement.querySelectorAll(Yt).forEach(e=>{const n=t.has(e.dataset.position);e.classList.toggle("champion-priority-selector__position-option--selected",n),e.setAttribute("aria-pressed",String(n))})}toggleChampionPosition(t){if(!this.enablePositionRestrictions||this.positionMenuChampionId===null)return;const e=I(t);if(!e)return;const n=String(this.positionMenuChampionId),i=new Set(this.positionsByChampionId[n]||[]);i.has(e)?i.delete(e):i.add(e);const s=E.map(l=>l.value).filter(l=>i.has(l));s.length>0?this.positionsByChampionId[n]=s:delete this.positionsByChampionId[n],this.renderPositionMenu();const r=this.iconButtons.get(this.positionMenuChampionId),a=this.selectedChampionIds.indexOf(this.positionMenuChampionId);r&&a!==-1&&this.getIconButton(this.positionMenuChampionId,a),this.saveConfig()}closePositionMenuOnOutsidePointerDown(t){var e;(e=this.positionMenuElement)!=null&&e.contains(t.target)||this.closePositionMenu()}closePositionMenuOnKeyDown(t){t.key==="Escape"&&this.closePositionMenu()}closePositionMenu(){this.positionMenuElement&&(this.positionMenuElement.hidden=!0,this.positionMenuChampionId=null,document.removeEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.removeEventListener("keydown",this.handlePositionMenuKeyDown,!0))}startDrag(t,e){var i;if(t.button===X){t.preventDefault();return}if(t.button!==Vt)return;this.dragState&&this.clearDragState();const n=this.iconButtons.get(e);if(n){this.dragState={championId:e,pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,active:!1,moved:!1};try{(i=n.setPointerCapture)==null||i.call(n,t.pointerId)}catch{}window.addEventListener("pointermove",this.handleWindowPointerMove),window.addEventListener("pointerup",this.handleWindowPointerUp),window.addEventListener("pointercancel",this.handleWindowPointerCancel)}}removeChampionOnMiddleClick(t,e){t.button===X&&(t.preventDefault(),t.stopPropagation(),this.removeChampion(e))}moveDrag(t){var h;if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.championId,n=t.clientX-this.dragState.startX,i=t.clientY-this.dragState.startY,s=Math.hypot(n,i);if(!this.dragState.active){if(s<Xt)return;this.dragState.active=!0,(h=this.iconButtons.get(e))==null||h.classList.add("champion-priority-selector__icon--dragging")}t.preventDefault();const r=this.getDropIndex(t.clientX,e),a=this.selectedChampionIds.indexOf(e);if(r===a||r===-1)return;const l=this.getIconPositions();this.moveChampionToIndex(e,r)&&(this.dragState.moved=!0,this.renderSelectedChampions(l,e))}finishDrag(t){if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.active,n=this.dragState.moved;this.clearDragState(),e&&n&&this.saveConfig()}cancelDrag(t){!this.dragState||this.dragState.pointerId!==t.pointerId||this.clearDragState()}clearDragState(){var i;if(!this.dragState)return;const{championId:t,pointerId:e}=this.dragState,n=this.iconButtons.get(t);n==null||n.classList.remove("champion-priority-selector__icon--dragging");try{(i=n==null?void 0:n.releasePointerCapture)==null||i.call(n,e)}catch{}window.removeEventListener("pointermove",this.handleWindowPointerMove),window.removeEventListener("pointerup",this.handleWindowPointerUp),window.removeEventListener("pointercancel",this.handleWindowPointerCancel),this.dragState=null}getDropIndex(t,e){const n=this.selectedChampionIds.filter(i=>i!==e);for(let i=0;i<n.length;i++){const s=this.iconButtons.get(n[i]);if(!s)continue;const r=s.getBoundingClientRect();if(t<r.left+r.width/2)return i}return n.length}getIconPositions(){const t=new Map;for(const e of this.selectedChampionIds){const n=this.iconButtons.get(e);n&&t.set(e,n.getBoundingClientRect())}return t}animateReorder(t,e){for(const n of this.selectedChampionIds){if(n===e)continue;const i=this.iconButtons.get(n),s=t.get(n);if(!i||!s||typeof i.animate!="function")continue;const r=i.getBoundingClientRect(),a=s.left-r.left,l=s.top-r.top;a===0&&l===0||i.animate([{transform:`translate(${a}px, ${l}px)`},{transform:"translate(0, 0)"}],{duration:Kt,easing:Jt})}}}const Qt=200,k="auto-select-champ-select-menu--collapsed",Zt="auto-select-champ-select-menu-button-wrapper--open";class v{constructor(t,e){this.element=document.createElement(p.radioInputOption),this.element.classList.add("lol-settings-voice-input-mode-option","auto-select-checkbox"),this.element.innerText=t,this.config=null,this.configKey=e,this.setupComplete=!1}setup(){this.syncFromConfig(),this.setupComplete||(this.element.addEventListener("click",()=>this.toggle()),this.setupComplete=!0)}syncFromConfig(){this.config=at(this.configKey),this.element.toggleAttribute("selected",this.config.enabled===!0)}toggle(){return console.debug("auto-champion-select: Toggling",this.configKey),this.config=N(this.configKey,t=>(t.enabled=!t.enabled,t)),this.element.toggleAttribute("selected",this.config.enabled===!0),this.config.enabled}}class te{constructor(t,e,n){this.element=document.createElement("div"),this.element.classList.add("auto-select-champ-select-menu",k),this.buttonWrapper=document.createElement("div"),this.buttonWrapper.classList.add("auto-select-champ-select-menu-button-wrapper"),this.headerElement=document.createElement("button"),this.headerElement.classList.add("auto-select-champ-select-menu__header"),this.headerElement.type="button",this.headerElement.setAttribute("aria-label",t),this.headerElement.setAttribute("aria-expanded","false"),this.headerElement.addEventListener("click",()=>this.toggle()),this.contentElement=document.createElement("div"),this.contentElement.classList.add("auto-select-champ-select-menu__content"),this.titleElement=document.createElement("div"),this.titleElement.classList.add("auto-select-champ-select-menu__title"),this.titleElement.textContent=t,this.buttonWrapper.append(this.headerElement,this.element),this.contentElement.appendChild(this.titleElement),this.element.appendChild(this.contentElement),this.returnControlsToSocialRoster=e,this.controlElements=n,this.boundCloseOnOutsideInteraction=i=>this.closeOnOutsideInteraction(i),this.buttonObserver=null,this.buttonMountFrame=null,this.buttonMountTask=null,this.hiddenStates=new WeakMap,this.mounted=!1}async mount(){return this.mounted?this.mountButton():(this.mounted=!0,this.controlElements.forEach(t=>{this.hiddenStates.set(t,t.classList.contains("hidden")),t.classList.remove("hidden"),this.contentElement.appendChild(t)}),this.observeButtonContainer(),document.addEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.mountButton())}unmount(){return this.mounted?(this.mounted=!1,this.stopButtonMounting(),document.removeEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.setOpen(!1),this.buttonWrapper.remove(),this.restoreHiddenStates(),this.returnControlsToSocialRoster()):this.returnControlsToSocialRoster()}stopButtonMounting(){var t;(t=this.buttonObserver)==null||t.disconnect(),this.buttonObserver=null,this.buttonMountFrame!==null&&(cancelAnimationFrame(this.buttonMountFrame),this.buttonMountFrame=null),this.buttonMountTask=null}restoreHiddenStates(){this.controlElements.forEach(t=>{t.classList.toggle("hidden",this.hiddenStates.get(t)===!0),this.hiddenStates.delete(t)})}isOpen(){return!this.element.classList.contains(k)}setOpen(t){this.element.classList.toggle(k,!t),this.buttonWrapper.classList.toggle(Zt,t),this.headerElement.setAttribute("aria-expanded",String(t))}toggle(){this.setOpen(!this.isOpen())}closeOnOutsideInteraction(t){if(!this.isOpen())return;(typeof t.composedPath=="function"?t.composedPath():[]).includes(this.buttonWrapper)||this.buttonWrapper.contains(t.target)||this.setOpen(!1)}observeButtonContainer(){this.buttonObserver=new MutationObserver(()=>this.scheduleMountButton()),this.buttonObserver.observe(document.body,{childList:!0,subtree:!0})}scheduleMountButton(){this.buttonMountFrame===null&&(this.buttonMountFrame=requestAnimationFrame(()=>{this.buttonMountFrame=null,this.mountButton()}))}mountButton(){return this.buttonMountTask||(this.buttonMountTask=this.appendButtonToContainer().finally(()=>{this.buttonMountTask=null})),this.buttonMountTask}async appendButtonToContainer(){let t=L();for(;this.mounted&&!t;)await g(Qt),t=L();if(!this.mounted||!t)return;const e=t.querySelector(c.firstChampSelectSquareButton);this.buttonWrapper.parentNode===t&&this.buttonWrapper.nextSibling===e||t.insertBefore(this.buttonWrapper,e)}}class ee{constructor(t,...e){this.element=document.createElement(p.socialRosterGroup),this.element.addEventListener("post-render",()=>this.onPostRender()),this.element.addEventListener("click",()=>this.onClick()),this.label=t,this.collapsibleElements=e,this.waitRender()}waitRender(){new MutationObserver((t,e)=>{if(this.element.querySelector(c.socialRosterGroupLabel)){const n=new Event("post-render");this.element.dispatchEvent(n),e.disconnect()}}).observe(this.element,{childList:!0})}onPostRender(){var t;this.element.querySelector(c.socialRosterGroupLabel).innerText=this.label,(t=this.element.querySelector(c.socialRosterGroupHeader))==null||t.removeAttribute("draggable")}onClick(){var t;this.collapsibleElements.forEach(e=>{e.closest(".auto-select-champ-select-menu")||e.classList.toggle("hidden")}),(t=this.element.querySelector(c.socialRosterGroupArrow))==null||t.toggleAttribute("open")}}function mt(o){var t,e;o&&((e=(t=globalThis.Toast)==null?void 0:t.success)==null||e.call(t,o))}function B(o){var t,e;o&&((e=(t=globalThis.Toast)==null?void 0:t.error)==null||e.call(t,o))}function ne(o,t){const e=globalThis.Toast;return typeof(e==null?void 0:e.promise)=="function"?e.promise(o,t):o}const y="Balaclava: Auto Champion Select";function oe(o){return typeof(o==null?void 0:o.then)=="function"}class F{constructor({id:t,name:e,legend:n,tags:i,group:s,callback:r,toasts:a}){this.id=t,this.name=e,this.legend=n,this.tags=i,this.group=s,this.perform=this.perform.bind(this),this.callback=r,this.toasts=a}perform(){try{const t=this.callback();if(oe(t))return ne(t,{loading:this.toasts.loading,success:this.toasts.success,error:this.toasts.error});const e=this.toasts.success||(t?this.toasts.on:this.toasts.off);mt(e)}catch(t){B(this.toasts.error),console.error(t)}}}class ft extends F{constructor(t,e,n){super({id:`${e}Switch`,name:()=>`Auto ${t} [${C(e).enabled?"ON":"OFF"}]`,legend:()=>C(e).enabled?"Turn OFF":"Turn ON",tags:[y,e,"switch"],group:y,callback:n,toasts:{on:`Auto ${t} is ON!`,off:`Auto ${t} is OFF!`,error:`Failed to toggle Auto ${t}. Check console.`}})}}function ie(o){return N(o,e=>(e.force=!e.force,e)).force}class gt extends F{constructor(t,e){super({id:`${e}ForceSwitch`,name:()=>`Force ${t} [${C(e).force?"ON":"OFF"}]`,legend:()=>`Ignore team intent and force ${t} the selected champion`,tags:[y,e,"force","switch"],group:y,callback:()=>ie(e),toasts:{on:`Force ${t} is ON!`,off:`Force ${t} is OFF!`,error:`Failed to toggle Force ${t}. Check console.`}})}}class se extends F{constructor(t){super({id:"RefreshDropdowns",name:()=>"Refresh Champions",legend:()=>"Normally champion selectors refresh automatically...",tags:[y,"refresh"],group:y,callback:t,toasts:{success:"Refreshed Champions!",error:"Failed to refresh Champions. Check console."}})}}class re extends ft{constructor(t){super("Pick","controladoPick",t)}}class ae extends ft{constructor(t){super("Ban","controladoBan",t)}}class le extends gt{constructor(){super("Pick","controladoPick")}}class ce extends gt{constructor(){super("Ban","controladoBan")}}function de(o){for(const t of o)CommandBar.addAction(t)}const he=200,ue=6e4,J=2e3,pe=".ready-check-root-element",me="#lol-uikit-layer-manager-wrapper > .modal",fe="Accepted ready check!",Q="Failed to accept ready check. Check console.",ge=".auto-select-champ-select-menu__header",b=Object.freeze({autoAccept:"controladoAutoAccept",pick:"controladoPick",ban:"controladoBan"});function Ct(){return C(b.autoAccept).enabled===!0}class Ce{constructor(t){this.isEnabled=t,this.observer=null,this.hiddenModal=null,this.hiddenModalStyles=new WeakMap,this.sync=this.sync.bind(this)}start(){this.observer||(this.observer=new MutationObserver(()=>this.sync()),this.observer.observe(document.body,{childList:!0,subtree:!0}),this.sync())}sync(){const t=we();if(!t){this.restore();return}if(!this.isEnabled()){this.restore();return}this.hide(t)}hide(t){this.hiddenModal!==t&&(this.restore(),this.hiddenModal=t,this.hiddenModalStyles.set(t,{display:t.style.getPropertyValue("display"),displayPriority:t.style.getPropertyPriority("display"),pointerEvents:t.style.getPropertyValue("pointer-events"),pointerEventsPriority:t.style.getPropertyPriority("pointer-events")}),t.style.setProperty("display","none","important"),t.style.setProperty("pointer-events","none","important"))}restore(){if(!this.hiddenModal)return;const t=this.hiddenModal,e=this.hiddenModalStyles.get(t);Z(t,"display",e==null?void 0:e.display,e==null?void 0:e.displayPriority),Z(t,"pointer-events",e==null?void 0:e.pointerEvents,e==null?void 0:e.pointerEventsPriority),this.hiddenModalStyles.delete(t),this.hiddenModal=null}}function we(){const o=document.querySelector(pe);return(o==null?void 0:o.closest(me))||null}function Z(o,t,e,n){e?o.style.setProperty(t,e,n||""):o.style.removeProperty(t)}async function be(o){function t(){return Ct()?!1:(o.restore(),!0)}if(t()||(console.debug(`auto-champion-select(auto-accept): Ready check detected, accepting in ${J}ms...`),await g(J),t()))return;let e=!1;try{e=await ye()}catch(n){throw o.restore(),B(Q),n}e?mt(fe):(o.restore(),B(Q))}async function ye(){const o=await f("POST",u.readyCheckAccept);return o.ok?(console.debug("auto-champion-select(auto-accept): Accepted ready check"),!0):(console.error("auto-champion-select(auto-accept): Failed to accept ready check",o),!1)}async function Se(o){const t=await f("GET",u.gameflowPhase),e=t.ok?await t.json():null;o.handleGameflowPhase(e)}function Pe({championSelect:o,champSelectControlsMenu:t,readyCheckModalSuppressor:e,setupChampionSelectors:n}){let i=0;return async function(l){const h=++i;try{await s(l,h)}catch(A){console.error("auto-champion-select: Failed to handle gameflow phase",A)}};async function s(a,l){a==="ReadyCheck"?be(e).catch(h=>{console.error("auto-champion-select(auto-accept): Failed to handle ready check",h)}):e.restore(),await r(a),l===i&&await n()}async function r(a){a==="ChampSelect"?(o.mount(),await t.mount()):(o.unmount(),await t.unmount())}}function Ee(){const o=new $t,t=new v("Accept",b.autoAccept),e=new v("Pick",b.pick),n=new K("Add pick",b.pick,Dt,{enablePositionRestrictions:!0}),i=new v("Ban",b.ban),s=new K("Add ban",b.ban,xt),r=Ie(n,s),a=Ae(t,e,i),l=new ee("Auto champion select",r,a);return{championSelect:o,autoAcceptToggle:t,pickToggle:e,banToggle:i,pickChampionSelector:n,banChampionSelector:s,selectorsContainer:r,checkboxesContainer:a,pluginSection:l,championSelectors:[n,s]}}function Ie(...o){const t=document.createElement("div");return t.append(...o.map(e=>e.element)),t}function Ae(...o){const t=document.createElement("div");return t.classList.add("auto-select-checkboxes-div"),t.append(...o.map(e=>e.element)),t}function Oe({pluginSection:o,checkboxesContainer:t,selectorsContainer:e}){let n=null,i=0,s=()=>!1;async function r(a){let l=Y();for(;!l;){if(s()||a!==i)return;await g(he),l=Y()}s()||a!==i||l.append(o.element,t,e)}return{setIsChampSelectControlsMounted(a){s=a},returnControlsToSocialRoster(){if(n)return n;const a=++i;return n=r(a).catch(l=>console.error("auto-champion-select: Failed to return controls to social roster",l)).finally(()=>{n=null}),n}}}function Te({autoAcceptToggle:o,pickToggle:t,banToggle:e,readyCheckModalSuppressor:n}){o.setup(),o.element.addEventListener("click",()=>n.sync()),t.setup(),e.setup()}async function _e(o){await Promise.all(o.map(t=>t.setup()))}async function ke(o){await Promise.all(o.map(t=>t.refresh()))}function ve(){const o=Ee(),t=new Ce(Ct),e=Oe(o),n=new te("Auto Champion Select",e.returnControlsToSocialRoster,[o.checkboxesContainer,o.selectorsContainer]);e.setIsChampSelectControlsMounted(()=>n.mounted);const i={...o,champSelectControlsMenu:n,readyCheckModalSuppressor:t,setupToggles:()=>Te({...o,readyCheckModalSuppressor:t}),setupChampionSelectors:()=>_e(o.championSelectors),refreshChampionSelectors:()=>ke(o.championSelectors),refreshPickChampionSelector:async()=>{await o.pickChampionSelector.refresh()}};return i.handleGameflowPhase=Pe(i),i}function Me(o){$(u.gameflowPhase,t=>{o.handleGameflowPhase(t.data)}),$(u.wallet,async t=>{if(t.eventType==="Update"){console.debug("auto-champion-select(wallet): Refreshing champion selectors...");try{await o.refreshPickChampionSelector()}catch(e){console.error("auto-champion-select(wallet): Failed to refresh champion selectors",e)}}})}function Re({pickToggle:o,banToggle:t,refreshChampionSelectors:e}){de([new re(()=>o.toggle()),new ae(()=>t.toggle()),new le,new ce,new se(e)])}function Le(o){let t=null,e=null;function n(){e==null||e.disconnect(),e=null,t!==null&&(cancelAnimationFrame(t),t=null)}const i=setTimeout(()=>{n()},ue);function s(){if(!(L()!==null))return;clearTimeout(i),n(),document.querySelector(ge)!==null||o.handleGameflowPhase("ChampSelect")}e=new MutationObserver(()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,s()}))}),e.observe(document.body,{childList:!0,subtree:!0}),s()}async function Be(){const o=ve();o.setupToggles(),o.readyCheckModalSuppressor.start(),Re(o),Me(o),await Se(o),Le(o),console.debug(`auto-champion-select(${wt}): Report bugs to Balaclava#1912`)}let tt=!1;function et(){tt||(tt=!0,Be().catch(o=>console.error("auto-champion-select: Failed to initialize",o)))}document.readyState==="loading"?window.addEventListener("load",et,{once:!0}):et();export{et as load};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "auto-champion-select",
3
- "version": "1.8.6",
3
+ "version": "1.8.7",
4
4
  "description": "Pick or ban automatically! 🐧",
5
5
  "author": "balaclava",
6
6
  "repository": {