working communication with backend, signals and frontend

main
Laurin Weger 2 weeks ago
parent bc17629a67
commit 760bfb79cb
No known key found for this signature in database
GPG Key ID: 9B372BB0B792770F
  1. 27
      src/frontends/react/HelloWorld.tsx
  2. 15
      src/frontends/svelte/HelloWorld.svelte
  3. 31
      src/frontends/vue/HelloWorld.vue
  4. 7
      src/ng-mock/js-land/connector/applyDiff.ts
  5. 77
      src/ng-mock/js-land/connector/ngSignals.ts
  6. 19
      src/ng-mock/js-land/frontendAdapters/react/useShape.ts
  7. 13
      src/ng-mock/js-land/frontendAdapters/svelte/useShape.ts
  8. 13
      src/ng-mock/js-land/frontendAdapters/vue/useShape.ts
  9. 45
      src/ng-mock/js-land/signalLibs/alienSignals.ts
  10. 0
      src/ng-mock/tests/subscriptionToStore.test.ts
  11. 25
      src/ng-mock/tests/updatesWithWasm.test.ts
  12. 11
      src/ng-mock/wasm-land/requestShape.ts
  13. 4
      src/ng-mock/wasm-land/updateShape.ts

@ -1,22 +1,25 @@
import React from "react"; import React from "react";
import { useSignal } from "@gn8/alien-signals-react"; import useShape from "../../ng-mock/js-land/frontendAdapters/react/useShape";
import {
deepSignalExample,
computedSignalFromExample,
} from "src/ng-mock/js-land/signalLibs/alienSignals";
export function HelloWorldReact() { export function HelloWorldReact() {
const [state] = useSignal(deepSignalExample); const state = useShape("Shape2", "");
const [computed] = useSignal(computedSignalFromExample);
window.reactState = state;
console.log("react render", state);
if (!state) return <>Loading state</>;
return ( return (
<div> <div>
<p>Hello World from React!</p> <p>Hello World from React!</p>
<p>Here is a reactive object with {computed.get()} props.</p> {state.name} lives at {state.address.street}
<pre>{JSON.stringify(state, null, 4)}</pre> <p></p>
<button onClick={() => state.array.push(state.array.at(-1) + 1)}> <button
Click to add val onClick={() => {
state.name = `${state.name} ${state.name}`;
}}
>
Double name
</button> </button>
</div> </div>
); );

@ -1,24 +1,19 @@
<script> <script>
import { useSignal } from "@gn8/alien-signals-svelte"; import useShape from "../../ng-mock/js-land/frontendAdapters/svelte/useShape";
import {
deepSignalExample,
computedSignalFromExample,
} from "src/ng-mock/js-land/signalLibs/alienSignals";
const nestedObject = useSignal(deepSignalExample); const nestedObject = useShape("Shape1", null);
const computed = useSignal(computedSignalFromExample);
</script> </script>
<div> <div>
<p>Hello World from Svelte!</p> <p>Hello World from Svelte!</p>
<p>Here is a reactive object with {$computed.get()} props.</p>
<pre>{JSON.stringify($nestedObject, null, 4)}</pre> <pre>{JSON.stringify($nestedObject, null, 4)}</pre>
<button <button
on:click={() => { on:click={() => {
$nestedObject.array.splice(0, 1); window.svelteState = $nestedObject;
$nestedObject.name = $nestedObject.name.toUpperCase();
}} }}
> >
Click to remove first array element upper-case name
</button> </button>
</div> </div>

@ -1,22 +1,29 @@
<script setup lang="ts"> <script setup lang="ts">
import {useSignal} from '@gn8/alien-signals-vue'; import type { WritableComputedRef } from 'vue';
import { import useShape from '../../ng-mock/js-land/frontendAdapters/vue/useShape';
deepSignalExample,
computedSignalFromExample,
} from "src/ng-mock/js-land/signalLibs/alienSignals";
const state = useSignal(deepSignalExample); const shapeObj = useShape("Shape1", "null");
const computed = useSignal(computedSignalFromExample);
window.vueState= shapeObj;
const setName = () => {
shapeObj.value.name = "Bobby"
}
</script> </script>
<template> <template>
<div> <div>
<p>Hello World from Vue!</p> <p>Hello World from Vue!</p>
<p>Here is a reactive object with {{computed.get()}} props.</p> <div v-if="shapeObj != null">
<pre>{{JSON.stringify(state, null, 4)}}</pre> <p>Type is <em>{{shapeObj.type}}</em> with street <em>{{shapeObj.address.street}}</em></p>
<button @click="state.array.push(state.array.at(-1) + 1)">
Click to add val <button @click="setName">
</button> Click to switch name
</button>
</div>
<div v-else>
Loading state
</div>
</div> </div>
</template> </template>

@ -1,6 +1,9 @@
import type { Diff } from "../types"; import type { Diff } from "../types";
/** Mock function to apply diffs. Just uses a copy of the diff as the new object. */ /** Mock function to apply diffs. Just uses a copy of the diff as the new object. */
export function applyDiff(currentState: object, diff: Diff): object { export function applyDiff(currentState: any, diff: Diff) {
return JSON.parse(JSON.stringify(diff)); const clone = JSON.parse(JSON.stringify(diff));
Object.keys(clone).forEach((k) => {
currentState[k] = clone[k];
});
} }

@ -1,31 +1,70 @@
import handleShapeUpdate from "src/ng-mock/wasm-land/handleShapeUpdate"; import updateShape from "src/ng-mock/wasm-land/updateShape";
import type { Connection, Diff, Scope, Shape } from "../types"; import type { Connection, Diff, Scope, Shape } from "../types";
import handleShapeRequest from "src/ng-mock/wasm-land/handleShapeRequest"; import requestShape from "src/ng-mock/wasm-land/requestShape";
import { applyDiff } from "./applyDiff"; import { applyDiff } from "./applyDiff";
import { batch, deepSignal, watch } from "alien-deepsignals";
import { signal } from "alien-signals";
export async function createSignalObjectForShape(shape: Shape, scope?: Scope) { // TODO: The code is horrible.
const ret: { export function createSignalObjectForShape(shape: Shape, scope?: Scope) {
state?: any; // TODO:
connectionId?: Connection["id"]; // DeepSignal has a different API to alien-signals.
update: (diff: Diff) => Promise<void>; // Therefore, we need to create a "root signal" wrapper that is
} = { // triggered on deepSignal changes.
async update(diff) { const rootSignal = signal<null | object>(null);
if (!ret.connectionId)
throw new Error("Connection not established yet for shape" + shape); // State
await handleShapeUpdate(ret.connectionId, diff); let stopWatcher: any = null;
}, let suspendWatcher = false;
// To update the root signal
const setUpDeepSignal = (
newSignal: ReturnType<typeof deepSignal>,
connectionId: Connection["id"]
) => {
stopWatcher?.();
// Notify DB on changes.
stopWatcher = watch(
newSignal,
(newVal, oldVal, onCleanup) => {
if (!suspendWatcher) updateShape(connectionId, newVal);
},
{ deep: true }
);
// Update the root signal.
rootSignal(newSignal);
}; };
const onDbUpdate = (diff: Diff) => { const onUpdateFromDb = (diff: Diff, connectionId: Connection["id"]) => {
ret.state = applyDiff(ret.state || {}, diff); const nestedObj = rootSignal();
console.log("Update received", connectionId, diff);
// Set new value from applying the diffs to the old value.
// suspendWatcher = true;
// We need to replace the root signal for now, so this is redundant.
// batch(() => {
// if (!nestedObj) return; // This shouldn't happen but we make the compiler happy.
// applyDiff(nestedObj, diff);
// });
// suspendWatcher = false;nestedObj
// Create a new deep signal.
// We need to do that because the deepSignals ref hasn't changed otherwise
// and no update is triggered.
const newDeepSignal = deepSignal(JSON.parse(JSON.stringify(diff)));
setUpDeepSignal(newDeepSignal, connectionId);
}; };
await handleShapeRequest(shape, onDbUpdate).then( // Do the actual db request.
requestShape(shape, scope, onUpdateFromDb).then(
({ connectionId, shapeObject }) => { ({ connectionId, shapeObject }) => {
ret.state = shapeObject; // Create a deepSignal to put into the vanilla alien-signal.
ret.connectionId = connectionId; const deepSignalFromDb = deepSignal(shapeObject);
setUpDeepSignal(deepSignalFromDb, connectionId);
} }
); );
return ret; return rootSignal;
} }

@ -0,0 +1,19 @@
import { useSignal } from "@gn8/alien-signals-react";
import { useMemo } from "react";
import { createSignalObjectForShape } from "src/ng-mock/js-land/connector/ngSignals";
import type { Scope, Shape } from "src/ng-mock/js-land/types";
const useShape = (shape: Shape, scope: Scope) => {
const signalOfShape = useMemo(() => {
console.log("react memo called...");
return createSignalObjectForShape(shape, scope);
}, [shape, scope]);
const [shapeObject, setShapeObject] = useSignal(signalOfShape);
// We don't need the setter.
// The object is recursively proxied and changes are recorded there.
return shapeObject;
};
export default useShape;

@ -0,0 +1,13 @@
import { useSignal } from "@gn8/alien-signals-svelte";
import { createSignalObjectForShape } from "src/ng-mock/js-land/connector/ngSignals";
import type { Scope, Shape } from "src/ng-mock/js-land/types";
const useShape = (shape: Shape, scope: Scope) => {
const signalOfShape = createSignalObjectForShape(shape, scope);
const writeableStoreForShape = useSignal(signalOfShape);
return writeableStoreForShape;
};
export default useShape;

@ -0,0 +1,13 @@
import { useSignal } from "@gn8/alien-signals-vue";
import { createSignalObjectForShape } from "src/ng-mock/js-land/connector/ngSignals";
import type { Scope, Shape } from "src/ng-mock/js-land/types";
const useShape = (shape: Shape, scope: Scope) => {
const signalOfShape = createSignalObjectForShape(shape, scope);
const refOfShape = useSignal(signalOfShape);
return refOfShape;
};
export default useShape;

@ -1,45 +0,0 @@
import { deepSignal, watch, computed } from "alien-deepsignals";
import { signal } from "alien-signals";
const deepSignalExample = deepSignal({
count: 0,
name: "John",
nested: {
deep: "value",
},
array: [1, 2, 3],
set: new Set(["el1"]),
});
const computedSignalFromExample = computed(() => {
return Object.keys(deepSignalExample).length;
});
/** Create a vanilla alien-signals Signal so that it can be normally used by universe-alien-signals. */
const wrapDeepIntoAlienSignal = <T extends object>(
nestedSignal: ReturnType<typeof deepSignal<T>>
) => {
const alienSignal = signal(nestedSignal);
// Watch deep signal and notify vanilla alien-signal on changes.
watch(
nestedSignal,
(value) => {
// We need to destructure because the object otherwise remained the same.
alienSignal({ ...nestedSignal });
},
{ deep: true }
);
return alienSignal;
};
const wrappedDeepSignalState = wrapDeepIntoAlienSignal(deepSignalExample);
const wrappedComputedPropertiesOfObj = wrapDeepIntoAlienSignal(
computedSignalFromExample
);
export {
wrappedDeepSignalState as deepSignalExample,
wrappedComputedPropertiesOfObj as computedSignalFromExample,
};

@ -1,23 +1,30 @@
import { expect, test } from "vitest"; import { expect, test } from "vitest";
import { createSignalObjectForShape } from "../js-land/connector/ngSignals"; import { createSignalObjectForShape } from "../js-land/connector/ngSignals";
const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// TODO: Redo
test("shape object notification comes back to others", async () => { test("shape object notification comes back to others", async () => {
const object1 = await createSignalObjectForShape("Shape1"); const object1 = createSignalObjectForShape("Shape1");
const object2 = await createSignalObjectForShape("Shape1"); const object2 = createSignalObjectForShape("Shape1");
const object3 = createSignalObjectForShape("Shape2");
const object4 = createSignalObjectForShape("Shape2");
const object3 = await createSignalObjectForShape("Shape2"); wait(50);
const object4 = await createSignalObjectForShape("Shape2");
// Update object 1 and expect object 2 to update as well. // Update object 1 and expect object 2 to update as well.
await object1.update({ name: "Updated name from object1" }); object1()!.name = "Updated name from object1";
expect(object2.state?.name).toBe("Updated name from object1"); wait(30);
expect(object2()!.name).toBe("Updated name from object1");
// Expect object of different shape not to have changed. // Expect object of different shape not to have changed.
expect(object3.state?.name).toBe("Niko's cat"); expect(object3().name).toBe("Niko's cat");
// Update object 4 and expect object 3 with same shape to have updated. // Update object 4 and expect object 3 with same shape to have updated.
await object4.update({ name: "Updated name from object4" }); object4()!.name = "Updated name from object4";
expect(object3.state?.name).toBe("Updated name from object4"); wait(30);
expect(object3()!.name).toBe("Updated name from object4");
}); });

@ -1,6 +1,5 @@
import { randomUUID } from "crypto";
import * as shapeManager from "./shapeManager"; import * as shapeManager from "./shapeManager";
import type { WasmConnection, Diff } from "./types"; import type { WasmConnection, Diff, Scope } from "./types";
import type { Shape } from "../js-land/types"; import type { Shape } from "../js-land/types";
const mockShapeObject1 = { const mockShapeObject1 = {
@ -20,19 +19,21 @@ const mockShapeObject2 = {
numberOfHomes: 3, numberOfHomes: 3,
address: { address: {
street: "Niko's street", street: "Niko's street",
compartment: 2, houseNumber: "15",
floor: 0,
}, },
}; };
export default async function handleShapeRequest( export default async function requestShape(
shape: Shape, shape: Shape,
scope: Scope | undefined,
callback: (diff: Diff, connectionId: WasmConnection["id"]) => void callback: (diff: Diff, connectionId: WasmConnection["id"]) => void
): Promise<{ ): Promise<{
connectionId: string; connectionId: string;
shapeObject: object; shapeObject: object;
}> { }> {
const connection: WasmConnection = { const connection: WasmConnection = {
id: randomUUID(), id: Math.random().toFixed(4),
shape, shape,
// Create a deep copy to prevent accidental by-reference changes. // Create a deep copy to prevent accidental by-reference changes.
state: JSON.parse( state: JSON.parse(

@ -1,13 +1,15 @@
import * as shapeManager from "./shapeManager"; import * as shapeManager from "./shapeManager";
import type { WasmConnection, Diff } from "./types"; import type { WasmConnection, Diff } from "./types";
export default async function handleShapeUpdate( export default async function updateShape(
connectionId: WasmConnection["id"], connectionId: WasmConnection["id"],
diff: Diff diff: Diff
) { ) {
const connection = shapeManager.connections.get(connectionId); const connection = shapeManager.connections.get(connectionId);
if (!connection) throw new Error("No Connection found."); if (!connection) throw new Error("No Connection found.");
console.log("BACKEND: Received update request from ", connectionId);
const newState = shapeManager.applyDiff(connection.state, diff); const newState = shapeManager.applyDiff(connection.state, diff);
connection.state = newState; connection.state = newState;
Loading…
Cancel
Save