How to use useArgs method in storybook-root

Best JavaScript code snippet using storybook-root

system.effects.ts

Source:system.effects.ts Github

copy

Full Screen

1import RG from '../rg';2import {SystemBase} from './system.base';3import {EventPool} from '../eventpool';4import {Dice} from '../dice';5import * as Component from '../component';6import {ELEM} from '../../data/elem-constants';7import {ObjectShell} from '../objectshellparser';8import {Element} from '../element';9import {ISuccessCheck, TPropType, TCoord, IAnimArgs} from '../interfaces';10import {Geometry} from '../geometry';11import {Entity} from '../entity';12import {Menu} from '../menu';13type Cell = import('../map.cell').Cell;14import {IEffArgs} from '../interfaces';15const handlerTable = {16 AddComp: true,17 ModifyCompValue: true,18 AddEntity: true,19 RemoveEntity: true,20 AddElement: true,21 RemoveElement: true,22 ChangeElement: true,23 RemoveComp: true24};25type HandleFunc = (ent: Entity, comp) => boolean;26type Target = Entity | Cell;27const TARGET_SPECIFIER = '$$target';28const CELL_SPECIFIER = '$$cell';29const SELF_SPECIFIER = 'self';30const ITEM_SPECIFIER = '$$item';31const CHOOSE_ARG = '$chooseArg';32// Can be updated when addEffect() if called33let handlerNames = Object.keys(handlerTable);34export class SystemEffects extends SystemBase {35 public static handlerTable: {[key: string]: boolean};36 //---------------37 // HANDLERS END38 //---------------39 /** Adds an effect into the effect system.40 * @param {string} effName - Name of the effect.41 * @param {function} func - Function to process the effect.42 * @return {boolean}43 * func receives args (srcEnt, effComp).44 */45 public static addEffect(effName: string, func: HandleFunc): boolean {46 if (!handlerTable.hasOwnProperty(effName)) {47 const handlerName = 'handle' + effName.capitalize();48 (SystemEffects as any).prototype[handlerName] = func;49 (handlerTable as any)[effName] = true;50 handlerNames = Object.keys(handlerTable);51 return true;52 }53 else {54 RG.err('SystemEffects', 'addEffect',55 `Effect ${effName} already exists.`);56 }57 return false;58 }59 /* Returns the target for the effect. Priority of targets is:60 * 1. actors 2. items 3. elements 4. base element61 */62 public static getEffectTargets(useArgs): Target[] {63 const objTarget = useArgs.target;64 if (!objTarget) {65 const msg = 'Possibly missing args for useItem().';66 RG.err('system.effects.js', 'getEffectTargets',67 `Given object was null/undefined. ${msg}`);68 }69 if (useArgs.applyToAllTargets) {70 return SystemEffects.getAllTargetsFromObj(objTarget, useArgs.targetType);71 }72 const actualTarget = SystemEffects.getTargetFromObj(objTarget, useArgs.targetType);73 if (actualTarget) {return [actualTarget];}74 return [];75 }76 public static getTargetFromObj(objTarget, targetTypes) {77 if (objTarget.hasOwnProperty('target')) {78 const cell = objTarget.target;79 let targetType = targetTypes;80 if (!targetType) {81 targetType = ['actors', 'items', 'elements', 'baseElem'];82 }83 if (!Array.isArray(targetType)) {targetType = [targetType];}84 if (targetType[0] === 'cell') {return cell;}85 for (let i = 0; i < targetType.length; i++) {86 if (cell.hasProp(targetType[i])) {87 return cell.getProp(targetType[i])[0];88 }89 else if (/base/.test(targetType[i])) {90 return cell.getBaseElem();91 }92 }93 }94 else {95 return objTarget;96 }97 return null;98 }99 public static getAllTargetsFromObj(objTarget, targetTypes): Entity[] {100 let res = [];101 let cell = objTarget;102 if (objTarget.hasOwnProperty('target')) {103 cell = objTarget.target;104 }105 let targetType = targetTypes;106 if (!targetType) {107 targetType = ['actors', 'items', 'elements', 'baseElem'];108 }109 if (!Array.isArray(targetType)) {targetType = [targetType];}110 for (let i = 0; i < targetType.length; i++) {111 if (cell.hasProp(targetType[i])) {112 const props = cell.getProp(targetType[i])!;113 res = res.concat(props);114 }115 else if (/base/.test(targetType[i])) {116 res.push(cell.getBaseElem());117 }118 }119 return res;120 }121 private _dtable: {[key: string]: HandleFunc};122 constructor(compTypes: string[], pool: EventPool) {123 super(RG.SYS.EFFECTS, compTypes, pool);124 this._dtable = {};125 Object.keys(handlerTable).forEach(effName => {126 if (handlerTable[effName]) {127 const handlerName = 'handle' + effName.capitalize();128 this._dtable[effName] = this[handlerName].bind(this);129 }130 });131 }132 public updateEntity(ent): void {133 const comps = ent.getList('Effects');134 comps.forEach(effComp => {135 const effType = effComp.getEffectType();136 const effArgs: IEffArgs = effComp.getArgs();137 let targets = [];138 if (effArgs.area) {139 targets = getTargetCellsFromArea(ent, effArgs.area);140 if (effArgs.anim) {141 addAreaAnimation(ent, effArgs);142 }143 }144 else {145 targets = [effArgs.target];146 }147 if (effType && effType !== '') {148 if (this._dtable.hasOwnProperty(effType)) {149 targets.forEach(target => {150 effArgs.target = target;151 this._checkStartMsgEmits(ent, effComp);152 const ok = this._dtable[effType](ent, effComp);153 this._checkEndMsgEmits(ent, effComp, ok);154 this._postEffectChecks(ent, effComp, ok);155 });156 }157 else {158 RG.err('SystemEffects', 'updateEntity',159 `Effect |${effType}| not in handler list: ${handlerNames}`);160 }161 }162 else {163 RG.err('SystemEffects', 'updateEntity',164 'No effect type in Effects comp');165 }166 ent.remove(effComp);167 });168 }169 public _checkStartMsgEmits(ent, effComp): void {170 const useArgs = effComp.getArgs();171 if (useArgs.startMsg) {172 RG.gameMsg({cell: ent.getCell(), msg: useArgs.startMsg});173 }174 }175 public _checkEndMsgEmits(ent, effComp, ok: boolean): void {176 const useArgs = effComp.getArgs();177 if (useArgs.endMsg) {178 RG.gameMsg({cell: ent.getCell(), msg: useArgs.endMsg});179 }180 if (ok && useArgs.successMsg) {181 RG.gameMsg({cell: ent.getCell(), msg: useArgs.successMsg});182 }183 if (!ok && useArgs.failureMsg) {184 RG.gameWarn({cell: ent.getCell(), msg: useArgs.failureMsg});185 }186 }187 public _postEffectChecks(ent, effComp, ok: boolean): void {188 const useArgs = effComp.getArgs();189 if (!ok) {return;}190 const item = effComp.getItem();191 if (item) {192 RG.reduceCountOrCharge(item, ent, this.pool);193 }194 }195 //--------------------196 // HANDLER FUNCTIONS197 //--------------------198 /* Handler for effect 'AddComp'. Adds a component to target entity199 * for a given duration. */200 public handleAddComp(srcEnt, effComp): boolean {201 const useArgs: IEffArgs = effComp.getArgs();202 const targetEnts = SystemEffects.getEffectTargets(useArgs);203 let abortAddDueToCb = false;204 this._emitDbgMsg('handleAddComp start', srcEnt);205 // TODO multiple targets and selection will not work206 targetEnts.forEach(targetEnt => {207 // Prevent adding affecting the srcEnt itself (important for area208 // effects)209 if (useArgs.applyToSelf) return;210 const compName = getCompName(useArgs, targetEnt);211 let compToAdd = null;212 if (Component.hasOwnProperty(compName)) {213 compToAdd = new Component[compName]();214 }215 else {216 RG.err('System.Effects', 'handleAddComp',217 `Failed to create comp |${compName}|`);218 }219 // If setters are given, alter the values of added component220 if (useArgs.setters) {221 const setters = useArgs.setters;222 Object.keys(setters).forEach(setFunc => {223 if (setFunc === CHOOSE_ARG && srcEnt.isPlayer()) {224 const chooseArg = setters[setFunc];225 // Must create new menu with callback, we need to create226 // a new Effect comp with replaced info227 const selOptions = (arg) => {228 const newSet = RG.clone(setters);229 newSet[chooseArg.func] = arg;230 delete newSet.$chooseArg;231 const newUseArgs = Object.assign({}, useArgs);232 newUseArgs.setters = newSet;233 const newEffComp = new Component.Effects(newUseArgs);234 newEffComp.setItem(effComp.getItem());235 srcEnt.add(newEffComp);236 };237 const args = setters[setFunc].args;238 const menuChoices = args.map((arg, i) => {239 return [arg, selOptions.bind(this, arg)];240 });241 const menuSel = new Menu.SelectRequired(menuChoices);242 menuSel.addPre(chooseArg.menuMsg);243 srcEnt.getBrain().setSelectionObject(menuSel);244 abortAddDueToCb = true;245 return;246 }247 else if (typeof compToAdd[setFunc] === 'function') {248 const valueToSet = setters[setFunc];249 // Use the final target as value for setter '$$target'250 if (valueToSet === TARGET_SPECIFIER) {251 compToAdd[setFunc](targetEnt);252 }253 else if (valueToSet === ITEM_SPECIFIER) {254 compToAdd[setFunc](useArgs.effectSource);255 }256 else {257 const numValue = convertValueIfNeeded(valueToSet);258 compToAdd[setFunc](numValue);259 }260 }261 else {262 const json = JSON.stringify(compToAdd);263 RG.err('useEffect', 'addComp',264 `No ${setFunc} in comp ${json}`);265 }266 });267 }268 if (abortAddDueToCb) {return;}269 // Track also the source of adding component, to track who gets270 // experience/blame from killing something271 if (compToAdd && compToAdd.setSource) {272 if (useArgs.source) {273 compToAdd.setSource(useArgs.source);274 }275 else if (srcEnt.has('Created')) {276 compToAdd.setSource(srcEnt.get('Created').getCreator());277 }278 else {279 compToAdd.setSource(srcEnt);280 }281 }282 // How to switch the entity here?283 if (useArgs.addOnUser) {284 targetEnt = srcEnt;285 }286 if (RG.isEntity(targetEnt)) {287 if (useArgs.duration) {288 const dur = Dice.getValue(useArgs.duration);289 const expirMsg = useArgs.expireMsg;290 Component.addToExpirationComp(targetEnt, compToAdd, dur, expirMsg);291 }292 else {293 targetEnt.add(compToAdd);294 }295 }296 });297 return true;298 }299 /* Called when element needs to be added to a cell. */300 public handleAddElement(srcEnt, effComp): boolean {301 const useArgs = effComp.getArgs();302 const cell = getTargetCellOrFail(useArgs);303 if (!useArgs.elementName) {304 RG.err('System.Effects', 'handleAddElement',305 'No elementName found in useArgs: ' + JSON.stringify(useArgs));306 }307 let newElem = Element.create(useArgs.elementName);308 if (!newElem) {309 // Try the ObjectShellParser, usually not what we want310 // with elements311 const parser = ObjectShell.getParser();312 newElem = parser.createEntity(useArgs.elementName);313 }314 if (newElem) {315 const [x, y] = [cell.getX(), cell.getY()];316 const level = srcEnt.getLevel();317 const existingElems = cell.getPropType(newElem.getType());318 if (useArgs.successCheck) {319 if (!this._successCheck(cell, useArgs.successCheck)) {320 return false;321 }322 }323 if (!existingElems || existingElems.length < useArgs.numAllowed) {324 if (!level.addElement(newElem, x, y)) {325 console.error('Failed to add element ' + useArgs.elementName);326 return false;327 }328 if (typeof newElem.onSystemAdd === 'function') {329 newElem.onSystemAdd(cell);330 }331 if (useArgs.setters) {332 this._applySetters(newElem, useArgs.setters);333 }334 return true;335 }336 else {337 return false;338 }339 }340 else {341 const msg = 'Failed to create elem: ' + JSON.stringify(useArgs);342 RG.err('System.Effects', 'handleAddElement', msg);343 }344 return false;345 }346 /* Called when element needs to be added to a cell. */347 public handleRemoveElement(srcEnt, effComp): boolean {348 const useArgs = effComp.getArgs();349 const cell = getTargetCellOrFail(useArgs);350 if (!useArgs.elementName) {351 RG.err('System.Effects', 'handleRemoveElement',352 'No elementName found in useArgs: ' + JSON.stringify(useArgs));353 }354 const foundElems = cell.getPropType(useArgs.elementName);355 if (foundElems.length > 0) {356 const foundElem = foundElems[0];357 const [x, y] = [cell.getX(), cell.getY()];358 const level = srcEnt.getLevel();359 if (level.removeElement(foundElem, x, y)) {360 if (typeof foundElem.onSystemRemove === 'function') {361 foundElem.onSystemRemove(cell);362 }363 return true;364 }365 }366 return false;367 }368 /* Adds a value to an existing component value. Returns true if at least on369 * component is modified. */370 public handleModifyCompValue(srcEnt, effComp): boolean {371 const useArgs = effComp.getArgs();372 const targetEnts = SystemEffects.getEffectTargets(useArgs);373 let ok = false;374 targetEnts.forEach(targetEnt => {375 const compName = getCompName(useArgs, targetEnt);376 if (RG.isEntity(targetEnt) && targetEnt.has(compName)) {377 const comp = targetEnt.get(compName);378 const currValue = comp[useArgs.get]();379 const value = useArgs.value;380 const numValue = convertValueIfNeeded(value);381 comp[useArgs.set](currValue + numValue);382 ok = true;383 }384 });385 return ok;386 }387 /* Adds an entity to target cell. */388 public handleAddEntity(srcEnt, effComp): boolean {389 const useArgs: IEffArgs = effComp.getArgs();390 const cell = getTargetCellOrFail(useArgs);391 const parser = ObjectShell.getParser();392 const entity = parser.createEntity(useArgs.entityName);393 if (entity) {394 const [x, y] = [cell.getX(), cell.getY()];395 const level = useArgs.level || srcEnt.getLevel();396 if (!level) {397 RG.err('SystemEffects', 'handleAddEntity',398 'level must exist for adding the entity');399 }400 if (level.addEntity(entity, x, y)) {401 if (useArgs.duration) {402 const fadingComp = new Component.Fading();403 const {duration} = useArgs;404 fadingComp.setDuration(duration);405 entity.add(fadingComp);406 }407 // Add the srcEnt to created entity to track its damage etc408 // for experience and action monitoring409 const createdComp = new Component.Created();410 createdComp.setCreator(srcEnt);411 entity.add(createdComp);412 return true;413 }414 }415 return false;416 }417 public handleRemoveEntity(srcEnt, effComp): boolean {418 const useArgs: IEffArgs = effComp.getArgs();419 let ok = false;420 // Self-removal case421 if (useArgs.target === SELF_SPECIFIER) {422 if (RG.isItem(srcEnt) && srcEnt.getTopOwner()) {423 // TODO this case won't get triggered at the moment424 RG.err('system.effects.ts', 'handleRemoveEntity',425 'Not supported for owned items (in inventory)');426 }427 else {428 const [x, y] = srcEnt.get('Location').getXY();429 const level = srcEnt.get('Location').getLevel();430 if (level.removeEntity(srcEnt, x, y)) {431 ok = true;432 }433 }434 }435 else {436 RG.err('system.effects.ts', 'handleRemoveEntity',437 'Other targets than "self" unsupported for now');438 }439 return ok;440 }441 public handleChangeElement(srcEnt, effComp): boolean {442 const useArgs = effComp.getArgs();443 const cell = getTargetCellOrFail(useArgs);444 const fromType = useArgs.fromType;445 const toType = useArgs.toType || ELEM.FLOOR;446 if (cell.getBaseElem().getType() === fromType) {447 cell.setBaseElem(toType);448 return true;449 }450 return false;451 }452 public handleRemoveComp(srcEnt, effComp): boolean {453 const useArgs = effComp.getArgs();454 const targetEnts = SystemEffects.getEffectTargets(useArgs);455 let ok = false;456 targetEnts.forEach(targetEnt => {457 const compName = getCompName(useArgs, targetEnt);458 if (RG.isEntity(targetEnt) && targetEnt.has(compName)) {459 if (useArgs.all) {460 targetEnt.removeAll(compName);461 }462 else {463 targetEnt.remove(compName);464 }465 ok = true;466 }467 });468 return ok;469 }470 /* Used for any success checks required for applying the effect. */471 protected _successCheck(cell: Cell, checks: ISuccessCheck[]): boolean {472 let successOk = true;473 checks.forEach((check: ISuccessCheck) => {474 RG.PROP_TYPES.forEach((propType: TPropType) => {475 if (!check[propType]) return; // Dont care about prop for this cell476 // Process positive checks. Cell must have the prop, and we must477 // get a positive match478 ['has', 'hasAll'].forEach(func => {479 if (check[propType][func]) {480 if (propType !== RG.TYPE_ELEM && !cell.hasProp(propType)) {481 successOk = false;482 }483 else {484 let props = cell.getProp(propType);485 if (props) {props = props.slice();} // Avoid modifying the original486 if (propType === RG.TYPE_ELEM) {487 if (!props) {props = [];}488 props.push(cell.getBaseElem() as any);489 }490 let resultFound = false;491 // props cannot be null due to hasProp check492 props!.forEach(prop => {493 // Results in prop.has('CompName') or494 // prop.hasAll(['Comp1', 'Comp2'])495 const funcArgs = check[propType][func];496 if (prop[func](funcArgs)) {497 resultFound = true;498 }499 });500 successOk = successOk && resultFound;501 }502 }503 });504 ['hasNot', 'hasNone'].forEach(func => {505 let props = cell.getProp(propType);506 if (props) {props = props.slice();} // Avoid modifying the original507 if (propType === RG.TYPE_ELEM) {508 if (!props) {props = [];}509 props.push(cell.getBaseElem() as any);510 }511 if (props) {512 props.forEach(prop => {513 let resultOk = true;514 if (check[propType][func]) {515 if (!prop[func](check[propType][func])) {516 resultOk = false;517 }518 }519 successOk = successOk && resultOk;520 });521 }522 });523 });524 });525 return successOk;526 }527 protected _applySetters(ent: Entity, setterList): void {528 let funcs = [];529 const cell = (ent as any).getCell();530 if (Array.isArray(setterList)) {531 funcs = setterList;532 }533 else {534 funcs = [setterList];535 }536 funcs.forEach(setterObj => {537 let targetObj = ent;538 // If 'get' present, fetch the component first539 if (setterObj.get) {targetObj = ent.get(setterObj.get);}540 // Go through all func names in setterObj, and use func name to set541 // values in the target object542 Object.keys(setterObj).forEach(setter => {543 if (setter !== 'get') {544 const valToSet = setterObj[setter];545 (targetObj as any)[setter](valToSet);546 }547 });548 });549 }550}551SystemEffects.handlerTable = handlerTable;552//-------------------553// HELPER FUNCTIONS554//-------------------555function getCompName(useArgs, targetEnt) {556 const compName = useArgs.name || useArgs.comp;557 if (!compName) {558 const json = JSON.stringify(useArgs);559 let errorMsg = 'Unknown comp value. useArgs: ' + json;560 if (targetEnt) {errorMsg += ' targetEnt ' + JSON.stringify(targetEnt);}561 RG.err('SystemEffects', 'getCompName',562 errorMsg);563 }564 return compName.capitalize();565}566/**567 * @param {int|string|RG.Die} intStrOrDie - Value for the die roll568 * @return {int} - Return of the die roll569 */570/*571const getDieValue = function(intStrOrDie) {572 if (Number.isInteger(intStrOrDie)) {573 return intStrOrDie;574 }575 else if (typeof intStrOrDie === 'string') {576 // const arr = RG.parseDieSpec(intStrOrDie);577 // const durDie = new RG.Die(arr[0], arr[1], arr[2]);578 const durDie = Dice.create(intStrOrDie);579 const duration = durDie.roll();580 return duration;581 }582 else if (intStrOrDie.roll) {583 return intStrOrDie.roll();584 }585 RG.err('system.effects.js', 'getDieValue',586 'Could not extract value from ' + intStrOrDie);587 return 0;588};589*/590const convertValueIfNeeded = function(intStrOrDie) {591 if (Number.isInteger(intStrOrDie)) {592 return intStrOrDie;593 }594 else if (typeof intStrOrDie === 'string') {595 if (Dice.isDieSpec(intStrOrDie)) {596 const durDie = Dice.create(intStrOrDie);597 const duration = durDie.roll();598 return duration;599 }600 const float = Number.parseFloat(intStrOrDie);601 if (!Number.isNaN(float)) {602 return float;603 }604 }605 return intStrOrDie;606};607function getTargetCellOrFail(useArgs) {608 if (useArgs.target) {609 const targetObj = useArgs.target;610 if (targetObj.target) {611 return targetObj.target;612 }613 }614 const json = JSON.stringify(useArgs);615 RG.err('system.effects.js', 'getTargetCellOrFail',616 'Prop target must exist in useArgs. Got: |' + json);617 return null;618}619function parseArea(areaStr: string): [number, number] {620 const res = areaStr.split('x');621 if (res.length !== 2) {622 RG.err('system.effects.ts', 'parseArea',623 `Wrong area spec given: ${areaStr} (exp NxM)`);624 }625 return [parseInt(res[0], 10), parseInt(res[1], 10)];626}627function getTargetCellsFromArea(ent, area): Cell[] {628 const res = [];629 const level = ent.get('Location').getLevel();630 const [x, y]: TCoord = ent.get('Location').getXY();631 const [aX, aY] = parseArea(area);632 if (aX !== aY) {633 RG.err('system.effects.ts', 'getTargetCellsFromArea',634 `Only NxN format supported. Got ${area}`);635 }636 const d = Math.round((aX - 1) / 2);637 const coord: TCoord[] = Geometry.getBoxAround(x, y, d, true);638 const map = level.getMap();639 return map.getCellsWithCoord(coord);640}641function addAreaAnimation(ent, effArgs): void {642 const [aX, aY] = parseArea(effArgs.area);643 const anim: IAnimArgs = effArgs.anim;644 const [cX, cY] = ent.get('Location').getXY();645 const level = ent.get('Location').getLevel();646 const animArgs: IAnimArgs = {647 range: 1,648 cX, cY,649 className: anim.className,650 level651 };652 const animComp = new Component.Animation(animArgs);653 ent.add(animComp);...

