svelte/store#derived TypeScript Examples

The following examples show how to use svelte/store#derived. 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.ts    From musetree with MIT License 7 votes vote down vote up
export function maybeDerived<S extends Stores, T>(
  stores: S,
  func: (values: StoresValues<S>) => T,
  initial: T,
  equality: (last: T, next: T) => boolean = (a, b) => (a === b)
): Readable<T> {
  let lastValue: T = initial;
  const actualFunc = (stores: StoresValues<S>, set: (value: T) => void) => {
    const nextValue = func(stores);
    if (!equality(lastValue, nextValue)) {
      lastValue = nextValue;
      set(nextValue);
    }
  };
  return derived(stores, actualFunc, initial);
}
Example #2
Source File: notes.ts    From musetree with MIT License 6 votes vote down vote up
export function createBranchNotesStore(parent: NotesStore, sectionStore: SectionStore): NotesStore {
  let lastParent: ProcessedNotes = createEmptyNotes();
  let lastChild: ProcessedNotes = createEmptyNotes();
  return derived([parent, sectionStore], ([$parent, $sectionStore]: [NotesState, SectionState], set: (newValue: NotesState) => void) => {
    if (notesEquality($parent.notes, lastParent) && notesEquality($sectionStore.section.notes, lastChild)) return;
    lastParent = $parent.notes;
    lastChild = $sectionStore.section.notes;
    const parentNotes: ProcessedNotes = $parent.notes;
    const childNotes: ProcessedNotes = $sectionStore.section.notes;
    const combinedNotes: ProcessedNotes = createEmptyNotes();
    instruments.forEach(instrument => {
      combinedNotes[instrument] = [...parentNotes[instrument], ...childNotes[instrument]];
    });
    set({ notes: combinedNotes });
  }, { notes: createEmptyNotes() });
}
Example #3
Source File: tree.ts    From musetree with MIT License 6 votes vote down vote up
function deriveNumberOfLeavesStore(decoratedStateStore: StoreSafePlain_DecoratedState_Root<any, any, any, any>): Readable<number> {
  const summed: Readable<Readable<number>> = derived(decoratedStateStore, (state: State_Base<any, any, any, any, any>) => {
    const internalStores: StoreSafeDecorated_DecoratedState_Branch<any, any, any, any>[] = Object.values(state.children).map((child: StoreSafeDecorated_DecoratedState_Branch<any, any, any, any>) => child.numberOfLeavesStore)
    if (internalStores.length === 0) return writable(1);
    return derived(internalStores as [Readable<number>, ...Readable<number>[]], (numbers: number[]) => {
      if (numbers.length === 0) return 1;
      return numbers.reduce((a, b) => a + b, 0);
    })
  });
  return unwrapStoreNonNull<number, Readable<number>>(summed, 1);
}
Example #4
Source File: trackTree.ts    From musetree with MIT License 6 votes vote down vote up
function deriveBranchStateDecorationStore(parentStore: Parameters<typeof createEncodingStore>[0], sectionStore: SectionStore, pendingLoadStore: PendingLoadStore): Readable<BranchStateDecoration> {
  const encodingStore = createEncodingStore(parentStore, sectionStore);
  return derived([sectionStore, encodingStore, pendingLoadStore],
    ([$sectionStore, $encodingStore, $pendingLoadStore]) => ({
      ...$sectionStore,
      ...$encodingStore,
      ...$pendingLoadStore
    })
  );
}
Example #5
Source File: settings.ts    From musetree with MIT License 6 votes vote down vote up
configStore: Readable<Config> = derived(
  [
    generationLengthStore,
    maxRequestLengthStore,
    genreStore,
    instrumentsStore,
    temperatureStore,
    truncationStore
  ],
  ([
    $generationLengthStore,
    $maxRequestLengthStore,
    $genreStore,
    $instrumentsStore,
    $temperatureStore,
    $truncationStore
  ]) => ({
    audioFormat: "mp3",
    encoding: [],
    generationLength: $generationLengthStore,
    requestLength: $maxRequestLengthStore,
    genre: $genreStore[1],
    instrument: $instrumentsStore,
    temperature: $temperatureStore,
    truncation: $truncationStore
  })
)
Example #6
Source File: serialisation.ts    From musetree with MIT License 6 votes vote down vote up
export function deriveSerialisedRootStore(rootStore: Readable<TreeState>): Readable<string> {
  const initial: string = JSON.stringify({ children: [] });
  const nested: Readable<Readable<string>> = derived(rootStore, (rootState: TreeState) => {
    const childMap: Record<number, BranchStore> = rootState.children;
    const childStores: BranchStore[] = Object.values(childMap);
    const serialisedChildStores: Readable<string>[] = childStores.map(store => store.serialisedStore)
    const combinedChildStores: Readable<string[]> = serialisedChildStores.length === 0 ? writable([]) : derived(serialisedChildStores as [Readable<string>, ...Readable<string>[]], (states: string[]) => states);
    return maybeDerived(combinedChildStores, (state: string[]) => `{"children":[${state.join(",")}]}`, initial);
  });
  return unwrapStoreNonNull<string, Readable<string>>(nested, initial);
}
Example #7
Source File: serialisation.ts    From musetree with MIT License 6 votes vote down vote up
export function deriveSerialisedBranchStore(branchStore: Readable<BranchState>): Readable<string> {
  const initial: string = JSON.stringify({ encoding: "", children: [] });
  const nested: Readable<Readable<string>> = derived(branchStore, (branchState: BranchState) => {
    const childMap: Record<number, BranchStore> = branchState.children;
    const childStores: BranchStore[] = Object.values(childMap);
    const serialisedChildStores: Readable<string>[] = childStores.map(store => store.serialisedStore)
    const combinedChildStores: Readable<string[]> = serialisedChildStores.length === 0 ? writable([]) : derived(serialisedChildStores as [Readable<string>, ...Readable<string>[]], (states: string[]) => states);
    const encoding = encodingToString(branchState.section.encoding);
    return maybeDerived(combinedChildStores, (state: string[]) => `{"encoding":"${encoding}","children":[${state.join(",")}]}`, initial);
  });
  return unwrapStoreNonNull<string, Readable<string>>(nested, initial);
}
Example #8
Source File: section.ts    From musetree with MIT License 6 votes vote down vote up
export function deriveBranchSectionsStore(branchStore: Readable<BranchState>): Readable<Section[]> {
  const nested: Readable<Readable<Section[]>> = derived(branchStore, (branchState: BranchState) => {
    const selectedChildIdx: number | null = branchState.selectedChild;
    if (selectedChildIdx === null) return writable([branchState.section]);
    const childrenMap: Record<number, BranchStore> = branchState.children;
    const selectedChild: BranchStore | undefined = childrenMap[selectedChildIdx];
    if (selectedChild === undefined) return writable([branchState.section]);
    const childSectionsStore = selectedChild.selectedSectionsStore;
    return derived(childSectionsStore, (childSectionsState) => [branchState.section, ...childSectionsState]);
  });
  return unwrapStoreNonNull<Section[], Readable<Section[]>>(nested, [], sectionArrayEquality);
}
Example #9
Source File: section.ts    From musetree with MIT License 6 votes vote down vote up
export function deriveRootSectionsStore(rootStore: Readable<TreeState>): Readable<Section[]> {
  const nested: Readable<Readable<Section[]>> = derived(rootStore, (rootState: TreeState) => {
    const selectedChildIdx: number | null = rootState.selectedChild;
    if (selectedChildIdx === null) return writable([]);
    const childrenMap: Record<number, BranchStore> = rootState.children;
    const selectedChild: BranchStore | undefined = childrenMap[selectedChildIdx];
    if (selectedChild === undefined) return writable([]);
    return selectedChild.selectedSectionsStore;
  });
  return unwrapStoreNonNull<Section[], Readable<Section[]>>(nested, [], sectionArrayEquality);
}
Example #10
Source File: placement.ts    From musetree with MIT License 6 votes vote down vote up
export function derivePlacementStore(parentStore: Readable<Pick<NodeState, "children">>): Readable<Array<[number, number]>> {
  const nested: Readable<Readable<Array<[number, number]>>> = derived(parentStore, ({ children }: Pick<NodeState, "children">) => {
    const childStores: BranchStore[] = Object.values(children);
    if (childStores.length === 0) return writable([]);
    const leafStores: Array<Readable<[number, number]>> = childStores.map(store =>
      derived<[BranchStore, Readable<number>], [number, number]>([store, store.numberOfLeavesStore], ([state, numberOfLeaves]: [BranchState, number]) => [state.path[state.path.length - 1], numberOfLeaves])
    );
    const xPositionsStore: Readable<Array<[number, number]>> = derived(leafStores as [Readable<[number, number]>, ...Readable<[number, number]>[]], (leafState: Array<[number, number]>) => {
      let x: number = 0;
      const output: Array<[number, number]> = [];
      leafState.forEach(([idx, leaves]) => {
        output.push([idx, x + leaves / 2]);
        x += leaves;
      })
      return output;
    });
    return xPositionsStore;
  });
  return unwrapStoreNonNull<Array<[number, number]>, Readable<Array<[number, number]>>>(nested, [], placementEquality);
}
Example #11
Source File: colors.ts    From musetree with MIT License 6 votes vote down vote up
allInstrumentsVisibility: Readable<Record<Instrument, boolean>> = derived(
  [bassVisible, drumsVisible, guitarVisible, harpVisible, pianoVisible, violinVisible, celloVisible, fluteVisible, trumpetVisible, clarinetVisible],
  ([$bass, $drums, $guitar, $harp, $piano, $violin, $cello, $flute, $trumpet, $clarinet]) => ({
    bass: $bass,
    drums: $drums,
    guitar: $guitar,
    harp: $harp,
    piano: $piano,
    violin: $violin,
    cello: $cello,
    flute: $flute,
    trumpet: $trumpet,
    clarinet: $clarinet
  }))
