Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ import type { RawStoreWritable } from './internal/storeWritable';

const expectCorrectlyCleanedUp = <T>(store: StoreInput<T>) => {
const rawStore = (store as any)[rawStoreSymbol] as RawStoreWritable<T>;
expect(rawStore.consumerLinks.length).toBe(0);
expect(rawStore.consumerFirst).toBe(null);
expect(rawStore.consumerLast).toBe(null);
expect(rawStore.flags & RawStoreFlags.START_USE_CALLED).toBeFalsy();
};

Expand Down Expand Up @@ -2847,6 +2848,28 @@ describe('stores', () => {
a.next(4);
expect(values).toEqual([0, 6]);
});

it('should work to unsubscribe inside batch', () => {
const valuesA: number[] = [];
const valuesB: number[] = [];
const a = writable(0);
const b = computed(() => a() + 1);
const unsubscribeA = a.subscribe((v) => {
valuesA.push(v);
});
const unsubscribeB = b.subscribe((v) => {
valuesB.push(v);
});
expect(valuesA).toEqual([0]);
expect(valuesB).toEqual([1]);
batch(() => {
a.set(5);
unsubscribeB();
});
expect(valuesA).toEqual([0, 5]);
expect(valuesB).toEqual([1]);
unsubscribeA();
});
});

