A platform for community discussion. Free, open, simple.
FIX: Preserve checklist toggles across rerenders (#43065)
Sam2e354ebdce01
diff --git a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.jsindex fc80d73328c..f906d38b876 100644--- a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js+++ b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js@@ -1,15 +1,23 @@-import { schedule } from "@ember/runloop";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";-import { iconHTML } from "discourse/lib/icon-library";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_SPINNER_DURATION = 200;+const MINIMUM_PENDING_DURATION = 200;const MAX_CONFLICT_RETRIES = 2;+function timestampsAreEqual(first, second) {+ const firstTime = Date.parse(first);+ const secondTime = Date.parse(second);+ return (+ !Number.isNaN(firstTime) &&+ !Number.isNaN(secondTime) &&+ firstTime === secondTime+ );+}+function timestampIsOlder(candidate, reference) {const candidateTime = Date.parse(candidate);const referenceTime = Date.parse(reference);@@ -134,298 +142,576 @@ function configureAccessibility(box, editable) {}}-function addToggleBehavior(boxes, postModel, allBoxes = boxes) {- const renderedIndexes = new Map(allBoxes.map((box, index) => [box, index]));- const confirmedStates = boxes.map((box) => box.classList.contains("checked"));- const pendingStates = new Map();- const spinnerStates = new Map();- const cleanups = [];- let expectedRaw = postModel.raw;- let expectedUpdatedAt = postModel.updated_at;- let active = true;- let deferredCooked;- let saving = false;- let unregisterInFlightOptimisticUpdate;-- const stopSpinner = (index) => {- clearTimeout(spinnerStates.get(index)?.timer);- spinnerStates.delete(index);- boxes[index].classList.remove("is-saving");- boxes[index].removeAttribute("aria-disabled");+const checklistStates = new WeakMap();++function checkboxKey(renderedIndex, checkboxCount) {+ return `${renderedIndex}:${checkboxCount}`;+}++function checkboxTarget(box, renderedIndex, checkboxCount) {+ return {+ checkboxCount: box.dataset.chkSrc ? undefined : checkboxCount,+ checkboxSource: box.dataset.chkSrc,+ renderedIndex,};+}- const updateBusyState = (index, busy) => {- const box = boxes[index];+function checklistBindingSignature(boxes) {+ return boxes+ .filter((box) => !box.classList.contains("permanent"))+ .map((box) => `${box.dataset.chkSrc ?? "legacy"}:${checkboxLabel(box)}`)+ .join("\0");+}- if (busy) {- clearTimeout(spinnerStates.get(index)?.timer);- if (!box.querySelector(".checklist-spinner")) {- box.insertAdjacentHTML(- "beforeend",- iconHTML("spinner", { class: "checklist-spinner" })- );- }- spinnerStates.set(index, { startedAt: performance.now() });- box.classList.add("is-saving");- box.setAttribute("aria-busy", "true");- box.setAttribute("aria-disabled", "true");+function checklistFingerprint(raw, checkboxSources, includesLegacy) {+ if (typeof raw !== "string") {+ return;+ }++ if (includesLegacy) {+ return raw.replace(/\[(?: |x)?\]/g, "[ ]");+ }++ const sourcesByLine = new Map();+ checkboxSources.forEach((source) => {+ const [line, nth] = source.split(":").map(Number);+ if (!sourcesByLine.has(line)) {+ sourcesByLine.set(line, new Set());+ }+ sourcesByLine.get(line).add(nth);+ });++ const lines = raw.split("\n");+ let valid = true;+ sourcesByLine.forEach((indexes, lineNumber) => {+ if (lines[lineNumber] === undefined) {+ valid = false;return;}- box.removeAttribute("aria-busy");- const spinnerState = spinnerStates.get(index);- if (!spinnerState) {- box.classList.remove("is-saving");+ let markerIndex = -1;+ lines[lineNumber] = lines[lineNumber].replace(/\[[ xX]?\]/g, (marker) => {+ markerIndex += 1;+ return indexes.has(markerIndex) ? "[ ]" : marker;+ });+ if ([...indexes].some((index) => index > markerIndex)) {+ valid = false;+ }+ });+ 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;++ constructor(postModel) {+ this.#postModel = postModel;+ this.#baselineRaw = postModel.raw;+ this.#baselineUpdatedAt = postModel.updated_at;+ }++ bind(boxes, allBoxes = boxes) {+ this.#binding?.cleanup();++ 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+ );++ if (+ (this.#fingerprint !== undefined &&+ fingerprint !== undefined &&+ this.#fingerprint !== fingerprint) ||+ (this.#intents.size > 0 &&+ fingerprint === undefined &&+ this.#bindingSignature !== undefined &&+ this.#bindingSignature !== bindingSignature)+ ) {+ this.#discardIntents();+ }++ this.#bindingSignature = bindingSignature;+ this.#checkboxSources = checkboxSources;+ this.#includesLegacy = includesLegacy;+ if (fingerprint !== undefined || this.#intents.size === 0) {+ this.#fingerprint = fingerprint;+ }++ 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;+ }++ const binding = {+ cleaned: false,+ cleanup: undefined,+ cleanups: [],+ controls: new Map(),+ };++ boxes.forEach((box) => {+ if (box.classList.contains("permanent")) {+ return;+ }++ 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;+ }++ event.preventDefault();+ toggle();+ };++ box.addEventListener("click", onClick);+ box.addEventListener("keydown", onKeyDown);+ binding.cleanups.push(() => {+ box.removeEventListener("click", onClick);+ box.removeEventListener("keydown", onKeyDown);+ });+ });++ for (const key of this.#intents.keys()) {+ if (!binding.controls.has(key)) {+ this.#discardIntent(key);+ }+ }++ this.#binding = binding;+ binding.controls.forEach((box, key) => this.#syncControl(key, box));++ binding.cleanup = () => {+ if (binding.cleaned) {+ return;+ }++ binding.cleaned = true;+ binding.cleanups.forEach((cleanup) => cleanup());+ binding.controls.forEach((box) => {+ box.classList.remove("is-pending");+ box.removeAttribute("aria-busy");+ });+ if (this.#binding === binding) {+ this.#binding = undefined;+ }+ };+ return binding.cleanup;+ }++ #applyBaseline(raw, updatedAt) {+ this.#baselineRaw = raw;+ this.#baselineUpdatedAt = updatedAt;+ }++ #clearIndicator(key, indicator = this.#indicators.get(key)) {+ if (!indicator || this.#indicators.get(key) !== indicator) {return;}- clearTimeout(spinnerState.timer);- const elapsed = performance.now() - spinnerState.startedAt;- const remaining = Math.max(0, MINIMUM_SPINNER_DURATION - elapsed);+ clearTimeout(indicator.timer);+ this.#indicators.delete(key);+ const box = this.#binding?.controls.get(key);+ box?.classList.remove("is-pending");+ box?.removeAttribute("aria-busy");+ }++ #completeBatch(entries) {+ entries.forEach(([key, saved]) => {+ const current = this.#intents.get(key);+ if (!current) {+ return;+ }++ if (+ current.checked === saved.checked &&+ current.fingerprint === saved.fingerprint+ ) {+ this.#intents.delete(key);+ this.#finishIndicator(key);+ } else {+ current.confirmed = 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);+ }++ #discardIntents() {+ const keys = [...this.#intents.keys()];+ this.#intents.clear();+ keys.forEach((key) => this.#clearIndicator(key));+ }++ #failBatch(entries) {+ entries.forEach(([key, failed]) => {+ const current = this.#intents.get(key);+ if (current?.revision !== failed.revision) {+ return;+ }++ this.#intents.delete(key);+ const box = this.#binding?.controls.get(key);+ if (box) {+ setCheckboxState(box, failed.confirmed);+ }+ this.#finishIndicator(key);+ });+ }++ #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)+ );if (remaining === 0) {- stopSpinner(index);+ this.#clearIndicator(key, indicator);} else {- spinnerState.timer = setTimeout(() => stopSpinner(index), remaining);+ indicator.timer = setTimeout(+ () => this.#clearIndicator(key, indicator),+ remaining+ );}- };+ }- const restoreConfirmedStates = () => {- boxes.forEach((box, index) => {- setCheckboxState(box, confirmedStates[index]);- updateBusyState(index, false);- });- };+ #fingerprintFor(raw) {+ return checklistFingerprint(+ raw,+ this.#checkboxSources,+ this.#includesLegacy+ );+ }- const savePendingStates = async () => {- if (saving) {- return;+ #freshestBaseline(raw, updatedAt) {+ if (+ this.#postModel.raw != null &&+ (timestampIsOlder(updatedAt, this.#postModel.updated_at) ||+ (timestampsAreEqual(updatedAt, this.#postModel.updated_at) &&+ raw !== this.#postModel.raw))+ ) {+ return {+ raw: this.#postModel.raw,+ updatedAt: this.#postModel.updated_at,+ };+ }++ return { raw, updatedAt };+ }++ #refreshPost(reportError = false) {+ const refresh = this.#postModel.topic?.postStream?.refreshPost(+ this.#postModel.id+ );+ if (refresh) {+ void refresh.catch(reportError ? popupAjaxError : () => {});}+ }- saving = true;- let retryBatch;+ async #save() {+ if (this.#saving) {+ return;+ }+ this.#saving = true;try {- while (active && (retryBatch || pendingStates.size > 0)) {- const batch = retryBatch ?? {- states: [...pendingStates],- conflictRetries: 0,- };- retryBatch = undefined;- batch.states.forEach(([index, state]) => {- if (pendingStates.get(index) === state) {- pendingStates.delete(index);+ while (this.#intents.size > 0) {+ let entries = [...this.#intents].map(([key, intent]) => [+ key,+ { ...intent },+ ]);+ let retries = 0;++ while ((entries = this.#currentEntries(entries)).length > 0) {+ if (!(await this.#hydrate(entries))) {+ break;}- });-- if (expectedRaw == null) {- try {- const post = await ajax(`/posts/${postModel.id}`);- expectedRaw = post.raw;- expectedUpdatedAt = post.updated_at;- } catch (error) {- pendingStates.clear();- restoreConfirmedStates();- popupAjaxError(error);+ entries = this.#currentEntries(entries);+ if (entries.length === 0) {break;}- if (!active) {+ const fingerprint = entries[0][1].fingerprint;+ const baselineFingerprint = this.#fingerprintFor(this.#baselineRaw);+ if (+ fingerprint === undefined ||+ baselineFingerprint === undefined ||+ fingerprint !== baselineFingerprint+ ) {+ this.#failBatch(entries);+ entries.forEach(([key]) => this.#clearIndicator(key));+ this.#discardIntents();+ this.#refreshPost(true);break;}- }- const mutationId = crypto.randomUUID();- const {- startExpiration: startOptimisticUpdateExpiration,- unregister: unregisterOptimisticUpdate,- } = registerOptimisticPostUpdate(mutationId);- unregisterInFlightOptimisticUpdate = unregisterOptimisticUpdate;- const toggles = batch.states.map(([index, checked]) => {- const checkboxSource = boxes[index].dataset.chkSrc;- const toggle = {- checkbox_index: renderedIndexes.get(boxes[index]),- checkbox_source: checkboxSource,- checked,+ const mutationId = crypto.randomUUID();+ const {+ startExpiration: startOptimisticUpdateExpiration,+ unregister: unregisterOptimisticUpdate,+ } = registerOptimisticPostUpdate(mutationId);+ const data = {+ post_id: this.#postModel.id,+ toggles: entries.map(([, intent]) => {+ const toggle = {+ checkbox_index: intent.target.renderedIndex,+ checkbox_source: intent.target.checkboxSource,+ checked: intent.checked,+ };+ if (!intent.target.checkboxSource) {+ toggle.checkbox_count = intent.target.checkboxCount;+ }+ return toggle;+ }),+ expected_raw: this.#baselineRaw,+ expected_updated_at: this.#baselineUpdatedAt,+ mutation_id: mutationId,};- if (!checkboxSource) {- toggle.checkbox_count = allBoxes.length;- }- return toggle;- });- const data = {- post_id: postModel.id,- toggles,- expected_raw: expectedRaw,- expected_updated_at: expectedUpdatedAt,- mutation_id: mutationId,- };-- try {- const response = await ajax("/checklist/toggle", {- type: "PUT",- contentType: "application/json",- data: JSON.stringify(data),- });- const responseIsStale = timestampIsOlder(- response.updated_at,- postModel.updated_at- );- if (!responseIsStale) {- postModel.last_editor_id = response.last_editor_id;- postModel.updated_at = response.updated_at;- postModel.version = response.version;- }- if (response.revised) {- startOptimisticUpdateExpiration();- } else {- unregisterOptimisticUpdate();- }- unregisterInFlightOptimisticUpdate = undefined;-- if (!responseIsStale && (!active || pendingStates.size === 0)) {- postModel.raw = response.raw;- if (active) {- deferredCooked = {- cooked: response.cooked,- updatedAt: response.updated_at,- };+ try {+ const response = await ajax("/checklist/toggle", {+ type: "PUT",+ contentType: "application/json",+ data: JSON.stringify(data),+ });+ const stale =+ (Number.isFinite(response.version) &&+ Number.isFinite(this.#postModel.version) &&+ response.version < this.#postModel.version) ||+ timestampIsOlder(response.updated_at, this.#postModel.updated_at);++ if (response.revised) {+ startOptimisticUpdateExpiration();} else {- postModel.cooked = response.cooked;+ unregisterOptimisticUpdate();}- }- if (!active) {- break;- }+ if (stale) {+ if (response.raw === this.#postModel.raw) {+ this.#completeBatch(entries);+ this.#applyBaseline(+ this.#postModel.raw,+ this.#postModel.updated_at+ );+ break;+ }++ const baseline = this.#freshestBaseline(+ response.raw,+ response.updated_at+ );+ const canRetry =+ retries < MAX_CONFLICT_RETRIES &&+ this.#fingerprintFor(baseline.raw) === fingerprint;+ this.#applyBaseline(baseline.raw, baseline.updatedAt);+ if (canRetry) {+ retries += 1;+ continue;+ }- batch.states.forEach(([index, desiredState]) => {- confirmedStates[index] = desiredState;- if (pendingStates.get(index) === desiredState) {- pendingStates.delete(index);+ this.#failBatch(entries);+ this.#refreshPost();+ break;}- });- expectedRaw = response.raw;- expectedUpdatedAt = response.updated_at;- } catch (error) {- unregisterInFlightOptimisticUpdate = undefined;- unregisterOptimisticUpdate();-- if (!active) {- break;- }- const conflict = error.jqXHR?.responseJSON;- if (- error.jqXHR?.status === 409 &&- conflict?.retryable &&- conflict.raw &&- conflict.updated_at &&- batch.conflictRetries < MAX_CONFLICT_RETRIES- ) {- expectedRaw = conflict.raw;- expectedUpdatedAt = conflict.updated_at;- if (!timestampIsOlder(conflict.updated_at, postModel.updated_at)) {- postModel.updated_at = conflict.updated_at;+ if (this.#fingerprint !== fingerprint) {+ this.#applyBaseline(+ this.#postModel.raw,+ this.#postModel.updated_at+ );+ this.#refreshPost();+ break;}- retryBatch = {- states: batch.states,- conflictRetries: batch.conflictRetries + 1,- };- continue;- }- pendingStates.clear();- restoreConfirmedStates();- const postStream = postModel.topic?.postStream;- if (postStream) {- void postStream.refreshPost(postModel.id).catch(() => {});- }- popupAjaxError(error);- break;- } finally {- if (active) {- const retryingIndexes = new Set(- retryBatch?.states.map(([index]) => index)- );- for (const [index] of batch.states) {- if (!retryingIndexes.has(index) && !pendingStates.has(index)) {- updateBusyState(index, false);- }+ this.#postModel.last_editor_id = response.last_editor_id;+ this.#postModel.updated_at = response.updated_at;+ this.#postModel.version = response.version;+ 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;+ }+ break;+ } catch (error) {+ unregisterOptimisticUpdate();+ const conflict = error.jqXHR?.responseJSON;+ const baseline =+ conflict?.raw && conflict?.updated_at+ ? this.#freshestBaseline(conflict.raw, conflict.updated_at)+ : undefined;+ const canRetry =+ error.jqXHR?.status === 409 &&+ conflict?.retryable &&+ baseline &&+ retries < MAX_CONFLICT_RETRIES &&+ this.#fingerprintFor(baseline.raw) === entries[0][1].fingerprint;++ if (canRetry) {+ this.#applyBaseline(baseline.raw, baseline.updatedAt);+ retries += 1;+ continue;}++ this.#failBatch(entries);+ if (baseline) {+ this.#applyBaseline(baseline.raw, baseline.updatedAt);+ } else if (!error.jqXHR || error.jqXHR.status === 0) {+ this.#baselineRaw = undefined;+ } else if (this.#postModel.raw != null) {+ this.#applyBaseline(+ this.#postModel.raw,+ this.#postModel.updated_at+ );+ }+ this.#refreshPost();+ popupAjaxError(error);+ break;}}}} finally {- saving = false;+ this.#saving = false;}- };+ }- boxes.forEach((box, index) => {- if (box.classList.contains("permanent")) {- return;+ async #hydrate(entries) {+ if (this.#baselineRaw != null) {+ return true;}- const toggle = () => {- if (box.classList.contains("is-saving")) {- return;+ 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;}- const desiredState = !box.classList.contains("checked");- setCheckboxState(box, desiredState);- pendingStates.set(index, desiredState);- updateBusyState(index, true);- void savePendingStates();- };-- const onClick = (event) => {- event.preventDefault();- toggle();- };-- const onKeyDown = (event) => {- if (event.key !== " " && event.key !== "Enter") {- return;+ 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);+ popupAjaxError(error);+ return false;+ }+ }- event.preventDefault();- toggle();- };+ #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");+ }- box.addEventListener("click", onClick);- box.addEventListener("keydown", onKeyDown);- cleanups.push(() => {- box.removeEventListener("click", onClick);- box.removeEventListener("keydown", onKeyDown);- });- });+ #syncControl(key, box) {+ const intent = this.#intents.get(key);+ if (intent) {+ setCheckboxState(box, intent.checked);+ }- return () => {- active = false;- pendingStates.clear();- unregisterInFlightOptimisticUpdate?.();- unregisterInFlightOptimisticUpdate = undefined;- spinnerStates.forEach(({ timer }) => clearTimeout(timer));- boxes.forEach((box) => {- box.classList.remove("is-saving");+ 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");- if (box.classList.contains("is-interactive")) {- box.removeAttribute("aria-disabled");- }- });- cleanups.forEach((cleanup) => cleanup());-- const cookedUpdate = deferredCooked;- deferredCooked = undefined;- if (cookedUpdate) {- schedule("afterRender", () => {- if (!timestampIsOlder(cookedUpdate.updatedAt, postModel.updated_at)) {- postModel.cooked = cookedUpdate.cooked;- }- });}- };+ }+}++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) {diff --git a/plugins/checklist/assets/stylesheets/checklist.scss b/plugins/checklist/assets/stylesheets/checklist.scssindex be99f0dee0d..0e341b26ea3 100644--- a/plugins/checklist/assets/stylesheets/checklist.scss+++ b/plugins/checklist/assets/stylesheets/checklist.scss@@ -2,6 +2,18 @@ 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);@@ -17,6 +29,7 @@ span.chcklst-stroked {}span.chcklst-box {+ border-radius: 0.16em;display: inline-flex;position: relative;vertical-align: -0.125em;@@ -25,24 +38,8 @@ span.chcklst-box {cursor: pointer;touch-action: manipulation;- .checklist-spinner {- animation: rotate-forever 2s infinite linear;- color: var(--primary);- display: none;- height: 1em;- inset: 0;- position: absolute;- width: 1em;- }-- &.is-saving {- &::before {- visibility: hidden;- }-- .checklist-spinner {- display: inline-block;- }+ &.is-pending {+ animation: checklist-pending-pulse 950ms ease-in-out infinite alternate;}&:focus-visible {@@ -82,9 +79,18 @@ span.chcklst-box {}}+@media (forced-colors: active) {+ span.chcklst-box.is-interactive.is-pending {+ outline: 0.09em solid CanvasText;+ outline-offset: 0;+ }+}+@media (prefers-reduced-motion: reduce) {- span.chcklst-box.is-interactive .checklist-spinner {+ span.chcklst-box.is-interactive.is-pending {animation: none;+ background-color: var(--primary-low);+ box-shadow: 0 0 0 0.09em var(--primary-low);}}diff --git a/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rb b/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rbindex cb10563d514..92980ba38a1 100644--- a/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rb+++ b/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rb@@ -28,6 +28,19 @@ RSpec.describe Checklist::ToggleCheckbox doit { is_expected.to validate_length_of(:mutation_id).is_at_most(100) }end+ describe ".retryable_conflict?" do+ fab!(:post) { Fabricate(:post, raw: "[] first\n[X] fixed") }++ it "normalizes legacy mutable markers but not permanent markers" do+ expect(+ described_class.retryable_conflict?(post:, expected_raw: "[x] first\n[X] fixed"),+ ).to eq(true)+ expect(described_class.retryable_conflict?(post:, expected_raw: "[] first\n[x] fixed")).to eq(+ false,+ )+ end+ end+describe ".call" dosubject(:result) { described_class.call(params:, **dependencies) }diff --git a/plugins/checklist/test/javascripts/lib/checklist-test.js b/plugins/checklist/test/javascripts/lib/checklist-test.jsindex 4679440e3d4..85c4ee3e5f4 100644--- a/plugins/checklist/test/javascripts/lib/checklist-test.js+++ b/plugins/checklist/test/javascripts/lib/checklist-test.js@@ -13,23 +13,85 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";import { checklistSyntax } from "discourse/plugins/checklist/discourse/initializers/checklist";let decoratorCleanup;+let decoratedElement;+let failHeldRequest;+let holdHydration;let holdRequest;let hydrationRequests;let initialRaw;let postModel;+let releaseHydration;let releaseRequest;let requests;let retryableConflicts;let respondWithError;let responseRevised;let responseSequence;+let responseUpdatedAts;++function applyToggleToRaw(raw, toggle) {+ if (toggle.checkbox_source) {+ const [lineNumber, markerNumber] = toggle.checkbox_source+ .split(":")+ .map(Number);+ const lines = raw.split("\n");+ let markerIndex = -1;+ lines[lineNumber] = lines[lineNumber].replace(/\[[ xX]?\]/g, (marker) => {+ markerIndex += 1;+ return markerIndex === markerNumber+ ? toggle.checked+ ? "[x]"+ : "[ ]"+ : marker;+ });+ return lines.join("\n");+ }++ let checkboxIndex = -1;+ return raw.replace(/\[(?: |x)?\]/g, (marker) => {+ checkboxIndex += 1;+ return checkboxIndex === toggle.checkbox_index+ ? toggle.checked+ ? "[x]"+ : "[ ]"+ : marker;+ });+}function nextUpdatedAt() {responseSequence += 1;+ if (responseUpdatedAts.length > 0) {+ return responseUpdatedAts.shift();+ }+return `2026-08-27T08:00:0${responseSequence}.000Z`;}-async function prepare(raw, { canEdit = true, includeRaw = true } = {}) {+async function decorate(raw, { legacy = false } = {}) {+ const cooked = await cook(raw, {+ siteSettings: {+ checklist_enabled: true,+ discourse_local_dates_enabled: true,+ },+ });+ const decoratorHelper = { getModel: () => postModel };+ decoratedElement = document.createElement("div");+ decoratedElement.innerHTML = cooked.toString();+ if (legacy) {+ decoratedElement+ .querySelectorAll(".chcklst-box")+ .forEach((box) => delete box.dataset.chkSrc);+ }+ decoratorCleanup = checklistSyntax(decoratedElement, decoratorHelper);+ document.querySelector("#ember-testing").append(decoratedElement);++ return [...decoratedElement.querySelectorAll(".chcklst-box")];+}++async function prepare(+ raw,+ { canEdit = true, includeRaw = true, legacyCooked = false } = {}+) {initialRaw = raw;const cooked = await cook(raw, {siteSettings: {@@ -45,24 +107,25 @@ async function prepare(raw, { canEdit = true, includeRaw = true } = {}) {raw: includeRaw ? raw : undefined,updated_at: "2026-08-27T08:00:00.000Z",});- const decoratorHelper = { getModel: () => postModel };- const element = document.createElement("div");- element.innerHTML = cooked.toString();- decoratorCleanup = checklistSyntax(element, decoratorHelper);- document.querySelector("#ember-testing").append(element);- return [...element.querySelectorAll(".chcklst-box")];+ return decorate(raw, { legacy: legacyCooked });}acceptance("checklist", function (needs) {needs.pretender((server, helper) => {server.get("/posts/42", () => {hydrationRequests += 1;- return helper.response({+ const response = helper.response({id: 42,raw: initialRaw,updated_at: "2026-08-27T08:00:00.000Z",});+ if (holdHydration) {+ return new Promise((resolve) => {+ releaseHydration = () => resolve(response);+ });+ }+ return response;});server.put("/checklist/toggle", (request) => {@@ -70,23 +133,31 @@ acceptance("checklist", function (needs) {requests.push(body);if (retryableConflicts.length > 0) {+ const conflict = retryableConflicts.shift();return helper.response(409, {errors: ["The post changed"],- raw: "server conflict raw",- retryable: true,- updated_at: retryableConflicts.shift(),+ raw:+ typeof conflict === "string" ? "server conflict raw" : conflict.raw,+ retryable:+ typeof conflict === "string" ? true : (conflict.retryable ?? true),+ updated_at:+ typeof conflict === "string" ? conflict : conflict.updatedAt,});}if (respondWithError) {- return helper.response(422, {});+ return helper.response(respondWithError === "network" ? 0 : 422, {});}const updatedAt = nextUpdatedAt();+ const raw = body.toggles.reduce(+ (currentRaw, toggle) => applyToggleToRaw(currentRaw, toggle),+ body.expected_raw+ );const response = {cooked: `authoritative cooked ${responseSequence}`,last_editor_id: 1,- raw: `authoritative raw ${responseSequence}`,+ raw,revised: responseRevised,updated_at: updatedAt,version: responseSequence + 1,@@ -96,7 +167,13 @@ acceptance("checklist", function (needs) {}if (holdRequest) {return new Promise((resolve) => {- releaseRequest = () => resolve(helper.response(response));+ releaseRequest = () => {+ const shouldError = failHeldRequest;+ failHeldRequest = false;+ resolve(+ shouldError ? helper.response(422, {}) : helper.response(response)+ );+ };});}@@ -106,20 +183,26 @@ acceptance("checklist", function (needs) {needs.hooks.beforeEach(function () {decoratorCleanup = null;+ decoratedElement = null;+ failHeldRequest = false;+ holdHydration = false;holdRequest = false;hydrationRequests = 0;initialRaw = null;postModel = null;+ releaseHydration = null;releaseRequest = null;requests = [];retryableConflicts = [];respondWithError = false;responseRevised = true;responseSequence = 0;+ responseUpdatedAts = [];});needs.hooks.afterEach(function () {decoratorCleanup?.();+ releaseHydration?.();releaseRequest?.();document.querySelector("#ember-testing").innerHTML = "";});@@ -173,9 +256,8 @@ Actual checkboxes:);});- test("defers authoritative cooked content until teardown", async function (assert) {+ test("reconciles authoritative content after saving", async function (assert) {const [checkbox] = await prepare("[ ] first");- const initialCooked = postModel.cooked;await click(checkbox);@@ -185,52 +267,83 @@ Actual checkboxes:"last editor metadata is reconciled");assert.strictEqual(postModel.version, 2, "version metadata is reconciled");- assert.strictEqual(- postModel.raw,- "authoritative raw 1",- "raw content is reconciled"- );+ assert.strictEqual(postModel.raw, "[x] first", "raw content is reconciled");assert.strictEqual(postModel.cooked,- initialCooked,- "the visible cooked subtree is not rerendered"+ "authoritative cooked 1",+ "cooked content is reconciled");assert.true(checkbox.isConnected, "the decorated control stays connected");+ });- decoratorCleanup();- decoratorCleanup = null;+ test("rebases a desired state after a stale response", async function (assert) {+ holdRequest = true;+ const [checkbox] = await prepare("[ ] first");++ checkbox.click();+ await waitUntil(() => releaseRequest);+ postModel.updated_at = "2026-08-27T08:00:09.000Z";+ postModel.raw = "[ ] first";+ postModel.cooked = "newer cooked";+ responseUpdatedAts = ["2026-08-27T08:00:10.000Z"];+ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);await settled();++ assert.strictEqual(+ requests[1].expected_raw,+ "[ ] first",+ "the retry uses the newer authoritative raw"+ );+ assert.strictEqual(+ postModel.raw,+ "[x] first",+ "the rebased state becomes authoritative"+ );assert.strictEqual(postModel.cooked,- "authoritative cooked 1",- "cooked content is stored for the next render"+ "authoritative cooked 2",+ "the rebased cooked state is reconciled"+ );+ assert.strictEqual(+ postModel.updated_at,+ "2026-08-27T08:00:10.000Z",+ "the rebased response advances the timestamp");});- test("does not apply a response older than the loaded post", async function (assert) {+ test("does not accept an older version with the same timestamp", async function (assert) {holdRequest = true;const [checkbox] = await prepare("[ ] first");checkbox.click();await waitUntil(() => releaseRequest);- postModel.updated_at = "2026-08-27T08:00:09.000Z";- postModel.raw = "newer raw";+ postModel.version = 99;+ postModel.updated_at = "2026-08-27T08:00:01.000Z";postModel.cooked = "newer cooked";+ holdRequest = false;releaseRequest();releaseRequest = null;await settled();- assert.strictEqual(postModel.raw, "newer raw", "raw does not regress");+ assert.strictEqual(postModel.version, 99, "the newer version is retained");assert.strictEqual(postModel.cooked,"newer cooked",- "cooked does not regress"- );- assert.strictEqual(- postModel.updated_at,- "2026-08-27T08:00:09.000Z",- "the timestamp does not regress"+ "an older version cannot replace cooked content");+ assert+ .dom(checkbox)+ .doesNotHaveClass(+ "checked",+ "exhausted intent returns to confirmed state"+ );+ assert+ .dom(checkbox)+ .doesNotHaveAttribute("aria-busy", "exhausted intent is no longer busy");+ await waitUntil(() => !checkbox.classList.contains("is-pending"));});test("hydrates raw before the first stream toggle", async function (assert) {@@ -246,9 +359,116 @@ Actual checkboxes:);});+ test("preserves intent when a raw-less post rebinds during hydration", async function (assert) {+ holdHydration = true;+ const [first, second] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });++ first.click();+ await waitUntil(() => releaseHydration);+ second.click();+ first.click();++ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [firstReplacement, secondReplacement] = await decorate(+ "[ ] first\n[ ] second"+ );++ assert+ .dom(firstReplacement)+ .doesNotHaveClass("checked", "the latest first intent survives");+ assert+ .dom(secondReplacement)+ .hasClass("checked", "the queued second intent survives");+ assert+ .dom(secondReplacement)+ .hasClass("is-pending", "the replacement remains pending");++ holdHydration = false;+ releaseHydration();+ releaseHydration = null;+ await waitUntil(() => requests.length === 1);+ await settled();++ assert.deepEqual(+ requests[0].toggles.map(({ checked }) => checked),+ [false, true],+ "all intent captured during hydration uses the hydrated baseline"+ );+ });++ test("discards reordered raw-less sourced intent", async function (assert) {+ holdHydration = true;+ const [first] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });++ first.click();+ await waitUntil(() => releaseHydration);+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate("[ ] second\n[ ] first");++ assert+ .dom(replacement)+ .doesNotHaveClass("checked", "intent does not move to another item");+ 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");++ holdHydration = false;+ releaseHydration();+ releaseHydration = null;+ await settled();++ assert.strictEqual(+ requests.length,+ 0,+ "no positional legacy request is sent"+ );+ });+test("sends the checkbox count for legacy cooked HTML", async function (assert) {- const [checkbox] = await prepare("[ ] first\n[ ] second");- delete checkbox.dataset.chkSrc;+ const [checkbox] = await prepare("[ ] first\n[ ] second", {+ legacyCooked: true,+ });await click(checkbox);@@ -259,6 +479,206 @@ Actual checkboxes:);});+ test("persists queued legacy checkboxes", async function (assert) {+ holdRequest = true;+ const [first, second] = await prepare("[ ] first\n[ ] second", {+ legacyCooked: true,+ });++ first.click();+ await waitUntil(() => requests.length === 1);+ second.click();++ 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]],+ "legacy queue entries remain associated with their indexes"+ );+ assert.strictEqual(+ postModel.raw,+ "[x] first\n[x] second",+ "every queued legacy state is persisted"+ );+ });++ test("preserves legacy intent when sourced cooked replaces it", async function (assert) {+ holdRequest = true;+ const [checkbox] = await prepare("[ ] first", { legacyCooked: true });++ checkbox.click();+ await waitUntil(() => requests.length === 1);++ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate("[ ] first");++ assert+ .dom(replacement)+ .hasClass("checked", "legacy intent migrates to the sourced checkbox");+ assert+ .dom(replacement)+ .hasClass("is-pending", "the migrated checkbox remains pending");++ 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");+ });++ test("does not migrate legacy intent across a structural edit", async function (assert) {+ holdRequest = true;+ const [first] = await prepare("[ ] first\n[ ] second", {+ legacyCooked: true,+ });++ first.click();+ await waitUntil(() => requests.length === 1);++ postModel.raw = "[ ] second\n[ ] first";+ postModel.cooked = "structurally newer cooked";+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate(postModel.raw);++ assert+ .dom(replacement)+ .doesNotHaveClass(+ "checked",+ "legacy intent is not applied to a reordered checkbox"+ );++ releaseRequest();+ releaseRequest = null;+ await settled();++ assert.strictEqual(+ postModel.raw,+ "[ ] second\n[ ] first",+ "the discarded generation does not replace newer raw"+ );+ assert.strictEqual(+ postModel.cooked,+ "structurally newer cooked",+ "the discarded generation does not replace newer cooked"+ );+ });++ test("rejects structure comparisons when both normalizations fail", async function (assert) {+ await prepare("[ ] first");+ postModel.raw = "first invalid raw";+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [rebound] = await decorate("[ ] first");++ rebound.click();+ postModel.raw = "second invalid raw";+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate("[ ] first");+ await settled();++ assert+ .dom(replacement)+ .doesNotHaveClass(+ "checked",+ "invalid normalizations cannot preserve intent"+ );+ assert+ .dom(replacement)+ .doesNotHaveClass(+ "is-pending",+ "invalid intent is discarded immediately"+ );+ assert.strictEqual(requests.length, 0, "no invalid baseline is submitted");+ });++ test("does not rebase sourced intent across a structural edit", async function (assert) {+ holdRequest = true;+ const [first] = await prepare("[ ] first\n[ ] second");++ first.click();+ await waitUntil(() => requests.length === 1);++ postModel.raw = "[ ] second\n[ ] first";+ postModel.cooked = "newer cooked";+ postModel.updated_at = "2026-08-27T08:00:09.000Z";+ responseUpdatedAts = ["2026-08-27T08:00:10.000Z"];+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate(postModel.raw);+ replacement.click();++ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);+ await settled();++ assert.deepEqual(+ requests.map((request) => request.toggles[0].checked),+ [true, true],+ "only the old request and the new post-generation intent are sent"+ );+ assert+ .dom(replacement)+ .hasClass(+ "checked",+ "the new checkbox intent survives the old stale response"+ );+ });++ test("preserves new-generation intent after an old request fails", async function (assert) {+ holdRequest = true;+ const [first] = await prepare("[ ] first\n[ ] second");++ first.click();+ await waitUntil(() => requests.length === 1);++ postModel.raw = "[ ] second\n[ ] first";+ postModel.updated_at = "2026-08-27T08:00:09.000Z";+ responseUpdatedAts = ["2026-08-27T08:00:10.000Z"];+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate(postModel.raw);+ replacement.click();++ failHeldRequest = true;+ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);+ await settled();++ assert+ .dom(replacement)+ .hasClass("checked", "the replacement's intent survives the old failure");+ assert.true(+ requests[1].toggles[0].checked,+ "the replacement's intent is persisted"+ );+ });+test("unregisters optimistic tokens when no revision was needed", async function (assert) {responseRevised = false;const [checkbox] = await prepare("[ ] first");@@ -271,13 +691,11 @@ Actual checkboxes:);});- test("updates instantly without hiding or locking the checklist", async function (assert) {+ test("shows a pulse on only the pending checkbox", async function (assert) {holdRequest = true;- const [first, second] = await prepare("[ ] first\n[x] second");+ const [first, second] = await prepare("[ ] first [x] second");+ const initialWidth = first.getBoundingClientRect().width;- assert- .dom(".checklist-spinner")- .doesNotExist("spinners are created lazily");first.click();await waitUntil(() => requests.length === 1);@@ -290,27 +708,42 @@ Actual checkboxes:.hasAttribute("aria-busy","true",- "only the pending item is marked busy"+ "only the pending checkbox is marked busy");assert.dom(first)- .hasAttribute(+ .doesNotHaveAttribute("aria-disabled",- "true",- "the pending item ignores additional activation"+ "the pending checkbox remains interactive");- assert.dom(first).isVisible("the pending checkbox keeps its layout");assert- .dom(".checklist-spinner", first)- .isVisible("the familiar spinner is shown immediately");+ .dom(first)+ .hasClass("is-pending", "the pending checkbox gets the pulse state");+ assert+ .dom(second)+ .doesNotHaveClass(+ "is-pending",+ "an adjacent checkbox does not share the pending state"+ );+ assert+ .dom(second)+ .doesNotHaveAttribute(+ "aria-busy",+ "an adjacent checkbox is not marked busy"+ );+ assert.strictEqual(+ first.getBoundingClientRect().width,+ initialWidth,+ "the pending plate does not change the checkbox footprint"+ );assert.strictEqual(- getComputedStyle(first.querySelector(".checklist-spinner")).animationName,- "rotate-forever",- "the pending icon spins in place"+ getComputedStyle(first).animationName,+ "checklist-pending-pulse",+ "the neutral plate pulses behind the existing glyph");assert- .dom(second)- .doesNotHaveClass("readonly", "other checkboxes remain interactive");+ .dom(".checklist-spinner")+ .doesNotExist("the pending state does not render a spinner");releaseRequest();await settled();@@ -318,77 +751,284 @@ Actual checkboxes:assert.dom(first).doesNotHaveAttribute("aria-busy", "pending state clears after saving");+ await waitUntil(() => !first.classList.contains("is-pending"));+ assert+ .dom(first)+ .doesNotHaveClass("is-pending", "the pulse clears after its minimum");assert.dom(first).hasClass("checked", "the optimistic state remains after saving");});- test("shows every spinner for at least 200ms", async function (assert) {+ test("keeps a fast pulse visible without blocking another click", async function (assert) {const [checkbox] = await prepare("[ ] first");- const startedAt = performance.now();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-busy",- "the semantic busy state follows the completed request"+ "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)- .hasAttribute(- "aria-disabled",- "true",- "the control stays inactive while its spinner is visible"+ .doesNotHaveClass(+ "checked",+ "a click during the visual tail is accepted");assert- .dom(".checklist-spinner", checkbox)- .isVisible("a quick response still shows the spinner");+ .dom(checkbox)+ .hasClass(+ "is-pending",+ "the new click restarts the minimum display time"+ );- await waitUntil(() => !checkbox.classList.contains("is-saving"));+ await waitUntil(() => !checkbox.classList.contains("is-pending"));assert.true(- performance.now() - startedAt >= 190,- "the spinner remains visible for approximately 200ms"+ 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");++ checkbox.click();+ await waitUntil(() => requests.length === 1);+ checkbox.click();+assert- .dom(".checklist-spinner", checkbox)- .isNotVisible("the spinner clears after its minimum display time");+ .dom(checkbox)+ .doesNotHaveClass("checked", "the second click is immediately visible");assert.dom(checkbox)- .doesNotHaveAttribute(- "aria-disabled",- "the control is interactive again after the spinner clears"+ .hasClass(+ "is-pending",+ "the checkbox stays pending for the latest state");+ assert.strictEqual(+ requests.length,+ 1,+ "the next save waits for the active request"+ );++ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2 && releaseRequest);++ assert+ .dom(checkbox)+ .hasClass("is-pending", "pending state stays set between queued saves");+ assert+ .dom(checkbox)+ .hasAttribute("aria-busy", "true", "the queued save remains busy");++ checkbox.click();+ assert+ .dom(checkbox)+ .hasClass("checked", "another click during the queued save is visible");++ 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 server receives the latest state after each active save"+ );+ assert.strictEqual(+ requests[1].expected_raw,+ "[x] first",+ "the queued save uses the prior response as its baseline"+ );+ assert+ .dom(checkbox)+ .hasClass("checked", "the persisted state matches the visible state");+ await waitUntil(() => !checkbox.classList.contains("is-pending"));+ assert+ .dom(checkbox)+ .doesNotHaveClass(+ "is-pending",+ "pending state clears after the final save"+ );+ assert+ .dom(checkbox)+ .hasAttribute(+ "aria-checked",+ "true",+ "ARIA reflects the persisted state"+ );+ assert.strictEqual(+ postModel.raw,+ "[x] first",+ "the model stores the latest persisted state"+ );});- test("ignores repeat activation while the spinner is visible", async function (assert) {+ 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);- await waitUntil(() => !checkbox.hasAttribute("aria-busy"));+ checkbox.click();+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2 && releaseRequest);checkbox.click();- assert.strictEqual(requests.length, 1, "the extra click sends no request");+ decoratorCleanup();+ decoratorCleanup = null;+ decoratedElement.remove();+ const [replacement] = await decorate("[ ] first");+assert- .dom(checkbox)- .hasClass("checked", "the optimistic state is unchanged");+ .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");- await waitUntil(() => !checkbox.classList.contains("is-saving"));checkbox.click();+ await waitUntil(() => requests.length === 1);+ checkbox.click();+ checkbox.click();++ failHeldRequest = true;+ holdRequest = false;+ releaseRequest();+ releaseRequest = null;await waitUntil(() => requests.length === 2);+ await settled();assert.deepEqual(- requests.flatMap((request) =>- request.toggles.map((toggle) => toggle.checked)- ),- [true, false],- "the checkbox accepts input again after the spinner clears"+ requests.map((request) => request.toggles[0].checked),+ [true, true],+ "the repeated final state is sent as a distinct intent after failure"+ );+ assert+ .dom(checkbox)+ .hasClass("checked", "the latest repeated state is preserved");+ });++ test("restores the last confirmed state when a queued save fails", async function (assert) {+ holdRequest = true;+ const [checkbox] = await prepare("[ ] first");++ checkbox.click();+ await waitUntil(() => requests.length === 1);+ checkbox.click();++ holdRequest = false;+ respondWithError = true;+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);+ await settled();++ assert+ .dom(checkbox)+ .hasClass("checked", "the first save's confirmed state is restored");+ assert+ .dom(checkbox)+ .hasAttribute(+ "aria-checked",+ "true",+ "ARIA restores the confirmed state"+ );+ await waitUntil(() => !checkbox.classList.contains("is-pending"));+ assert+ .dom(checkbox)+ .doesNotHaveClass(+ "is-pending",+ "the failed checkbox is no longer pending"+ );+ assert+ .dom(checkbox)+ .doesNotHaveAttribute(+ "aria-busy",+ "the failed checkbox is no longer busy"+ );+ assert.strictEqual(+ postModel.raw,+ "[x] first",+ "the successful save remains reconciled"+ );+ });++ test("coalesces repeat activation back to the active save", async function (assert) {+ holdRequest = true;+ const [checkbox] = await prepare("[ ] first");++ checkbox.click();+ await waitUntil(() => requests.length === 1);+ checkbox.click();+ checkbox.click();++ releaseRequest();+ releaseRequest = null;+ await settled();++ assert.strictEqual(+ requests.length,+ 1,+ "no duplicate save is needed when the latest state matches the active save"+ );+ assert+ .dom(checkbox)+ .hasClass("checked", "the latest state remains visible");+ await waitUntil(() => !checkbox.classList.contains("is-pending"));+ assert+ .dom(checkbox)+ .doesNotHaveClass("is-pending", "the matching save clears pending state");+ assert.strictEqual(+ postModel.raw,+ "[x] first",+ "the model reconciles the matching response");});@@ -433,7 +1073,7 @@ Actual checkboxes:);assert.strictEqual(requests[1].expected_raw,- "authoritative raw 1",+ "[x] first\n[ ] second\n[ ] third","the second request uses the first response's raw");assert.strictEqual(@@ -443,7 +1083,7 @@ Actual checkboxes:);});- test("stops queued work after the decorated content is destroyed", async function (assert) {+ test("continues queued work after the decorated content is destroyed", async function (assert) {holdRequest = true;const [first, second] = await prepare("[ ] first\n[ ] second");@@ -451,32 +1091,106 @@ Actual checkboxes:second.click();await waitUntil(() => requests.length === 1);decoratorCleanup();- assert.false(- consumeOptimisticPostUpdate(requests[0].mutation_id),- "the detached decoration unregisters its in-flight mutation"- );+ decoratorCleanup = null;++ assert+ .dom(first)+ .doesNotHaveClass("is-pending", "cleanup removes stale presentation");+ assert+ .dom(first)+ .doesNotHaveAttribute("aria-busy", "cleanup removes stale busy state");+ assert+ .dom(second)+ .doesNotHaveClass("is-pending", "queued presentation is also removed");++ holdRequest = false;releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);await settled();- assert.strictEqual(- requests.length,- 1,- "detached controls do not send stale queued changes"+ assert.deepEqual(+ requests.map((request) =>+ request.toggles.map((toggle) => toggle.checkbox_index)+ ),+ [[0], [1]],+ "detached controls do not discard queued changes");assert.strictEqual(postModel.raw,- "authoritative raw 1",- "the detached model retains the confirmed raw content"+ "[x] first\n[x] second",+ "the detached model receives the final raw content");assert.strictEqual(postModel.cooked,- "authoritative cooked 1",- "the detached model retains the confirmed cooked content"+ "authoritative cooked 2",+ "the detached model receives the final cooked content"+ );+ });++ test("rejects clicks from old cooked after a structural conflict", async function (assert) {+ retryableConflicts = [+ {+ raw: "[ ] second\n[ ] first",+ retryable: false,+ updatedAt: "2026-08-27T08:00:10.000Z",+ },+ ];+ const [first] = await prepare("[ ] first\n[ ] second", {+ includeRaw: false,+ });++ await click(first);+ first.click();+ await settled();++ assert.strictEqual(+ requests.length,+ 1,+ "old cooked coordinates are not sent against the new baseline"+ );+ assert+ .dom(first)+ .doesNotHaveClass("checked", "the unsafe follow-up intent is discarded");+ });++ test("keeps conflict baselines out of post metadata", async function (assert) {+ holdRequest = true;+ retryableConflicts = [+ {+ raw: "[x] first",+ updatedAt: "2026-08-27T08:00:10.000Z",+ },+ ];+ responseUpdatedAts = ["2026-08-27T08:00:11.000Z"];+ const [checkbox] = await prepare("[ ] first");++ checkbox.click();+ await waitUntil(() => requests.length === 2 && releaseRequest);++ assert.strictEqual(+ postModel.updated_at,+ "2026-08-27T08:00:00.000Z",+ "a conflict baseline does not advance model metadata alone");++ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await settled();});test("recovers a stale request without discarding its backlog", async function (assert) {- retryableConflicts = ["2026-08-27T08:00:10.000Z"];+ retryableConflicts = [+ {+ raw: "[x] first\n[ ] second\n[ ] third",+ updatedAt: "2026-08-27T08:00:10.000Z",+ },+ ];+ responseUpdatedAts = [+ "2026-08-27T08:00:11.000Z",+ "2026-08-27T08:00:12.000Z",+ ];const [first, second, third] = await prepare("[ ] first\n[ ] second\n[ ] third");@@ -487,7 +1201,7 @@ Actual checkboxes:await waitUntil(() => requests.length === 3);await waitUntil(() =>[first, second, third].every(- (checkbox) => !checkbox.classList.contains("is-saving")+ (checkbox) => !checkbox.classList.contains("is-pending")));@@ -500,7 +1214,7 @@ Actual checkboxes:);assert.strictEqual(requests[1].expected_raw,- "server conflict raw",+ "[x] first\n[ ] second\n[ ] third","the retry uses the server's authoritative raw");assert.strictEqual(@@ -540,6 +1254,32 @@ Actual checkboxes:.doesNotHaveAttribute("aria-busy", "pending state is cleared");});+ test("recovers after a network error invalidates raw", async function (assert) {+ respondWithError = "network";+ const [checkbox] = await prepare("[ ] first");++ await click(checkbox);+ await waitUntil(() => !checkbox.hasAttribute("aria-busy"));+ respondWithError = false;+ const currentCheckbox = document.querySelector(+ ".chcklst-box.is-interactive"+ );+ await click(currentCheckbox);++ assert.strictEqual(hydrationRequests, 1, "the baseline is rehydrated");+ assert.strictEqual(requests.length, 2, "the next intent is persisted");+ assert.strictEqual(+ requests[1].expected_raw,+ "[ ] first",+ "the retry uses the hydrated baseline"+ );+ assert.strictEqual(+ postModel.version,+ 2,+ "the successful response is applied"+ );+ });+test("supports keyboard interaction and exposes checkbox semantics", async function (assert) {const [checkbox] = await prepare("[ ] Buy milk");@@ -558,13 +1298,27 @@ Actual checkboxes:.dom(checkbox).hasAttribute("aria-checked", "true", "Space checks the item");- await waitUntil(() => !checkbox.classList.contains("is-saving"));+ await waitUntil(() => !checkbox.classList.contains("is-pending"));await triggerKeyEvent(checkbox, "keydown", "Enter");assert.dom(checkbox).hasAttribute("aria-checked", "false", "Enter unchecks the item");});+ test("redecorating the same controls does not duplicate listeners", async function (assert) {+ const [checkbox] = await prepare("[ ] first");+ const replacementCleanup = checklistSyntax(decoratedElement, {+ getModel: () => postModel,+ });++ await click(checkbox);++ assert.strictEqual(requests.length, 1, "one activation sends one request");+ assert.dom(checkbox).hasClass("checked", "one activation toggles once");++ replacementCleanup();+ });+test("labels multiple controls from their own task text", async function (assert) {const [first, second] = await prepare("[ ] Buy milk [ ] Wash car");