Example #12
Source File: Time.ts    From ExpressiveAnimator with Apache License 2.0 6 votes vote down vote up
CurrentAnimatedElements = derived(
    [CurrentProject, CurrentDocumentAnimation, CurrentSelection, ShowOnlySelectedElementsAnimations],
    ([$project, $animation, $selection, $onlySelected]): AnimatedElement[] => {
        if (!$animation || ($onlySelected && $selection.isEmpty)) {
            return [];
        }

        return getAnimatedElements(
            $onlySelected ? getSelectedElementsProperties($animation, $selection) : $animation.getAnimatedElements(),
            $project.animatorSource
        );
    })
Example #13
Source File: pilot-sheet.ts    From foundryvtt-lancer with GNU General Public License v3.0 6 votes vote down vote up
async activateMech(mech: Mech) {
    let this_mm = this.actor.data.data.derived.mm as Pilot;
    // Set active mech
    this_mm.ActiveMechRef = mech.as_ref();
    if (mech.Pilot?.RegistryID != mech.RegistryID) {
      // Also set the mechs pilot if necessary
      mech.Pilot = this_mm;
      mech.writeback();
    }

    await this_mm.writeback();
  }
Example #14
Source File: pilot-sheet.ts    From foundryvtt-lancer with GNU General Public License v3.0 6 votes vote down vote up
export function all_mech_preview(_helper: HelperOptions): string {
  let this_mm: Pilot = _helper.data.root.mm;
  let active_mech: Mech | null = _helper.data.root.active_mech;

  let html = ``;

  /// I still feel like this is pretty inefficient... but it's probably the best we can do for now
  game?.actors
    ?.filter(
      a =>
        a.is_mech() &&
        !!a.data.data.pilot &&
        a.data.data.pilot.id === _helper.data.root.actor.id &&
        a.id !== active_mech?.RegistryID
    )
    .map((m, k) => {
      let inactive_mech = m.data.data.derived.mm;

      if (!inactive_mech) return;

      if (!is_reg_mech(inactive_mech)) return;

      let cd = ref_commons(inactive_mech);
      if (!cd) return simple_mm_ref(EntryType.MECH, inactive_mech, "ERROR LOADING MECH", "", true);

      html = html.concat(`
      <div class="flexrow inactive-row">
        <a class="activate-mech" ${ref_params(cd.ref)}><i class="cci cci-activate"></i></a>
        <div class="major valid ${cd.ref.type} ref" ${ref_params(cd.ref)}>${m.name}</div>
      </div>
    `);
    });

  let cd = ref_commons(this_mm);
  if (active_mech) return active_mech_preview(active_mech, "active_mech", _helper).concat(html);
  else return html;
}
Example #15
Source File: base.ts    From svelte-router with MIT License 6 votes vote down vote up
/** Returns a readable store that contains the given link's information */
  createLink(to: string | LocationInput): Readable<LinkState> {
    const input = typeof to === 'string' ? parseLocationInput(to) : to

    return derived(this.currentRoute, ($currentRoute) => {
      const replacedInput = this.replaceParams(input, $currentRoute.params)
      const href = this.createLinkHref(replacedInput)
      const path = this.getPath(replacedInput)

      if (path == null) {
        return {
          href,
          isActive: false,
          isExactActive: false
        }
      }

      const formattedPath = formatPath(path)
      const routePath = $currentRoute.path

      return {
        href,
        isActive: routePath.startsWith(formattedPath),
        isExactActive: routePath === formattedPath
      }
    })
  }