describe('Listeners and batch timing', () => {
Expand Down
10 changes: 7 additions & 3 deletions src/internal/batch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { createQueue } from './linkedQueue';
import type { SubscribeConsumer } from './subscribeConsumer';

export const subscribersQueue: SubscribeConsumer<any, any>[] = [];
let willProcessQueue = false;
const { add, remove, shift } = createQueue<SubscribeConsumer<any, any>>();

export { add as addToQueue, remove as removeFromQueue };

/**
* Batches multiple changes to stores while calling the provided function,
Expand Down Expand Up @@ -53,8 +56,8 @@ export const batch = <T>(fn: () => T): T => {
res = fn();
} finally {
if (needsProcessQueue) {
while (subscribersQueue.length > 0) {
const consumer = subscribersQueue.shift()!;
let consumer = shift();
while (consumer) {
try {
consumer.notify();
} catch (e) {
Expand All @@ -65,6 +68,7 @@ export const batch = <T>(fn: () => T): T => {
error = e;
}
}
consumer = shift();
}
willProcessQueue = false;
}
Expand Down
63 changes: 63 additions & 0 deletions src/internal/linkedQueue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
export interface QueueItem<T> {
next: T | null;
prev: T | null;
}

export const createQueue = <T extends QueueItem<T>>(): {
add: (item: T) => boolean;
remove: (item: T) => boolean;
shift: () => T | null;
} => {
let first: T | null = null;
let last: T | null = null;

const remove = (item: T): boolean => {
const { prev, next } = item;
if (prev || next || first === item) {
item.prev = null;
item.next = null;
if (prev) {
prev.next = next;
} else {
first = next;
}
if (next) {
next.prev = prev;
} else {
last = prev;
}
return true;
}
return false;
};

const add = (item: T): boolean => {
if (item === last) {
// already the last in the queue, nothing to do !
return false;
}
const existing = remove(item);
item.prev = last;
if (last) {
last.next = item;
} else {
first = item;
}
last = item;
return !existing;
};

const shift = (): T | null => {
const item = first;
if (item) {
remove(item);
}
return item;
};

return {
add,
remove,
shift,
};
};
1 change: 1 addition & 0 deletions src/internal/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export const enum RawStoreFlags {

export interface BaseLink<T> {
producer: RawStore<T, BaseLink<T>>;
nextInConsumer: BaseLink<any> | null;
skipMarkDirty?: boolean;
}

Expand Down
66 changes: 38 additions & 28 deletions src/internal/storeComputed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export class RawStoreComputed<T>
extends RawStoreComputedOrDerived<T>
implements Consumer, ActiveConsumer
{
private producerIndex = 0;
private producerLinks: BaseLink<any>[] = [];
private producerFirst: BaseLink<any> | null = null;
private producerLast: BaseLink<any> | null = null;
private epoch = -1;

constructor(private readonly computeFn: () => T) {
Expand Down Expand Up @@ -47,17 +47,21 @@ export class RawStoreComputed<T>
}

addProducer<U, L extends BaseLink<U>>(producer: RawStore<U, L>): U {
const producerLinks = this.producerLinks;
const producerIndex = this.producerIndex;
let link = producerLinks[producerIndex] as L | undefined;
if (link?.producer !== producer) {
if (link) {
producerLinks.push(link); // push the existing link at the end (to be removed later)
}
const nextLink = this.producerLast ? this.producerLast.nextInConsumer : this.producerFirst;
let link: L;
if (nextLink?.producer !== producer) {
// existing link cannot be reused
link = producer.registerConsumer(producer.newLink(this));
link.nextInConsumer = nextLink;
if (this.producerLast) {
this.producerLast.nextInConsumer = link;
} else {
this.producerFirst = link;
}
} else {
link = nextLink as L;
}
producerLinks[producerIndex] = link;
this.producerIndex = producerIndex + 1;
this.producerLast = link;
updateLinkProducerValue(link);
if (producer.flags & RawStoreFlags.HAS_VISIBLE_ONUSE) {
this.flags |= RawStoreFlags.HAS_VISIBLE_ONUSE;
Expand All @@ -66,34 +70,34 @@ export class RawStoreComputed<T>
}

override startUse(): void {
const producerLinks = this.producerLinks;
for (let i = 0, l = producerLinks.length; i < l; i++) {
const link = producerLinks[i];
let link = this.producerFirst;
while (link) {
link.producer.registerConsumer(link);
link = link.nextInConsumer;
}
this.flags |= RawStoreFlags.DIRTY;
}

override endUse(): void {
const producerLinks = this.producerLinks;
for (let i = 0, l = producerLinks.length; i < l; i++) {
const link = producerLinks[i];
let link = this.producerFirst;
while (link) {
link.producer.unregisterConsumer(link);
link = link.nextInConsumer;
}
}

override areProducersUpToDate(): boolean {
if (this.value === COMPUTED_UNSET) {
return false;
}
const producerLinks = this.producerLinks;
for (let i = 0, l = producerLinks.length; i < l; i++) {
const link = producerLinks[i];
let link = this.producerFirst;
while (link) {
const producer = link.producer;
updateLinkProducerValue(link);
if (!producer.isLinkUpToDate(link)) {
return false;
}
link = link.nextInConsumer;
}
return true;
}
Expand All @@ -102,7 +106,7 @@ export class RawStoreComputed<T>
let value: T;
const prevActiveConsumer = setActiveConsumer(this);
try {
this.producerIndex = 0;
this.producerLast = null;
this.flags &= ~RawStoreFlags.HAS_VISIBLE_ONUSE;
const computeFn = this.computeFn;
value = computeFn();
Expand All @@ -114,13 +118,19 @@ export class RawStoreComputed<T>
setActiveConsumer(prevActiveConsumer);
}
// Remove unused producers:
const producerLinks = this.producerLinks;
const producerIndex = this.producerIndex;
if (producerIndex < producerLinks.length) {
for (let i = 0, l = producerLinks.length - producerIndex; i < l; i++) {
const link = producerLinks.pop()!;
link.producer.unregisterConsumer(link);
}
let link: BaseLink<any> | null;
if (this.producerLast) {
link = this.producerLast.nextInConsumer;
this.producerLast.nextInConsumer = null;
} else {
link = this.producerFirst;
this.producerFirst = null;
}
while (link) {
const next = link.nextInConsumer;
link.producer.unregisterConsumer(link);
link.nextInConsumer = null;
link = next;
}
this.set(value);
}
Expand Down
1 change: 1 addition & 0 deletions src/internal/storeConst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export class RawStoreConst<T> implements RawStore<T, BaseLink<T>> {
newLink(_consumer: Consumer): BaseLink<T> {
return {
producer: this,
nextInConsumer: null,
};
}
registerConsumer(link: BaseLink<T>): BaseLink<T> {
Expand Down
39 changes: 24 additions & 15 deletions src/internal/storeTrackingUsage.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { createQueue, type QueueItem } from './linkedQueue';
import { RawStoreFlags } from './store';
import { checkNotInNotificationPhase, RawStoreWritable } from './storeWritable';
import { activeConsumer, untrack } from './untrack';

let flushUnusedQueue: RawStoreTrackingUsage<any>[] | null = null;
const { shift, add, remove } = createQueue<RawStoreTrackingUsage<any>>();
let inFlushUnused = false;
let plannedFlushUnused = false;

export const flushUnused = (): void => {
// Ignoring coverage for the following lines because, unless there is a bug in tansu (which would have to be fixed!)
Expand All @@ -12,24 +14,27 @@ export const flushUnused = (): void => {
if (inFlushUnused) {
throw new Error('assert failed: recursive flushUnused call');
}
plannedFlushUnused = false;
inFlushUnused = true;
try {
const queue = flushUnusedQueue;
if (queue) {
flushUnusedQueue = null;
for (let i = 0, l = queue.length; i < l; i++) {
const producer = queue[i];
producer.flags &= ~RawStoreFlags.FLUSH_PLANNED;
producer.checkUnused();
}
let producer = shift();
while (producer) {
producer.flags &= ~RawStoreFlags.FLUSH_PLANNED;
producer.checkUnused();
producer = shift();
}
} finally {
inFlushUnused = false;
}
};

export abstract class RawStoreTrackingUsage<T> extends RawStoreWritable<T> {
export abstract class RawStoreTrackingUsage<T>
extends RawStoreWritable<T>
implements QueueItem<RawStoreTrackingUsage<any>>
{
private extraUsages = 0;
next: RawStoreTrackingUsage<any> | null = null;
prev: RawStoreTrackingUsage<any> | null = null;
abstract startUse(): void;
abstract endUse(): void;

Expand All @@ -39,27 +44,31 @@ export abstract class RawStoreTrackingUsage<T> extends RawStoreWritable<T> {
// Ignoring coverage for the following lines because, unless there is a bug in tansu (which would have to be fixed!)
// there should be no way to trigger this error.
/* v8 ignore next 3 */
if (!this.extraUsages && !this.consumerLinks.length) {
if (!this.extraUsages && !this.consumerFirst) {
throw new Error('assert failed: untracked producer usage');
}
if (flags & RawStoreFlags.FLUSH_PLANNED) {
remove(this);
this.flags &= ~RawStoreFlags.FLUSH_PLANNED;
}
this.flags |= RawStoreFlags.START_USE_CALLED;
untrack(() => this.startUse());
}
}

override checkUnused(): void {
const flags = this.flags;
if (flags & RawStoreFlags.START_USE_CALLED && !this.extraUsages && !this.consumerLinks.length) {
if (flags & RawStoreFlags.START_USE_CALLED && !this.extraUsages && !this.consumerFirst) {
if (inFlushUnused || flags & RawStoreFlags.HAS_VISIBLE_ONUSE) {
this.flags &= ~RawStoreFlags.START_USE_CALLED;
untrack(() => this.endUse());
} else if (!(flags & RawStoreFlags.FLUSH_PLANNED)) {
this.flags |= RawStoreFlags.FLUSH_PLANNED;
if (!flushUnusedQueue) {
flushUnusedQueue = [];
if (!plannedFlushUnused) {
plannedFlushUnused = true;
queueMicrotask(flushUnused);
}
flushUnusedQueue.push(this);
add(this);
}
}
}
Expand Down
Loading
Loading