| 32 | * @returns {Writable<T>} |
| 33 | */ |
| 34 | export function writable(value, start = noop) { |
| 35 | /** @type {Unsubscriber | null} */ |
| 36 | let stop = null; |
| 37 | |
| 38 | /** @type {Set<SubscribeInvalidateTuple<T>>} */ |
| 39 | const subscribers = new Set(); |
| 40 | |
| 41 | /** |
| 42 | * @param {T} new_value |
| 43 | * @returns {void} |
| 44 | */ |
| 45 | function set(new_value) { |
| 46 | if (safe_not_equal(value, new_value)) { |
| 47 | value = new_value; |
| 48 | if (stop) { |
| 49 | // store is ready |
| 50 | const run_queue = !subscriber_queue.length; |
| 51 | for (const subscriber of subscribers) { |
| 52 | subscriber[1](); |
| 53 | subscriber_queue.push(subscriber, value); |
| 54 | } |
| 55 | if (run_queue) { |
| 56 | for (let i = 0; i < subscriber_queue.length; i += 2) { |
| 57 | subscriber_queue[i][0](subscriber_queue[i + 1]); |
| 58 | } |
| 59 | subscriber_queue.length = 0; |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * @param {Updater<T>} fn |
| 67 | * @returns {void} |
| 68 | */ |
| 69 | function update(fn) { |
| 70 | set(fn(/** @type {T} */ (value))); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * @param {Subscriber<T>} run |
| 75 | * @param {() => void} [invalidate] |
| 76 | * @returns {Unsubscriber} |
| 77 | */ |
| 78 | function subscribe(run, invalidate = noop) { |
| 79 | /** @type {SubscribeInvalidateTuple<T>} */ |
| 80 | const subscriber = [run, invalidate]; |
| 81 | subscribers.add(subscriber); |
| 82 | if (subscribers.size === 1) { |
| 83 | stop = start(set, update) || noop; |
| 84 | } |
| 85 | run(/** @type {T} */ (value)); |
| 86 | return () => { |
| 87 | subscribers.delete(subscriber); |
| 88 | if (subscribers.size === 0 && stop) { |
| 89 | stop(); |
| 90 | stop = null; |
| 91 | } |