repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.onOperatorChange
onOperatorChange($event) { this.formFilter.get('value').setValue(null); this.isMultipleSelectValue(); }
/** * When change operator set value to null, and set current multiple var * @param $event Operator */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L213-L216
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.applySelectFilter
applySelectFilter(): boolean { const fieldSelected = this.formFilter.get('field').value; // if field exist if (this.field) { if (this.field.type === ElasticDataTypesEnum.TEXT || this.field.type === ElasticDataTypesEnum.STRING) { /* if fields is type string or text determine if field is a keyword or not, if field is keyword return result of function operatorFieldSelectable() that return if current operator cant apply select or input */ if (fieldSelected.includes('.keyword')) { return this.operatorFieldSelectable(); } else { // if type of current filter is not keyword return result of validation if current operator is selectable or not return this.selectableOperators.includes(this.formFilter.get('operator').value); } } else if (this.field.type === ElasticDataTypesEnum.DATE) { return this.formFilter.get('operator').value === ElasticOperatorsEnum.IS_ONE_OF || this.formFilter.get('operator').value === ElasticOperatorsEnum.IS_NOT_ONE_OF; } else { // if current field is not a date or text return result of function if field filter value cant show select or input return this.operatorFieldSelectable(); } } else { return false; } }
/** * Return boolean, if show input or select values */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L221-L246
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.operatorFieldSelectable
operatorFieldSelectable(): boolean { return this.operator === this.operatorEnum.IS || this.operator === this.operatorEnum.IS_NOT || this.operator === this.operatorEnum.IS_ONE_OF || this.operator === this.operatorEnum.IS_NOT_ONE_OF; }
/** * Return boolean, using to determine if current operator is selectable or not */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L251-L254
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.operator
get operator(): ElasticOperatorsEnum { return this.formFilter.get('operator').value; }
/** * Return current operator */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L259-L261
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.getIndexField
getIndexField(): number { return this.fields.findIndex(value => value.name === this.formFilter.get('field').value); }
/** * Return index of field selected */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L276-L278
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.field
get field(): ElasticSearchFieldInfoType { const field = this.formFilter.get('field').value; const index = this.fields.findIndex(value => value.name === field); if (index !== -1) { return this.fields[index]; } }
/** * return current field selected */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L283-L289
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.getOperators
getOperators() { const index = this.getIndexField(); if (index !== -1) { const fieldType = this.fields[index].type; if (fieldType === ElasticDataTypesEnum.TEXT || fieldType === ElasticDataTypesEnum.STRING) { if (!this.field.name.includes('.keyword')) { this.operators = FILTER_OPERATORS.filter(value => value.operator !== ElasticOperatorsEnum.IS_BETWEEN && value.operator !== ElasticOperatorsEnum.IS_NOT_BETWEEN); } else { this.operators = FILTER_OPERATORS.filter(value => value.operator !== ElasticOperatorsEnum.IS_BETWEEN && value.operator !== ElasticOperatorsEnum.CONTAIN && value.operator !== ElasticOperatorsEnum.DOES_NOT_CONTAIN && value.operator !== ElasticOperatorsEnum.IS_NOT_BETWEEN); } } else if (fieldType === ElasticDataTypesEnum.LONG || fieldType === ElasticDataTypesEnum.NUMBER || fieldType === ElasticDataTypesEnum.DATE) { this.operators = FILTER_OPERATORS.filter(value => value.operator !== ElasticOperatorsEnum.CONTAIN && value.operator !== ElasticOperatorsEnum.DOES_NOT_CONTAIN); } else { this.operators = FILTER_OPERATORS; } } }
/** * Return operators based on field type */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L294-L320
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.isMultipleSelectValue
isMultipleSelectValue() { this.multiple = this.formFilter.get('operator').value === ElasticOperatorsEnum.IS_ONE_OF || this.formFilter.get('operator').value === ElasticOperatorsEnum.IS_NOT_ONE_OF || this.formFilter.get('operator').value === ElasticOperatorsEnum.CONTAIN_ONE_OF || this.formFilter.get('operator').value === ElasticOperatorsEnum.DOES_NOT_CONTAIN_ONE_OF; }
/** * Determine if a field select value cant choose multiple values or not */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L325-L330
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ElasticFilterAddComponent.setValueRange
setValueRange() { this.formFilter.get('value').setValue([this.valueFrom, this.valueTo]); }
/** * Set a filter value with a range */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/filters/utm-elastic-filter/elastic-filter-add/elastic-filter-add.component.ts#L335-L337
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
UtmDynamicTableComponent.isSortableColumn
isSortableColumn(column: UtmFieldType): boolean { if (column.type === ElasticDataTypesEnum.TEXT || column.type === ElasticDataTypesEnum.STRING) { return column.field.includes('.keyword'); } else { return true; } }
/** * Find in all field if column type text has keyword * @param column Column to check if column cant be sort */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/table/utm-table/dynamic-table/dynamic-table.component.ts#L122-L128
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
UtmScrollTopComponent.scrolled
scrolled(event: any): void { this.isScrolled = true; }
// <- Add scroll listener to window
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/components/utm/util/utm-scroll-top/utm-scroll-top.component.ts#L18-L20
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
SafePipe.constructor
constructor(protected _sanitizer: DomSanitizer) { }
// tslint:disable-next-line
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/pipes/safe.pipe.ts#L18-L19
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
SafePipe.transform
transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl { switch (type) { case 'html': return this._sanitizer.bypassSecurityTrustHtml(value); case 'style': return this._sanitizer.bypassSecurityTrustStyle(value); case 'script': return this._sanitizer.bypassSecurityTrustScript(value); case 'url': return this._sanitizer.bypassSecurityTrustUrl(value); case 'resourceUrl': return this._sanitizer.bypassSecurityTrustResourceUrl(value); default: return this._sanitizer.bypassSecurityTrustHtml(value); } }
/** * Transform * * @param value: string * @param type: string */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/pipes/safe.pipe.ts#L27-L42
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ActiveAdModuleActiveService.isADModuleActive
isADModuleActive(): Observable<boolean> { return new Observable<boolean>(subscriber => { this.moduleService.isActive(UtmModulesEnum.AD_AUDIT).subscribe(response => { subscriber.next(response.body); }); }); }
/** * Find is ad module is active */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/active-modules/active-ad-module.service.ts#L22-L28
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
ActiveAdModuleActiveService.getAdChanges
getAdChanges(): Observable<HttpResponse<any[]>> { return this.http.get<any[]>(this.resourceUrl + 'ad/utm-ad-trackers/tracking', {observe: 'response'}); }
// GET /api/ad/utm-ad-trackers/tracking
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/active-modules/active-ad-module.service.ts#L32-L34
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
UtmConfigSectionService.constructor
constructor(private http: HttpClient) { }
// GET /api/GET /api/utm-technologies
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/config/utm-config-section.service.ts#L15-L16
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.create
create(menu: IMenu): Observable<HttpResponse<IMenu>> { return this.http.post<IMenu>(this.resourceUrl, menu, {observe: 'response'}); }
/** * Create * @param menu : Menu to create */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L25-L27
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.update
update(menu: IMenu): Observable<HttpResponse<IMenu>> { return this.http.put<IMenu>(this.resourceUrl, menu, {observe: 'response'}); }
/** * Update * @param menu : Menu to update */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L33-L35
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.saveStructure
saveStructure(menus: IMenu[]): Observable<HttpResponse<IMenu>> { return this.http.post<IMenu>(this.resourceUrl + '/save-menu-structure', menus, {observe: 'response'}); }
// POST /api/menu/save-menu-structure
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L38-L40
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.find
find(name: string): Observable<HttpResponse<IMenu>> { return this.http.get<IMenu>(`${this.resourceUrl}/${name}`, {observe: 'response'}); }
/** * Find menus by name * @param name : Name to search */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L46-L48
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.query
query(query?: QueryType): Observable<HttpResponse<IMenu[]>> { return this.http.get<IMenu[]>(this.resourceUrl.concat(query ? query.toString() : ''), {observe: 'response'}); }
/** * Find menus by filters */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L53-L55
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.getMenuStructure
getMenuStructure(includeModulesMenus: boolean): Observable<HttpResponse<IMenu[]>> { return this.http.get<IMenu[]>(this.resourceUrl + '/all?includeModulesMenus=' + includeModulesMenus, {observe: 'response'}); }
/** * Find menus by filters */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L60-L62
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.delete
delete(id: number): Observable<HttpResponse<any>> { return this.http.delete(`${this.resourceUrl}/${id}`, {observe: 'response'}); }
/** * Delete menu * @param id : Menu identifier to delete */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L68-L70
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
MenuService.deleteByUrl
deleteByUrl(url: string): Observable<HttpResponse<any>> { return this.http.delete(this.resourceUrl + '/delete-by-url?url=' + url, {observe: 'response'}); }
/** * Delete menu by URL * @param url Menu url */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/services/menu/menu.service.ts#L77-L79
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
QueryType.add
add(field: string, value: any, operator?: Operator): QueryType { if (field && value !== null && typeof value !== 'undefined') { if (operator) { if (!this.query) { this.query = `?${field}.${operator}=${value}`; } else { this.query += `&${field}.${operator}=${value}`; } } else { if (!this.query) { this.query = `?${field}=${value}`; } else { this.query += `&${field}=${value}`; } } } return this; }
/** * Build a query based on url parameters * @param field : Name of the param * @param value : Value of the param * @param operator : Operator between param and value */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/types/query-type.ts#L12-L29
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
QueryType.toString
toString(): string { return this.query ? this.query : ''; }
/** * */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/types/query-type.ts#L34-L36
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
mixColor
function mixColor(colorOne, colorTwo, weight): string { function d2h(d) { return d.toString(16); } // convert a decimal value to hex function h2d(h) { return parseInt(h, 16); } weight = (typeof (weight) !== 'undefined') ? weight : 50; // set the weight to 50%, if that argument is omitted let color = '#'; for (let i = 0; i <= 5; i += 2) { // loop through each of the 3 hex pairs—red, green, and blue const v1 = h2d(colorOne.substr(i, 2)); // extract the current pairs const v2 = h2d(colorTwo.substr(i, 2)); // combine the current pairs from each source color, according to the specified weight let val = d2h(Math.floor(v2 + (v1 - v2) * (weight / 100.0))); while (val.length < 2) { val = '0' + val; } // prepend a '0' if val results in a single digit color += val; // concatenate val to our new color string } return color; }
/** * Mixing Two colors * @param colorOne Color one * @param colorTwo Color two * @param weight Weight */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/util/color-mixing.ts#L7-L32
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
InputClassResolve.resolveClassInput
resolveClassInput(control: AbstractControl): string { if (control.errors && (control.touched || control.dirty)) { return 'input-field-has-error'; } else { return 'input-field-has-noerror'; } }
/** * Return class to apply to input base on errors * @param control AbstractControl in form */
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/shared/util/input-class-resolve.ts#L15-L21
e00c7c4742b5ce01932668d00f6a87bb5307505d
UTMStack
github_2023
utmstack
typescript
VsTaskElementViewResolverService.resolveTrendClass
resolveTrendClass(trend: VsTaskTrendEnum): string { if (trend === VsTaskTrendEnum.UP || trend === VsTaskTrendEnum.MORE) { return 'badge-danger'; } else if (trend === VsTaskTrendEnum.LESS || trend === VsTaskTrendEnum.DOWN) { return 'badge-success'; } else { return 'badge-primary'; } }
// up|down|more|less|same
https://github.com/utmstack/UTMStack/blob/e00c7c4742b5ce01932668d00f6a87bb5307505d/frontend/src/app/vulnerability-scanner/shared/services/vs-task-element-view-resolver.service.ts#L58-L66
e00c7c4742b5ce01932668d00f6a87bb5307505d
Morpheus
github_2023
MorpheusAIs
typescript
deployOneYearLockFixture
async function deployOneYearLockFixture() { const ONE_YEAR_IN_SECS = 365 * 24 * 60 * 60; const ONE_GWEI = 1_000_000_000; const lockedAmount = ONE_GWEI; const unlockTime = (await time.latest()) + ONE_YEAR_IN_SECS; // Contracts are deployed using the first signer/account by default const [owner, otherAccount] = await ethers.getSigners(); const Lock = await ethers.getContractFactory("Lock"); const lock = await Lock.deploy(unlockTime, { value: lockedAmount }); return { lock, unlockTime, lockedAmount, owner, otherAccount }; }
// We define a fixture to reuse the same setup in every test.
https://github.com/MorpheusAIs/Morpheus/blob/c3012007db93f10d8d345b0f3f935598c12c21f4/contract_library/test/Lock.ts#L10-L24
c3012007db93f10d8d345b0f3f935598c12c21f4
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
init
async function init() { if (isIdentityLoaded.value) { return } isIdentityLoaded.value = true await refreshIdentity() }
/** * Initial request of the user identity for plugin initialization. * Only call this method when `sanctum.client.initialRequest` is false. */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/composables/useSanctumAuth.ts#L49-L56
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
refreshIdentity
async function refreshIdentity() { user.value = await client<T>(options.endpoints.user!) }
/** * Fetches the user object from the API and sets it to the current state */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/composables/useSanctumAuth.ts#L61-L63
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
login
async function login(credentials: Record<string, any>) { const currentRoute = useRoute() const currentPath = trimTrailingSlash(currentRoute.path) if (isAuthenticated.value) { if (!options.redirectIfAuthenticated) { throw new Error('User is already authenticated') } if ( options.redirect.onLogin === false || options.redirect.onLogin === currentPath ) { return } if (options.redirect.onLogin === undefined) { throw new Error('`sanctum.redirect.onLogin` is not defined') } await nuxtApp.runWithContext( async () => await navigateTo(options.redirect.onLogin as string), ) } if (options.endpoints.login === undefined) { throw new Error('`sanctum.endpoints.login` is not defined') } const response = await client<TokenResponse>(options.endpoints.login, { method: 'post', body: credentials, }) if (options.mode === 'token') { if (appConfig.tokenStorage === undefined) { throw new Error('`sanctum.tokenStorage` is not defined in app.config.ts') } if (response.token === undefined) { throw new Error('Token was not returned from the API') } await appConfig.tokenStorage.set(nuxtApp, response.token) } await refreshIdentity() if (options.redirect.keepRequestedRoute) { const requestedRoute = currentRoute.query.redirect as string | undefined if (requestedRoute && requestedRoute !== currentPath) { await nuxtApp.runWithContext(async () => await navigateTo(requestedRoute)) return } } if ( options.redirect.onLogin === false || currentRoute.path === options.redirect.onLogin ) { return } if (options.redirect.onLogin === undefined) { throw new Error('`sanctum.redirect.onLogin` is not defined') } await nuxtApp.runWithContext( async () => await navigateTo(options.redirect.onLogin as string), ) }
/** * Calls the login endpoint and sets the user object to the current state * * @param credentials Credentials to pass to the login endpoint */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/composables/useSanctumAuth.ts#L70-L141
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
logout
async function logout() { if (!isAuthenticated.value) { throw new Error('User is not authenticated') } const currentRoute = useRoute() const currentPath = trimTrailingSlash(currentRoute.path) if (options.endpoints.logout === undefined) { throw new Error('`sanctum.endpoints.logout` is not defined') } await client(options.endpoints.logout, { method: 'post' }) user.value = null if (options.mode === 'token') { if (appConfig.tokenStorage === undefined) { throw new Error('`sanctum.tokenStorage` is not defined in app.config.ts') } await appConfig.tokenStorage.set(nuxtApp, undefined) } if ( options.redirect.onLogout === false || currentPath === options.redirect.onLogout ) { return } if (options.redirect.onLogout === undefined) { throw new Error('`sanctum.redirect.onLogout` is not defined') } await nuxtApp.runWithContext( async () => await navigateTo(options.redirect.onLogout as string), ) }
/** * Calls the logout endpoint and clears the user object */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/composables/useSanctumAuth.ts#L146-L184
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
useServerHeaders
function useServerHeaders( headers: Headers, config: ModuleOptions, logger: ConsolaInstance, ): Headers { const clientHeaders = useRequestHeaders(['cookie', 'user-agent']) const origin = config.origin ?? useRequestURL().origin const headersToAdd = { Referer: origin, Origin: origin, ...(clientHeaders.cookie && { Cookie: clientHeaders.cookie }), ...(clientHeaders['user-agent'] && { 'User-Agent': clientHeaders['user-agent'] }), } logger.debug( '[request] added client headers to server request', Object.keys(headersToAdd), ) return appendRequestHeaders(headers, headersToAdd) }
/** * Pass all cookies, headers and referrer from the client to the API * @param headers Headers collection to extend * @param config Module configuration * @param logger Logger instance * @returns Headers collection to pass to the API */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/interceptors/cookie/request.ts#L18-L39
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
initCsrfCookie
async function initCsrfCookie( config: ModuleOptions, logger: ConsolaInstance, ): Promise<void> { if (config.endpoints.csrf === undefined) { throw new Error('`sanctum.endpoints.csrf` is not defined') } await $fetch(config.endpoints.csrf, { baseURL: config.baseUrl, credentials: 'include', }) logger.debug('[request] CSRF cookie has been initialized') }
/** * Request a new CSRF cookie from the API * @param config Module configuration * @param logger Logger instance * @returns {Promise<void>} */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/interceptors/cookie/request.ts#L47-L61
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
useCsrfHeader
async function useCsrfHeader( headers: Headers, config: ModuleOptions, logger: ConsolaInstance, ): Promise<Headers> { if (config.csrf.cookie === undefined) { throw new Error('`sanctum.csrf.cookie` is not defined') } if (config.csrf.header === undefined) { throw new Error('`sanctum.csrf.header` is not defined') } let csrfToken = useCookie(config.csrf.cookie, COOKIE_OPTIONS) if (!csrfToken.value) { await initCsrfCookie(config, logger) csrfToken = useCookie(config.csrf.cookie, COOKIE_OPTIONS) } if (!csrfToken.value) { logger.warn(`${config.csrf.cookie} cookie is missing, unable to set ${config.csrf.header} header`) return headers } const headersToAdd = { [config.csrf.header]: csrfToken.value } logger.debug(`[request] added csrf token header`, Object.keys(headersToAdd)) return appendRequestHeaders(headers, headersToAdd) }
/** * Add CSRF token to the headers collection to pass from the client to the API * @param headers Headers collection to extend * @param config Module configuration * @param logger Logger instance * @returns Headers collection to pass to the API */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/interceptors/cookie/request.ts#L70-L100
a7084fb6c383f9f6229c2b70be3df60b19cf429f
nuxt-auth-sanctum
github_2023
manchenkoff
typescript
appendServerResponseHeaders
function appendServerResponseHeaders( app: NuxtApp, ctx: FetchContext, logger: ConsolaInstance, ): void { const event = useRequestEvent(app) const serverCookieName = 'set-cookie' const cookieHeader = ctx.response!.headers.get(serverCookieName) if (cookieHeader === null || event === undefined) { logger.debug(`[response] no cookies to pass to the client [${ctx.request}]`) return } const cookies = splitCookiesString(cookieHeader) const cookieNameList = [] for (const cookie of cookies) { appendResponseHeader(event, serverCookieName, cookie) const cookieName = cookie.split('=')[0] cookieNameList.push(cookieName) } logger.debug( `[response] pass cookies from server to client response`, cookieNameList, ) }
/** * Append server response headers to the client response * @param app Nuxt application instance * @param ctx Fetch context * @param logger Module logger instance */
https://github.com/manchenkoff/nuxt-auth-sanctum/blob/a7084fb6c383f9f6229c2b70be3df60b19cf429f/src/runtime/interceptors/cookie/response.ts#L12-L40
a7084fb6c383f9f6229c2b70be3df60b19cf429f
boardzilla-core
github_2023
boardzilla
typescript
GameManager.setSettings
setSettings(settings: Record<string, any>) { this.settings = settings; }
/** * configuration functions */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/game-manager.ts#L114-L116
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameManager.start
start() { if (this.phase === 'started') throw Error('cannot call start once started'); if (!this.players.length) { throw Error("No players"); } this.phase = 'started'; this.players.currentPosition = [...this.players].map(p => p.position) this.flowState = [{stack: [], currentPosition: this.players.currentPosition}]; this.startFlow(); }
// start the game fresh
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/game-manager.ts#L130-L139
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameManager.getState
getState(player?: P): GameState { return { players: this.players.map(p => p.toJSON() as PlayerAttributes), // TODO scrub for player settings: this.settings, position: this.flowJSON(!!player), board: this.game.allJSON(player?.position), sequence: this.sequence, messages: this.messages.filter(m => player && (!m.position || m.position === player?.position)), announcements: [...this.announcements], rseed: player ? '' : this.rseed, } }
/** * state functions * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/game-manager.ts#L245-L256
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameManager.getAction
getAction(name: string, player: P) { if (this.godMode) { const godModeAction = this.godModeActions()[name]; if (godModeAction) { godModeAction.name = name; return godModeAction as Action & {name: string}; } } if (!this.actions[name]) { throw Error(`No action found: "${name}". All actions must be specified in defineActions()`); } return this.inContextOfPlayer(player, () => { const action = this.actions[name](player); action.gameManager = this; action.name = name; return action as Action & {name: string}; }); }
/** * action functions */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/game-manager.ts#L318-L337
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameManager.processMove
processMove({ player, name, args }: Move): string | undefined { if (this.phase === 'finished') return 'Game is finished'; let result: string | SubflowSignal['data'][] | undefined; return this.inContextOfPlayer(player, () => { if (this.godMode && this.godModeActions()[name]) { const godModeAction = this.godModeActions()[name]; result = godModeAction._process(player, args); } else { result = this.flow().processMove({ name, player: player.position, args }); } console.debug(`Received move from player #${player.position} ${name}({${Object.entries(args).map(([k, v]) => `${k}: ${v}`).join(', ')}}) ${result ? (typeof result === 'string' ? '❌ ' + result : `⮕ ${result[0].name}({${Object.entries(result[0].args || {}).map(([k, v]) => `${k}: ${v}`).join(', ')}})`) : '✅'}`); if (result instanceof Array) { for (const flow of result.reverse()) this.beginSubflow(flow); } return typeof result === 'string' ? result : undefined; }); }
// moves
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/game-manager.ts#L380-L400
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action._getPendingMoves
_getPendingMoves(args: Record<string, Argument>, debug?: ActionDebug): PendingMove[] | undefined { if (debug) { debug[this.name!] = { args: {} }; for (const arg of Object.keys(args)) debug[this.name!].args[arg] = 'sel'; } const moves = this._getPendingMovesInner(args, debug); // resolve any combined selections now with only args up until first choice if (moves?.length) { for (const move of moves) { if (debug) { debug[move.name].args[move.selections[0].name] = 'ask'; } const combineWith = move.selections[0].clientContext?.combineWith; // guaranteed single selection let confirm: Selection['confirm'] | undefined = move.selections[0].confirm; let validation: Selection['validation'] | undefined = move.selections[0].validation; // look ahead for any selections that can/should be combined for (let i = this.selections.findIndex(s => s.name === move.selections[0].name) + 1; i !== this.selections.length; i++) { if (confirm) break; // do not skip an explicit confirm let selection: Selection | ResolvedSelection = this.selections[i]; if (combineWith?.includes(selection.name)) selection = selection.resolve(move.args); if (!selection.isResolved()) break; const arg = selection.isForced(); if (arg !== undefined) { // forced future args are added here to shorten the form and pre-prompt any confirmation move.args[selection.name] = arg; if (debug) { debug[move.name].args[selection.name] = 'forced'; } } else if (combineWith?.includes(selection.name)) { // future combined selections are added as well move.selections.push(selection); if (debug) { debug[move.name].args[selection.name] = 'ask'; } } else { break; } confirm = selection.confirm ?? confirm; // find latest confirm for the overall combination validation = selection.validation ?? validation; } if (confirm) move.selections[0].confirm = confirm; // and put it on top if (validation) move.selections[move.selections.length - 1].validation = validation; // on bottom } } return moves; }
// TODO memoize
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L127-L170
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action._nextSelection
_nextSelection(args: Record<string, Argument>): ResolvedSelection | undefined { let nextSelection: ResolvedSelection | undefined = undefined; for (const s of this.selections) { const selection = s.resolve(args); if (selection.skipIf === true) continue; if (!(s.name in args)) { nextSelection = selection; break; } } return nextSelection; }
/** * given a partial arg list, returns a selection object for continuation if one exists. * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L247-L258
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action._process
_process(player: Player, args: Record<string, Argument>): string | undefined { // truncate invalid args - is this needed? let error: string | undefined = undefined; if (!this.isPossible(args as A)) return `${this.name} action not possible`; for (const selection of this.selections) { if (args[selection.name] === undefined) { const arg = selection.resolve(args).isForced() if (arg) args[selection.name] = arg; } error = this._withDecoratedArgs(args as A, args => selection.error(args)) if (error) { console.error(`Invalid choice for ${selection.name}. Got "${args[selection.name]}" ${error}`); break; } } if (error) return error; // revalidate on server. quite expensive. easier way? I think this might just be counting the args since the validation already passed ^^ if (!globalThis.window) { const pendingMoves = this._getPendingMoves(args); if (!pendingMoves) { console.error('attempted to process invalid args', this.name, args); return error || 'unknown error during action._process'; } if (pendingMoves.length) { return error || 'incomplete action'; } } let moveIndex = 0; let messageIndex = 0; for (const seq of this.order) { if (seq === 'move') { this.moves[moveIndex++](args); } else { const message = this.messages[messageIndex++]; const messageArgs = ((typeof message.args === 'function') ? message.args(args as A) : message.args); if (message.position) { this.gameManager.game.messageTo(message.position, message.text, {...args, player, ...messageArgs}); } else { this.gameManager.game.message(message.text, {...args, player, ...messageArgs}); } } } }
/** * process this action with supplied args. returns error if any * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L264-L309
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action._withDecoratedArgs
_withDecoratedArgs(args: A, fn: (args: A) => any) { if (args['__placement__']) { const placementSelection = this.selections.find(s => s.name === '__placement__'); if (placementSelection && args[placementSelection.placePiece!]) { args = {...args}; // temporarily set piece to place to access position properties const placePiece = (args[placementSelection.placePiece!] as Piece<Game>); const { row, column, _rotation } = placePiece; const [newColumn, newRow, newRotation] = args['__placement__'] as [number, number, number?]; placePiece.column = newColumn; placePiece.row = newRow; placePiece.rotation = newRotation ?? 0; const result = fn(args); placePiece.column = column; placePiece.row = row; placePiece._rotation = _rotation; return result; } } return fn(args); }
// fn must be idempotent
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L319-L339
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.do
do(move: (args: A) => any): Action<A> { this.mutated = true; this.moves.push(move); this.order.push('move'); return this; }
/** * Add behaviour to this action to alter game state. After adding the choices * to an action, calling `do` causes Boardzilla to use the player choices to * actually do something with those choices. Call this method after all the * methods for player choices so that the choices are properly available to * the `do` function. * * @param move - The action to perform. This function accepts one argument * with key-value pairs for each choice added to the action using the provided * names. * * @example * player => action({ * prompt: 'Take resources', * }).chooseFrom({ * 'resource', ['lumber', 'steel'], * { prompt: 'Select resource' } * }).chooseNumber( * 'amount', { * prompt: 'Select amount', * max: 3 * }).do(({ resource, amount }) => { * // the choices are automatically passed in with their proper type * game.firstN(amount, Resource, {resource}).putInto( * player.my('stockPile') * ); * }) * @category Behaviour */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L383-L388
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.message
message(text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>)) { this.messages.push({text, args}); this.order.push('message'); return this; }
/** * Add a message to this action that will be broadcast in the chat. Call this * method after all the methods for player choices so that the choices are * properly available to the `message` function. However the message should be * called before or after any `do` behaviour depending on whether you want the * message to reflect the game state before or after the move is performs. The * action's `message` and `do` functions can be intermixed in this way to * generate messages at different points int the execution of a move. * * @param text - The text of the message to send. This can contain interpolated * strings with double braces just as when calling {@link Game#message} * directly. However when using this method, the player performing the action, * plus any choices made in the action are automatically made available. * * @param args - If additional strings are needed in the message besides * 'player' and the player choices, these can be specified here. This can also * be specified as a function that accepts the player choices and returns * key-value pairs of strings for interpolation. * * @example * action({ * prompt: 'Say something', * }).enterText({ * 'message', * }).message( * '{{player}} said {{message}}' // no args needed * ).message( * "I said, {{player}} said {{loudMessage}}", * ({ message }) => ({ loudMessage: message.toUpperCase() }) * ) * @category Behaviour */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L422-L426
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.messageTo
messageTo(player: (Player | number) | (Player | number)[], text: string, args?: Record<string, Argument> | ((a: A) => Record<string, Argument>)) { if (!(player instanceof Array)) player = [player]; for (const p of player) { this.messages.push({position: typeof p === 'number' ? p : p.position, text, args}); this.order.push('message'); } return this; }
/** * Add a message to this action that will be broadcast in the chat to the * specified player(s). Call this method after all the methods for player * choices so that the choices are properly available to the `message` * function. However the message should be called before or after any `do` * behaviour depending on whether you want the message to reflect the game * state before or after the move is performs. The action's `message` and `do` * functions can be intermixed in this way to generate messages at different * points int the execution of a move. * * @param player - Player or players to receive the message * * @param text - The text of the message to send. This can contain interpolated * strings with double braces just as when calling {@link Game#message} * directly. However when using this method, the player performing the action, * plus any choices made in the action are automatically made available. * * @param args - If additional strings are needed in the message besides * 'player' and the player choices, these can be specified here. This can also * be specified as a function that accepts the player choices and returns * key-value pairs of strings for interpolation. * * @example * action({ * prompt: 'Say something', * }).enterText({ * 'message', * }).message( * '{{player}} said {{message}}' // no args needed * ).message( * "I said, {{player}} said {{loudMessage}}", * ({ message }) => ({ loudMessage: message.toUpperCase() }) * ) * @category Behaviour */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L463-L470
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.chooseFrom
chooseFrom<N extends string, T extends SingleArgument>( name: N, choices: (T & (string | number | boolean))[] | { label: string, choice: T }[] | ((args: A) => (T & (string | number | boolean))[] | { label: string, choice: T }[]), options?: { prompt?: string | ((args: A) => string) confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: T}) => Record<string, Argument>) | undefined] validate?: ((args: A & {[key in N]: T}) => string | boolean | undefined) // initial?: T | ((...arg: A) => T), // needed for select-boxes? skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean); } ): Action<A & {[key in N]: T}> { this._addSelection(new Selection(name, { prompt: options?.prompt, validation: options?.validate, confirm: options?.confirm, skipIf: options?.skipIf, selectFromChoices: { choices } })); return this as unknown as Action<A & {[key in N]: T}>; }
/** * Add a choice to this action from a list of options. These choices will be * displayed as buttons in the UI. * * @param name - The name of this choice. This name will be used in all * functions that accept the player's choices * * @param choices - An array of choices. This may be an array of simple values * or an array of objects in the form: `{ label: string, choice: value }` * where value is the actual choice that will be passed to the rest of the * action, but label is the text presented to the player that they will be * prompted to click. Use the object style when you want player text to * contain additional logic or differ in some way from the choice, similiar to * `<option value="key">Some text</option>` in HTML. This can also be a * function that returns the choice array. This function will accept arguments * for each choice the player has made up to this point in the action. * * @param {Object} options * @param options.prompt - Prompt displayed to the user for this choice. * @param options.skipIf - One of 'always', 'never' or 'only-one' or a * function returning a boolean. (Default 'only-one'). * * <ul> * <li>only-one: If there is only valid choice in the choices given, the game * will skip this choice, prompting the player for subsequent choices, if any, * or completing the action otherwise. * <li>always: Rather than present this choice directly, the player will be * prompted with choices from the *next choice* in the action for each * possible choice here, essentially expanding the choices ahead of time to * save the player a step. This option only has relevance if there are * subsequent choices in the action. * <li>never: Always present this choice, even if the choice is forced * <li>function: A function that accepts all player choices up to this point * and returns a boolean. If returning true, this choice will be skipped. * This form is useful in the rare situations where the choice at the time may * be meaningless, e.g. selecting from a set of identical tokens. In this case * the game will make the choice for the player using the first viable option. * </ul> * * @param options.validate - A function that takes an object of key-value * pairs for all player choices and returns a boolean. If false, the game will * not allow the player to submit this choice. If a string is returned, this * will display as the reason for disallowing these selections. * * @param options.confirm - A confirmation message that the player will always * see before commiting this choice. This can be useful to present additional * information about the consequences of this choice, or simply to force the * player to hit a button with a clear message. This can be a simple string, * or a 2-celled array in the same form as {@link message} with a string * message and a set of key-value pairs for string interpolation, optionally * being a function that takes an object of key-value pairs for all player * choices, and returns the interpolation object. * * @example * action({ * prompt: 'Choose color', * }).chooseFrom( * 'color', ['white', 'blue', 'red'], * ).do( * ({ color }) => ... color will be equal to the player-selected color ... * ) * * // a more complex example: * action({ * prompt: 'Take resources', * }).chooseFrom( * 'resource', ['lumber', 'steel', 'oil'], * { prompt: 'Select resource' } * ).chooseFrom( * // Use the functional style to include the resource choice in the text * // Also use object style to have the value simply be "high" or "low" * 'grade', ({ resource }) => [ * { choice: 'high', label: `High grade ${resource}` } * { choice: 'low', label: `Low grade ${resource}` } * ], * { * // A follow-up choice that doesn't apply to "oil" * skipIf: ({ resource }) => resource === 'oil', * // Add an 'are you sure?' message * confirm: ['Buy {{grade}} grade {{resource}}?', ({ grade }) = ({ grade: grade.toUpperCase() })] * } * ).do ( * ({ resource, grade }) => { * // resource will equal 'lumber', 'steel' or 'oil' * // grade will equal 'high' or 'low' * } * ) * @category Choices */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L561-L580
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.enterText
enterText<N extends string>(name: N, options?: { prompt?: string | ((args: A) => string), validate?: ((args: A & {[key in N]: string}) => string | boolean | undefined), regexp?: RegExp, initial?: string | ((args: A) => string) }): Action<A & {[key in N]: string}> { const { prompt, validate, regexp, initial } = options || {} this._addSelection(new Selection(name, { prompt, validation: validate, enterText: { regexp, initial }})); return this as unknown as Action<A & {[key in N]: string}>; }
/** * Prompt the user for text entry. Use this in games where players submit * text, like word-guessing games. * * @param name - The name of this text input. This name will be used in all * functions that accept the player's choices * * @param {Object} options * @param options.initial - Default text that can appear initially before a * user types. * @param options.prompt - Prompt displayed to the user for entering this * text. * * @param options.validate - A function that takes an object of key-value * pairs for all player choices and returns a boolean. If false, the game will * not allow the player to submit this text. If a string is returned, this * will display as the reason for disallowing this text. * * @example * action({ * prompt: 'Guess a word', * }).enterText({ * 'guess', * { prompt: 'Your guess', } * }).message( * guess => `{{player}} guessed ${guess}` * }) * @category Choices */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L611-L620
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.chooseNumber
chooseNumber<N extends string>(name: N, options: { min?: number | ((args: A) => number), max?: number | ((args: A) => number), prompt?: string | ((args: A) => string), confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in N]: number}) => Record<string, Argument>) | undefined] validate?: ((args: A & {[key in N]: number}) => string | boolean | undefined), initial?: number | ((args: A) => number), skipIf?: 'never' | 'always' | 'only-one' | ((args: A) => boolean); } = {}): Action<A & {[key in N]: number}> { const { min, max, prompt, confirm, validate, initial, skipIf } = options; this._addSelection(new Selection(name, { prompt, confirm, validation: validate, skipIf, selectNumber: { min, max, initial } })); return this as unknown as Action<A & {[key in N]: number}>; }
/** * Add a numerical choice for this action. This will be presented with a * number picker. * * @param name - The name of this choice. This name will be used in all * functions that accept the player's choices * * @param {Object} options * * @param options.prompt - Prompt displayed to the user for entering this * number. * * @param options.min - Minimum allowed. Default 1. * * @param options.max - Maximum allowed. Default Infinity * * @param options.initial - Initial value to display in the picker * * @param options.skipIf - One of 'always', 'never' or 'only-one' or a * function returning a boolean. (Default 'only-one'). * * <ul> * <li>only-one: If there is only valid choice in the choices given, the game * will skip this choice, prompting the player for subsequent choices, if any, * or completing the action otherwise. * <li>always: Rather than present this choice directly, the player will be * prompted with choices from the *next choice* in the action for each * possible choice here, essentially expanding the choices ahead of time to * save the player a step. This option only has relevance if there are * subsequent choices in the action. * <li>never: Always present this choice, even if the choice is forced * <li>function: A function that accepts all player choices up to this point * and returns a boolean. If returning true, this choice will be skipped. * This form is useful in the rare situations where the choice at the time may * be meaningless, e.g. selecting from a set of identical tokens. In this case * the game will make the choice for the player using the first viable option. * </ul> * * @param options.validate - A function that takes an object of key-value * pairs for all player choices and returns a boolean. If false, the game will * not allow the player to submit this choice. If a string is returned, this * will display as the reason for disallowing these selections. * * @param options.confirm - A confirmation message that the player will always * see before commiting this choice. This can be useful to present additional * information about the consequences of this choice, or simply to force the * player to hit a button with a clear message. This can be a simple string, * or a 2-celled array in the same form as {@link message} with a string * message and a set of key-value pairs for string interpolation, optionally * being a function that takes an object of key-value pairs for all player * choices, and returns the interpolation object. * * @example * player => action({ * prompt: 'Buy resources', * }).chooseNumber( * 'amount', { * min: 5, * max: 10 // select from 5 - 10 * }).do( * ({ amount }) => player.resource += amount * ); * @category Choices */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L686-L698
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.chooseGroup
chooseGroup<R extends Group>( choices: R, options?: { validate?: (args: ExpandGroup<A, R>) => string | boolean | undefined, confirm?: string | [string, Record<string, Argument> | ((args: ExpandGroup<A, R>) => Record<string, Argument>) | undefined] } ): Action<ExpandGroup<A, R>> { for (const [name, choice] of Object.entries(choices)) { if (choice[0] === 'number') this.chooseNumber(name, choice[1]); if (choice[0] === 'select') this.chooseFrom(name, choice[1], choice[2]); if (choice[0] === 'text') this.enterText(name, choice[1]); } if (options?.confirm) this.selections[this.selections.length - 1].confirm = typeof options.confirm === 'string' ? [options.confirm, undefined] : options.confirm; if (options?.validate) this.selections[this.selections.length - 1].validation = options.validate for (let i = 1; i < Object.values(choices).length; i++) { this.selections[this.selections.length - 1 - i].clientContext = {combineWith: this.selections.slice(-i).map(s => s.name)}; } return this as unknown as Action<ExpandGroup<A, R>>; }
/** * Create a multi-selection choice. These selections will be presented all at * once as a form. This is used for form-like choices that have a number of * choices that are not board choices, i.e. chooseFrom, chooseNumber and * enterText * * @param choices - An object containing the selections. This is a set of * key-value pairs where each key is the name of the selection and each value * is an array of options where the first array element is a string indicating * the type of choice ('number', 'select', 'text') and subsequent elements * contain the options for the appropriate choice function (`chooseNumber`, * `chooseFrom` or `enterText`). * * @param options.validate - A function that takes an object of key-value * pairs for all player choices and returns a boolean. If false, the game will * not allow the player to submit these choices. If a string is returned, this * will display as the reason for disallowing these selections. * * @param options.confirm - A confirmation message that the player will always * see before commiting this choice. This can be useful to present additional * information about the consequences of this choice, or simply to force the * player to hit a button with a clear message. This can be a simple string, * or a 2-celled array in the same form as {@link message} with a string * message and a set of key-value pairs for string interpolation, optionally * being a function that takes an object of key-value pairs for all player * choices, and returns the interpolation object. * * @example * action({ * prompt: 'purchase' * }).chooseGroup({ * lumber: ['number', { min: 2 }], * steel: ['number', { min: 2 }] * }, { * // may not purchase more than 10 total resources * validate: ({ lumber, steel }) => lumber + steel <= 10 * }); * @category Choices */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L901-L919
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.confirm
confirm(prompt: string | ((args: A) => string)): Action<A> { this._addSelection(new Selection('__confirm__', { prompt, confirm: typeof prompt === 'string' ? prompt : ['{{__message__}}', (args: A) => ({__message__: prompt(args)})], value: true })); return this; }
/** * Add a confirmtation step to this action. This can be useful if you want to * present additional information to the player related to the consequences of * their choice, like a cost incurred. Or this can simply be used to force the * user to click an additional button on a particular important choice. * * @param prompt - Button text for the confirmation step. This can be a * function returning the text which accepts each choice the player has made * up till now as an argument. * * @example * action({ * prompt: "Buy resources", * }).chooseNumber({ * 'amount', { * prompt: "Amount", * max: Math.floor(player.coins / 5) * }).confirm( * ({ amount }) => `Spend ${amount * 5} coins` * }).do(({ amount }) => { * player.resource += amount; * player.coins -= amount * 5; * }); */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L945-L952
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.move
move(piece: keyof A | Piece<Game>, into: keyof A | GameElement) { this.do((args: A) => { const selectedPiece = piece instanceof Piece ? piece : args[piece] as Piece<Game> | Piece<Game>[]; const selectedInto = into instanceof GameElement ? into : args[into] as GameElement; if (selectedPiece instanceof Array) { new ElementCollection(...selectedPiece).putInto(selectedInto); } else { selectedPiece.putInto(selectedInto); } }); const pieceSelection = typeof piece === 'string' ? this.selections.find(s => s.name === piece) : undefined; const intoSelection = typeof into === 'string' ? this.selections.find(s => s.name === into) : undefined; if (intoSelection && intoSelection.type !== 'board') throw Error(`Invalid move: "${into as string}" must be the name of a previous chooseOnBoard`); if (pieceSelection && pieceSelection.type !== 'board') throw Error(`Invalid move: "${piece as string}" must be the name of a previous chooseOnBoard`); if (intoSelection?.isMulti()) throw Error("Invalid move: May not move into a multiple choice selection"); if (pieceSelection && !pieceSelection.isMulti()) pieceSelection.clientContext = { dragInto: intoSelection ?? into }; if (intoSelection) intoSelection.clientContext = { dragFrom: pieceSelection ?? piece }; return this; }
/** * Perform a move with the selected element(s) into a selected * Space/Piece. This is almost the equivalent of calling Action#do and adding * a putInto command, except that the game will also permit the UI to allow a * mouse drag for the move. * * @param piece - A {@link Piece} to move or the name of the piece selection in this action * @param into - A {@link GameElement} to move into or the name of the * destination selection in this action. * * player => action({ * prompt: 'Discard a card from hand' * }).chooseOnBoard( * 'card', player.my(Card) * ).move( * 'card', $.discard * ) * @category Behaviour */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L973-L991
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.swap
swap(piece1: keyof A | Piece<Game>, piece2: keyof A | Piece<Game>) { this.do((args: A) => { const p1 = piece1 instanceof Piece ? piece1 : args[piece1] as Piece<Game>; const p2 = piece2 instanceof Piece ? piece2 : args[piece2] as Piece<Game>; const parent1 = p1._t.parent!; const parent2 = p2._t.parent!; const pos1 = p1.position(); const pos2 = p2.position(); const row1 = p1.row; const column1 = p1.column; const row2 = p2.row; const column2 = p2.column; p1.putInto(parent2, { position: pos2, row: row2, column: column2 }); p2.putInto(parent1, { position: pos1, row: row1, column: column1 }); }); const piece1Selection = typeof piece1 === 'string' ? this.selections.find(s => s.name === piece1) : undefined; const piece2Selection = typeof piece2 === 'string' ? this.selections.find(s => s.name === piece2) : undefined; if (piece1Selection && piece1Selection.type !== 'board') throw Error(`Invalid swap: "${piece1 as string}" must be the name of a previous chooseOnBoard`); if (piece2Selection && piece2Selection.type !== 'board') throw Error(`Invalid swap: "${piece2 as string}" must be the name of a previous chooseOnBoard`); if (piece1Selection) piece1Selection.clientContext = { dragInto: piece2Selection ?? piece2 }; return this; }
/** * Swap the location of two Pieces. Each of the two pieces can either be the * name of a previous `chooseOnBoard`, or a simply provide a piece if it is * not a player choice. The game will also allow a mouse drag for the swap. * * @param piece1 - A {@link Piece} to swap or the name of the piece selection in this action * @param piece2 - A {@link Piece} to swap or the name of the piece selection in this action * * player => action({ * prompt: 'Exchange a card from hand with the top of the deck' * }).chooseOnBoard( * 'card', player.my(Card) * ).swap( * 'card', $.deck.first(Card)! * ) * @category Behaviour */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L1010-L1031
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.reorder
reorder(collection: Piece<Game>[], options?: { prompt?: string | ((args: A) => string), }) { const { prompt } = options || {}; if (this.selections.some(s => s.name === '__reorder_from__')) throw Error(`Invalid reorder: only one reorder allowed`); if (collection.some(c => c._t.parent !== collection[0]._t.parent)) throw Error(`Invalid reorder: all elements must belong to the same parent`); const pieceSelection = this._addSelection(new Selection( '__reorder_from__', { prompt, selectOnBoard: { chooseFrom: collection }} )); const intoSelection = this._addSelection(new Selection( '__reorder_to__', { prompt, selectOnBoard: { chooseFrom: ({ __reorder_from__ }) => collection.filter(e => e !== __reorder_from__) }} )); pieceSelection.clientContext = { dragInto: intoSelection }; intoSelection.clientContext = { dragFrom: pieceSelection }; this.do((args: A) => { const reorderFrom = args['__reorder_from__'] as Piece<Game>; const reorderTo = args['__reorder_to__'] as Piece<Game>; let position = reorderTo.position(); reorderFrom.putInto(reorderFrom._t.parent!, { position }); }); return this as unknown as Action<A & {__reorder_to__: Piece<Game>, __reorder_from__: number}>; }
/** * Have the player select one of the Pieces in the collection and select a new * position within the collection while keeping everything else in the same * order. The game will also permit a mouse drag for the reorder. * * @param collection - A collection of {@link Piece}s to reorder * * @param options.prompt - Prompt displayed to the user for this reorder * choice. * * player => action({ * prompt: 'Reorder cards in hand' * }).reorder( * player.my(Card) * ) * @category Behaviour */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L1050-L1071
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Action.placePiece
placePiece<T extends keyof A & string>(piece: T, into: PieceGrid<Game>, options?: { prompt?: string | ((args: A) => string), confirm?: string | [string, Record<string, Argument> | ((args: A & {[key in T]: { column: number, row: number }}) => Record<string, Argument>) | undefined] validate?: ((args: A & {[key in T]: { column: number, row: number }}) => string | boolean | undefined), rotationChoices?: number[], }) { const { prompt, confirm, validate } = options || {}; if (this.selections.some(s => s.name === '__placement__')) throw Error(`Invalid placePiece: only one placePiece allowed`); const pieceSelection = this.selections.find(s => s.name === piece); if (!pieceSelection) throw (`No selection named ${String(piece)} for placePiece`) const positionSelection = this._addSelection(new Selection( '__placement__', { prompt, confirm, validation: validate, selectPlaceOnBoard: {piece, rotationChoices: options?.rotationChoices} } )); positionSelection.clientContext = { placement: { piece, into } }; this.do((args: A & {__placement__: number[]}) => { const selectedPiece = args[piece]; if (!(selectedPiece instanceof Piece)) throw Error(`Cannot place piece selection named ${String(piece)}. Returned ${selectedPiece} instead of a piece`); selectedPiece.putInto(into, { column: args['__placement__'][0], row: args['__placement__'][1] }); selectedPiece.rotation = args['__placement__'][2]; }); if (pieceSelection) pieceSelection.clientContext = { dragInto: into }; return this as unknown as Action<A & {__placement__: number[]} & {[key in T]: { column: number, row: number }}>; }
/** * Add a placement selection to this action. This will be presented as a piece * that players can move into the desired location, snapping to the grid of * the destination as the player moves. * * @param piece - The name of the piece selection in this action from a * `chooseOnBoard` prior to this * @param into - A {@link GameElement} to move into * * @param options.prompt - Prompt displayed to the user for this placement * choice. * * @param options.validate - A function that takes an object of key-value * pairs for all player choices and returns a boolean. The position selected * during the piece placement can be checked by reading the 'column', 'row' * and `rotation` properties of the `piece` as provided in the first * argument. If false, the game will not allow the player to submit these * choices. If a string is returned, this will display as the reason for * disallowing these selections. * * @param options.confirm - A confirmation message that the player will always * see before commiting this choice. This can be useful to present additional * information about the consequences of this choice, or simply to force the * player to hit a button with a clear message. This can be a simple string, * or a 2-celled array in the same form as {@link message} with a string * message and a set of key-value pairs for string interpolation, optionally * being a function that takes an object of key-value pairs for all player * choices, and returns the interpolation object. * * @param options.rotationChoices = An array of valid rotations in * degrees. These choices must be normalized to numbers between 0-359°. If * supplied the piece will be given rotation handles for the player to set the * rotation and position together. * * player => action({ * prompt: 'Place your tile' * }).chooseOnBoard( * 'tile', player.my(Tile) * ).placePiece( * 'tile', $.map, { * confirm: ({ tile }) => [ * 'Place tile into row {{row}} and column {{column}}?', * tile * ] * }) * @category Choices */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/action.ts#L1120-L1142
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Selection.error
error(args: Record<string, Argument>): string | undefined { const arg = args[this.name]; const s = this.resolve(args); if (s.validation) { const error = s.validation(args); if (error !== undefined && error !== true) return error || 'Invalid selection'; } if (s.type === 'choices' && s.choices) { if (arg instanceof Array) return "multi-choice stil unsupported"; return s.choiceValues().includes(arg) ? undefined : "Not a valid choice"; } if (s.type === 'board' && s.boardChoices) { const results = s.boardChoices; if (!results) console.warn('Attempted to validate an impossible move', s); if (this.isMulti()) { if (!(arg instanceof Array)) throw Error("Required multi select"); if (results && arg.some(a => !results.includes(a as GameElement))) return "Selected elements are not valid"; if (s.min !== undefined && arg.length < s.min) return "Below minimum"; if (s.max !== undefined && arg.length > s.max) return "Above maximum"; } else { return (results && results.includes(arg as GameElement)) ? undefined : "Selected element is not valid"; } } if (s.type === 'text') { return (typeof arg === 'string' && (!s.regexp || arg.match(s.regexp))) ? undefined : "Invalid text entered"; } if (s.type === 'number') { if (typeof arg !== 'number') return "Not a number"; if (s.min !== undefined && arg < s.min) return "Below minimum"; if (s.max !== undefined && arg > s.max) return "Above maximum"; return undefined; } return undefined; }
/** * check specific selection with a given arg. evaluates within the context of * previous args, so any selection elements that have previous-arg-function * forms are here evaluated with the previous args. returns new selection and * error if any */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/selection.ts#L204-L243
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
Selection.options
options(this: ResolvedSelection): Argument[] { if (this.isUnbounded()) return []; if (this.type === 'number') return range(this.min ?? 1, this.max!); const choices = this.choiceValues() if (this.isMulti()) return combinations(this.boardChoices || choices, this.min ?? 1, this.max ?? Infinity); if (this.boardChoices) return this.boardChoices; if (this.choices) return choices; return []; }
// All possible valid Arguments to this selection. Have to make some assumptions here to tree shake possible moves
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/action/selection.ts#L246-L254
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ConnectedSpaceMap.isAdjacent
isAdjacent(el1: GameElement, el2: GameElement) { const n1 = this._positionedParentOf(el1); const n2 = this._positionedParentOf(el2); return this._graph.areNeighbors(n1._t.ref, n2._t.ref); }
/** * Returns whether 2 elements contained within this space have an adjacency to * each other. The elements are considered adjacent if they are child Spaces * that have been connected, or if the provided elements are placed inside * such connected Spaces. * @category Adjacency */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/connected-space-map.ts#L41-L45
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ConnectedSpaceMap.connect
connect(space1: Space<G>, space2: Space<G>, distance: number = 1) { this.connectOneWay(space1, space2, distance); // assume bidirectional unless directly called in reverse if (!this._graph.hasDirectedEdge(space2._t.ref, space1._t.ref)) this._graph.addDirectedEdge(space2._t.ref, space1._t.ref, {distance}); }
/** * Make these two Spaces adjacent. This creates a two-way adjacency * relationship. If called twice with the Spaces reversed, different distances * can be created for the adjacency in each direction. * @category Adjacency * * @param space1 - {@link Space} to connect * @param space2 - {@link Space} to connect * @param distance - Add a custom distance to this connection for the purposes * of distance-measuring. This distance is when measuring from space1 to space2. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/connected-space-map.ts#L58-L62
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ConnectedSpaceMap.connectOneWay
connectOneWay(space1: Space<G>, space2: Space<G>, distance: number = 1) { if (this !== space1._t.parent || this !== space2._t.parent) throw Error("Both spaces must be children of the space to be connected"); if (!this._graph.hasNode(space1._t.ref)) this._graph.addNode(space1._t.ref, {space: space1}); if (!this._graph.hasNode(space2._t.ref)) this._graph.addNode(space2._t.ref, {space: space2}); this._graph.mergeEdge(space1._t.ref, space2._t.ref, {distance}); }
// @internal
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/connected-space-map.ts#L65-L72
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ConnectedSpaceMap.distanceBetween
distanceBetween(el1: GameElement, el2: GameElement) { const n1 = this._positionedParentOf(el1); const n2 = this._positionedParentOf(el2); return this._distanceBetweenNodes(String(n1._t.ref), String(n2._t.ref)); }
/** * Finds the shortest distance between two elements using this space. Elements * must be connected Spaces of this element or be elements inside such spaces. * @category Adjacency * * @param el1 - {@link GameElement} to measure distance from * @param el2 - {@link GameElement} to measure distance to * @returns shortest distance measured by the `distance` values added to each * connection in {@link connectTo} */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/connected-space-map.ts#L84-L88
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.showToAll
showToAll(this: ElementCollection<Piece<BaseGame>>) { for (const el of this) { delete(el._visible); } }
/** * Show these elements to all players * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L280-L284
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.showOnlyTo
showOnlyTo(this: ElementCollection<Piece<BaseGame>>, player: Player | number) { if (typeof player !== 'number') player = player.position; for (const el of this) { el._visible = { default: false, except: [player] }; } }
/** * Show these elements only to the given player * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L290-L298
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.showTo
showTo(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] | number[]) { if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position); for (const el of this) { if (el._visible === undefined) continue; if (el._visible.default) { if (!el._visible.except) continue; el._visible.except = el._visible.except.filter(i => !(player as number[]).includes(i)); } else { el._visible.except = Array.from(new Set([...(el._visible.except instanceof Array ? el._visible.except : []), ...(player as number[])])) } } }
/** * Show these elements to the given players without changing it's visibility to * any other players. * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L305-L316
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.hideFromAll
hideFromAll(this: ElementCollection<Piece<BaseGame>>) { for (const el of this) { el._visible = {default: false}; } }
/** * Hide this element from all players * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L322-L326
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.hideFrom
hideFrom(this: ElementCollection<Piece<BaseGame>>, ...player: Player[] | number[]) { if (typeof player[0] !== 'number') player = (player as Player[]).map(p => p.position); for (const el of this) { if (el._visible?.default === false && !el._visible.except) continue; if (el._visible === undefined || el._visible.default === true) { el._visible = { default: true, except: Array.from(new Set([...(el._visible?.except instanceof Array ? el._visible.except : []), ...(player as number[])])) }; } else { if (!el._visible.except) continue; el._visible.except = el._visible.except.filter(i => !(player as number[]).includes(i)); } } }
/** * Hide these elements from the given players without changing it's visibility to * any other players. * @category Visibility */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L333-L347
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.sortBy
sortBy<E extends T>(key: Sorter<E> | Sorter<E>[], direction?: "asc" | "desc") { const rank = (e: E, k: Sorter<E>) => typeof k === 'function' ? k(e) : e[k as keyof E] const [up, down] = direction === 'desc' ? [-1, 1] : [1, -1]; return this.sort((a, b) => { const keys = key instanceof Array ? key : [key]; for (const k of keys) { const r1 = rank(a as E, k); const r2 = rank(b as E, k); if (r1 > r2) return up; if (r1 < r2) return down; } return 0; }); }
/** * Sorts this collection by some {@link Sorter}. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L353-L366
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.sortedBy
sortedBy(key: Sorter<T> | (Sorter<T>)[], direction: "asc" | "desc" = "asc") { return (this.slice(0, this.length) as this).sortBy(key, direction); }
/** * Returns a copy of this collection sorted by some {@link Sorter}. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L372-L374
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.sum
sum(key: ((e: T) => number) | (keyof {[K in keyof T]: T[K] extends number ? never: K})) { return this.reduce((sum, n) => sum + (typeof key === 'function' ? key(n) : n[key] as unknown as number), 0); }
/** * Returns the sum of all elements in this collection measured by a provided key * @category Queries * * @example * deck.create(Card, '2', { pips: 2 }); * deck.create(Card, '3', { pips: 3 }); * deck.all(Card).sum('pips'); // => 5 */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L385-L387
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.withHighest
withHighest(...attributes: Sorter<T>[]): T | undefined { return this.sortedBy(attributes, 'desc')[0]; }
/** * Returns the element in this collection with the highest value of the * provided key(s). * @category Queries * * @param attributes - any number of {@link Sorter | Sorter's} used for * comparing. If multiple are provided, subsequent ones are used to break ties * on earlier ones. * * @example * army.create(Soldier, 'a', { strength: 2, initiative: 3 }); * army.create(Soldier, 'b', { strength: 3, initiative: 1 }); * army.create(Soldier, 'c', { strength: 3, initiative: 2 }); * army.all(Solider).withHighest('strength', 'initiative'); // => Soldier 'c' */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L404-L406
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.withLowest
withLowest(...attributes: Sorter<T>[]): T | undefined { return this.sortedBy(attributes, 'asc')[0]; }
/** * Returns the element in this collection with the lowest value of the * provided key(s). * @category Queries * * @param attributes - any number of {@link Sorter | Sorter's} used for * comparing. If multiple are provided, subsequent ones are used to break ties * on earlier ones. * * @example * army.create(Soldier, 'a', { strength: 2, initiative: 3 }); * army.create(Soldier, 'b', { strength: 3, initiative: 1 }); * army.create(Soldier, 'c', { strength: 2, initiative: 2 }); * army.all(Solider).withLowest('strength', 'initiative'); // => Soldier 'c' */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L423-L425
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.max
max<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ? K2 : never}[keyof T] | ((t: T) => K)): K | undefined { const el = this.sortedBy(key, 'desc')[0]; if (!el) return; return typeof key === 'function' ? key(el) : el[key] as K; }
/** * Returns the highest value of the provided key(s) found on any element in * this collection. * @category Queries * * @param key - a {@link Sorter | Sorter's} used for comparing and extracting * the max. * * @example * army.create(Soldier, 'a', { strength: 2, initiative: 3 }); * army.create(Soldier, 'b', { strength: 3, initiative: 1 }); * army.create(Soldier, 'c', { strength: 2, initiative: 2 }); * army.all(Solider).max('strength'); // => 3 */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L441-L445
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.min
min<K extends number | string>(key: {[K2 in keyof T]: T[K2] extends K ? K2 : never}[keyof T] | ((t: T) => K)): K | undefined { const el = this.sortedBy(key, 'asc')[0] if (!el) return; return typeof key === 'function' ? key(el) : el[key] as K; }
/** * Returns the lowest value of the provided key(s) found on any element in * this collection. * @category Queries * * @param key - a {@link Sorter | Sorter's} used for comparing and extracting * the minimum. * * @example * army.create(Soldier, 'a', { strength: 2, initiative: 3 }); * army.create(Soldier, 'b', { strength: 3, initiative: 1 }); * army.create(Soldier, 'c', { strength: 2, initiative: 2 }); * army.all(Solider).min('initiative'); // => 1 */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L461-L465
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.areAllEqual
areAllEqual(key: keyof T): boolean { if (this.length === 0) return true; return this.every(el => el[key] === this[0][key]); }
/** * Returns whether all elements in this collection have the same value for key. * @category Queries */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L471-L474
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.remove
remove() { for (const el of this) { if ('isSpace' in el) throw Error('cannot move Space'); (el as unknown as Piece<Game>).remove(); } }
/** * Remove all elements in this collection from the playing area and place them * into {@link Game#pile} * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L481-L486
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.putInto
putInto(to: GameElement, options?: {position?: number, fromTop?: number, fromBottom?: number}) { if (this.some(el => el.hasMoved()) || to.hasMoved()) to.game.addDelay(); for (const el of this) { if ('isSpace' in el) throw Error('cannot move Space'); (el as unknown as Piece<Game>).putInto(to, options); } }
/** * Move all pieces in this collection into another element. See {@link Piece#putInto}. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L492-L498
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.layout
layout( applyTo: T['_ui']['layouts'][number]['applyTo'], attributes: Partial<GameElement['_ui']['layouts'][number]['attributes']> ) { for (const el of this) el.layout(applyTo, attributes); }
/** * Apply a layout to some of the elements directly contained within the elements * in this collection. See {@link GameElement#layout} * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L507-L512
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.configureLayout
configureLayout( attributes: Partial<GameElement['_ui']['layouts'][number]['attributes']> ) { for (const el of this) el.configureLayout(attributes); }
/** * Configure the layout for all elements contained within this collection. See * {@link GameElement#configureLayout} * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L520-L524
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
ElementCollection.appearance
appearance(appearance: ElementUI<T>['appearance']) { for (const el of this) el.appearance(appearance); }
/** * Define the appearance of the elements in this collection. Any values * provided override previous ones. See {@link GameElement#appearance}. * @category UI */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element-collection.ts#L531-L533
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.constructor
constructor(ctx: Partial<ElementContext>) { this._ctx = ctx as ElementContext; this._ctx.classRegistry ??= []; if (!ctx.top) { this._ctx.top = this as unknown as GameElement; this._ctx.sequence = 0; } if (!this._ctx.namedSpaces) { this._ctx.uniqueNames = {}; this._ctx.namedSpaces = {}; } this._t = { children: new ElementCollection(), id: this._ctx.sequence, ref: this._ctx.sequence, setId: (id?: number) => { if (id !== undefined) { this._t.id = id; if (this._ctx.sequence < id) this._ctx.sequence = id; } }, }; this._ctx.sequence += 1; }
/** * Do not use the constructor directly. Instead Call {@link * GameElement#create} or {@link GameElement#createMany} on the element in * which you want to create a new element. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L319-L343
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.toString
toString() { return this.name || this.constructor.name.replace(/([a-z0-9])([A-Z])/g, "$1 $2"); }
/** * String used for representng this element in game messages when the object * is passed directly, e.g. when taking the choice directly from a * chooseOnBoard choice. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L351-L353
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.isAdjacentTo
isAdjacentTo(element: GameElement): boolean { const graph = this.containerWithProperty('isAdjacent'); if (!graph) return false; return (graph as AdjacencySpace<G>).isAdjacent(this, element); }
/** * If this element is adjacent to some other element, using the nearest * containing space that has an adjacency map. * @category Adjacency */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L514-L518
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.distanceTo
distanceTo(element: GameElement): number { const graph = this.containerWithProperty('distanceBetween'); if (!graph) return Infinity; return (graph as ConnectedSpaceMap<G>).distanceBetween(this, element); }
/** * Finds the shortest distance between two spaces * @category Adjacency * * @param element - {@link element} to measure distance to */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L526-L530
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.setOrder
setOrder(order: typeof this._t.order) { this._t.order = order; }
/** * Set this class to use a different ordering style. * @category Structure * @param order - ordering style * - "normal": Elements placed into this element are put at the end of the * list (default) * - "stacking": Used primarily for stacks of cards. Elements placed into this * element are put at the beginning of the list. E.g. if a stack of cards * has `order` set to `stacking` the {@link first} method will return the * last card placed in the stack, rather than the first one placed in the * stack. Hidden items in the stack are not tracked or animated while * reordered to prevent their identity from being exposed as they move */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L573-L575
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.container
container<T extends GameElement>(className?: ElementClass<T>): T | undefined { if (!className) return this._t.parent as T; if (this._t.parent) return this._t.parent instanceof className ? this._t.parent as T: this._t.parent.container(className); }
/** * Returns this elements parent. * @category Queries * @param className - If provided, searches up the parent tree to find the first * matching element. E.g. if a Token is placed on a Card in a players * Tableau. calling `token.container(Tableau)` can be used to find the * grandparent. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L585-L590
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.containerWithProperty
containerWithProperty(property: string, value?: any): GameElement | undefined { const parent = this._t.parent; if (parent) return property in parent && (value === undefined || parent[property as keyof typeof parent] === value) ? parent: parent.containerWithProperty(property, value); }
/** * Returns this elements containing element that also has a given property. * @category Queries */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L596-L601
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.isEmpty
isEmpty() { return !this._t.children.length; }
/** * Returns whether this element has no elements placed within it. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L607-L609
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.sortBy
sortBy(key: GenericSorter | GenericSorter[], direction?: "asc" | "desc"): ElementCollection<GameElement<G, P>> { return this._t.children.sortBy(key as Sorter<GameElement> | Sorter<GameElement>[], direction) as ElementCollection<GameElement<G, P>> }
/** * Sorts the elements directly contained within this element by some {@link Sorter}. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L615-L617
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.shuffle
shuffle() { const refs = this.childRefsIfObscured(); shuffleArray(this._t.children, this._ctx.gameManager?.random || Math.random); if (refs) this.assignChildRefs(refs); }
/** * re-orders the elements directly contained within this element randomly. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L623-L627
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.owner
get owner(): P | undefined { return this.player !== undefined ? this.player as P : this._t.parent?.owner as P; }
/** * The player that owns this element, or the first element that contains this * element searching up through the parent hierarchy. This is related to, but * different than {@link player}. E.g. if a standard playing card is in a * player's hand, typically the `hand.player` will be assigned to that player * but the card itself would not have a `player`. In this case the * card.owner() will equal the player in whose hand the card is placed. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L638-L640
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.mine
get mine() { if (!this._ctx.player) return false; // throw? return this.owner === this._ctx.player; }
/** * Whether this element belongs to the player viewing the game. A player is * considered to be currently viewing the game if this is called in the * context of an action taken by a given player (during an action taken by a * player or while the game is viewed by a given player.) It is an error to * call this method when not in the context of a player action. When querying * for elements using {@link ElementFinder} such as {@link all} and {@link * first}, {@link mine} is available as a search key that accepts a value of * true/false @category Queries */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L653-L656
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.create
create<T extends GameElement>(className: ElementClass<T>, name: string, attributes?: ElementAttributes<T>): T { if (this._ctx.gameManager?.phase === 'started') throw Error('Game elements cannot be created once game has started.'); const el = this.createElement(className, name, attributes); el._t.parent = this; const firstPiece = this._t.children.findIndex(c => !('isSpace' in c)); if (this._t.order === 'stacking' && !('isSpace' in el)) { if (firstPiece > 0) { this._t.children.splice(firstPiece, 0, el); } else { this._t.children.unshift(el); } } else { if ('isSpace' in el && firstPiece !== -1) { this._t.children.splice(firstPiece, 0, el) } else { this._t.children.push(el); } } if ('isSpace' in el && name) { if (name in this._ctx.uniqueNames) { // no longer unique delete this._ctx.namedSpaces[name]; this._ctx.uniqueNames[name] = false } else { this._ctx.namedSpaces[name] = el as unknown as Space<Game>; this._ctx.uniqueNames[name] = true; } } return el as T; }
/** * Create an element inside this element. This can only be called during the * game setup (see {@link createGame}. Any game elements that are required * must be created before the game starts. Elements that only appear later in * the game can be created inside the {@link Game#pile} or made invisible. * @category Structure * * @param className - Class to create. This class must be included in the `elementClasses` in {@link createGame}. * @param name - Sets {@link GameElement#name | name} * @param attributes - Sets any attributes of the class that are defined in * your own class that extend {@link Space}, {@link Piece}, or {@link * Game}. Can also include {@link player}. * * @example * deck.create(Card, 'ace-of-hearts', { suit: 'H', value: '1' }); */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L674-L702
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.createMany
createMany<T extends GameElement>(n: number, className: ElementClass<T>, name: string, attributes?: ElementAttributes<T> | ((n: number) => ElementAttributes<T>)): ElementCollection<T> { return new ElementCollection<T>(...times(n, i => this.create(className, name, typeof attributes === 'function' ? attributes(i) : attributes))); }
/** * Create n elements inside this element of the same class. This can only be * called during the game setup (see {@link createGame}. Any game elements * that are required must be created before the game starts. Elements that * only appear later in the game can be created inside the {@link Game#pile} * or made invisible. * @category Structure * * @param n - Number to create * @param className - Class to create. This class must be included in the `elementClasses` in {@link createGame}. * @param name - Sets {@link GameElement#name | name} * @param attributes - Sets any attributes of the class that are defined in * your own class that extend {@link Space}, {@link Piece}, or {@link * Game}. Can also include {@link player}. If a function is supplied here, a * single number argument will be passed with the number of the added element, * starting with 1. */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L721-L723
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.createElement
createElement<T extends GameElement>(className: ElementClass<T>, name: string, attrs?: ElementAttributes<T>): T { if (!this._ctx.classRegistry.includes(className)) { this._ctx.classRegistry.push(className); } const el = new className(this._ctx); el.game = this.game; el.name = name; Object.assign(el, attrs); if ('afterCreation' in el) (el.afterCreation as () => void).bind(el)(); return el; }
/** * Base element creation method * @internal */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L729-L739
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.destroy
destroy() { if (this._ctx.gameManager?.phase === 'started') throw Error('Game elements cannot be destroy once game has started.'); const position = this.position(); this._t.parent?._t.children.splice(position, 1); }
/** * Permanently remove an element. This can only be done while defining the * game, and is usually only useful when creating groups of elements, such as * {@link createMany} or {@link createGrid} where some of the created elements * are not needed. * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L748-L752
d701cb628e876cbe59171e837862ee09c925d6c9
boardzilla-core
github_2023
boardzilla
typescript
GameElement.rotation
get rotation() { if (this._rotation === undefined) return 0; return (this._rotation % 360 + 360) % 360; }
/** * Rotation of element if set, normalized to 0-359 degrees * @category Structure */
https://github.com/boardzilla/boardzilla-core/blob/d701cb628e876cbe59171e837862ee09c925d6c9/src/board/element.ts#L758-L761
d701cb628e876cbe59171e837862ee09c925d6c9