8000 fix(reorder): serialize structural mutations to stop drag&drop reverts by Klehm · Pull Request #1 · Klehm/content-blocks-project · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
8000
Original file line number Diff line number Diff line change
Expand Up @@ -551,10 +551,42 @@ export default class extends Controller {
}

/**
* Shared AJAX helper. Pulls the CSRF token from the shell wrapper element
* (`data-cb-csrf-token`) and forwards it as `X-CSRF-Token`.
* Shared AJAX helper for every structural mutation. Calls are SERIALIZED:
* each request waits for the previous one to settle before it starts, so at
* most one mutation is ever in flight.
*
* Why serialize? Every reorder / duplicate / create / delete endpoint does a
* read-modify-write of a whole sibling set's previewPosition (the draft
* order). Two overlapping requests would each read the other's pre-commit
* state, and whichever committed last would clobber the earlier reorder — a
* classic lost update. The visible symptom was a drag that looked like it
* worked but silently snapped back to its old slot after a reload:
* intermittent, and worse on large pages where slower requests widen the
* overlap window. Funnelling every mutation through one in-flight slot
* removes the race entirely; the added latency is invisible for
* click/drag-driven actions.
*/
_jsonRequest(method, url, body) {
const exec = () => this._performJsonRequest(method, url, body);
// Chain onto the queue tail (run on both fulfil and reject so a prior
// failure still releases the slot). _performJsonRequest never rejects —
// it catches network + non-OK and resolves to null — so callers keep
// getting their result (or null) in submission order.
const result = this._mutationQueue
? this._mutationQueue.then(exec, exec)
: exec();
// Swallow rejections on the tail only, so one failed request can't wedge
// every later mutation behind a permanently-rejected promise.
this._mutationQueue = result.catch(() => {});

return result;
}

/**
* Performs a single JSON request. Pulls the CSRF token from the shell
* wrapper element (`data-cb-csrf-token`) and forwards it as `X-CSRF-Token`.
*/
async _jsonRequest(method, url, body) {
async _performJsonRequest(method, url, body) {
const csrfToken = this.element.dataset.cbCsrfToken || '';
const init = {
method,
Expand Down
53 changes: 53 additions & 0 deletions packages/content-blocks/assets/test/cb-builder.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,59 @@ describe('cb-builder: _jsonRequest', () => {
});
});

describe('cb-builder: _jsonRequest serialization', () => {
let controller;
// setTimeout(0) drains the microtask queue AND lets the serialization
// chain advance to the next request — robust without fake timers.
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));

beforeEach(() => {
({ controller } = setupController());
controller.element.dataset.cbCsrfToken = 'csrf-xyz';
vi.spyOn(console, 'error').mockImplementation(() => {});
});

it('runs structural requests one at a time, in submission order', async () => {
// Each fetch hangs until we resolve it by hand, so we can observe that
// the second request never starts while the first is still in flight.
const resolvers = [];
global.fetch = vi.fn(() => new Promise((resolve) => { resolvers.push(resolve); }));

controller._jsonRequest('POST', '/first');
controller._jsonRequest('POST', '/second');
await flush();

// Only the first request was dispatched; the second waits in the queue.
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch.mock.calls[0][0]).toBe('/first');

// Settling the first must release the slot for the second.
resolvers[0]({ ok: true, json: () => Promise.resolve({}) });
await flush();

expect(global.fetch).toHaveBeenCalledTimes(2);
expect(global.fetch.mock.calls[1][0]).toBe('/second');

resolvers[1]({ ok: true, json: () => Promise.resolve({}) });
await flush();
});

it('a failed request does not wedge the queued ones behind it', async () => {
global.fetch = vi.fn()
.mockImplementationOnce(() => Promise.reject(new Error('offline')))
.mockImplementationOnce(() => Promise.resolve({ ok: true, json: () => Promise.resolve({ ok: 1 }) }));

const firstP = controller._jsonRequest('POST', '/first');
const secondP = controller._jsonRequest('POST', '/second');
const [first, second] = await Promise.all([firstP, secondP]);
await flush();

expect(first).toBeNull(); // network failure → null, slot released
expect(second).toEqual({ ok: 1 }); // the queue advanced past the failure
expect(global.fetch).toHaveBeenCalledTimes(2);
});
});

describe('cb-builder: setViewport', () => {
let controller, element, iframe;

Expand Down
6 changes: 6 additions & 0 deletions packages/content-blocks/src/Controller/BlocksController.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,12 @@ public function move(int $id, Request $request): JsonResponse
$source->getBlocks()->toArray(),
fn (Block $b) => $b->getId() !== $block->getId() && !$b->isDeleted(),
));
// Sort by previewPosition before re-indexing: getBlocks() is ordered
// by the *published* position (the collection's #[OrderBy]), so a
// source column carrying an unpublished reorder would otherwise be
// re-indexed back into published order — reverting the draft order of
// the blocks left behind. The target branch below already sorts first.
usort($sourceBlocks, fn (Block $a, Block $b) => $a->getPreviewPosition() <=> $b->getPreviewPosition());
$this->reindexPreview($sourceBlocks);

$block->setColumn($target);
Expand Down
23 changes: 23 additions & 0 deletions packages/content-blocks/tests/Controller/BlocksControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,29 @@ public function testMoveAcrossColumnsReindexesBothSides(): void
$this->assertSame(0, $staying->getPreviewPosition());
}

public function testMoveAcrossColumnsPreservesTheSourceColumnDraftOrder(): void
{
$area = $this->makeArea(1);
$section = $this->makeSection($area, 2);
$source = $this->makeColumn($section, 3, previewPosition: 0);
$target = $this->makeColumn($section, 4, previewPosition: 1);

// Insertion order ($a then $b) — the collection's in-memory order, and
// the *published*-position order once hydrated from the DB — is the
// reverse of the draft order encoded in previewPosition ($b before $a).
$moving = $this->makeBlock($source, 10, previewPosition: 1);
$a = $this->makeBlock($source, 11, previewPosition: 2);
$b = $this->makeBlock($source, 12, previewPosition: 0);
$controller = $this->makeController($this->makeEm([$source, $target, $moving]));

$controller->move(10, $this->makeJsonRequest(['toColumnId' => 4, 'position' => 0]));

// The survivors keep their draft order (B before A), densely reindexed —
// not reset to the published/insertion order, which would put A first.
$this->assertSame(0, $b->getPreviewPosition());
$this->assertSame(1, $a->getPreviewPosition());
}

public function testMoveIgnoresDeletedSiblingsInPositionMath(): void
{
$column = $this->makeGraph();
Expand Down
0