The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Share the remote element command queue (#28332)
Raphaël Bosic2ce81b792e5
diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/createInputSelectionCommandQueue.test.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/createInputSelectionCommandQueue.test.tsdeleted file mode 100644index 15345b00783..00000000000--- a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/__tests__/createInputSelectionCommandQueue.test.ts+++ /dev/null@@ -1,67 +0,0 @@-import { updateRemoteElementProperty } from '@remote-dom/core/elements';--import { createInputSelectionCommandQueue } from '../createInputSelectionCommandQueue';--jest.mock('@remote-dom/core/elements', () => ({- updateRemoteElementProperty: jest.fn(),-}));--const updateRemoteElementPropertyMock = jest.mocked(- updateRemoteElementProperty,-);--describe('createInputSelectionCommandQueue', () => {- beforeEach(() => {- updateRemoteElementPropertyMock.mockClear();- });-- it('should number commands in request order across elements', () => {- const commandQueue = createInputSelectionCommandQueue();- const firstElement = {};- const secondElement = {};-- commandQueue.enqueueCommand({- element: firstElement,- request: { method: 'select' },- });- commandQueue.enqueueCommand({- element: secondElement,- request: { method: 'select' },- });- commandQueue.enqueueCommand({- element: firstElement,- request: { property: 'selectionEnd', value: 2 },- });-- expect(commandQueue.readPendingCommands(firstElement)).toEqual([- { sequence: 1, request: { method: 'select' } },- { sequence: 3, request: { property: 'selectionEnd', value: 2 } },- ]);- expect(commandQueue.readPendingCommands(secondElement)).toEqual([- { sequence: 2, request: { method: 'select' } },- ]);- });-- it('should not resend the queue when the host acknowledges no new command', () => {- const commandQueue = createInputSelectionCommandQueue();- const element = {};-- commandQueue.enqueueCommand({ element, request: { method: 'select' } });- updateRemoteElementPropertyMock.mockClear();- commandQueue.acknowledgeCommands({- element,- acknowledgedCommandSequence: 0,- });-- expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();- expect(commandQueue.readPendingCommands(element)).toHaveLength(1);- });-- it('should send nothing when discarding an element without pending commands', () => {- const commandQueue = createInputSelectionCommandQueue();-- commandQueue.discardPendingCommands({});-- expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();- });-});diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.ts b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.tsindex 8592d436320..d2c166347b9 100644--- a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createWorkerInputSelectionStore.ts@@ -1,100 +1,54 @@-import { updateRemoteElementProperty } from '@remote-dom/core/elements';-import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';import { isElementUnderRemoteRoot } from '@/polyfills/geometry/utils/isElementUnderRemoteRoot';import { type WorkerInputSelectionStore } from '@/polyfills/input-selection/types/WorkerInputSelectionStore';-import { createInputSelectionCommandQueue } from '@/polyfills/input-selection/utils/createInputSelectionCommandQueue';import { resolveOptimisticInputSelectionState } from '@/polyfills/input-selection/utils/resolveOptimisticInputSelectionState';+import { createRemoteElementCommandQueue } from '@/polyfills/utils/createRemoteElementCommandQueue';+import { createRemoteElementHostSubscriptions } from '@/polyfills/utils/createRemoteElementHostSubscriptions';+import { acknowledgedNativeEditSequenceByRemoteElement } from '@/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement';import { type InputSelectionRequest } from '@/types/InputSelectionRequest';import { type InputSelectionSnapshot } from '@/types/InputSelectionSnapshot';import { type InputSelectionState } from '@/types/InputSelectionState';export const createWorkerInputSelectionStore =(): WorkerInputSelectionStore => {- const commandQueue = createInputSelectionCommandQueue();+ const commandQueue = createRemoteElementCommandQueue<InputSelectionRequest>(+ {+ bridgeProperty: INPUT_SELECTION_BRIDGE_PROPERTIES.request,+ readAcknowledgedNativeEditSequence: (element) =>+ acknowledgedNativeEditSequenceByRemoteElement.get(element),+ },+ );const hostSelectionStates = new WeakMap<object, InputSelectionState>();- const hostSelectionSubscriptions = new WeakMap<- object,- (snapshot: InputSelectionSnapshot) => void- >();- const trackedElements = new Set<object>();-let rootElement: object | null = null;- let hasScheduledDetachedElementSweep = false;-- const renewHostSelectionSubscription = (element: object): void => {- const handleSelectionUpdate = (snapshot: InputSelectionSnapshot) => {- const isLatestSubscription =- hostSelectionSubscriptions.get(element) === handleSelectionUpdate;-- if (- !isLatestSubscription ||- !isElementUnderRemoteRoot(element, rootElement)- ) {- return;- }-- hostSelectionStates.set(element, snapshot);- trackedElements.add(element);- commandQueue.acknowledgeCommands({- element,- acknowledgedCommandSequence: snapshot.selectionCommandSequence ?? 0,- });- };- hostSelectionSubscriptions.set(element, handleSelectionUpdate);- updateRemoteElementProperty(- element as Element,- INPUT_SELECTION_BRIDGE_PROPERTIES.update,- handleSelectionUpdate,- );- };+ const hostSelectionSubscriptions =+ createRemoteElementHostSubscriptions<InputSelectionSnapshot>({+ updateBridgeProperty: INPUT_SELECTION_BRIDGE_PROPERTIES.update,+ readRootElement: () => rootElement,+ onHostUpdate: ({ element, hostUpdate: snapshot }) => {+ hostSelectionStates.set(element, snapshot);+ hostSelectionSubscriptions.trackElement(element);+ commandQueue.acknowledgeCommands({+ element,+ acknowledgedCommandSequence: snapshot.selectionCommandSequence ?? 0,+ });+ },+ onForgetElement: (element) => {+ hostSelectionStates.delete(element);+ commandQueue.discardPendingCommands(element);+ },+ });const subscribeToHostSelection = (element: object): boolean => {if (!isElementUnderRemoteRoot(element, rootElement)) {return false;}- trackedElements.add(element);-- if (!hostSelectionSubscriptions.has(element)) {- renewHostSelectionSubscription(element);- }+ hostSelectionSubscriptions.subscribe(element);return true;};- const forgetDetachedElement = (element: object): void => {- trackedElements.delete(element);- hostSelectionStates.delete(element);- commandQueue.discardPendingCommands(element);-- if (hostSelectionSubscriptions.has(element)) {- renewHostSelectionSubscription(element);- }- };-- const sweepDetachedElements = (): void => {- hasScheduledDetachedElementSweep = false;-- for (const element of trackedElements) {- if (isElementUnderRemoteRoot(element, rootElement)) {- continue;- }-- forgetDetachedElement(element);- }- };-- const scheduleDetachedElementSweep = (): void => {- if (hasScheduledDetachedElementSweep || trackedElements.size === 0) {- return;- }-- hasScheduledDetachedElementSweep = true;- queueMicrotask(sweepDetachedElements);- };-const applySnapshot = ({element,state,@@ -105,7 +59,7 @@ export const createWorkerInputSelectionStore =hostSelectionStates.set(element, state);if (isElementUnderRemoteRoot(element, rootElement)) {- trackedElements.add(element);+ hostSelectionSubscriptions.trackElement(element);}};@@ -138,7 +92,8 @@ export const createWorkerInputSelectionStore =rootElement = nextRootElement;},applySnapshot,- scheduleDetachedElementSweep,+ scheduleDetachedElementSweep:+ hostSelectionSubscriptions.scheduleDetachedElementSweep,read: readSelection,request: requestSelection,};diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/__tests__/createRemoteElementCommandQueue.test.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/__tests__/createRemoteElementCommandQueue.test.tsnew file mode 100644index 00000000000..896440ff2ce--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/__tests__/createRemoteElementCommandQueue.test.ts@@ -0,0 +1,133 @@+import { updateRemoteElementProperty } from '@remote-dom/core/elements';++import { NODE_TYPE_BY_NAME } from '@/polyfills/dom/constants/NodeTypeByName';+import { createRemoteElementCommandQueue } from '@/polyfills/utils/createRemoteElementCommandQueue';+import { type InputSelectionRequest } from '@/types/InputSelectionRequest';++jest.mock('@remote-dom/core/elements', () => ({+ updateRemoteElementProperty: jest.fn(),+}));++const updateRemoteElementPropertyMock = jest.mocked(+ updateRemoteElementProperty,+);++const createElementStub = () => ({ nodeType: NODE_TYPE_BY_NAME.ELEMENT });++describe('createRemoteElementCommandQueue', () => {+ beforeEach(() => {+ updateRemoteElementPropertyMock.mockClear();+ });++ it('should number commands in request order across elements', () => {+ const commandQueue = createRemoteElementCommandQueue<InputSelectionRequest>(+ {+ bridgeProperty: 'request',+ },+ );+ const firstElement = createElementStub();+ const secondElement = createElementStub();++ commandQueue.enqueueCommand({+ element: firstElement,+ request: { method: 'select' },+ });+ commandQueue.enqueueCommand({+ element: secondElement,+ request: { method: 'select' },+ });+ commandQueue.enqueueCommand({+ element: firstElement,+ request: { property: 'selectionEnd', value: 2 },+ });++ expect(commandQueue.readPendingCommands(firstElement)).toEqual([+ { sequence: 1, request: { method: 'select' } },+ { sequence: 3, request: { property: 'selectionEnd', value: 2 } },+ ]);+ expect(commandQueue.readPendingCommands(secondElement)).toEqual([+ { sequence: 2, request: { method: 'select' } },+ ]);+ });++ it('should not resend the queue when the host acknowledges no new command', () => {+ const commandQueue = createRemoteElementCommandQueue<InputSelectionRequest>(+ {+ bridgeProperty: 'request',+ },+ );+ const element = createElementStub();++ commandQueue.enqueueCommand({ element, request: { method: 'select' } });+ updateRemoteElementPropertyMock.mockClear();+ commandQueue.acknowledgeCommands({+ element,+ acknowledgedCommandSequence: 0,+ });++ expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();+ expect(commandQueue.readPendingCommands(element)).toHaveLength(1);+ });++ it('should keep and send only the latest commands when the pending limit is reached', () => {+ const commandQueue = createRemoteElementCommandQueue<InputSelectionRequest>(+ {+ bridgeProperty: 'request',+ maxPendingCommands: 2,+ },+ );+ const element = createElementStub();++ commandQueue.enqueueCommand({+ element,+ request: { property: 'selectionStart', value: 1 },+ });+ commandQueue.enqueueCommand({+ element,+ request: { property: 'selectionEnd', value: 2 },+ });+ commandQueue.enqueueCommand({ element, request: { method: 'select' } });++ const latestCommands = [+ { sequence: 2, request: { property: 'selectionEnd', value: 2 } },+ { sequence: 3, request: { method: 'select' } },+ ];++ expect(commandQueue.readPendingCommands(element)).toEqual(latestCommands);+ expect(updateRemoteElementPropertyMock).toHaveBeenCalledTimes(3);+ expect(updateRemoteElementPropertyMock).toHaveBeenLastCalledWith(+ element,+ 'request',+ latestCommands,+ );+ });++ it('should send nothing when discarding an element without pending commands', () => {+ const commandQueue = createRemoteElementCommandQueue<InputSelectionRequest>(+ {+ bridgeProperty: 'request',+ },+ );++ commandQueue.discardPendingCommands(createElementStub());++ expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();+ });++ it('should not write the bridge property for a non-element object', () => {+ const commandQueue = createRemoteElementCommandQueue<InputSelectionRequest>(+ {+ bridgeProperty: 'request',+ },+ );+ const nonElement = {};++ commandQueue.enqueueCommand({+ element: nonElement,+ request: { method: 'select' },+ });++ expect(updateRemoteElementPropertyMock).not.toHaveBeenCalled();+ expect(commandQueue.readPendingCommands(nonElement)).toHaveLength(1);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/createRemoteElementCommandQueue.tssimilarity index 61%rename from packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.tsrename to packages/twenty-front-component-renderer/src/polyfills/utils/createRemoteElementCommandQueue.tsindex 73896f1d1a1..146f2b7fd3a 100644--- a/packages/twenty-front-component-renderer/src/polyfills/input-selection/utils/createInputSelectionCommandQueue.ts+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/createRemoteElementCommandQueue.ts@@ -1,15 +1,21 @@import { updateRemoteElementProperty } from '@remote-dom/core/elements';import { isDefined } from 'twenty-shared/utils';-import { INPUT_SELECTION_BRIDGE_PROPERTIES } from '@/constants/InputSelectionBridgeProperties';-import { acknowledgedNativeEditSequenceByRemoteElement } from '@/remote/elements/states/acknowledgedNativeEditSequenceByRemoteElement';-import { type InputSelectionCommand } from '@/types/InputSelectionCommand';-import { type InputSelectionRequest } from '@/types/InputSelectionRequest';--export const createInputSelectionCommandQueue = () => {+import { isElementNode } from '@/polyfills/dom/utils/isElementNode';+import { type RemoteElementCommand } from '@/types/RemoteElementCommand';++export const createRemoteElementCommandQueue = <TRequest>({+ bridgeProperty,+ maxPendingCommands = Number.POSITIVE_INFINITY,+ readAcknowledgedNativeEditSequence,+}: {+ bridgeProperty: string;+ maxPendingCommands?: number;+ readAcknowledgedNativeEditSequence?: (element: object) => number | undefined;+}) => {const pendingCommandsByElement = new WeakMap<object,- InputSelectionCommand[]+ RemoteElementCommand<TRequest>[]>();let lastCommandSequence = 0;@@ -19,13 +25,13 @@ export const createInputSelectionCommandQueue = () => {commands,}: {element: object;- commands: InputSelectionCommand[];+ commands: RemoteElementCommand<TRequest>[];}): void => {- updateRemoteElementProperty(- element as Element,- INPUT_SELECTION_BRIDGE_PROPERTIES.request,- commands,- );+ if (!isElementNode(element)) {+ return;+ }++ updateRemoteElementProperty(element, bridgeProperty, commands);};const updatePendingCommands = ({@@ -33,13 +39,15 @@ export const createInputSelectionCommandQueue = () => {commands,}: {element: object;- commands: InputSelectionCommand[];+ commands: RemoteElementCommand<TRequest>[];}): void => {pendingCommandsByElement.set(element, commands);sendPendingCommandsToHost({ element, commands });};- const readPendingCommands = (element: object): InputSelectionCommand[] =>+ const readPendingCommands = (+ element: object,+ ): RemoteElementCommand<TRequest>[] =>pendingCommandsByElement.get(element) ?? [];const enqueueCommand = ({@@ -47,21 +55,23 @@ export const createInputSelectionCommandQueue = () => {request,}: {element: object;- request: InputSelectionRequest;+ request: TRequest;}): void => {lastCommandSequence += 1;+ const commands = [+ ...readPendingCommands(element),+ {+ sequence: lastCommandSequence,+ request,+ acknowledgedNativeEditSequence:+ readAcknowledgedNativeEditSequence?.(element),+ },+ ];+updatePendingCommands({element,- commands: [- ...readPendingCommands(element),- {- sequence: lastCommandSequence,- request,- acknowledgedNativeEditSequence:- acknowledgedNativeEditSequenceByRemoteElement.get(element),- },- ],+ commands: commands.slice(-maxPendingCommands),});};diff --git a/packages/twenty-front-component-renderer/src/polyfills/utils/createRemoteElementHostSubscriptions.ts b/packages/twenty-front-component-renderer/src/polyfills/utils/createRemoteElementHostSubscriptions.tsnew file mode 100644index 00000000000..9087bead126--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/utils/createRemoteElementHostSubscriptions.ts@@ -0,0 +1,96 @@+import { updateRemoteElementProperty } from '@remote-dom/core/elements';++import { isElementNode } from '@/polyfills/dom/utils/isElementNode';+import { isElementUnderRemoteRoot } from '@/polyfills/geometry/utils/isElementUnderRemoteRoot';++export const createRemoteElementHostSubscriptions = <THostUpdate>({+ updateBridgeProperty,+ readRootElement,+ onHostUpdate,+ onForgetElement,+}: {+ updateBridgeProperty: string;+ readRootElement: () => object | null;+ onHostUpdate: (input: { element: object; hostUpdate: THostUpdate }) => void;+ onForgetElement: (element: object) => void;+}) => {+ const hostUpdateSubscriptions = new WeakMap<+ object,+ (hostUpdate: THostUpdate) => void+ >();+ const trackedElements = new Set<object>();++ let hasScheduledDetachedElementSweep = false;++ const renewHostUpdateSubscription = (element: object): void => {+ const handleHostUpdate = (hostUpdate: THostUpdate) => {+ const isLatestSubscription =+ hostUpdateSubscriptions.get(element) === handleHostUpdate;++ if (+ !isLatestSubscription ||+ !isElementUnderRemoteRoot(element, readRootElement())+ ) {+ return;+ }++ onHostUpdate({ element, hostUpdate });+ };++ hostUpdateSubscriptions.set(element, handleHostUpdate);++ if (!isElementNode(element)) {+ return;+ }++ updateRemoteElementProperty(+ element,+ updateBridgeProperty,+ handleHostUpdate,+ );+ };++ const trackElement = (element: object): void => {+ trackedElements.add(element);+ };++ const subscribe = (element: object): void => {+ trackedElements.add(element);++ if (!hostUpdateSubscriptions.has(element)) {+ renewHostUpdateSubscription(element);+ }+ };++ const forgetDetachedElement = (element: object): void => {+ trackedElements.delete(element);+ onForgetElement(element);++ if (hostUpdateSubscriptions.has(element)) {+ renewHostUpdateSubscription(element);+ }+ };++ const sweepDetachedElements = (): void => {+ hasScheduledDetachedElementSweep = false;++ for (const element of trackedElements) {+ if (isElementUnderRemoteRoot(element, readRootElement())) {+ continue;+ }++ forgetDetachedElement(element);+ }+ };++ const scheduleDetachedElementSweep = (): void => {+ if (hasScheduledDetachedElementSweep || trackedElements.size === 0) {+ return;+ }++ hasScheduledDetachedElementSweep = true;+ queueMicrotask(sweepDetachedElements);+ };++ return { trackElement, subscribe, scheduleDetachedElementSweep };+};diff --git a/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts b/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.tsindex c9c4863b3b3..afa9e912666 100644--- a/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts+++ b/packages/twenty-front-component-renderer/src/types/InputSelectionCommand.ts@@ -1,7 +1,4 @@import { type InputSelectionRequest } from '@/types/InputSelectionRequest';+import { type RemoteElementCommand } from '@/types/RemoteElementCommand';-export type InputSelectionCommand = {- sequence: number;- acknowledgedNativeEditSequence?: number;- request: InputSelectionRequest;-};+export type InputSelectionCommand = RemoteElementCommand<InputSelectionRequest>;diff --git a/packages/twenty-front-component-renderer/src/types/RemoteElementCommand.ts b/packages/twenty-front-component-renderer/src/types/RemoteElementCommand.tsnew file mode 100644index 00000000000..17729a633bf--- /dev/null+++ b/packages/twenty-front-component-renderer/src/types/RemoteElementCommand.ts@@ -0,0 +1,5 @@+export type RemoteElementCommand<TRequest> = {+ sequence: number;+ acknowledgedNativeEditSequence?: number;+ request: TRequest;+};