Example #16
Source File: settings.ts    From musetree with MIT License 5 votes vote down vote up
instrumentsStore = derived<[Readable<boolean>, ...Readable<boolean>[]], Record<InstrumentCategory, boolean>>(
  instrumentStoreValues as [Readable<boolean>, ...Readable<boolean>[]],
  (enabledArray: [boolean, ...boolean[]]) =>
    enabledArray.reduce((acc, enabled, idx) => {
      acc[instrumentCategories[idx]] = enabled;
      return acc;
    }, {} as Record<InstrumentCategory, boolean>)
)
Example #17
Source File: pilot-sheet.ts    From foundryvtt-lancer with GNU General Public License v3.0 5 votes vote down vote up
async deactivateMech() {
    let this_mm = this.actor.data.data.derived.mm as Pilot;

    // Unset active mech
    this_mm.ActiveMechRef = null;

    await this_mm.writeback();
  }
Example #18
Source File: tree.ts    From musetree with MIT License 5 votes vote down vote up
function createBranchStore<RD, BD, RM, BM>(path: number[], decorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>, selectionInfoStore: StoreSafe_DefaultStateDecoration<RD, BD, RM, BM>, selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>): StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> {
  const initialState: State_Branch<RD, BD, RM, BM> = {
    type: "branch",
    nextChildIndex: 1,
    children: {},
    hiddenChildren: {},
    selectedChild: null,
    lastSelected: null,
    path
  };
  const internalStore: StoreUnsafePlain_State_Branch<RD, BD, RM, BM> = writable(initialState);

  const decoratedStateStore: StoreSafePlain_DecoratedState_Branch<RD, BD, RM, BM> = derived(
    [internalStore, decorationStore, selectionInfoStore],
    ([$internalStore, $decorationStore, $selectionInfoStore]) => ({
      ...$internalStore,
      ...$decorationStore,
      ...$selectionInfoStore
    }));

  let partDecorated: StoreSafePartDecorated_DecoratedState_Branch<RD, BD, RM, BM>;
  let fullyDecorated: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>;
  const select = () => {
    selectedStore.set(fullyDecorated)
  };
  partDecorated = {
    type: "branch" as const,
    ...decoratedStateStore,
    selectedChildStore_2: deriveSelectedChildStore(decoratedStateStore),
    numberOfLeavesStore: deriveNumberOfLeavesStore(decoratedStateStore),
    internalSelect: (path: number[]) => branchSelect(internalStore, select, path),
    addChild: (stateDecorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>) => addChild(internalStore, decoratedStateStore, selectedStore, stateDecorationStore, storeDecorationSupplier),
    deleteChild: (childIdx: number) => branchDeleteChild(internalStore, select, childIdx),
    showChild: (childIdx: number) => branchShowChild(internalStore, childIdx),
    hideChild: (childIdx: number) => branchHideChild(internalStore, select, childIdx),
    resetNextChildIndex: () => nodeResetNextChildIdx(internalStore)
  };
  fullyDecorated = {
    ...partDecorated,
    ...storeDecorationSupplier(partDecorated)
  };
  return fullyDecorated;
}
Example #19
Source File: tree.ts    From musetree with MIT License 5 votes vote down vote up
function createRootStore<RD, BD, RM, BM>(stateDecorationStore: Readable<RD>, storeDecorationSupplier_Root: StoreDecorationSupplier_Root<RD, BD, RM, BM>): StoreSafeDecorated_DecoratedState_Root<RD, BD, RM, BM> {
  const initialState: State_Root<RD, BD, RM, BM> = {
    type: "root",
    children: {},
    hiddenChildren: {},
    nextChildIndex: 1,
    selectedChild: null,
    lastSelected: null,
    path: [],
  };
  const internalStore: StoreUnsafePlain_State_Root<RD, BD, RM, BM> = writable(initialState);
  const selectionInfoStore: StoreSafe_DefaultStateDecoration<RD, BD, RM, BM> = writable({
    selectedByParent: true,
    wasLastSelectedByParent: false,
    onSelectedPath: true
  });
  const decoratedStateStore: StoreSafePlain_DecoratedState_Root<RD, BD, RM, BM> = derived(
    [internalStore, stateDecorationStore, selectionInfoStore],
    ([$internalStore, $decorationStore, $selectionInfoStore]) => ({
      ...$internalStore,
      ...$decorationStore,
      ...$selectionInfoStore
    }));

  const mutableSelectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM> = writable(null);

  let partDecorated: StoreSafePartDecorated_DecoratedState_Root<RD, BD, RM, BM>;
  partDecorated = {
    type: "root" as const,
    ...decoratedStateStore,
    selectedChildStore_2: deriveSelectedChildStore(decoratedStateStore),
    numberOfLeavesStore: deriveNumberOfLeavesStore(decoratedStateStore),
    addChild: (stateDecorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>) => addChild(internalStore, decoratedStateStore, mutableSelectedStore, stateDecorationStore, storeDecorationSupplier),
    select: (path: number[]) => rootSelect(internalStore, mutableSelectedStore, path),
    deleteChild: (childIdx: number) => rootDeleteChild(internalStore, mutableSelectedStore, childIdx),
    showChild: (childIdx: number) => rootShowChild(internalStore, childIdx),
    hideChild: (childIdx: number) => rootHideChild(internalStore, mutableSelectedStore, childIdx),
    resetNextChildIndex: () => nodeResetNextChildIdx(internalStore),
    selectedStore_2: mutableSelectedStore
  };

  return {
    ...partDecorated,
    ...storeDecorationSupplier_Root(partDecorated)
  }
}
Example #20
Source File: trackTree.ts    From musetree with MIT License 5 votes vote down vote up
selectedStoreAndState: Readable<null | [BranchStore, BranchState]> = derived([root.selectedStore_2, selectedBranchStore], ([storeValue, stateValue]) => {
  if (storeValue === null || stateValue === null) return null;
  return [storeValue, stateValue];
})
Example #21
Source File: trackTree.ts    From musetree with MIT License 5 votes vote down vote up
export function toReadableNodeState(nodeStore: NodeStore): Readable<NodeState> {
  return derived(nodeStore, (nodeState) => nodeState)
}
Example #22
Source File: is-dragging.ts    From foundryvtt-lancer with GNU General Public License v3.0 5 votes vote down vote up
isDragging = derived(dataTransfer, (dt) => !!dt)
Example #23
Source File: settings.ts    From musetree with MIT License 5 votes vote down vote up
maxRequestLengthStore: Readable<number> = derived([generationLengthStore, maxResponseLengthStore], ([$generationLengthStore, $maxResponseLengthStore]) => $maxResponseLengthStore - $generationLengthStore)
Example #24
Source File: Time.ts    From ExpressiveAnimator with Apache License 2.0 5 votes vote down vote up
CurrentMaxTime = derived([CurrentDocumentAnimation, CurrentTime],
    ([$animation, $time]) => Math.max($time, $animation ? $animation.endTime : 0) * MAX_TIME_SCALE)
