svelte/store#get JavaScript Examples

The following examples show how to use svelte/store#get. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.js    From lnft with GNU Affero General Public License v3.0 7 votes vote down vote up
addressLabel = (address) => {
  let $addresses = get(addresses);

  let r;

  if ($addresses) {
    r = $addresses.find((u) => u.multisig === address);
    if (r) return r.username + " 2of2";
    r = $addresses.find((u) => u.address === address);
    if (r) return r.username;
  }

  return address.length > 6 ? address.substr(0, 6) + "..." : address;
}
Example #2
Source File: SongService.js    From ZzFXM with MIT License 6 votes vote down vote up
serializeSong = (options = {}) => {
  const tidyMeta = removeEmptyStringValues(get(meta));
  let serializedMeta;

  if (!options.noMeta) {
    serializedMeta = {
      ...tidyMeta,
      ...{
        title: get(title),
        instruments: get(instrumentsMeta),
        patterns: get(patternsMeta)
      }
    };
  }

  return encodeSong([
    get(instruments),
    get(patterns),
    get(sequence),
    get(speed),
    serializedMeta
  ]);
}
Example #3
Source File: use-theme-classes.js    From konsta with MIT License 6 votes vote down vote up
useThemeClasses = (props, classesObj, addBaseClassName = '', cb) => {
  let theme = get(KonstaStore).theme;
  const calcClasses = () => {
    return themeClasses(
      typeof classesObj === 'function' ? classesObj() : classesObj,
      theme,
      addBaseClassName
    );
  };
  if (props.ios) theme = 'ios';
  else if (props.material) theme = 'material';
  else {
    KonstaStore.subscribe((context) => {
      theme = context.theme || 'ios';
      if (cb) {
        cb(calcClasses());
      }
    });
  }
  return calcClasses();
}
Example #4
Source File: auth.js    From lnft with GNU Affero General Public License v3.0 6 votes vote down vote up
requireLogin = async (page) => {
  if (page && page.path === "/login") return;
  try {
    if (expired(get(token))) throw new Error("Login required");
  } catch (e) {
    console.log(e);
    goto("/login");
    throw e;
  }
}
Example #5
Source File: test.js    From sveltik with MIT License 6 votes vote down vote up
test('touches fields on submit', async () => {
    const { instance } = await mount('./src/Sveltik.svelte', {
        props: {
            initialValues: {
                email: '',
                password: '',
            },
            validate: values => {
                const errors = {}
                if (!values.email) {
                    errors.email = 'Required'
                }
                return errors
            },
            validateOnMount: true,
        },
        inspect: true,
    })

    const { errors } = instance.inspect()

    expect(get(errors)).toMatchObject({ email: 'Required' })
})
Example #6
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 6 votes vote down vote up
cancelSwap = async (artwork) => {
  let { asset } = artwork;
  let out = isMultisig(artwork) ? multisig() : singlesig();

  let p = new Psbt().addOutput({
    asset,
    nonce,
    script: out.output,
    value: 1,
  });

  await fund(p, out, asset, 1);
  await fund(p, singlesig(), btc, get(fee));

  addFee(p);

  return p;
}
Example #7
Source File: test.js    From sveltik with MIT License 6 votes vote down vote up
test('handles resetForm', async () => {
    const { instance } = await mount('./src/Sveltik.svelte', {
        props: {
            initialValues: {
                email: '',
                password: '',
            },
        },
        inspect: true,
    })

    const { setValues, resetForm, values } = instance.inspect()

    setValues({ email: 'hello' })
    expect(get(values)).toMatchObject({ email: 'hello' })
    resetForm()
    expect(get(values)).toMatchObject({ email: '' })
    resetForm({ values: { email: 'hi' }, status: 'reset' })
    expect(get(values)).toMatchObject({ email: 'hi' })

    const { status } = instance.inspect()
    expect(status).toBe('reset')
})
Example #8
Source File: SequenceService.js    From ZzFXM with MIT License 6 votes vote down vote up
getCumlativeRowAtPosition = sequencePos => {
  const patts = get(patterns);
  const seq = get(sequence);
  let row = 0;
  sequencePos = sequencePos % (seq.length);
  for (let sequenceIndex = 0; sequenceIndex < sequencePos; sequenceIndex++) {
    row += patts[seq[sequenceIndex]][0].length - 2;
  }
  return row;
}
Example #9
Source File: cache.js    From ethernal with MIT License 6 votes vote down vote up
calculateReachableRooms() {
    const previous = cache.reachableRooms;
    const recalculated =
      !this.characterCoordinates || get(needFood) || this.characterStatus !== 'exploring'
        ? {[this.characterCoordinates]: this.currentRoom}
        : bfs(this.rooms, this.moves, this.characterCoordinates, get(_characterBalances).keys);
    if (!equal(previous, recalculated)) {
      _reachableRooms.set(recalculated);
    }
  }
