svelte/store#readable TypeScript Examples
The following examples show how to use
svelte/store#readable.
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 |
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: utils.ts From musetree with MIT License | 7 votes |
export function unwrapStoreNonNull<T, INNER extends Readable<T>>(store_2: Readable<INNER>, initialValue: T, equality: (a: T, b: T) => boolean = (a, b) => a === b): Readable<T> {
let value: T = initialValue;
const output: Writable<T> = writable(initialValue);
let unsubscribe: () => void = () => { };
store_2.subscribe((store: INNER) => {
unsubscribe();
unsubscribe = store.subscribe((state: T) => {
if (!equality(value, state)) {
value = state;
output.set(state);
}
})
});
return output;
}
Example #3
Source File: utils.ts From musetree with MIT License | 7 votes |
export function unwrapStore<T, INNER extends Readable<T | null>>(store_2: Readable<INNER | null>, equality: (a: T, b: T) => boolean = (a, b) => a === b): Readable<T | null> {
let value: T | null = null;
const output: Writable<T | null> = writable(null);
let unsubscribe: () => void = () => { };
store_2.subscribe((store: INNER | null) => {
unsubscribe();
if (store !== null) {
unsubscribe = store.subscribe((state: T | null) => {
if (
(value === null && state !== null) ||
(value !== null && state === null) ||
(value !== null && state !== null && !equality(value, state))
) {
value = state;
output.set(state);
}
})
} else {
unsubscribe = () => { };
value = null;
output.set(null);
}
});
return output;
}
Example #4
Source File: section.ts From musetree with MIT License | 6 votes |
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 #5
Source File: utils.ts From svelte-site-jp with MIT License | 6 votes |
export function get_store_value<T>(store: Readable<T>): T {
let value;
subscribe(store, _ => value = _)();
return value;
}
Example #6
Source File: tree.ts From musetree with MIT License | 6 votes |
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 #7
Source File: tree.ts From musetree with MIT License | 6 votes |
async function addChild<RD, BD, RM, BM,
STATE extends State_Either<RD, BD, RM, BM>>(
internalStore: Writable<STATE>,
decoratedStore: StoreSafePlain_DecoratedState_Either<RD, BD, RM, BM>,
selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>,
stateDecorationStore: Readable<BD>,
storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>
): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>> {
return await new Promise(resolve => {
internalStore.update((state: STATE) => {
const childIndex = state.nextChildIndex;
const selectionInfoStore: StoreSafe_DefaultStateDecoration<RD, BD, RM, BM> = maybeDerived(decoratedStore, ($parentTotal: DecoratedState_Either<RD, BD, RM, BM>) => ({
selectedByParent: $parentTotal.selectedChild === childIndex,
wasLastSelectedByParent: $parentTotal.lastSelected === childIndex,
onSelectedPath: $parentTotal.onSelectedPath && $parentTotal.selectedChild === childIndex
}), { selectedByParent: false, wasLastSelectedByParent: false, onSelectedPath: false }, (a, b) => a.selectedByParent === b.selectedByParent && a.wasLastSelectedByParent === b.wasLastSelectedByParent && a.onSelectedPath === b.onSelectedPath);
const newChild: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> = createBranchStore([...state.path, childIndex], stateDecorationStore, storeDecorationSupplier, selectionInfoStore, selectedStore);
resolve(newChild);
const children: Record<number, StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>> = { ...state.children };
children[state.nextChildIndex] = newChild;
return {
...state,
children,
nextChildIndex: childIndex + 1
}
})
})
}
Example #8
Source File: trackTree.ts From musetree with MIT License | 6 votes |
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 #9
Source File: settings.ts From musetree with MIT License | 6 votes |
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 #10
Source File: serialisation.ts From musetree with MIT License | 6 votes |
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 #11
Source File: serialisation.ts From musetree with MIT License | 6 votes |
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 #12
Source File: section.ts From musetree with MIT License | 6 votes |
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 #13
Source File: placement.ts From musetree with MIT License | 6 votes |
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 #14
Source File: colors.ts From musetree with MIT License | 6 votes |
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 #15
Source File: expectedv2.ts From language-tools with MIT License | 6 votes |
function render() {
const store = readable(Promise.resolve('test'), () => {})/*Ωignore_startΩ*/;let $store = __sveltets_1_store_get(store);/*Ωignore_endΩ*/;
;
async () => {
{
{ svelteHTML.createElement("p", {}); }
const $$_value = await ((__sveltets_1_store_get(store), $store));{ const data = $$_value;
data;
}}};
return { props: {}, slots: {}, getters: {}, events: {} }}
Example #16
Source File: is-dragging.ts From foundryvtt-lancer with GNU General Public License v3.0 | 6 votes |
dataTransfer = readable(null as DataTransfer | null, update => {
function updateData(e: DragEvent) {
update(e.defaultPrevented ? null : e.dataTransfer ?? null);
}
document.addEventListener('dragstart', e => {
// for now, only check on the next tick
// all event handlers process on the current tick, right...?
setTimeout(() => updateData(e), 0);
}, {
capture: true,
passive: true
});
document.addEventListener('dragend', e => {
update(null);
}, {
capture: true,
passive: true
});
})
Example #17
Source File: user-targets.ts From foundryvtt-lancer with GNU General Public License v3.0 | 6 votes |
userTargets = readable([] as Token[], update => {
function updateData() {
update(Array.from(game!.user!.targets));
}
Hooks.on('targetToken', (user: User, _token: Token, _isNewTarget: boolean) => {
if (user.isSelf) {
updateData();
}
})
Hooks.on('createActiveEffect', updateData);
Hooks.on('deleteActiveEffect', updateData);
// updateToken triggers on things like token movement (spotter) and probably a lot of other things
Hooks.on('updateToken', updateData);
})
Example #18
Source File: storage.ts From HyperChat with GNU Affero General Public License v3.0 | 6 votes |
translatorClient = readable(null as (null | IframeTranslatorClient), (set) => {
let client: IframeTranslatorClient | null = null;
const destroyIf = (): void => {
if (client !== null) {
client.destroy();
client = null;
}
set(null);
};
// eslint-disable-next-line @typescript-eslint/no-misused-promises
const unsub = translateTargetLanguage.subscribe(async ($translateTargetLanguage) => {
if (!$translateTargetLanguage) {
destroyIf();
return;
}
if (client) return;
client = await getClient();
set(client);
});
translateTargetLanguage.ready().then(() => {
// migrate from old language value to new language code
const oldString = translateTargetLanguage.getCurrent() as string;
if (!(oldString in AvailableLanguages)) {
const newKey = (
Object.keys(AvailableLanguages) as AvailableLanguageCodes[]
).find(key => AvailableLanguages[key] === oldString);
translateTargetLanguage.set(newKey ?? '').catch(console.error);
}
}).catch(console.error);
return () => {
unsub();
destroyIf();
};
})
Example #19
Source File: base.ts From svelte-router with MIT License | 6 votes |
constructor(routes: RouteRecord[]) {
this.routeMatcher = new RouteMatcher(routes)
this.currentRoute = readable(this.getCurrentRoute(), (set) => {
const handleChange = () => set(this.getCurrentRoute())
window.addEventListener(LOCATION_CHANGE, handleChange)
return () => window.removeEventListener(LOCATION_CHANGE, handleChange)
})
// Format URL on page load
this.navigate(this.getCurrentLocationInput(), true)
}
Example #20
Source File: expected.tsx From language-tools with MIT License | 6 votes |
function render() {
const store = readable(Promise.resolve('test'), () => {})/*Ωignore_startΩ*/;let $store = __sveltets_1_store_get(store);/*Ωignore_endΩ*/;
;
() => (<>
{() => {let _$$p = ((__sveltets_1_store_get(store), $store)); <>
<p>loading</p>
</>; __sveltets_1_awaitThen(_$$p, (data) => {<>
{data}
</>})}}</>);
return { props: {}, slots: {}, getters: {}, events: {} }}
Example #21
Source File: base.ts From svelte-router with MIT License | 6 votes |
/** 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 #22
Source File: trackTree.ts From musetree with MIT License | 5 votes |
selectedEncodingStore: Readable<number[] | null> = maybeDerived(selectedBranchStore, state => state === null ? null : state.encoding, null, (a, b) => arrayEqualNullable(a, b))
Example #23
Source File: Project.ts From ExpressiveAnimator with Apache License 2.0 | 5 votes |
CurrentDocument = derived<Readable<AnimationProject>, AnimationDocument>(project, ($project): AnimationDocument => {
return $project ? $project.document : null;
})
Example #24
Source File: sidebar-width.ts From foundryvtt-lancer with GNU General Public License v3.0 | 5 votes |
sidebarWidth = readable(0, update => {
const sidebar = $("#sidebar");
function setWidth() { update(sidebar.width() || 0); }
setWidth();
Hooks.on('collapseSidebar', setWidth);
})
Example #25
Source File: Project.ts From ExpressiveAnimator with Apache License 2.0 | 5 votes |
CurrentDocumentAnimation = derived<[Readable<AnimationDocument>, Readable<number>], DocumentAnimation>([CurrentDocument, animationGenId], ([$document]): DocumentAnimation => {
return $document ? $document.animation : null;
})
Example #26
Source File: Project.ts From ExpressiveAnimator with Apache License 2.0 | 5 votes |
CurrentKeyframeSelection = derived<[Readable<AnimationProject>, Readable<number>], KeyframeSelection>([project, keyframeSelectionGenId], ([$project]) => {
return $project ? $project.keyframeSelection : null;
})
Example #27
Source File: Project.ts From ExpressiveAnimator with Apache License 2.0 | 5 votes |
CurrentProjectState = derived<[Readable<AnimationProject>, Readable<number>], AnimationState>([project, stateGenId], ([$project]) => {
return $project ? ($project.state as AnimationState) : null;
})
Example #28
Source File: tree.ts From musetree with MIT License | 5 votes |
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 #29
Source File: tree.ts From musetree with MIT License | 5 votes |
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)
}
}