svelte/store#writable TypeScript Examples
The following examples show how to use
svelte/store#writable.
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 ExpressiveAnimator with Apache License 2.0 | 7 votes |
export function createGenIdStore(): AsyncGenIdStore {
const {subscribe, set, update} = writable<number>(0);
return {
subscribe,
set,
update,
invalidate(): void {
update(plusOne)
}
}
}
Example #2
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 #3
Source File: chat-actions.ts From HyperChat with GNU Affero General Public License v3.0 | 6 votes |
export function useBanHammer(
message: Ytc.ParsedMessage,
action: ChatUserActions,
port: Chat.Port | null
): void {
if (action === ChatUserActions.BLOCK) {
port?.postMessage({
type: 'executeChatAction',
message,
action
});
} else if (action === ChatUserActions.REPORT_USER) {
const store = writable(null as null | ChatReportUserOptions);
reportDialog.set({
callback: (selection) => {
port?.postMessage({
type: 'executeChatAction',
message,
action,
reportOption: selection
});
},
optionStore: store
});
}
}
Example #4
Source File: Canvas.ts From ExpressiveAnimator with Apache License 2.0 | 6 votes |
CanvasEngineState = {
showGuides: writable<boolean>(true),
lockGuides: writable<boolean>(false),
showRuler: writable<boolean>(true),
showGrid: writable<boolean>(false),
showGridToBack: writable<boolean>(true),
highQuality: writable<boolean>(true),
snapping: writable({
// Global flag
enabled: false,
// Individual flags
grid: true,
guides: true,
pixel: true,
document: true,
objects: true,
points: true,
}),
}
Example #5
Source File: api.ts From obsidian-todoist-plugin with MIT License | 6 votes |
constructor(token: string) {
this.token = token;
this.metadata = writable({
projects: new ExtendedMap<ProjectID, IProjectRaw>(),
sections: new ExtendedMap<SectionID, ISectionRaw>(),
labels: new ExtendedMap<LabelID, string>(),
});
this.metadata.subscribe((value) => (this.metadataInstance = value));
}
Example #6
Source File: stores.ts From obsidian-calendar-plugin with MIT License | 6 votes |
function createDailyNotesStore() {
let hasError = false;
const store = writable<Record<string, TFile>>(null);
return {
reindex: () => {
try {
const dailyNotes = getAllDailyNotes();
store.set(dailyNotes);
hasError = false;
} catch (err) {
if (!hasError) {
// Avoid error being shown multiple times
console.log("[Calendar] Failed to find daily notes folder", err);
}
store.set({});
hasError = true;
}
},
...store,
};
}
Example #7
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 #8
Source File: expected.tsx From language-tools with MIT License | 6 votes |
function render() {
const count = writable(0)/*Ωignore_startΩ*/;let $count = __sveltets_1_store_get(count);/*Ωignore_endΩ*/;
let myvar = 42 // to show that this is different from ++ or --
const handler1 = () => count.set( $count + myvar)
const handler2 = () => count.set( $count - myvar)
const handler3 = () => count.set( $count * myvar)
const handler4 = () => count.set( $count / myvar)
const handler5 = () => count.set( $count ** myvar)
const handler6 = () => count.set( $count % myvar)
const handler7 = () => count.set( $count << myvar)
const handler8 = () => count.set( $count >> myvar)
const handler9 = () => count.set( $count >>> myvar)
const handler10 = () => count.set( $count & myvar)
const handler11 = () => count.set( $count ^ myvar)
const handler12 = () => count.set( $count | myvar)
;
() => (<>
<button onclick={() => count.set( $count + myvar)}>add</button>
<button onclick={() => count.set( $count - myvar)}>subtract</button>
<button onclick={() => count.set( $count * myvar)}>multiply</button>
<button onclick={() => count.set( $count / myvar)}>divide</button>
<button onclick={() => count.set( $count ** myvar)}>exponent</button>
<button onclick={() => count.set( $count % myvar)}>mod</button>
<button onclick={() => count.set( $count << myvar)}>leftshift</button>
<button onclick={() => count.set( $count >> myvar)}>rightshift</button>
<button onclick={() => count.set( $count >>> myvar)}>unsigned rightshift</button>
<button onclick={() => count.set( $count & myvar)}>AND</button>
<button onclick={() => count.set( $count ^ myvar)}>XOR</button>
<button onclick={() => count.set( $count | myvar)}>OR</button></>);
return { props: {}, slots: {}, getters: {}, events: {} }}
Example #9
Source File: broker.ts From musetree with MIT License | 6 votes |
async function requestInternal(config: Config, store: NodeStore, prevEncoding: MusenetEncoding, prevActiveNotesAtEnd: ProcessedActiveNotes, prevSectionStart: number, prevSectionEnd: number) {
const truncatedEncoding = prevEncoding.slice(-config.requestLength);
const data = {
...config,
encoding: encodingToString(truncatedEncoding),
audioFormat: "mp3"
};
type ResponseData = {
completions: Completion[]
};
store.updatePendingLoad(it => it + 4);
let response: Completion[] | null = null;
while (response === null) {
response = await axios({
method: "POST",
url: "https://musenet.openai.com/sample",
data
})
.then((res: AxiosResponse<ResponseData>) => res.data.completions)
.catch(() => []); // Temporary change to stop the retry logic see issue #88
}
const promises = response.map((completion: Completion) => parseCompletion(completion, truncatedEncoding, prevActiveNotesAtEnd, prevSectionStart, prevSectionEnd));
return Promise.all(promises)
.then((sections: Section[]) => sections.map((section: Section) => createSectionStore(section)))
.then((sectionStores: Writable<SectionState>[]) =>
sectionStores.map((sectionStore: Writable<SectionState>) => store.addChild(sectionStore)))
.finally(() => store.updatePendingLoad(it => it - 4));
}
Example #10
Source File: storage.ts From HyperChat with GNU Affero General Public License v3.0 | 5 votes |
refreshScroll = writable(false)
Example #11
Source File: store.ts From candy-machine-v2 with MIT License | 5 votes |
candyMachineState = writable<CandyMachineAccount>()
Example #12
Source File: global.ts From svelte-router with MIT License | 5 votes |
writableRoute = writable<Route>({
path: '',
params: {},
matched: [],
search: new URLSearchParams(),
hash: ''
})
Example #13
Source File: App.ts From ExpressiveAnimator with Apache License 2.0 | 5 votes |
IsFillSelected = writable<boolean>(true)
Example #14
Source File: stores.ts From obsidian-rss with GNU General Public License v3.0 | 5 votes |
configuredFeedsStore = writable<Array<RssFeed>>([])
Example #15
Source File: stores.ts From obsidian-calendar-plugin with MIT License | 5 votes |
settings = writable<ISettings>(defaultSettings)
Example #16
Source File: formReferences.ts From svelte-use-form with MIT License | 5 votes |
formReferences = writable<FormReference[]>([])
Example #17
Source File: audioPlayer.ts From musetree with MIT License | 5 votes |
audioStatusStoreInternal: Writable<AudioStatus> = writable({ type: "off" })
Example #18
Source File: tweened.ts From svelte-site-jp with MIT License | 5 votes |
export function tweened<T>(value?: T, defaults: Options<T> = {}): Tweened<T> {
const store = writable(value);
let task: Task;
let target_value = value;
function set(new_value: T, opts?: Options<T>) {
if (value == null) {
store.set(value = new_value);
return Promise.resolve();
}
target_value = new_value;
let previous_task = task;
let started = false;
let {
delay = 0,
duration = 400,
easing = linear,
interpolate = get_interpolator
} = assign(assign({}, defaults), opts);
if (duration === 0) {
if (previous_task) {
previous_task.abort();
previous_task = null;
}
store.set(value = target_value);
return Promise.resolve();
}
const start = now() + delay;
let fn;
task = loop(now => {
if (now < start) return true;
if (!started) {
fn = interpolate(value, new_value);
if (typeof duration === 'function') duration = duration(value, new_value);
started = true;
}
if (previous_task) {
previous_task.abort();
previous_task = null;
}
const elapsed = now - start;
if (elapsed > duration) {
store.set(value = new_value);
return false;
}
// @ts-ignore
store.set(value = fn(easing(elapsed / duration)));
return true;
});
return task.promise;
}
return {
set,
update: (fn, opts?: Options<T>) => set(fn(target_value, value), opts),
subscribe: store.subscribe
};
}
Example #19
Source File: expected.tsx From language-tools with MIT License | 5 votes |
function render() {
const foo = writable(1)/*Ωignore_startΩ*/;let $foo = __sveltets_1_store_get(foo);/*Ωignore_endΩ*/;
type Foo = typeof $foo;
;
() => (<></>);
return { props: {}, slots: {}, getters: {}, events: {} }}
Example #20
Source File: storage.ts From HyperChat with GNU Affero General Public License v3.0 | 5 votes |
reportDialog = writable(null as null | {
callback: (selection: ChatReportUserOptions) => void;
optionStore: Writable<null | ChatReportUserOptions>;
})