Full Screen

Full Screen

effects.ts

Source:effects.ts Github

copy

Full Screen

1/* eslint comma-dangle: 0 */2import RG from '../src/rg';3import {Dice} from '../src/dice';4import * as Component from '../src/component';5import {IEffArgs} from '../src/interfaces';6const entities = ['actors', 'items', 'elements'];7const getTargetActor = (obj) => {8 if (!obj) {9 const msg = 'Possibly missing args for useItem().';10 RG.err('effects.js', 'getTargetActor',11 `Given object was null/undefined. ${msg}`);12 }13 if (obj.hasOwnProperty('target')) {14 const cell = obj.target;15 if (cell.hasActors()) {16 return cell.getProp('actors')[0];17 }18 }19 return null;20};21const getTopOwnerActor = (itemOrActor) => {22 if (itemOrActor.getTopOwner) {23 return itemOrActor.getTopOwner();24 }25 return itemOrActor;26};27export const createUseItemComp = (item, target, effArgs?: IEffArgs) => {28 const useItem = new Component.UseItem();29 useItem.setTarget(target);30 useItem.setItem(item);31 if (effArgs) {32 useItem.setEffect(effArgs);33 }34 const useType = RG.getEffectUseType(item, target);35 useItem.setUseType(useType);36 const owner = getTopOwnerActor(item);37 owner.add(useItem);38};39const getDuration = function(durStr: string): number {40 const arr = Dice.parseDieSpec(durStr);41 const durDie = new Dice(arr[0], arr[1], arr[2]);42 const duration = durDie.roll();43 return duration;44};45export const Effects = {46 // Effects can be used in items freely.47 // Each obj arg will have {target:cell}48 // In use-function, 'this' bound to the used item or actor with ability49 // Item user is generally item owner: const user = this.getTopOwner();50 // Each effect entry looks like the following51 // { name: "effectName",52 // func: function(obj) {...}, // 'this' bound to the used item53 // requires: required args inside item, these can be used inside functions54 // using this.useArgs.argName.55 // Example:56 // Given EFFECT:57 // {name: "heal", func: function(obj) {..}, requires: "hp"}58 // The item must be specified in the following way:59 // {60 // name: "Healing potion",61 // use: {heal: {hp: "2d4+8"}}62 // }63 effects: [64 // Generic use function added to all items with use effects65 // Calls each use-function implementation66 {67 name: 'use',68 func(obj, idx=-1) {69 if (this.getCharges) {70 if (this.getCharges() === 0) {71 const name = this.getName();72 RG.gameMsg(`${name} does not have any charges left`);73 return false;74 }75 }76 // This is used when one of the effects/abilities is chosen77 if (idx >= 0) {78 return this.useFuncs[idx].call(this, obj);79 }80 // This is used for items when no specific effect chosen81 for (let i = 0; i < this.useFuncs.length; i++) {82 if (this.useFuncs[i].call(this, obj)) {83 return true;84 }85 }86 return false;87 },88 },89 // Adds an effect (via Component) for specified duration90 // Example: {addComp: {name: "Ethereal", duration: "3d3"}}91 // In fact, addComp: {name: "Stun", duration: "1d6"} is identical to92 // 'stun' effect.93 //94 // To create temporary boosts, you can use the following:95 // use: {addComp:96 // {name: 'CombatMods', setters: {setDefense: 5}, duration: '2d4'}97 // }98 {99 name: 'addComp',100 requires: ['name'],101 optional: ['addOnUser', 'area', 'duration', 'setters', 'targetType'],102 func(obj) {103 const effArgs: IEffArgs = {104 duration: this.useArgs.duration,105 effectType: 'AddComp',106 name: this.useArgs.name,107 target: obj,108 targetType: ['actors', 'items']109 };110 if (this.useArgs.area) {111 effArgs.area = this.useArgs.area;112 }113 if (this.useArgs.setters) {114 effArgs.setters = this.useArgs.setters;115 }116 if (this.useArgs.addOnUser) {117 effArgs.addOnUser = this.useArgs.addOnUser;118 }119 if (this.useArgs.targetType) {120 effArgs.targetType = this.useArgs.targetType;121 }122 createUseItemComp(this, obj, effArgs);123 return true;124 },125 },126 // Removes a component from an entity.127 // Optionally all: true can be given to remove all comps128 {129 name: 'removeComp',130 requires: ['name'],131 optional: ['all'],132 func(obj) {133 const effArgs: IEffArgs = {134 all: this.useArgs.all,135 effectType: 'RemoveComp',136 name: this.useArgs.name,137 target: obj,138 targetType: entities139 };140 createUseItemComp(this, obj, effArgs);141 return true;142 },143 },144 // Modifies specified component value.145 // Given use: {modifyCompValue: {name: 'Health', set: 'setHP', get:146 // 'getHP', value: -1}},147 // one can be subtracted from hp of Health component.148 {149 name: 'modifyCompValue',150 requires: ['name', 'set', 'get', 'value'],151 optional: ['op'],152 func(obj) {153 const effArgs = {154 target: obj,155 targetType: entities,156 name: this.useArgs.name,157 set: this.useArgs.set, get: this.useArgs.get,158 value: this.useArgs.value,159 effectType: 'ModifyCompValue'160 };161 createUseItemComp(this, obj, effArgs);162 return true;163 },164 },165 // Cures an effect specified in use: {cure: {effect: Poison}}166 {167 name: 'cure',168 requires: ['effect'],169 func(obj) {170 const actor = getTargetActor(obj);171 if (actor) {172 const effectName = this.useArgs.effect.capitalize();173 if (actor.has(effectName)) {174 // const rmvComp = actor.get(effectName);175 actor.remove(effectName);176 RG.gameMsg(actor.getName()177 + ' seems to be cured of ' + effectName);178 }179 else {180 RG.gameMsg(this.getName() + ' was wasted');181 }182 createUseItemComp(this, actor);183 return true;184 }185 return false;186 },187 },188 // Digger effect can be used to dig into stones and rocks189 {190 name: 'digger',191 func(obj) {192 const effArgs: IEffArgs = {193 effectType: 'AddComp',194 name: 'Mining',195 target: obj,196 // Use Cell as target of effect as we need to modify197 // baseElem, and add possible items from Mining198 targetType: ['cell'],199 effectSource: this,200 setters: {201 // Uses whatever is found as target202 setTarget: '$$target',203 setItem: '$$item',204 },205 // Component is added to user, not to the target206 addOnUser: true207 };208 createUseItemComp(this, obj, effArgs);209 return true;210 },211 },212 // Healing effect restores hit points to the target213 {214 name: 'heal',215 requires: ['hp'],216 func(obj) {217 const actor = getTargetActor(obj);218 if (actor) {219 const die = Dice.create(this.useArgs.hp);220 const pt = die.roll();221 if (actor.has('Health')) {222 actor.get('Health').addHP(pt);223 createUseItemComp(this, actor);224 RG.gameMsg(actor.getName() +225 ' drinks ' + this.getName());226 return true;227 }228 }229 else {230 RG.gameWarn(231 'Cannot see anyone there for using the potion.');232 }233 return false;234 },235 }, // heal236 // Poison effect which deals damage for a period of time bypassing any237 // protection238 {239 name: 'poison',240 requires: ['duration', 'damage', 'prob'],241 func(obj) {242 const arr = Dice.parseDieSpec(this.useArgs.damage);243 const dmgDie = new Dice(arr[0], arr[1], arr[2]);244 const effArgs = {245 target: obj,246 targetType: ['actors', 'items'],247 name: 'Poison',248 duration: this.useArgs.duration,249 effectType: 'AddComp',250 setters: {251 setDamageDie: dmgDie,252 setProb: this.useArgs.prob,253 setSource: getTopOwnerActor(this)254 }255 };256 createUseItemComp(this, obj, effArgs);257 return true;258 },259 }, // poison260 // Stun effect261 {262 name: 'stun',263 requires: ['duration'],264 func(obj) {265 const actor = getTargetActor(obj);266 if (actor) {267 const stunDur = getDuration(this.useArgs.duration);268 const stunComp = new Component.Stun();269 const expiration = new Component.Expiration();270 expiration.addEffect(stunComp, stunDur);271 const itemOwner = getTopOwnerActor(this);272 stunComp.setSource(itemOwner);273 actor.add(stunComp);274 actor.add(expiration);275 createUseItemComp(this, actor);276 RG.gameMsg(actor.getName() +277 ' is stunned by ' + this.getName());278 return true;279 }280 return false;281 }282 }, // stun283 // Modifies of the actor stats with given value284 {285 name: 'modifyStat',286 requires: ['statName', 'value'],287 func(obj) {288 const effArgs = {289 target: obj,290 targetType: ['actors'],291 name: 'Stats',292 set: 'set' + this.useArgs.statName.capitalize(),293 get: 'get' + this.useArgs.statName.capitalize(),294 value: this.useArgs.value,295 effectType: 'ModifyCompValue'296 };297 createUseItemComp(this, obj, effArgs);298 return true;299 }300 },301 // Adds an entity into a cell. Use this only if entity is specified302 // using object shells in data/items.ts, data/actors.ts or303 // data/elements.ts. If you want to use your own constructor for an304 // element, then use 'addElement'305 {306 name: 'addEntity',307 requires: ['entityName'],308 optional: ['duration', 'endMsg'],309 func(obj) {310 const effArgs = {311 target: obj,312 targetType: ['cell'],313 entityName: this.useArgs.entityName,314 effectType: 'AddEntity',315 duration: this.useArgs.duration,316 endMsg: this.useArgs.endMsg317 };318 createUseItemComp(this, obj, effArgs);319 return true;320 }321 },322 // Adds an element into a cell. numAllowed indicates how many of these323 // elements can be piled up into a cell324 {325 name: 'addElement',326 requires: ['elementName'],327 optional: ['duration', 'numAllowed', 'successMsg', 'failureMsg', 'successCheck', 'setters'],328 func(obj) {329 const effArgs = {330 target: obj,331 targetType: ['cell'],332 elementName: this.useArgs.elementName,333 effectType: 'AddElement',334 duration: this.useArgs.duration,335 numAllowed: this.useArgs.numAllowed || 1,336 successMsg: this.useArgs.successMsg,337 successCheck: this.useArgs.successCheck,338 failureMsg: this.useArgs.failureMsg,339 setters: this.useArgs.setters,340 };341 createUseItemComp(this, obj, effArgs);342 return true;343 }344 },345 // Removes an element from a cell. Notice that there is no support for346 // temporal removal (too tricky to implement for now)347 {348 name: 'removeElement',349 requires: ['elementName'],350 optional: ['successMsg', 'failureMsg'],351 func(obj) {352 const effArgs = {353 target: obj,354 targetType: ['cell'],355 elementName: this.useArgs.elementName,356 effectType: 'RemoveElement',357 successMsg: this.useArgs.successMsg,358 failureMsg: this.useArgs.failureMsg,359 };360 createUseItemComp(this, obj, effArgs);361 return true;362 }363 },364 ],...

Full Screen

Full Screen

client.js

Source:client.js Github

copy

Full Screen

1const {2 apiController,3} = require('@mazeltov/core/lib/controller');4const {5 validate: {6 hasMaxLen,7 hasMinLen,8 isNotEmpty,9 isUnsigned,10 isString,11 isBoolean,12 withLabel,13 },14} = require('@mazeltov/core/lib/util');15const {16 useArgs,17 validateArgs,18 canAccess,19 consumeArgs,20 viewJSON,21} = require('@mazeltov/core/lib/middleware');22module.exports = ( ctx = {} ) => {23 const {24 models,25 publicKeyPem,26 loggerLib,27 services,28 _requireAuth,29 } = ctx;30 const {31 clientModel,32 } = models;33 return apiController('client', ctx)34 .get('/client', [35 _requireAuth,36 useArgs, {37 query: ['id'],38 },39 validateArgs, {40 validator: clientModel.validateGet,41 },42 canAccess, {43 checkMethod: clientModel.canGet,44 },45 consumeArgs, {46 consumer: clientModel.get,47 },48 viewJSON(),49 ])50 .get('/client/list', [51 _requireAuth,52 useArgs, {53 query: [54 'id',55 'page',56 'limit',57 'owner',58 'isConfidential',59 'label',60 ],61 },62 validateArgs, {63 validator: clientModel.validateList,64 },65 canAccess, {66 checkMethod: clientModel.canList,67 },68 consumeArgs, {69 consumer: clientModel.list,70 },71 viewJSON(),72 ])73 .post('/client', [74 _requireAuth,75 useArgs, {76 body: [77 'secret',78 'label',79 'isConfidential',80 'redirect_urls',81 ],82 },83 validateArgs, {84 validator: clientModel.validateCreate,85 },86 canAccess, {87 checkMethod: clientModel.canCreate,88 },89 consumeArgs, {90 consumer: clientModel.create,91 },92 viewJSON(),93 ])94 .put('/client/:id', [95 _requireAuth,96 useArgs, {97 params: [98 'id',99 ],100 body: [101 'secret',102 'label',103 'isConfidential',104 'redirect_urls',105 ],106 },107 validateArgs, {108 validator: clientModel.validateUpdate,109 },110 canAccess, {111 checkMethod: clientModel.canUpdate,112 },113 consumeArgs, {114 consumer: clientModel.update,115 },116 viewJSON(),117 ])118 .delete('/client/:id', [119 _requireAuth,120 useArgs, {121 params: [122 'id',123 ],124 },125 validateArgs, {126 validator: clientModel.validateRemove,127 },128 canAccess, {129 checkMethod: clientModel.canRemove,130 },131 consumeArgs, {132 consumer: clientModel.remove,133 },134 viewJSON(),135 ]);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useArgs } from '@storybook/addons';2export const MyComponent = () => {3 const [args, updateArgs] = useArgs();4 return (5 <p>MyComponent: {args.name}</p>6 <button onClick={() => updateArgs({ name: 'Updated' })}>7 );8};9MyComponent.story = {10 args: {11 },12};13 (Story, context) => {14 const [args, updateArgs] = useArgs();15 return (16 <p>Decorator: {args.name}</p>17 <button onClick={() => updateArgs({ name: 'Updated' })}>18 <Story {...context} />19 );20 },21];22export const parameters = {23 actions: { argTypesRegex: '^on[A-Z].*' },24 controls: {25 matchers: {26 color: /(background|color)$/i,27 },28 },29};30export const globalTypes = {31 theme: {32 toolbar: {33 },34 },35};36export const globalArgs = {37};38 async () => {39 const data = await response.json();40 return data;41 },42];

