77 lines
2.5 KiB
JavaScript
77 lines
2.5 KiB
JavaScript
import { Gt as queue_micro_task, a as get, f as untrack, ft as source, j as render_effect, ln as tag, st as increment, w as effect_tracking } from "./runtime-BOFXI46e.js";
|
|
import "./esm-env-D8Yi5ac9.js";
|
|
// node_modules/svelte/src/reactivity/create-subscriber.js
|
|
/**
|
|
* Returns a `subscribe` function that integrates external event-based systems with Svelte's reactivity.
|
|
* It's particularly useful for integrating with web APIs like `MediaQuery`, `IntersectionObserver`, or `WebSocket`.
|
|
*
|
|
* If `subscribe` is called inside an effect (including indirectly, for example inside a getter),
|
|
* the `start` callback will be called with an `update` function. Whenever `update` is called, the effect re-runs.
|
|
*
|
|
* If `start` returns a cleanup function, it will be called when the effect is destroyed.
|
|
*
|
|
* If `subscribe` is called in multiple effects, `start` will only be called once as long as the effects
|
|
* are active, and the returned teardown function will only be called when all effects are destroyed.
|
|
*
|
|
* It's best understood with an example. Here's an implementation of [`MediaQuery`](https://svelte.dev/docs/svelte/svelte-reactivity#MediaQuery):
|
|
*
|
|
* ```js
|
|
* import { createSubscriber } from 'svelte/reactivity';
|
|
* import { on } from 'svelte/events';
|
|
*
|
|
* export class MediaQuery {
|
|
* #query;
|
|
* #subscribe;
|
|
*
|
|
* constructor(query) {
|
|
* this.#query = window.matchMedia(`(${query})`);
|
|
*
|
|
* this.#subscribe = createSubscriber((update) => {
|
|
* // when the `change` event occurs, re-run any effects that read `this.current`
|
|
* const off = on(this.#query, 'change', update);
|
|
*
|
|
* // stop listening when all the effects are destroyed
|
|
* return () => off();
|
|
* });
|
|
* }
|
|
*
|
|
* get current() {
|
|
* // This makes the getter reactive, if read in an effect
|
|
* this.#subscribe();
|
|
*
|
|
* // Return the current state of the query, whether or not we're in an effect
|
|
* return this.#query.matches;
|
|
* }
|
|
* }
|
|
* ```
|
|
* @param {(update: () => void) => (() => void) | void} start
|
|
* @since 5.7.0
|
|
*/
|
|
function createSubscriber(start) {
|
|
let subscribers = 0;
|
|
let version = source(0);
|
|
/** @type {(() => void) | void} */
|
|
let stop;
|
|
tag(version, "createSubscriber version");
|
|
return () => {
|
|
if (effect_tracking()) {
|
|
get(version);
|
|
render_effect(() => {
|
|
if (subscribers === 0) stop = untrack(() => start(() => increment(version)));
|
|
subscribers += 1;
|
|
return () => {
|
|
queue_micro_task(() => {
|
|
subscribers -= 1;
|
|
if (subscribers === 0) {
|
|
stop?.();
|
|
stop = void 0;
|
|
increment(version);
|
|
}
|
|
});
|
|
};
|
|
});
|
|
}
|
|
};
|
|
}
|
|
export { createSubscriber as t };
|