Example #10
Source File: RendererService.js    From ZzFXM with MIT License 6 votes vote down vote up
playPattern = async (pattern, fromStart = false) => {
  if (processor) {
    return false;
  }

  playbackSequence = [pattern];

  if (fromStart) {
    pos = 0;
  } else {
    pos = get(selectedRow);
  }
  await play();
}
Example #11
Source File: MapRenderer.js    From ethernal with MIT License 6 votes vote down vote up
updateAllFog() {
    this.hideFurthestChunks();
    if (this.activeChunks.length) {
      const reachableCoordinates = Object.keys(get(reachableRooms));
      const updateChunksIds = Array.from(new Set([...reachableCoordinates, ...this.previousReachable])).reduce(
        (s, coordinates) => s.add(coordinatesChunkId(coordinates)),
        new Set(),
      );
      this.activeChunks.forEach(({ id }) => updateChunksIds.add(id));
      Array.from(updateChunksIds).forEach(id => this.createChunk(id).renderFog());
      this.placeArrows();
    }
  }
Example #12
Source File: SequenceService.js    From ZzFXM with MIT License 6 votes vote down vote up
getSongLength = () => {
  const patts = get(patterns);
  const seq = get(sequence);
  let length = 0
  for (let sequenceIndex = 0; sequenceIndex < seq.length; sequenceIndex++) {
    length += patts[seq[sequenceIndex]][0].length - 2;
  }
  return length;
}
Example #13
Source File: location.js    From tinro with MIT License 6 votes vote down vote up
function locationMethods(l){

    const getQ = ()=>l.get().query;
    const setQ = (v)=>l.set({query:v})
    const updQ = (fn)=>setQ(fn(getQ()));

    const getH = ()=>l.get().hash;
    const setH = (v)=>l.set({hash:v})

    return {
        hash: {
            get: getH,
            set: setH,
            clear: ()=>setH('')
        },
        query: {
            replace: setQ,
            clear: ()=>setQ(''),
            get(name){
                return name ? getQ()[name] : getQ();
            },
            set(name,v){
                updQ(q => (q[name]=v,q))
            },
            delete(name){
                updQ(q => ((q[name] && delete q[name]),q));
            }
        }
    }
}
Example #14
Source File: MapRenderer.js    From ethernal with MIT License 6 votes vote down vote up
placeArrows() {
    this.removeArrows();
    if (moving) return;

    Object.values(get(reachableRooms)).forEach(room => {
      if (!room) return;
      if (room.status === 'undiscovered') {
        const { parent } = room;
        const dir = parent.exit;
        const parentRoom = this.rooms[parent.coordinates];
        if (!parentRoom) return;
        this.createArrow(room.coordinates, dir, parentRoom);
        this.dirty = true;
      }
    });
  }
Example #15
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
createRelease = async ({ asset, owner }, tx) => {
  let p = new Psbt().addOutput({
    asset,
    nonce,
    script: Address.toOutputScript(owner.address, network),
    value: 1,
  });

  let index = tx.outs.findIndex(
    (o) =>
      parseAsset(o.asset) === btc &&
      parseVal(o.value) >= get(fee) &&
      o.script.toString("hex") === singlesig().output.toString("hex")
  );

  if (index > -1) {
    p.addInput({
      index,
      hash: tx.getId(),
      nonWitnessUtxo: Buffer.from(tx.toHex(), "hex"),
      redeemScript: singlesig().redeem.output,
    });

    if (parseVal(tx.outs[index].value) > get(fee)) {
      p.addOutput({
        asset: btc,
        nonce,
        script: singlesig().output,
        value: parseVal(tx.outs[index].value) - get(fee),
      });
    }
  } else {
    await fund(p, singlesig(), btc, get(fee), 1, false);
  }

  index = tx.outs.findIndex((o) => parseAsset(o.asset) === asset);

  p.addInput({
    index,
    hash: tx.getId(),
    nonWitnessUtxo: Buffer.from(tx.toHex(), "hex"),
    redeemScript: multisig().redeem.output,
    witnessScript: multisig().redeem.redeem.output,
  });

  addFee(p);

  psbt.set(p);

  return sign();
}
Example #16
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
async action(type, actionData) {
    this.socket.emit(type, actionData);

    return new Promise(resolve => {
      // @TODO: make this more modular (handling related to the specific action should be where the action is triggered)
      // @TODO: consider moving to lang file
      this.socket.once(`${type}-reply`, data => {
        switch (type) {
          case 'attack': {
            this.pushHistory(combatText.attack);
            break;
          }
          case 'escape': {
            let text;
            if (data.success) {
              const turn = inflictionText(data.turn.inflictions.defender);
              text = combatText.escape.success({ turn });
            } else {
              text = combatText.escape.failure;
            }
            this.pushHistory(text);
            break;
          }
          case 'finish': {
            const reward = get(rewardsToCollect);
            const notifyAboutEquip = reward && reward.gear && get(defaultGearEquipped);
            this.pushHistory(combatText.finish.success);
            if (notifyAboutEquip) {
              this.pushHistory(combatText.finish.notifyEquip);
            }
            break;
          }
          default: {
            break;
          }
        }
        resolve(data);
      });
    });
  }