Example #25
Source File: Project.ts    From ExpressiveAnimator with Apache License 2.0 5 votes vote down vote up
CurrentSelection = derived<[Readable<AnimationProject>, Readable<number>], AnimationSelection>([project, selectionGenId], ([$project]) => {
    return $project ? $project.selection : null;
})
Example #26
Source File: Project.ts    From ExpressiveAnimator with Apache License 2.0 5 votes vote down vote up
CurrentProjectState = derived<[Readable<AnimationProject>, Readable<number>], AnimationState>([project, stateGenId], ([$project]) => {
    return $project ? ($project.state as AnimationState) : null;
})
Example #27
Source File: Project.ts    From ExpressiveAnimator with Apache License 2.0 5 votes vote down vote up
CurrentKeyframeSelection = derived<[Readable<AnimationProject>, Readable<number>], KeyframeSelection>([project, keyframeSelectionGenId], ([$project]) => {
    return $project ? $project.keyframeSelection : null;
})
Example #28
Source File: Project.ts    From ExpressiveAnimator with Apache License 2.0 5 votes vote down vote up
CurrentSelectedElement = derived<[Readable<AnimationSelection>, Readable<number>, Readable<number>], Element>([CurrentSelection, propertiesGenId, stateGenId], ([$selection]) => {
    return $selection ? $selection.activeElement : null;
})
Example #29
Source File: Project.ts    From ExpressiveAnimator with Apache License 2.0 5 votes vote down vote up
CurrentDocument = derived<Readable<AnimationProject>, AnimationDocument>(project, ($project): AnimationDocument => {
    return $project ? $project.document : null;
})