A platform for community discussion. Free, open, simple.
FIX: Preserve checklist toggles across rerenders (#43360)
Same5feeae77da6
diff --git a/frontend/discourse/app/components/post/cooked-html.gjs b/frontend/discourse/app/components/post/cooked-html.gjsindex 907127b3e0d..2573eb8c492 100644--- a/frontend/discourse/app/components/post/cooked-html.gjs+++ b/frontend/discourse/app/components/post/cooked-html.gjs@@ -196,6 +196,7 @@ export default class PostCookedHtml extends Component {}}@html={{trustHTML this.cooked}}@model={{@post}}+ @preservePointerTarget={{true}}/></template>}diff --git a/frontend/discourse/app/ui-kit/d-decorated-html.gjs b/frontend/discourse/app/ui-kit/d-decorated-html.gjsindex 14a01cc4cd6..8575a9512ec 100644--- a/frontend/discourse/app/ui-kit/d-decorated-html.gjs+++ b/frontend/discourse/app/ui-kit/d-decorated-html.gjs@@ -1,6 +1,8 @@import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";import { untrack } from "@glimmer/validator";import { trackedArray } from "@ember/reactive/collections";+import { cancel, next } from "@ember/runloop";import { isHTMLSafe, trustHTML } from "@ember/template";import helperFn from "discourse/helpers/helper-fn";import {@@ -107,19 +109,27 @@ export function resetHtmlDecorators() {* @param {Object} [context] - Context object passed to decorators via helper.context* @param {string} [className] - CSS class name for the wrapper div* @param {string} [id] - ID attribute for the wrapper div+ * @param {boolean} [preservePointerTarget] - Defer replacement until a pointer activation finishes.*/export default class DDecoratedHtml extends Component {renderGlimmerInfos = trackedArray();-- decoratedContent = helperFn(({ decorateArgs }, on) => {+ decoratedContent = helperFn(({ decorateArgs }) => {+ // Releasing a deferred render must consume the latest arguments.+ this._pointerRevision;+ if (this.#pressedElement) {+ this.#renderDeferred = true;+ return this.#pressedElement;+ }const cookedDiv = this.elementToDecorate;+ // Helper cleanup must wait for replacement, not a deferred recomputation.+ this.#htmlHelper?.teardown();const helper = new DecorateHtmlHelper({renderGlimmerInfos: this.renderGlimmerInfos,model: this.args.model,context: this.args.context,});- on.cleanup(() => helper.teardown());+ this.#htmlHelper = helper;const decorateFn = this.args.decorate;@@ -153,6 +163,30 @@ export default class DDecoratedHtml extends Component {return cookedDiv;});+ #htmlHelper;+ #renderDeferred = false;+ #pressedElement;+ #pointerListeners;+ #pointerReleaseTimer;+ #releasePointer = () => {+ cancel(this.#pointerReleaseTimer);+ this.#pointerReleaseTimer = undefined;+ this.#pointerListeners?.abort();+ this.#pointerListeners = undefined;+ this.#pressedElement = undefined;+ if (this.#renderDeferred && !this.isDestroying) {+ this.#renderDeferred = false;+ this._pointerRevision++;+ }+ };+ @tracked _pointerRevision = 0;++ willDestroy() {+ super.willDestroy(...arguments);+ this.#releasePointer();+ this.#htmlHelper?.teardown();+ this.#htmlHelper = undefined;+ }get elementToDecorate() {const cooked = this.args.html || trustHTML("");@@ -161,6 +195,13 @@ export default class DDecoratedHtml extends Component {}const cookedDiv = detachedDocument.createElement("div");cookedDiv.innerHTML = cooked.toString();+ if (this.args.preservePointerTarget) {+ cookedDiv.addEventListener(+ "pointerdown",+ (event) => this.#holdElement(event, cookedDiv),+ true+ );+ }if (this.args.id) {cookedDiv.id = this.args.id;@@ -198,6 +239,47 @@ export default class DDecoratedHtml extends Component {return result;}+ #holdElement(event, element) {+ if (event.button !== 0 || event.isPrimary === false) {+ return;+ }+ this.#releasePointer();+ this.#pressedElement = element;+ this.#pointerListeners = new AbortController();+ const options = { capture: true, signal: this.#pointerListeners.signal };+ const afterClick = (releaseEvent) => {+ if (releaseEvent.pointerId !== event.pointerId) {+ return;+ }+ // Replacing the pressed target before click would discard its activation.+ cancel(this.#pointerReleaseTimer);+ this.#pointerReleaseTimer = next(this.#releasePointer);+ };+ document.addEventListener("pointerup", afterClick, options);+ document.addEventListener("pointercancel", afterClick, options);+ window.addEventListener(+ "blur",+ (blurEvent) => {+ if (blurEvent.target === window) {+ this.#releasePointer();+ }+ },+ options+ );+ document.addEventListener(+ "pointermove",+ (moveEvent) => {+ if (+ moveEvent.pointerId === event.pointerId &&+ moveEvent.buttons === 0+ ) {+ this.#releasePointer();+ }+ },+ options+ );+ }+<template>{{~this.decoratedContent decorateArgs=@decorateArgs~}}diff --git a/frontend/discourse/tests/integration/ui-kit/d-decorated-html-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-decorated-html-test.gjsindex 0f6f7e1b3ab..80ae8e75833 100644--- a/frontend/discourse/tests/integration/ui-kit/d-decorated-html-test.gjs+++ b/frontend/discourse/tests/integration/ui-kit/d-decorated-html-test.gjs@@ -1,7 +1,13 @@import { tracked } from "@glimmer/tracking";import { getOwner } from "@ember/owner";import { trustHTML } from "@ember/template";-import { render, settled } from "@ember/test-helpers";+import {+ clearRender,+ find,+ render,+ settled,+ triggerEvent,+} from "@ember/test-helpers";import curryComponent from "ember-curry-component";import { module, test } from "qunit";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -27,6 +33,147 @@ module("Integration | ui-kit | DDecoratedHtml", function (hooks) {assert.dom("h1").hasText("Updated");});+ test("defers replacement until the pressed control receives its click", async function (assert) {+ const state = new (class {+ @tracked html = trustHTML('<button id="target">Initial</button>');+ })();+ let clicks = 0;+ const decorate = (element, helper) => {+ element.querySelector("button").addEventListener("click", () => clicks++);+ helper.renderGlimmer(+ element,+ <template>+ <span id="nested">Nested content</span>+ </template>+ );+ };+ await render(+ <template>+ <DDecoratedHtml+ @html={{state.html}}+ @preservePointerTarget={{true}}+ @decorate={{decorate}}+ />+ </template>+ );+ const target = find("#target");+ await triggerEvent(target, "pointerdown", {+ button: 0,+ isPrimary: true,+ pointerId: 1,+ });+ state.html = trustHTML('<button id="target">Updated</button>');+ await settled();+ assert.strictEqual(+ find("#target"),+ target,+ "the pressed DOM node is retained"+ );+ assert+ .dom("#nested")+ .hasText(+ "Nested content",+ "nested components survive deferred rendering"+ );+ state.html = trustHTML('<button id="target">Updated again</button>');+ await settled();+ target.addEventListener("pointerup", (event) => event.stopPropagation());+ target.dispatchEvent(+ new PointerEvent("pointerup", { bubbles: true, button: 0, pointerId: 1 })+ );+ target.click();+ await settled();+ assert.strictEqual(+ clicks,+ 1,+ "the original control receives its activation"+ );+ assert+ .dom("#target")+ .hasText("Updated again", "the newest HTML appears after click");+ assert+ .dom("#nested")+ .hasText("Nested content", "nested components render in the replacement");+ for (let i = 0; i < 3; i++) {+ state.html = trustHTML(`<button id="target">Update ${i}</button>`);+ await settled();+ assert+ .dom("#nested")+ .exists(+ { count: 1 },+ "old nested components are removed on each replacement"+ );+ }+ });++ test("ignores descendant blur but releases on window blur", async function (assert) {+ const state = new (class {+ @tracked html = trustHTML('<button id="target">Initial</button>');+ })();+ await render(+ <template>+ <DDecoratedHtml @html={{state.html}} @preservePointerTarget={{true}} />+ </template>+ );+ const target = find("#target");+ await triggerEvent(target, "pointerdown", {+ button: 0,+ isPrimary: true,+ pointerId: 1,+ });+ target.dispatchEvent(new FocusEvent("blur"));+ state.html = trustHTML('<button id="target">Updated</button>');+ await settled();+ assert.strictEqual(+ find("#target"),+ target,+ "losing focus does not cancel the press"+ );+ assert.dom(target).hasText("Initial", "replacement remains deferred");++ window.dispatchEvent(new FocusEvent("blur"));+ await settled();+ assert+ .dom("#target")+ .hasText("Updated", "leaving the window releases the update");+ });++ test("releases deferred HTML on pointer cancellation", async function (assert) {+ const state = new (class {+ @tracked html = trustHTML('<button id="target">Initial</button>');+ })();+ await render(+ <template>+ <DDecoratedHtml @html={{state.html}} @preservePointerTarget={{true}} />+ </template>+ );+ const target = find("#target");+ await triggerEvent(target, "pointerdown", {+ button: 0,+ isPrimary: true,+ pointerId: 1,+ });+ state.html = trustHTML('<button id="target">Updated</button>');+ await settled();+ await triggerEvent(target, "pointercancel", { pointerId: 1 });++ assert+ .dom("#target")+ .hasText("Updated", "cancellation releases the deferred update");+ await triggerEvent(find("#target"), "pointerdown", {+ button: 0,+ isPrimary: true,+ pointerId: 1,+ });+ await clearRender();+ await triggerEvent(document, "pointerup", { pointerId: 1 });+ assert+ .dom("#target")+ .doesNotExist(+ "a late release after destruction does not recreate content"+ );+ });+test("can decorate content, including renderGlimmer", async function (assert) {const state = new (class {@tracked html = trustHTML("<h1>Initial</h1>");diff --git a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.jsindex f906d38b876..0f3d056da5d 100644--- a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js+++ b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js@@ -1,31 +1,24 @@+import { cancel } from "@ember/runloop";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";+import discourseDebounce from "discourse/lib/debounce";import { registerOptimisticPostUpdate } from "discourse/lib/optimistic-post-updates";import { withPluginApi } from "discourse/lib/plugin-api";import { i18n } from "discourse-i18n";import richEditorExtension from "../../lib/rich-editor-extension";-const MINIMUM_PENDING_DURATION = 200;+const SAVE_DEBOUNCE_DURATION = 150;const MAX_CONFLICT_RETRIES = 2;+// Keep request batches within the toggle endpoint's contract.+const MAX_BATCH_SIZE = 50;+const REQUEST_TIMEOUT = 30000;function timestampsAreEqual(first, second) {- const firstTime = Date.parse(first);- const secondTime = Date.parse(second);- return (- !Number.isNaN(firstTime) &&- !Number.isNaN(secondTime) &&- firstTime === secondTime- );+ return Date.parse(first) === Date.parse(second);}function timestampIsOlder(candidate, reference) {- const candidateTime = Date.parse(candidate);- const referenceTime = Date.parse(reference);- return (- !Number.isNaN(candidateTime) &&- !Number.isNaN(referenceTime) &&- candidateTime < referenceTime- );+ return Date.parse(candidate) < Date.parse(reference);}function setCheckboxState(checkbox, checked) {@@ -142,10 +135,8 @@ function configureAccessibility(box, editable) {}}-const checklistStates = new WeakMap();--function checkboxKey(renderedIndex, checkboxCount) {- return `${renderedIndex}:${checkboxCount}`;+function checkboxKey(box, renderedIndex, checkboxCount) {+ return box.dataset.chkSrc ?? `legacy:${renderedIndex}:${checkboxCount}`;}function checkboxTarget(box, renderedIndex, checkboxCount) {@@ -156,13 +147,6 @@ function checkboxTarget(box, renderedIndex, checkboxCount) {};}-function checklistBindingSignature(boxes) {- return boxes- .filter((box) => !box.classList.contains("permanent"))- .map((box) => `${box.dataset.chkSrc ?? "legacy"}:${checkboxLabel(box)}`)- .join("\0");-}-function checklistFingerprint(raw, checkboxSources, includesLegacy) {if (typeof raw !== "string") {return;@@ -181,7 +165,7 @@ function checklistFingerprint(raw, checkboxSources, includesLegacy) {sourcesByLine.get(line).add(nth);});- const lines = raw.split("\n");+ const lines = raw.split(/\r\n?|\n/);let valid = true;sourcesByLine.forEach((indexes, lineNumber) => {if (lines[lineNumber] === undefined) {@@ -201,168 +185,266 @@ function checklistFingerprint(raw, checkboxSources, includesLegacy) {return valid ? lines.join("\n") : undefined;}-class ChecklistState {- #baselineRaw;- #baselineUpdatedAt;- #binding;- #bindingSignature;- #checkboxSources = [];- #fingerprint;- #includesLegacy = false;- #indicators = new Map();- #intents = new Map();- #postModel;- #revision = 0;- #saving = false;+const activeChecklistOperations = new Map();+const uncertainChecklistBaseline = Symbol("uncertain-checklist-baseline");- constructor(postModel) {- this.#postModel = postModel;- this.#baselineRaw = postModel.raw;- this.#baselineUpdatedAt = postModel.updated_at;+function cookedChecklistFingerprint(cooked) {+ if (typeof cooked !== "string") {+ return;}+ const document = new DOMParser().parseFromString(cooked, "text/html");+ document.querySelectorAll(".chcklst-box:not(.permanent)").forEach((box) => {+ if (!isInsideSourcedQuote(box)) {+ box.classList.remove("checked", "fa-square-o", "fa-square-check-o");+ }+ });+ return document.body.innerHTML;+}- bind(boxes, allBoxes = boxes) {- this.#binding?.cleanup();+export function activeChecklistOperationCountForTesting() {+ return activeChecklistOperations.size;+}- const renderedIndexes = new Map(allBoxes.map((box, index) => [box, index]));- const mutableBoxes = allBoxes.filter(- (box) => !box.classList.contains("permanent")- );- const bindingSignature = checklistBindingSignature(allBoxes);- const checkboxSources = mutableBoxes- .map((box) => box.dataset.chkSrc)- .filter(Boolean);- const includesLegacy = mutableBoxes.some((box) => !box.dataset.chkSrc);- const raw = this.#postModel.raw ?? this.#baselineRaw;- const fingerprint = checklistFingerprint(- raw,- checkboxSources,- includesLegacy- );+function checklistRendering(postModel, boxes) {+ const mutableBoxes = boxes.filter(+ (box) => !box.classList.contains("permanent")+ );+ const checkboxSources = mutableBoxes+ .map((box) => box.dataset.chkSrc)+ .filter(Boolean);+ const includesLegacy = mutableBoxes.some((box) => !box.dataset.chkSrc);+ const fingerprintFor = (raw) =>+ checklistFingerprint(raw, checkboxSources, includesLegacy);+ const fingerprint = fingerprintFor(postModel.raw);+ const coverage = mutableBoxes+ .map((box) => box.dataset.chkSrc ?? "legacy")+ .join("\0");+ const generation =+ fingerprint === undefined+ ? `${postModel.updated_at ?? "unknown"}\0${mutableBoxes+ .map(+ (box) => `${box.dataset.chkSrc ?? "legacy"}:${checkboxLabel(box)}`+ )+ .join("\0")}`+ : `${fingerprint}\0${coverage}`;- if (- (this.#fingerprint !== undefined &&- fingerprint !== undefined &&- this.#fingerprint !== fingerprint) ||- (this.#intents.size > 0 &&- fingerprint === undefined &&- this.#bindingSignature !== undefined &&- this.#bindingSignature !== bindingSignature)- ) {- this.#discardIntents();- }+ return {+ baselineUpdatedAt: postModel.updated_at,+ coverage,+ cookedFingerprint:+ fingerprint === undefined+ ? cookedChecklistFingerprint(postModel.cooked)+ : undefined,+ fingerprint,+ fingerprintFor,+ generation,+ invalid: false,+ };+}- this.#bindingSignature = bindingSignature;- this.#checkboxSources = checkboxSources;- this.#includesLegacy = includesLegacy;- if (fingerprint !== undefined || this.#intents.size === 0) {- this.#fingerprint = fingerprint;- }+function confirmChecklistPresentation(presentation, checked) {+ const { control, token } = presentation;+ if (control.state?.token === token) {+ control.state.confirmed = checked;+ }+}- if (- !this.#saving &&- this.#intents.size === 0 &&- this.#postModel.raw != null &&- !timestampIsOlder(this.#postModel.updated_at, this.#baselineUpdatedAt)- ) {- this.#baselineRaw = this.#postModel.raw;- this.#baselineUpdatedAt = this.#postModel.updated_at;- }+function setChecklistPending(control, pending) {+ control.box?.classList.toggle("is-pending", pending);+ if (pending) {+ control.box?.setAttribute("aria-busy", "true");+ } else {+ control.box?.removeAttribute("aria-busy");+ }+}- const binding = {- cleaned: false,- cleanup: undefined,- cleanups: [],- controls: new Map(),- };+function settleChecklistPresentation(presentation, checked) {+ const { control, token } = presentation;+ if (control.state?.token !== token) {+ return;+ }- boxes.forEach((box) => {- if (box.classList.contains("permanent")) {- return;- }+ control.state = undefined;+ if (control.box) {+ setCheckboxState(control.box, checked);+ }+ setChecklistPending(control, false);+}- const renderedIndex = renderedIndexes.get(box);- const key = checkboxKey(renderedIndex, allBoxes.length);- const target = checkboxTarget(box, renderedIndex, allBoxes.length);- binding.controls.set(key, box);-- const toggle = () => {- const checked = !box.classList.contains("checked");- const previous = this.#intents.get(key);- this.#intents.set(key, {- checked,- confirmed: previous?.confirmed ?? !checked,- fingerprint: this.#fingerprint,- revision: (this.#revision += 1),- target,- });- setCheckboxState(box, checked);- this.#startIndicator(key);- void this.#save();- };- const onClick = (event) => {- event.preventDefault();- toggle();- };- const onKeyDown = (event) => {- if (event.key !== " " && event.key !== "Enter") {- return;- }+function enqueueChecklistChange(change) {+ const postId = change.postModel.id;+ if (postId == null) {+ settleChecklistPresentation(+ { control: change.control, token: change.token },+ change.confirmed+ );+ return;+ }- event.preventDefault();- toggle();- };+ let operation = activeChecklistOperations.get(postId);+ if (!operation) {+ operation = new ChecklistOperation(change.postModel);+ activeChecklistOperations.set(postId, operation);+ }+ operation.enqueue(change);+}- box.addEventListener("click", onClick);- box.addEventListener("keydown", onKeyDown);- binding.cleanups.push(() => {- box.removeEventListener("click", onClick);- box.removeEventListener("keydown", onKeyDown);- });- });+function bindChecklist(boxes, postModel) {+ const rendering = checklistRendering(postModel, boxes);+ const abortController = new AbortController();+ const controls = [];- for (const key of this.#intents.keys()) {- if (!binding.controls.has(key)) {- this.#discardIntent(key);- }+ boxes.forEach((box, renderedIndex) => {+ if (box.classList.contains("permanent")) {+ return;}- this.#binding = binding;- binding.controls.forEach((box, key) => this.#syncControl(key, box));+ const control = {+ box,+ key: checkboxKey(box, renderedIndex, boxes.length),+ rendering,+ state: undefined,+ target: checkboxTarget(box, renderedIndex, boxes.length),+ };+ controls.push(control);++ const activate = (event) => {+ if (+ event.type === "keydown" &&+ event.key !== " " &&+ event.key !== "Enter"+ ) {+ return;+ }- binding.cleanup = () => {- if (binding.cleaned) {+ event.preventDefault();+ if (event.repeat || rendering.invalid) {return;}- binding.cleaned = true;- binding.cleanups.forEach((cleanup) => cleanup());- binding.controls.forEach((box) => {- box.classList.remove("is-pending");- box.removeAttribute("aria-busy");+ const checked = !control.box.classList.contains("checked");+ const token = Symbol();+ const confirmed = control.state?.confirmed ?? !checked;+ control.state = { confirmed, token };+ setCheckboxState(control.box, checked);+ setChecklistPending(control, true);+ enqueueChecklistChange({+ checked,+ confirmed,+ control,+ key: control.key,+ postModel,+ rendering,+ target: control.target,+ token,});- if (this.#binding === binding) {- this.#binding = undefined;- }};- return binding.cleanup;++ box.addEventListener("click", activate, {+ signal: abortController.signal,+ });+ box.addEventListener("keydown", activate, {+ signal: abortController.signal,+ });+ activeChecklistOperations.get(postModel.id)?.adopt(control);+ });++ return () => {+ abortController.abort();+ controls.forEach((control) => {+ setChecklistPending(control, false);+ control.box = undefined;+ control.state = undefined;+ });+ };+}++class ChecklistOperation {+ #baselineRaw;+ #baselineUpdatedAt;+ #intents = new Map();+ #inFlight = new Set();+ #hydratedGenerations = new Map();+ #postModel;+ #revision = 0;+ #saveTimer;+ #saving = false;++ constructor(postModel) {+ this.#postModel = postModel;+ this.#baselineRaw = postModel[uncertainChecklistBaseline]+ ? undefined+ : postModel.raw;+ this.#baselineUpdatedAt = postModel.updated_at;}- #applyBaseline(raw, updatedAt) {- this.#baselineRaw = raw;- this.#baselineUpdatedAt = updatedAt;+ adopt(control) {+ this.#resolveGeneration(control.rendering);+ const intent = this.#intents.get(+ `${control.rendering.generation}\0${control.key}`+ );+ if (!intent) {+ return;+ }++ const token = Symbol();+ control.state = { confirmed: intent.confirmed, token };+ setCheckboxState(control.box, intent.checked);+ setChecklistPending(control, true);+ intent.presentations = intent.presentations.filter(+ (presentation) =>+ presentation.control.box && presentation.control !== control+ );+ intent.presentations.push({ control, token });}- #clearIndicator(key, indicator = this.#indicators.get(key)) {- if (!indicator || this.#indicators.get(key) !== indicator) {+ enqueue(change) {+ this.#observePostModel(change.postModel);+ this.#resolveGeneration(change.rendering);++ const intentKey = `${change.rendering.generation}\0${change.key}`;+ const previous = this.#intents.get(intentKey);+ const presentations = (previous?.presentations ?? []).filter(+ (presentation) =>+ presentation.control.box && presentation.control !== change.control+ );+ presentations.push({ control: change.control, token: change.token });+ const confirmed = previous?.confirmed ?? change.confirmed;+ if (+ (!this.#saving ||+ (this.#inFlight.size > 0 && !this.#inFlight.has(intentKey))) &&+ change.checked === confirmed+ ) {+ this.#intents.delete(intentKey);+ presentations.forEach((presentation) =>+ settleChecklistPresentation(presentation, confirmed)+ );+ this.#retireIfDrained();return;}- clearTimeout(indicator.timer);- this.#indicators.delete(key);- const box = this.#binding?.controls.get(key);- box?.classList.remove("is-pending");- box?.removeAttribute("aria-busy");+ this.#intents.set(intentKey, {+ checked: change.checked,+ confirmed,+ fingerprint: previous?.fingerprint ?? change.rendering.fingerprint,+ presentations,+ rendering: previous?.rendering ?? change.rendering,+ revision: (this.#revision += 1),+ target: change.target,+ });++ if (!this.#saving) {+ this.#saveTimer = discourseDebounce(+ this,+ this.#save,+ SAVE_DEBOUNCE_DURATION+ );+ }+ }++ #applyBaseline(raw, updatedAt) {+ this.#baselineRaw = raw;+ this.#baselineUpdatedAt = updatedAt;}#completeBatch(entries) {@@ -377,31 +459,32 @@ class ChecklistState {current.fingerprint === saved.fingerprint) {this.#intents.delete(key);- this.#finishIndicator(key);+ current.presentations.forEach((presentation) =>+ settleChecklistPresentation(presentation, saved.checked)+ );} else {current.confirmed = saved.checked;+ current.presentations.forEach((presentation) =>+ confirmChecklistPresentation(presentation, saved.checked)+ );}});}#currentEntries(entries) {- return entries- .map(([key, saved]) => {- const current = this.#intents.get(key);- return current?.checked === saved.checked ? [key, saved] : undefined;- })- .filter(Boolean);- }-- #discardIntent(key) {- this.#intents.delete(key);- this.#clearIndicator(key);+ return entries.filter(+ ([key, saved]) => this.#intents.get(key)?.checked === saved.checked+ );}- #discardIntents() {- const keys = [...this.#intents.keys()];- this.#intents.clear();- keys.forEach((key) => this.#clearIndicator(key));+ #entriesForNextGeneration() {+ const first = this.#intents.values().next().value;+ return [...this.#intents]+ .filter(+ ([, intent]) =>+ intent.rendering.generation === first.rendering.generation+ )+ .slice(0, MAX_BATCH_SIZE);}#failBatch(entries) {@@ -412,44 +495,28 @@ class ChecklistState {}this.#intents.delete(key);- const box = this.#binding?.controls.get(key);- if (box) {- setCheckboxState(box, failed.confirmed);- }- this.#finishIndicator(key);+ current.presentations.forEach((presentation) =>+ settleChecklistPresentation(presentation, current.confirmed)+ );});}- #finishIndicator(key) {- const indicator = this.#indicators.get(key);- const box = this.#binding?.controls.get(key);- box?.removeAttribute("aria-busy");- if (!indicator) {- box?.classList.remove("is-pending");- return;- }-- clearTimeout(indicator.timer);- const remaining = Math.max(- 0,- MINIMUM_PENDING_DURATION - (performance.now() - indicator.startedAt)+ #failGeneration(generation, invalidate = false) {+ const entries = [...this.#intents].filter(+ ([, intent]) => intent.rendering.generation === generation);- if (remaining === 0) {- this.#clearIndicator(key, indicator);- } else {- indicator.timer = setTimeout(- () => this.#clearIndicator(key, indicator),- remaining- );+ if (invalidate) {+ entries.forEach(([, intent]) => {+ intent.rendering.invalid = true;+ intent.presentations.forEach((presentation) => {+ presentation.control.rendering.invalid = true;+ if (presentation.control.box) {+ configureAccessibility(presentation.control.box, false);+ }+ });+ });}- }-- #fingerprintFor(raw) {- return checklistFingerprint(- raw,- this.#checkboxSources,- this.#includesLegacy- );+ this.#failBatch(entries);}#freshestBaseline(raw, updatedAt) {@@ -468,6 +535,117 @@ class ChecklistState {return { raw, updatedAt };}+ async #hydrate(entries) {+ if (+ this.#baselineRaw != null &&+ entries.every(([, intent]) => intent.fingerprint !== undefined)+ ) {+ return true;+ }++ const rendering = entries[0][1].rendering;+ try {+ const post = await ajax(`/posts/${this.#postModel.id}`, {+ timeout: REQUEST_TIMEOUT,+ ignoreUnsent: false,+ });+ const baseline = this.#postModel[uncertainChecklistBaseline]+ ? { raw: post.raw, updatedAt: post.updated_at }+ : this.#freshestBaseline(post.raw, post.updated_at);+ const fingerprint = rendering.fingerprintFor(baseline.raw);+ const canUseBaseline = entries.every(([, intent]) => {+ return (+ timestampsAreEqual(+ intent.rendering.baselineUpdatedAt,+ baseline.updatedAt+ ) ||+ (intent.fingerprint !== undefined &&+ intent.rendering.fingerprintFor(baseline.raw) ===+ intent.fingerprint) ||+ (intent.rendering.cookedFingerprint !== undefined &&+ intent.rendering.cookedFingerprint ===+ cookedChecklistFingerprint(post.cooked))+ );+ });+ if (!canUseBaseline || fingerprint === undefined) {+ this.#failGeneration(rendering.generation, true);+ this.#refreshPost(true);+ return false;+ }++ const oldGeneration = rendering.generation;+ const resolved = {+ fingerprint,+ generation: `${fingerprint}\0${rendering.coverage}`,+ };+ this.#hydratedGenerations.set(oldGeneration, resolved);+ for (const [key, intent] of [...this.#intents]) {+ if (+ intent.rendering.generation !== oldGeneration &&+ !key.startsWith(`${oldGeneration}\0`)+ ) {+ continue;+ }+ this.#resolveGeneration(intent.rendering);+ intent.fingerprint = fingerprint;+ intent.presentations.forEach(({ control }) =>+ this.#resolveGeneration(control.rendering)+ );+ const newKey = `${resolved.generation}${key.slice(oldGeneration.length)}`;+ const existing = this.#intents.get(newKey);+ let merged = intent;+ if (existing && existing !== intent) {+ const latest =+ existing.revision > intent.revision ? existing : intent;+ merged = {+ ...latest,+ presentations: [+ ...existing.presentations,+ ...intent.presentations,+ ].filter(+ ({ control, token }) =>+ control.box && control.state?.token === token+ ),+ };+ }+ this.#intents.delete(key);+ this.#intents.set(newKey, merged);+ entries.forEach((entry) => {+ if (entry[0] === key) {+ entry[0] = newKey;+ entry[1].fingerprint = fingerprint;+ if (existing && existing !== intent) {+ entry[1] = merged;+ }+ }+ });+ }+ this.#applyBaseline(baseline.raw, baseline.updatedAt);+ delete this.#postModel[uncertainChecklistBaseline];+ if (this.#postModel.raw == null) {+ this.#postModel.raw = baseline.raw;+ }+ return true;+ } catch (error) {+ this.#postModel[uncertainChecklistBaseline] = true;+ this.#failGeneration(rendering.generation);+ popupAjaxError(error);+ return false;+ }+ }++ #observePostModel(postModel) {+ if (+ this.#postModel.raw == null ||+ timestampIsOlder(this.#postModel.updated_at, postModel.updated_at) ||+ (Number.isFinite(postModel.version) &&+ Number.isFinite(this.#postModel.version) &&+ postModel.version > this.#postModel.version)+ ) {+ this.#postModel = postModel;+ }+ }+#refreshPost(reportError = false) {const refresh = this.#postModel.topic?.postStream?.refreshPost(this.#postModel.id@@ -477,7 +655,29 @@ class ChecklistState {}}+ #resolveGeneration(rendering) {+ const resolved = this.#hydratedGenerations.get(rendering.generation);+ if (resolved) {+ Object.assign(rendering, resolved);+ }+ }++ #retireIfDrained() {+ if (this.#saving || this.#intents.size > 0) {+ return;+ }++ if (this.#saveTimer) {+ cancel(this.#saveTimer);+ this.#saveTimer = undefined;+ }+ if (activeChecklistOperations.get(this.#postModel.id) === this) {+ activeChecklistOperations.delete(this.#postModel.id);+ }+ }+async #save() {+ this.#saveTimer = undefined;if (this.#saving) {return;}@@ -485,10 +685,7 @@ class ChecklistState {this.#saving = true;try {while (this.#intents.size > 0) {- let entries = [...this.#intents].map(([key, intent]) => [- key,- { ...intent },- ]);+ let entries = this.#entriesForNextGeneration();let retries = 0;while ((entries = this.#currentEntries(entries)).length > 0) {@@ -500,16 +697,34 @@ class ChecklistState {break;}+ if (+ this.#postModel.raw != null &&+ timestampIsOlder(+ this.#baselineUpdatedAt,+ this.#postModel.updated_at+ )+ ) {+ this.#applyBaseline(+ this.#postModel.raw,+ this.#postModel.updated_at+ );+ }++ const rendering = entries[0][1].rendering;const fingerprint = entries[0][1].fingerprint;- const baselineFingerprint = this.#fingerprintFor(this.#baselineRaw);+ const baselineFingerprint = rendering.fingerprintFor(+ this.#baselineRaw+ );+ const modelFingerprint = rendering.fingerprintFor(+ this.#postModel.raw+ );if (fingerprint === undefined ||baselineFingerprint === undefined ||- fingerprint !== baselineFingerprint+ fingerprint !== baselineFingerprint ||+ (this.#postModel.raw != null && fingerprint !== modelFingerprint)) {- this.#failBatch(entries);- entries.forEach(([key]) => this.#clearIndicator(key));- this.#discardIntents();+ this.#failGeneration(rendering.generation, true);this.#refreshPost(true);break;}@@ -538,8 +753,11 @@ class ChecklistState {};try {+ this.#inFlight = new Set(entries.map(([key]) => key));const response = await ajax("/checklist/toggle", {type: "PUT",+ timeout: REQUEST_TIMEOUT,+ ignoreUnsent: false,contentType: "application/json",data: JSON.stringify(data),});@@ -571,7 +789,7 @@ class ChecklistState {);const canRetry =retries < MAX_CONFLICT_RETRIES &&- this.#fingerprintFor(baseline.raw) === fingerprint;+ rendering.fingerprintFor(baseline.raw) === fingerprint;this.#applyBaseline(baseline.raw, baseline.updatedAt);if (canRetry) {retries += 1;@@ -583,11 +801,12 @@ class ChecklistState {break;}- if (this.#fingerprint !== fingerprint) {+ if (rendering.fingerprintFor(this.#postModel.raw) !== fingerprint) {this.#applyBaseline(this.#postModel.raw,this.#postModel.updated_at);+ this.#failGeneration(rendering.generation, true);this.#refreshPost();break;}@@ -598,9 +817,7 @@ class ChecklistState {this.#postModel.raw = response.raw;this.#applyBaseline(response.raw, response.updated_at);this.#completeBatch(entries);- if (this.#intents.size === 0) {- this.#postModel.cooked = response.cooked;- }+ this.#postModel.cooked = response.cooked;break;} catch (error) {unregisterOptimisticUpdate();@@ -614,7 +831,7 @@ class ChecklistState {conflict?.retryable &&baseline &&retries < MAX_CONFLICT_RETRIES &&- this.#fingerprintFor(baseline.raw) === entries[0][1].fingerprint;+ rendering.fingerprintFor(baseline.raw) === fingerprint;if (canRetry) {this.#applyBaseline(baseline.raw, baseline.updatedAt);@@ -622,11 +839,20 @@ class ChecklistState {continue;}- this.#failBatch(entries);+ const structuralConflict =+ error.jqXHR?.status === 409 &&+ baseline &&+ rendering.fingerprintFor(baseline.raw) !== fingerprint;+ if (structuralConflict) {+ this.#failGeneration(rendering.generation, true);+ } else {+ this.#failBatch(entries);+ }if (baseline) {this.#applyBaseline(baseline.raw, baseline.updatedAt);} else if (!error.jqXHR || error.jqXHR.status === 0) {this.#baselineRaw = undefined;+ this.#postModel[uncertainChecklistBaseline] = true;} else if (this.#postModel.raw != null) {this.#applyBaseline(this.#postModel.raw,@@ -636,84 +862,21 @@ class ChecklistState {this.#refreshPost();popupAjaxError(error);break;+ } finally {+ this.#inFlight.clear();}}}- } finally {- this.#saving = false;- }- }-- async #hydrate(entries) {- if (this.#baselineRaw != null) {- return true;- }-- try {- const post = await ajax(`/posts/${this.#postModel.id}`);- const baseline = this.#freshestBaseline(post.raw, post.updated_at);- const fingerprint = this.#fingerprintFor(baseline.raw);- const canUseBaseline =- timestampsAreEqual(this.#baselineUpdatedAt, baseline.updatedAt) ||- (this.#fingerprint !== undefined && fingerprint === this.#fingerprint);- if (!canUseBaseline || fingerprint === undefined) {- this.#failBatch(entries);- entries.forEach(([key]) => this.#clearIndicator(key));- this.#refreshPost(true);- return false;- }-- this.#fingerprint = fingerprint;- entries.forEach(([, intent]) => (intent.fingerprint = fingerprint));- for (const intent of this.#intents.values()) {- intent.fingerprint ??= fingerprint;- }- this.#applyBaseline(baseline.raw, baseline.updatedAt);- if (this.#postModel.raw == null) {- this.#postModel.raw = baseline.raw;- }- return true;} catch (error) {- this.#failBatch(entries);+ this.#failBatch([...this.#intents]);popupAjaxError(error);- return false;- }- }-- #startIndicator(key) {- const existing = this.#indicators.get(key);- clearTimeout(existing?.timer);- this.#indicators.set(key, { startedAt: performance.now() });- const box = this.#binding?.controls.get(key);- box?.classList.add("is-pending");- box?.setAttribute("aria-busy", "true");- }-- #syncControl(key, box) {- const intent = this.#intents.get(key);- if (intent) {- setCheckboxState(box, intent.checked);- }-- const indicator = this.#indicators.get(key);- box.classList.toggle("is-pending", Boolean(indicator));- if (intent) {- box.setAttribute("aria-busy", "true");- } else {- box.removeAttribute("aria-busy");+ } finally {+ this.#saving = false;+ this.#retireIfDrained();}}}-function addToggleBehavior(boxes, postModel, allBoxes = boxes) {- let checklistState = checklistStates.get(postModel);- if (!checklistState) {- checklistState = new ChecklistState(postModel);- checklistStates.set(postModel, checklistState);- }- return checklistState.bind(boxes, allBoxes);-}-function isInsideSourcedQuote(box) {return Boolean(box.closest(@@ -735,8 +898,8 @@ export function checklistSyntax(elem, postDecorator) {configureAccessibility(box, editable && interactiveBoxSet.has(box)));- if (editable) {- return addToggleBehavior(interactiveBoxes, postModel);+ if (editable && interactiveBoxes.length > 0) {+ return bindChecklist(interactiveBoxes, postModel);}}diff --git a/plugins/checklist/assets/stylesheets/checklist.scss b/plugins/checklist/assets/stylesheets/checklist.scssindex 0e341b26ea3..b51cc8ff23d 100644--- a/plugins/checklist/assets/stylesheets/checklist.scss+++ b/plugins/checklist/assets/stylesheets/checklist.scss@@ -2,18 +2,6 @@ span.chcklst-stroked {text-decoration: line-through;}-@keyframes checklist-pending-pulse {- from {- background-color: var(--primary-low);- box-shadow: 0 0 0 0.09em var(--primary-low);- }-- to {- background-color: var(--primary-very-low);- box-shadow: 0 0 0 0.09em var(--primary-very-low);- }-}-@mixin checklist-svg-icon($svg) {&::before {background-color: var(--primary);@@ -39,7 +27,8 @@ span.chcklst-box {touch-action: manipulation;&.is-pending {- animation: checklist-pending-pulse 950ms ease-in-out infinite alternate;+ background-color: var(--primary-low);+ box-shadow: 0 0 0 0.09em var(--primary-low);}&:focus-visible {@@ -86,14 +75,6 @@ span.chcklst-box {}}-@media (prefers-reduced-motion: reduce) {- span.chcklst-box.is-interactive.is-pending {- animation: none;- background-color: var(--primary-low);- box-shadow: 0 0 0 0.09em var(--primary-low);- }-}-ul li.has-checkbox {list-style-type: none;diff --git a/plugins/checklist/spec/system/page_objects/components/cooked_checklist.rb b/plugins/checklist/spec/system/page_objects/components/cooked_checklist.rbnew file mode 100644index 00000000000..91e50c26022--- /dev/null+++ b/plugins/checklist/spec/system/page_objects/components/cooked_checklist.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class CookedChecklist < PageObjects::Components::Base+ CHECKBOX_SELECTOR = ".cooked .chcklst-box"++ def click_checkbox+ find(CHECKBOX_SELECTOR).click+ self+ end++ def has_saved_checked?+ has_css?("#{CHECKBOX_SELECTOR}.checked:not([aria-busy])")+ end+ end+ end+enddiff --git a/plugins/checklist/spec/system/toggle_checkbox_spec.rb b/plugins/checklist/spec/system/toggle_checkbox_spec.rbindex 9fd1a809b43..67b0d4a6274 100644--- a/plugins/checklist/spec/system/toggle_checkbox_spec.rb+++ b/plugins/checklist/spec/system/toggle_checkbox_spec.rb@@ -5,6 +5,8 @@ RSpec.describe "Checklist toggles" dofab!(:topic) { Fabricate(:topic, user:) }fab!(:post) { Fabricate(:post, topic:, user:, raw: "- [ ] first") }+ let(:checklist) { PageObjects::Components::CookedChecklist.new }+before doSiteSetting.checklist_enabled = truesign_in(user)@@ -13,10 +15,12 @@ RSpec.describe "Checklist toggles" doit "hydrates raw and toggles a checklist from the topic stream" dopage.visit "/t/#{topic.slug}/#{topic.id}"- find(".chcklst-box").click+ checklist.click_checkbox++ expect(checklist).to have_saved_checked++ page.refresh- expect(page).to have_css(".chcklst-box.checked")- expect(page).to have_no_css(".chcklst-box.is-saving")- expect(post.reload.raw).to eq("- [x] first")+ expect(checklist).to have_saved_checkedendenddiff --git a/plugins/checklist/test/javascripts/lib/checklist-test.js b/plugins/checklist/test/javascripts/lib/checklist-test.jsindex 85c4ee3e5f4..1f05bb3c319 100644--- a/plugins/checklist/test/javascripts/lib/checklist-test.js+++ b/plugins/checklist/test/javascripts/lib/checklist-test.js@@ -10,7 +10,10 @@ import { consumeOptimisticPostUpdate } from "discourse/lib/optimistic-post-updatimport { cook } from "discourse/lib/text";import Post from "discourse/models/post";import { acceptance } from "discourse/tests/helpers/qunit-helpers";-import { checklistSyntax } from "discourse/plugins/checklist/discourse/initializers/checklist";+import {+ activeChecklistOperationCountForTesting,+ checklistSyntax,+} from "discourse/plugins/checklist/discourse/initializers/checklist";let decoratorCleanup;let decoratedElement;@@ -18,6 +21,7 @@ let failHeldRequest;let holdHydration;let holdRequest;let hydrationRequests;+let hydrationResponse;let initialRaw;let postModel;let releaseHydration;@@ -28,6 +32,7 @@ let respondWithError;let responseRevised;let responseSequence;let responseUpdatedAts;+let responseCookeds;function applyToggleToRaw(raw, toggle) {if (toggle.checkbox_source) {@@ -74,6 +79,10 @@ async function decorate(raw, { legacy = false } = {}) {discourse_local_dates_enabled: true,},});+ return decorateCooked(cooked.toString(), { legacy });+}++function decorateCooked(cooked, { legacy = false } = {}) {const decoratorHelper = { getModel: () => postModel };decoratedElement = document.createElement("div");decoratedElement.innerHTML = cooked.toString();@@ -117,8 +126,9 @@ acceptance("checklist", function (needs) {hydrationRequests += 1;const response = helper.response({id: 42,- raw: initialRaw,- updated_at: "2026-08-27T08:00:00.000Z",+ raw: hydrationResponse?.raw ?? initialRaw,+ cooked: hydrationResponse?.cooked,+ updated_at: hydrationResponse?.updatedAt ?? "2026-08-27T08:00:00.000Z",});if (holdHydration) {return new Promise((resolve) => {@@ -145,8 +155,12 @@ acceptance("checklist", function (needs) {});}+ if (respondWithError === "network") {+ request.onerror();+ return helper.response(0, {});+ }if (respondWithError) {- return helper.response(respondWithError === "network" ? 0 : 422, {});+ return helper.response(422, {});}const updatedAt = nextUpdatedAt();@@ -155,7 +169,8 @@ acceptance("checklist", function (needs) {body.expected_raw);const response = {- cooked: `authoritative cooked ${responseSequence}`,+ cooked:+ responseCookeds.shift() ?? `authoritative cooked ${responseSequence}`,last_editor_id: 1,raw,revised: responseRevised,@@ -188,6 +203,7 @@ acceptance("checklist", function (needs) {holdHydration = false;holdRequest = false;hydrationRequests = 0;+ hydrationResponse = null;initialRaw = null;postModel = null;releaseHydration = null;@@ -198,15 +214,219 @@ acceptance("checklist", function (needs) {responseRevised = true;responseSequence = 0;responseUpdatedAts = [];+ responseCookeds = [];});- needs.hooks.afterEach(function () {+ needs.hooks.afterEach(async function (assert) {decoratorCleanup?.();releaseHydration?.();releaseRequest?.();+ await settled();+ assert.strictEqual(+ activeChecklistOperationCountForTesting(),+ 0,+ "no coordinator survives test teardown"+ );document.querySelector("#ember-testing").innerHTML = "";});+ test("adopts pending state after raw-less hydration completes", async function (assert) {+ holdRequest = true;+ const [first, second] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });+ first.click();+ await waitUntil(() => releaseRequest);+ second.click();+ decoratorCleanup();+ decoratedElement.remove();+ const [replacementFirst, replacementSecond] = decorateCooked(+ postModel.cooked+ );+ assert+ .dom(replacementFirst)+ .hasClass("checked", "in-flight state is adopted after hydration");+ assert+ .dom(replacementSecond)+ .hasClass("checked", "the second click is retained");+ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await settled();+ assert.strictEqual(+ postModel.raw,+ "[x] first\n[x] second",+ "both changes persist"+ );+ });++ test("a late raw-less rendering joins the hydrated queue", async function (assert) {+ holdRequest = true;+ const [first] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });+ const firstCleanup = decoratorCleanup;+ const [, second] = await decorate("[ ] first\n[ ] second");+ first.click();+ await waitUntil(() => releaseRequest);+ second.click();+ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await settled();+ firstCleanup();+ assert.strictEqual(+ postModel.raw,+ "[x] first\n[x] second",+ "the late rendering shares validated hydration"+ );+ });++ test("an idle raw-less rendering revalidates after the coordinator retires", async function (assert) {+ const [first] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });+ const firstCleanup = decoratorCleanup;+ const [, second] = await decorate("[ ] first\n[ ] second");+ await click(first);+ hydrationResponse = {+ raw: postModel.raw,+ cooked: (await cook(postModel.raw)).toString(),+ updatedAt: postModel.updated_at,+ };+ await click(second);+ firstCleanup();+ assert.strictEqual(+ postModel.raw,+ "[x] first\n[x] second",+ "old cooked is validated before reusing its coordinates"+ );+ });++ test("hydration merges colliding generations without losing presentations", async function (assert) {+ holdHydration = true;+ const [first] = await prepare("[ ] first", { includeRaw: false });+ const firstCleanup = decoratorCleanup;+ first.click();+ await waitUntil(() => releaseHydration);+ postModel.raw = "[ ] first";+ const [replacement] = await decorate("[ ] first");+ replacement.click();+ replacement.click();+ holdHydration = false;+ releaseHydration();+ releaseHydration = null;+ await settled();+ firstCleanup();+ assert.strictEqual(+ postModel.raw,+ "[ ] first",+ "the newer desired state wins on generation merge"+ );+ assert+ .dom(replacement)+ .doesNotHaveAttribute("aria-busy", "the newer rendering settles");+ });++ test("a failed hydrated generation merge does not resend the rejected change", async function (assert) {+ holdHydration = true;+ respondWithError = true;+ const [first] = await prepare("[ ] first", { includeRaw: false });+ const firstCleanup = decoratorCleanup;+ first.click();+ await waitUntil(() => releaseHydration);+ postModel.raw = "[ ] first";+ const [replacement] = await decorate("[ ] first");+ replacement.click();+ holdHydration = false;+ releaseHydration();+ releaseHydration = null;+ await settled();+ firstCleanup();++ assert.strictEqual(+ requests.length,+ 1,+ "a non-retryable failure is not sent twice"+ );+ assert+ .dom(replacement)+ .doesNotHaveAttribute("aria-busy", "the merged rendering settles");+ assert+ .dom(replacement)+ .doesNotHaveClass("checked", "the rejected change is reverted");+ });++ test("uncertain baseline survives cooked replacement without deleting raw", async function (assert) {+ respondWithError = "network";+ const [first] = await prepare("[ ] first");+ await click(first);+ decoratorCleanup();+ decoratedElement.remove();+ const [replacement] = decorateCooked(postModel.cooked);+ respondWithError = false;+ await click(replacement);+ assert.strictEqual(+ hydrationRequests,+ 1,+ "the replacement revalidates the uncertain model baseline"+ );+ assert.strictEqual(postModel.raw, "[x] first", "recovered work is saved");+ });++ test("limits coalesced requests to the server batch size", async function (assert) {+ const boxes = await prepare(+ Array.from({ length: 51 }, (_, i) => `[ ] task ${i}`).join("\n")+ );+ boxes.forEach((box) => box.click());+ await settled();+ assert.deepEqual(+ requests.map(({ toggles }) => toggles.length),+ [50, 1],+ "oversized work is split into serialized batches"+ );+ assert.true(+ postModel.raw.split("\n").every((line) => line.startsWith("[x]")),+ "all changes persist"+ );+ });++ test("network failure preserves raw while requiring a fresh baseline", async function (assert) {+ respondWithError = "network";+ const [checkbox] = await prepare("[ ] first");+ await click(checkbox);+ assert.strictEqual(+ postModel.raw,+ "[ ] first",+ "transport failure does not erase shared model data"+ );+ respondWithError = false;+ await click(checkbox);+ assert.strictEqual(+ hydrationRequests,+ 1,+ "a later operation revalidates the uncertain baseline"+ );+ });++ test("retires the coordinator after its work drains", async function (assert) {+ const [checkbox] = await prepare("[ ] first");++ checkbox.click();++ assert.strictEqual(+ activeChecklistOperationCountForTesting(),+ 1,+ "the active post has one coordinator"+ );+ await settled();+ assert.strictEqual(+ activeChecklistOperationCountForTesting(),+ 0,+ "the idle post retains no coordinator"+ );+ });+test("sends the direct source location without a redundant count", async function (assert) {const boxes = await prepare(`\`[x]\`@@ -359,7 +579,28 @@ Actual checkboxes:);});- test("preserves intent when a raw-less post rebinds during hydration", async function (assert) {+ test("rejects raw-less work when hydration finds a structural change", async function (assert) {+ hydrationResponse = {+ raw: "[ ] second\n[ ] first",+ updatedAt: "2026-08-27T08:00:01.000Z",+ };+ const [checkbox] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });++ await click(checkbox);++ assert.strictEqual(hydrationRequests, 1, "the current raw is fetched once");+ assert.strictEqual(requests.length, 0, "no stale target is submitted");+ assert+ .dom(checkbox)+ .doesNotHaveClass("checked", "the optimistic state is reverted");+ assert+ .dom(checkbox)+ .doesNotHaveAttribute("aria-busy", "the stale control is no longer busy");+ });++ test("continues a raw-less operation across teardown", async function (assert) {holdHydration = true;const [first, second] = await prepare("[ ] first\n[ ] second", {includeRaw: false,@@ -379,13 +620,16 @@ Actual checkboxes:assert.dom(firstReplacement)- .doesNotHaveClass("checked", "the latest first intent survives");+ .doesNotHaveClass("checked", "the latest first state is adopted");+ assert+ .dom(firstReplacement)+ .hasClass("is-pending", "the latest first state remains pending");assert.dom(secondReplacement)- .hasClass("checked", "the queued second intent survives");+ .hasClass("checked", "the queued second state is adopted");assert.dom(secondReplacement)- .hasClass("is-pending", "the replacement remains pending");+ .hasClass("is-pending", "the queued second state remains pending");holdHydration = false;releaseHydration();@@ -400,7 +644,7 @@ Actual checkboxes:);});- test("discards reordered raw-less sourced intent", async function (assert) {+ test("keeps accepted raw-less work independent of another rendering", async function (assert) {holdHydration = true;const [first] = await prepare("[ ] first\n[ ] second", {includeRaw: false,@@ -415,43 +659,10 @@ Actual checkboxes:assert.dom(replacement)- .doesNotHaveClass("checked", "intent does not move to another item");+ .doesNotHaveClass("checked", "the replacement uses its rendered state");assert.dom(replacement)- .doesNotHaveClass("is-pending", "unverifiable intent is discarded");-- holdHydration = false;- releaseHydration();- releaseHydration = null;- await settled();-- assert.strictEqual(requests.length, 0, "no stale source is submitted");- });-- test("discards unverifiable legacy intent during raw-less rebind", async function (assert) {- holdHydration = true;- const [checkbox] = await prepare("[ ] first", {- includeRaw: false,- legacyCooked: true,- });-- checkbox.click();- await waitUntil(() => releaseHydration);-- decoratorCleanup();- decoratorCleanup = null;- decoratedElement.remove();- const [replacement] = await decorate("[ ] first");-- assert- .dom(replacement)- .doesNotHaveClass(- "checked",- "unverifiable legacy intent is not migrated"- );- assert- .dom(replacement)- .doesNotHaveClass("is-pending", "unverifiable legacy work is discarded");+ .doesNotHaveClass("is-pending", "the replacement has no pending work");holdHydration = false;releaseHydration();@@ -460,8 +671,13 @@ Actual checkboxes:assert.strictEqual(requests.length,- 0,- "no positional legacy request is sent"+ 1,+ "the accepted operation is submitted"+ );+ assert.strictEqual(+ requests[0].toggles[0].checkbox_source,+ "0:0",+ "the operation retains its original target");});@@ -509,7 +725,7 @@ Actual checkboxes:);});- test("preserves legacy intent when sourced cooked replaces it", async function (assert) {+ test("continues a legacy operation when sourced cooked appears", async function (assert) {holdRequest = true;const [checkbox] = await prepare("[ ] first", { legacyCooked: true });@@ -523,22 +739,20 @@ Actual checkboxes:assert.dom(replacement)- .hasClass("checked", "legacy intent migrates to the sourced checkbox");+ .doesNotHaveClass("checked", "the new rendering uses cooked state");assert.dom(replacement)- .hasClass("is-pending", "the migrated checkbox remains pending");+ .doesNotHaveClass("is-pending", "pending UI is not transferred");releaseRequest();releaseRequest = null;await settled();- assert- .dom(replacement)- .hasClass("checked", "the migrated intent remains after persistence");- await waitUntil(() => !replacement.classList.contains("is-pending"));- assert- .dom(replacement)- .doesNotHaveClass("is-pending", "the migrated pulse clears normally");+ assert.strictEqual(+ postModel.raw,+ "[x] first",+ "the accepted legacy operation is persisted"+ );});test("does not migrate legacy intent across a structural edit", async function (assert) {@@ -611,6 +825,28 @@ Actual checkboxes:assert.strictEqual(requests.length, 0, "no invalid baseline is submitted");});+ test("rejects a stale rendering after the post structure changes", async function (assert) {+ const [oldFirst] = await prepare("[ ] first\n[ ] second");+ postModel.raw = "[ ] second\n[ ] first";+ postModel.updated_at = "2026-08-27T08:00:01.000Z";++ await click(oldFirst);++ assert.strictEqual(requests.length, 0, "no stale target is submitted");+ assert+ .dom(oldFirst)+ .doesNotHaveClass("checked", "the stale optimistic state is reverted");+ assert+ .dom(oldFirst)+ .doesNotHaveClass("is-interactive", "the stale control is deactivated");+ assert+ .dom(oldFirst)+ .hasAttribute("aria-readonly", "true", "the stale state is communicated");+ assert+ .dom(oldFirst)+ .doesNotHaveAttribute("tabindex", "the stale control leaves tab order");+ });+test("does not rebase sourced intent across a structural edit", async function (assert) {holdRequest = true;const [first] = await prepare("[ ] first\n[ ] second");@@ -691,7 +927,7 @@ Actual checkboxes:);});- test("shows a pulse on only the pending checkbox", async function (assert) {+ test("shows pending state on only the changed checkbox", async function (assert) {holdRequest = true;const [first, second] = await prepare("[ ] first [x] second");const initialWidth = first.getBoundingClientRect().width;@@ -718,7 +954,7 @@ Actual checkboxes:);assert.dom(first)- .hasClass("is-pending", "the pending checkbox gets the pulse state");+ .hasClass("is-pending", "the changed checkbox gets the pending state");assert.dom(second).doesNotHaveClass(@@ -738,8 +974,8 @@ Actual checkboxes:);assert.strictEqual(getComputedStyle(first).animationName,- "checklist-pending-pulse",- "the neutral plate pulses behind the existing glyph"+ "none",+ "the pending treatment does not flash");assert.dom(".checklist-spinner")@@ -754,55 +990,12 @@ Actual checkboxes:await waitUntil(() => !first.classList.contains("is-pending"));assert.dom(first)- .doesNotHaveClass("is-pending", "the pulse clears after its minimum");+ .doesNotHaveClass("is-pending", "pending state clears after saving");assert.dom(first).hasClass("checked", "the optimistic state remains after saving");});- test("keeps a fast pulse visible without blocking another click", async function (assert) {- const [checkbox] = await prepare("[ ] first");-- checkbox.click();- await waitUntil(() => requests.length === 1);- await waitUntil(() => !checkbox.hasAttribute("aria-busy"));-- assert- .dom(checkbox)- .hasClass("is-pending", "a fast save retains its visual feedback");- assert- .dom(checkbox)- .doesNotHaveAttribute(- "aria-disabled",- "the minimum display time does not disable the checkbox"- );-- const secondClickAt = performance.now();- checkbox.click();- await waitUntil(() => requests.length === 2);- await waitUntil(() => !checkbox.hasAttribute("aria-busy"));-- assert- .dom(checkbox)- .doesNotHaveClass(- "checked",- "a click during the visual tail is accepted"- );- assert- .dom(checkbox)- .hasClass(- "is-pending",- "the new click restarts the minimum display time"- );-- await waitUntil(() => !checkbox.classList.contains("is-pending"));-- assert.true(- performance.now() - secondClickAt >= 190,- "the pulse remains visible for approximately 200ms after the latest click"- );- });-test("persists repeat activation while a request is pending", async function (assert) {holdRequest = true;const [checkbox] = await prepare("[ ] first");@@ -882,53 +1075,6 @@ Actual checkboxes:);});- test("preserves latest intent across an intermediate cooked replacement", async function (assert) {- holdRequest = true;- const [checkbox] = await prepare("[ ] first");-- checkbox.click();- await waitUntil(() => requests.length === 1);- checkbox.click();-- releaseRequest();- releaseRequest = null;- await waitUntil(() => requests.length === 2 && releaseRequest);- checkbox.click();-- decoratorCleanup();- decoratorCleanup = null;- decoratedElement.remove();- const [replacement] = await decorate("[ ] first");-- assert- .dom(replacement)- .hasClass("checked", "local intent overlays intermediate cooked content");- assert- .dom(replacement)- .hasClass("is-pending", "pending state survives cooked replacement");- assert- .dom(replacement)- .hasAttribute("aria-busy", "true", "the replacement remains busy");-- holdRequest = false;- releaseRequest();- releaseRequest = null;- await waitUntil(() => requests.length === 3);- await settled();-- assert.deepEqual(- requests.map((request) => request.toggles[0].checked),- [true, false, true],- "the latest state is persisted after replacement"- );- assert- .dom(replacement)- .hasClass("checked", "the replacement never regresses visually");- assert- .dom(replacement)- .doesNotHaveAttribute("aria-busy", "the final save clears busy state");- });-test("preserves ABA intent after the original request fails", async function (assert) {holdRequest = true;const [checkbox] = await prepare("[ ] first");@@ -1032,6 +1178,43 @@ Actual checkboxes:);});+ test("coalesces a rapid sequence before sending", async function (assert) {+ const boxes = await prepare(+ "[ ] first\n[ ] second\n[ ] third\n[ ] fourth\n[ ] fifth\n[ ] sixth"+ );++ boxes.forEach((box) => box.click());+ await settled();++ assert.strictEqual(requests.length, 1, "the sequence sends one request");+ assert.deepEqual(+ requests[0].toggles.map(({ checkbox_index }) => checkbox_index),+ [0, 1, 2, 3, 4, 5],+ "all six changes share the request"+ );+ boxes.forEach((box) =>+ assert.dom(box).hasClass("checked", "each change remains visible")+ );+ });++ test("drops a coalesced change that returns to its confirmed state", async function (assert) {+ const [checkbox] = await prepare("[ ] first");++ checkbox.click();+ checkbox.click();+ await settled();++ assert.strictEqual(requests.length, 0, "no redundant request is sent");+ assert.strictEqual(+ activeChecklistOperationCountForTesting(),+ 0,+ "the empty coordinator retires immediately"+ );+ assert+ .dom(checkbox)+ .doesNotHaveClass("checked", "the confirmed state remains visible");+ });+test("waits for the active request before sending another checkbox", async function (assert) {holdRequest = true;const [first, second, third] = await prepare(@@ -1069,7 +1252,7 @@ Actual checkboxes:request.toggles.map((toggle) => toggle.checkbox_index)),[[0], [1, 2]],- "the first change is immediate and the backlog is one batch"+ "the in-flight change finishes before the batched backlog");assert.strictEqual(requests[1].expected_raw,@@ -1083,6 +1266,53 @@ Actual checkboxes:);});+ test("preserves queued state across an intermediate cooked replacement", async function (assert) {+ holdRequest = true;+ const [first, second] = await prepare("[ ] first\n[ ] second");++ responseCookeds = [(await cook("[x] first\n[ ] second")).toString()];++ first.click();+ await waitUntil(() => releaseRequest);+ second.click();++ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2 && releaseRequest);++ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacementFirst, replacementSecond] = decorateCooked(+ postModel.cooked+ );++ assert+ .dom(replacementFirst)+ .hasClass("checked", "the saved state comes from intermediate cooked");+ assert+ .dom(replacementSecond)+ .hasClass("checked", "the queued state overlays intermediate cooked");+ assert+ .dom(replacementSecond)+ .hasClass("is-pending", "the replacement adopts pending presentation");+ assert+ .dom(replacementSecond)+ .hasAttribute("aria-busy", "true", "the replacement remains busy");++ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await settled();++ assert+ .dom(replacementSecond)+ .hasClass("checked", "the queued state remains after persistence");+ assert+ .dom(replacementSecond)+ .doesNotHaveClass("is-pending", "the pending state clears after saving");+ });+test("continues queued work after the decorated content is destroyed", async function (assert) {holdRequest = true;const [first, second] = await prepare("[ ] first\n[ ] second");@@ -1106,15 +1336,14 @@ Actual checkboxes:holdRequest = false;releaseRequest();releaseRequest = null;- await waitUntil(() => requests.length === 2);await settled();assert.deepEqual(requests.map((request) =>request.toggles.map((toggle) => toggle.checkbox_index)),- [[0], [1]],- "detached controls do not discard queued changes"+ [[0, 1]],+ "detached controls do not discard the coalesced changes");assert.strictEqual(postModel.raw,@@ -1123,7 +1352,7 @@ Actual checkboxes:);assert.strictEqual(postModel.cooked,- "authoritative cooked 2",+ "authoritative cooked 1","the detached model receives the final cooked content");});@@ -1198,7 +1427,7 @@ Actual checkboxes:first.click();second.click();third.click();- await waitUntil(() => requests.length === 3);+ await waitUntil(() => requests.length === 2);await waitUntil(() =>[first, second, third].every((checkbox) => !checkbox.classList.contains("is-pending")@@ -1209,8 +1438,11 @@ Actual checkboxes:requests.map((request) =>request.toggles.map((toggle) => toggle.checkbox_index)),- [[0], [0], [1, 2]],- "the failed batch is retried before the accumulated backlog"+ [+ [0, 1, 2],+ [0, 1, 2],+ ],+ "the coalesced batch is retried together");assert.strictEqual(requests[1].expected_raw,@@ -1230,8 +1462,8 @@ Actual checkboxes:assert.dom(first).hasClass("checked", "the retried optimistic state is retained");- assert.dom(second).hasClass("checked", "the backlog is retained");- assert.dom(third).hasClass("checked", "the backlog remains batched");+ assert.dom(second).hasClass("checked", "the coalesced state is retained");+ assert.dom(third).hasClass("checked", "the coalesced state is retained");assert.dom(first).doesNotHaveAttribute(@@ -1254,7 +1486,7 @@ Actual checkboxes:.doesNotHaveAttribute("aria-busy", "pending state is cleared");});- test("recovers after a network error invalidates raw", async function (assert) {+ test("recovers after a network error makes the baseline uncertain", async function (assert) {respondWithError = "network";const [checkbox] = await prepare("[ ] first");@@ -1293,6 +1525,17 @@ Actual checkboxes:.dom(checkbox).hasAttribute("aria-label", "Buy milk", "the task labels the control");+ checkbox.dispatchEvent(+ new KeyboardEvent("keydown", {+ bubbles: true,+ cancelable: true,+ key: " ",+ repeat: true,+ })+ );+ assert.dom(checkbox).doesNotHaveClass("checked", "key repeat is ignored");+ assert.strictEqual(requests.length, 0, "key repeat schedules no save");+await triggerKeyEvent(checkbox, "keydown", " ");assert.dom(checkbox)@@ -1305,8 +1548,10 @@ Actual checkboxes:.hasAttribute("aria-checked", "false", "Enter unchecks the item");});- test("redecorating the same controls does not duplicate listeners", async function (assert) {+ test("redecorating cleaned controls does not duplicate listeners", async function (assert) {const [checkbox] = await prepare("[ ] first");+ decoratorCleanup();+ decoratorCleanup = null;const replacementCleanup = checklistSyntax(decoratedElement, {getModel: () => postModel,});@@ -1319,6 +1564,119 @@ Actual checkboxes:replacementCleanup();});+ test("keeps simultaneous renderings independently interactive", async function (assert) {+ const [firstCheckbox] = await prepare("[ ] first");+ const secondElement = document.createElement("div");+ secondElement.innerHTML = postModel.cooked;+ const secondCleanup = checklistSyntax(secondElement, {+ getModel: () => postModel,+ });+ document.querySelector("#ember-testing").append(secondElement);++ await click(firstCheckbox);++ assert.strictEqual(+ requests.length,+ 1,+ "decorating another rendering does not disable the first"+ );++ secondCleanup();+ });++ test("coalesces simultaneous renderings through one coordinator", async function (assert) {+ const [firstCheckbox] = await prepare("[ ] first\n[ ] second");+ const secondElement = document.createElement("div");+ secondElement.innerHTML = postModel.cooked;+ const secondCleanup = checklistSyntax(secondElement, {+ getModel: () => postModel,+ });+ const secondCheckbox = secondElement.querySelectorAll(".chcklst-box")[1];+ document.querySelector("#ember-testing").append(secondElement);++ firstCheckbox.click();+ secondCheckbox.click();+ await settled();++ assert.strictEqual(requests.length, 1, "one coalesced request is sent");+ assert.deepEqual(+ requests[0].toggles.map(({ checkbox_index }) => checkbox_index),+ [0, 1],+ "changes from both renderings share one batch"+ );+ assert.strictEqual(+ postModel.raw,+ "[x] first\n[x] second",+ "both render-local changes are persisted"+ );++ secondCleanup();+ });++ test("serializes later changes from simultaneous renderings", async function (assert) {+ holdRequest = true;+ const [firstCheckbox] = await prepare("[ ] first\n[ ] second");+ const secondElement = document.createElement("div");+ secondElement.innerHTML = postModel.cooked;+ const secondCleanup = checklistSyntax(secondElement, {+ getModel: () => postModel,+ });+ const secondCheckbox = secondElement.querySelectorAll(".chcklst-box")[1];+ document.querySelector("#ember-testing").append(secondElement);++ firstCheckbox.click();+ await waitUntil(() => requests.length === 1);+ secondCheckbox.click();++ assert.strictEqual(+ requests.length,+ 1,+ "the second rendering waits for the active request"+ );++ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);+ await settled();++ assert.strictEqual(+ requests[1].expected_raw,+ "[x] first\n[ ] second",+ "the second rendering uses the coordinated baseline"+ );+ assert.strictEqual(+ postModel.raw,+ "[x] first\n[x] second",+ "both serialized changes are persisted"+ );++ secondCleanup();+ });++ test("cleans up simultaneous renderings independently", async function (assert) {+ await prepare("[ ] first");+ const secondElement = document.createElement("div");+ secondElement.innerHTML = postModel.cooked;+ const secondCleanup = checklistSyntax(secondElement, {+ getModel: () => postModel,+ });+ const secondCheckbox = secondElement.querySelector(".chcklst-box");+ document.querySelector("#ember-testing").append(secondElement);++ decoratorCleanup();+ decoratorCleanup = null;+ await click(secondCheckbox);++ assert.strictEqual(+ requests.length,+ 1,+ "cleaning one rendering leaves the other interactive"+ );++ secondCleanup();+ });+test("labels multiple controls from their own task text", async function (assert) {const [first, second] = await prepare("[ ] Buy milk [ ] Wash car");