Example #17
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
requestSignature = async (psbt) => {
  let { base64 } = await api
    .url("/sign")
    .headers({ authorization: `Bearer ${get(token)}` })
    .post({ psbt: psbt.toBase64() })
    .json();
  return Psbt.fromBase64(base64);
}
Example #18
Source File: sveltik.test.js    From sveltik with MIT License 5 votes vote down vote up
test('prevents submit on invalid', async () => {
    let hasSubmitted = false

    const { sveltik } = await mount('./src/Sveltik.svelte', {
        props: {
            initialValues: {
                email: '',
            },
            validate: values => {
                const errors = {}

                if (!values.email) {
                    errors.email = 'Required'
                }

                return errors
            },
            onSubmit: () => {
                hasSubmitted = true
                return Promise.resolve()
            },
        },
        inspect: true,
    })

    const { handleSubmit } = sveltik.inspect()

    handleSubmit()

    const state = sveltik.inspect()

    expect(state).toMatchObject({
        submitAttemptCount: 1,
        submitFailureCount: 1,
        submitSuccessCount: 0,
    })

    expect(get(state.errors)).toMatchObject({
        email: 'Required',
    })

    expect(hasSubmitted).toBe(false)
})
Example #19
Source File: MapRenderer.js    From ethernal with MIT License 5 votes vote down vote up
addObjectAtCoords(item, coords, options = {}) {
    const { parentGroup, animate } = options;

    // Add room data if known
    if (!this.rooms[coords]) {
      const roomData = global.dungeon.cache.rooms[coords];
      if (roomData) {
        this.addRoom(roomData);
      }
    }

    // Get room, otherwise return items
    const room = this.rooms[coords];
    if (!room) {
      return item;
    }

    if (item.charId) {
      const position = room.getPosition(item.charId);
      item.x = position.x;
      item.y = position.y;
    } else {
      item.x = room.center.x;
      item.y = room.center.y;
    }

    if (typeof parentGroup !== 'undefined') {
      item.parentGroup = parentGroup;
    }
    if (animate) {
      item.alpha = 0;
      if (item.appear) {
        item.appear(item.x, item.y);
      } else {
        ease.add(item, { alpha: 1 }, { duration: 1000 });
      }
    }
    const [rx, ry] = coords.split(',').map(Number);
    const chunkCoordinates = toChunkCoordinates(rx, ry);
    const chunkId = `${chunkCoordinates.x},${chunkCoordinates.y}`;
    const chunk = this.chunks.get(chunkId);
    chunk.contentUpper.addChild(item);
    return item;
  }
Example #20
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
bumpFee = (v) => fee.set(get(fee) + v)
Example #21
Source File: MapRenderer.js    From ethernal with MIT License 5 votes vote down vote up
moveCharacter(charId, from, to, mode, path) {
    const character = this.characters[charId];
    if (!character) {
      // eslint-disable-next-line no-console
      console.error(`no character on map with id: ${charId}, need to be added first, adding it for now...`);
      this.addCharacter(charId, to);
      return;
    }

    let chunk;
    const roomTo = this.rooms[to];
    if (roomTo) {
      chunk = roomTo.chunk;
    } else {
      const [rx, ry] = to.split(',').map(Number);
      const chunkCoordinates = toChunkCoordinates(rx, ry);
      const chunkId = `${chunkCoordinates.x},${chunkCoordinates.y}`;
      chunk = this.chunks.get(chunkId);
    }
    chunk.contentUpper.addChild(character);

    if (charId === this.myCharacter.charId) {
      this.moveMyCharacter(from, to);
      return;
    }

    if (character.dstRoom === to && character.path) {
      if (character.path.isFinished()) {
        character.notifyDestinationReached();
      } else {
        character.path.finish();
      }
      return;
    }

    // eslint-disable-next-line no-console
    character.dstRoom = to;

    if (character === this.myCharacter) {
      // ...
    } else {
      character.path = this.createPath(character, from, to, path);
      if (character.path) {
        const len = character.path.steps.length;
        let prevRoom;
        character.path.play(
          (index, step) => {
            if (prevRoom) {
              this.updateRoomCharacters(prevRoom, [], [character]);
            }
            this.updateRoomCharacters(step.room, [character], [], [character]);

            if (index < len - 1) {
              prevRoom = step.room;
            } else {
              prevRoom = undefined;
            }
          },
          () => {
            if (prevRoom) {
              this.updateRoomCharacters(prevRoom, [], [character]);
            }
            character.path = undefined;
            character.moving = false;
            character.stop();
          },
        );
        if (this.rooms[from]) {
          this.updateRoomCharacters(this.rooms[from], [], [character]);
        }
        character.moving = true;
      }
    }
  }
