Skip to content

Commit

Permalink
feat(vdom): add universal syncable value PROPERTY()
Browse files Browse the repository at this point in the history
Universal syncable value for assigning properties instead of attributes.
  • Loading branch information
localvoid committed Jun 13, 2018
1 parent 9f1de27 commit 111c309
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
34 changes: 34 additions & 0 deletions packages/ivi-core/src/__tests__/syncable_value.spec.ts
@@ -0,0 +1,34 @@
import { PROPERTY, SYNCABLE_VALUE_SKIP_UNDEFINED } from "../syncable_value";

describe(`PROPERTY()`, () => {
test(`undefined should return SYNCABLE_VALUE_SKIP_UNDEFINED`, () => {
expect(PROPERTY(undefined)).toBe(SYNCABLE_VALUE_SKIP_UNDEFINED);
});

test(`value`, () => {
expect(PROPERTY(1).v).toBe(1);
});

test(`assign custom property`, () => {
const e = document.createElement("div");
const p = PROPERTY(1);
p.s(e, "_custom", void 0, 1);
expect((e as any)._custom).toBe(1);
});

test(`update custom property`, () => {
const e = document.createElement("div");
const p = PROPERTY(1);
p.s(e, "_custom", void 0, 1);
p.s(e, "_custom", void 0, 2);
expect((e as any)._custom).toBe(2);
});

test(`update custom property with the same value`, () => {
const e = document.createElement("div");
const p = PROPERTY(1);
p.s(e, "_custom", void 0, 1);
p.s(e, "_custom", void 0, 1);
expect((e as any)._custom).toBe(1);
});
});
1 change: 1 addition & 0 deletions packages/ivi-core/src/index.ts
Expand Up @@ -30,6 +30,7 @@ export {
export {
SyncableValue,
SYNCABLE_VALUE_SKIP_UNDEFINED, SYNCABLE_VALUE_REMOVE_ATTR_UNDEFINED,
PROPERTY,
} from "./syncable_value";

export { SVG_NAMESPACE, XLINK_NAMESPACE, XML_NAMESPACE, KeyCode, KeyLocation, KeyName, MouseButtons } from "./const";
Expand Down
10 changes: 10 additions & 0 deletions packages/ivi-core/src/syncable_value.ts
Expand Up @@ -19,3 +19,13 @@ export const SYNCABLE_VALUE_REMOVE_ATTR_UNDEFINED = {
}
},
};

export function PROPERTY<T>(v: T | undefined): SyncableValue<T> {
return (v === void 0) ? SYNCABLE_VALUE_SKIP_UNDEFINED : { v, s: syncProperty };
}

function syncProperty(element: Element, key: string, prev: any, next: any) {
if (prev !== next) {
(element as any)[key] = next!;
}
}
2 changes: 1 addition & 1 deletion packages/ivi/src/index.ts
@@ -1,7 +1,7 @@
/**
* Common types and functions re-exported from ivi-core.
*/
export { KeyCode, KeyLocation, MouseButtons, SyncableValue, _ } from "ivi-core";
export { KeyCode, KeyLocation, MouseButtons, SyncableValue, PROPERTY, _ } from "ivi-core";

// Virtual DOM
export { VNodeFlags } from "./vdom/flags";
Expand Down

0 comments on commit 111c309

Please sign in to comment.