Skip to content
Draft

cell #21047

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
1 change: 1 addition & 0 deletions packages/@glimmer/validator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ if (Reflect.has(globalThis, GLIMMER_VALIDATOR_REGISTRATION)) {

Reflect.set(globalThis, GLIMMER_VALIDATOR_REGISTRATION, true);

export { cell } from './lib/cell';
export { trackedArray } from './lib/collections/array';
export { trackedMap } from './lib/collections/map';
export { trackedObject } from './lib/collections/object';
Expand Down
60 changes: 60 additions & 0 deletions packages/@glimmer/validator/lib/cell.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { UpdatableTag } from '@glimmer/interfaces';

import { consumeTag } from './tracking';
import { createUpdatableTag, DIRTY_TAG } from './validators';
import type { ReactiveOptions } from './collections/types';

class Cell<Value> {
#options: ReactiveOptions<Value>;
#value: Value;
readonly #tag: UpdatableTag;

constructor(value: Value, options: ReactiveOptions<Value>) {
this.#value = value;
this.#options = options;
this.#tag = createUpdatableTag();
}

get current() {
consumeTag(this.#tag);

return this.#value;
}

read(): Value {
consumeTag(this.#tag);

return this.#value;
}

set(value: Value): boolean {
if (this.#options.equals?.(this.#value, value)) {
return false;
}

this.#value = value;

DIRTY_TAG(this.#tag);

return true;
}

update(updater: (value: Value) => Value): void {
this.set(updater(this.#value));
}

freeze(): void {
throw new Error(`Not Implemented`);
}
}

export function cell<T>(
value: T,

options?: { equals?: (a: T, b: T) => boolean; description?: string }
) {
return new Cell(value, {
equals: options?.equals ?? Object.is,
description: options?.description,
});
}
28 changes: 28 additions & 0 deletions packages/@glimmer/validator/test/cell-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { cell } from '@glimmer/validator';

import { module, test } from './-utils';

module('cell', () => {
test('creates reactive storage', (assert) => {
const x = cell('hello');
assert.strictEqual(x.read(), 'hello');
});

test('updates when set', (assert) => {
const x = cell('hello');
x.set('world');
assert.strictEqual(x.read(), 'world');
});

test('updates when update() is called', (assert) => {
const x = cell('hello');
x.update((value) => value + ' world');
assert.strictEqual(x.read(), 'hello world');
});

test('is frozen when freeze() is called', (assert) => {
const x = cell('hello');
x.freeze();
assert.throws(() => x.set('world'));
});
});
Loading