Example #22
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
getTx = async (txid) => {
  let tx = Transaction.fromHex(await getHex(txid));
  txcache.set({ ...get(txcache), txid: tx });
  return tx;
}
Example #23
Source File: use-dark-classes.js    From konsta with MIT License 5 votes vote down vote up
useDarkClasses = () => {
  return (classNames) => {
    const context = get(KonstaStore);
    if (!context.dark) return '';
    return classNames;
  };
}
Example #24
Source File: RendererService.js    From ZzFXM with MIT License 5 votes vote down vote up
setPosition = () => {
  pos = getCumlativeRowAtPosition(get(selectedSequence));
  pos += get(selectedRow);
  currentOffset = 0;
  channels = null;
}
Example #25
Source File: auth.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
activate = (ticket) => {
  return api.url("/activate").query({ ticket }).get().res();
}
Example #26
Source File: location.js    From tinro with MIT License 5 votes vote down vote up
function createLocation(){
    let MODE = MODES.getDefault();

    let listener;

    const reset = _ => window.onhashchange = window.onpopstate = memoURL = null;
    const dispatch = _ => listener && listener(readLocation(MODE));

    const setMode = (newMode)=>{
        newMode && (MODE = newMode);
        reset();
        MODE !== MODES.OFF 
        && MODES.run( MODE ,
            _ => window.onpopstate = dispatch,
            _ => window.onhashchange = dispatch
        )
        && dispatch()
    }

    const makeURL = (parts)=>{
        const loc = Object.assign(readLocation(MODE),parts);
        return loc.path 
             + prefix(makeQuery(loc.query),'?') 
             + prefix(loc.hash,'#')
    }

    return {
        mode: setMode,
        get: _ => readLocation(MODE),
        go(href,replace){
            writeLocation(MODE,href,replace);
            dispatch();
        },
        start(fn){
            listener = fn;
            setMode()
        },
        stop(){
            listener = null;
            setMode(MODES.OFF)
        },
        set(parts){
            this.go(makeURL(parts), !parts.path);
        },
        methods(){return locationMethods(this)},
        base: newbase => base=newbase
    }
}
Example #27
Source File: screen.js    From ethernal with MIT License 5 votes vote down vote up
writableScreen = (defaultVals, opts) => {
  const store = writable(defaultVals);

  // Persist history of nav changes. (For back button use.)
  const len = 20;
  const list = [];

  // Store previous pageviews
  const addHistory = n => {
    list.unshift(n);
    list.splice(len, list.length - len);
  };
  // Track page views
  const track = page => {
    if (opts.trackable && window.ga) {
      window.ga('send', 'pageview', `/${page.screen}`);
    }
  };

  return {
    ...store,
    history: () => list,
    isOpen: () => {
      const current = get(store);
      return current && current.screen !== defaultVals.screen;
    },
    toggle: (screen, args) =>
      store.update(prev => {
        addHistory(prev);
        const page = screen !== prev.screen ? { screen, ...args } : defaultVals;
        track(page);
        return page;
      }),
    expand: () =>
      store.update(prev => {
        list[0] = { ...prev, expanded: true };
        return list[0];
      }),
    collapse: () =>
      store.update(prev => {
        list[0] = { ...prev, expanded: false };
        return list[0];
      }),
    open: (screen, opts) =>
      store.update(prev => {
        const page = { screen, ...opts };
        // Terrible, but only way to compare equally.
        if (JSON.stringify(prev) !== JSON.stringify(page)) {
          addHistory(prev);
        }
        track(page);
        return page;
      }),
    close: () =>
      store.update(prev => {
        addHistory(prev);
        track(defaultVals);
        return defaultVals;
      }),
    back: () =>
      store.update(() => {
        const page = list.shift();
        track(page);
        return page;
      }),
    find: screens => {
      const current = get(store);
      return current && screens && screens[current.screen] && { ...screens[current.screen], ...current };
    },
  };
}
Example #28
Source File: wallet.js    From lnft with GNU Affero General Public License v3.0 5 votes vote down vote up
getHex = async (txid) => {
  return electrs.url(`/tx/${txid}/hex`).get().text();
}
Example #29
Source File: cache.js    From ethernal with MIT License 5 votes vote down vote up
updateKeeperRooms() {
    const rooms = get(_keeper);
    // @TODO - HOW TO HANDLE ROOMS NOT ON CURRENT FLOOR
    _keeperRooms.set(rooms.map(coordinates => this.rooms[coordinates]).filter(identity));
  }