Full Screen

Using AI Code Generation

copy

Full Screen

1import { useArgs } from 'storybook-root';2const Story = () => {3 const [args, updateArgs] = useArgs();4 return (5 <button onClick={() => updateArgs({ name: 'John' })}>6 <div>{args.name}</div>7 );8};9export default Story;10import { useArgs } from '@storybook/client-api';11import { addDecorator } from '@storybook/react';12import React from 'react';13addDecorator((storyFn, context) => {14 const story = storyFn(context);15 return <story.type {...story.props} useArgs={useArgs} />;16});17const path = require('path');18module.exports = {19 stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'],20 webpackFinal: async (config) => {21 config.resolve.alias['storybook-root'] = path.resolve(__dirname, '../src');22 return config;23 },24};

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3storiesOf('test', module).add('test', () => {4 return <div>test</div>;5});6import { configure, addDecorator } from '@storybook/react';7import { withKnobs } from '@storybook/addon-knobs';8import { withRoot } from './storybook-root';9addDecorator(withKnobs);10addDecorator(withRoot);11configure(require.context('../src', true, /\.stories\.js$/), module);12import React from 'react';13import { useArgs } from '@storybook/client-api';14const StorybookRoot = ({ children }) => {15 const [args, updateArgs] = useArgs();16 return <div>{children}</div>;17};18export const withRoot = (storyFn) => <StorybookRoot>{storyFn()}</StorybookRoot>;19export default StorybookRoot;

Full Screen

Using AI Code Generation

copy

Full Screen

1import {useArgs} from '@storybook/addons';2export default function Test() {3 const [args, updateArgs] = useArgs();4 return <div>{args.myArg}</div>;5}6import Test from '../test';7export default {8 argTypes: {9 myArg: {control: 'text'},10 },11};12const Template = (args) => <Test {...args} />;13export const Primary = Template.bind({});14Primary.args = {15};

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful