A platform for community discussion. Free, open, simple.
FIX: Make checklist updates conflict-safe (#43000)
Sam24ca6775e3db
diff --git a/frontend/discourse/app/components/modal/history.gjs b/frontend/discourse/app/components/modal/history.gjsindex 98f4fed87d6..e43605eebb2 100644--- a/frontend/discourse/app/components/modal/history.gjs+++ b/frontend/discourse/app/components/modal/history.gjs@@ -204,7 +204,7 @@ export default class History extends Component {const postStream = this.args.model.post?.topic?.postStream;if (postStream) {- postStream.triggerChangedPost(postId, this.args.model);+ void postStream.refreshPost(postId).catch(() => {});}} finally {this.loading = false;diff --git a/frontend/discourse/app/controllers/topic.js b/frontend/discourse/app/controllers/topic.jsindex cc92d770604..9fa81ae20e0 100644--- a/frontend/discourse/app/controllers/topic.js+++ b/frontend/discourse/app/controllers/topic.js@@ -38,6 +38,7 @@ import { isTesting } from "discourse/lib/environment";import { wantsNewWindow } from "discourse/lib/intercept-click";import discourseLater from "discourse/lib/later";import { deepMerge } from "discourse/lib/object";+import { consumeOptimisticPostUpdate } from "discourse/lib/optimistic-post-updates";import { buildQuote } from "discourse/lib/quote";import QuoteState from "discourse/lib/quote-state";import { extractLinkMeta } from "discourse/lib/render-topic-featured-link";@@ -2079,9 +2080,11 @@ export default class TopicController extends Controller {switch (data.type) {case "acted":- postStream.triggerChangedPost(data.id, data.updated_at, {- preserveCooked: true,- });+ void postStream+ .triggerChangedPost(data.id, data.updated_at, {+ preserveCooked: true,+ })+ .catch(() => {});break;case "read": {postStream.triggerReadPost(data.id, data.readers_count);@@ -2099,7 +2102,11 @@ export default class TopicController extends Controller {}case "revised":case "rebaked": {- postStream.triggerChangedPost(data.id, data.updated_at);+ if (!consumeOptimisticPostUpdate(data.preserve_cooked_token)) {+ void postStream+ .triggerChangedPost(data.id, data.updated_at)+ .catch(() => {});+ }break;}case "deleted": {@@ -2111,7 +2118,7 @@ export default class TopicController extends Controller {break;}case "recovered": {- postStream.triggerRecoveredPost(data.id);+ void postStream.triggerRecoveredPost(data.id).catch(() => {});break;}case "created": {diff --git a/frontend/discourse/app/lib/optimistic-post-updates.js b/frontend/discourse/app/lib/optimistic-post-updates.jsnew file mode 100644index 00000000000..3adff755e91--- /dev/null+++ b/frontend/discourse/app/lib/optimistic-post-updates.js@@ -0,0 +1,47 @@+const MAX_PENDING_OPTIMISTIC_UPDATES = 100;+const OPTIMISTIC_UPDATE_TTL = 30_000;+const pendingOptimisticUpdates = new Map();++function removeOptimisticPostUpdate(token) {+ const update = pendingOptimisticUpdates.get(token);+ if (!update) {+ return;+ }++ clearTimeout(update.timeout);+ pendingOptimisticUpdates.delete(token);+}++export function registerOptimisticPostUpdate(token) {+ if (pendingOptimisticUpdates.has(token)) {+ removeOptimisticPostUpdate(token);+ } else if (pendingOptimisticUpdates.size >= MAX_PENDING_OPTIMISTIC_UPDATES) {+ removeOptimisticPostUpdate(pendingOptimisticUpdates.keys().next().value);+ }++ const update = {};+ pendingOptimisticUpdates.set(token, update);++ return {+ startExpiration() {+ if (!pendingOptimisticUpdates.has(token) || update.timeout) {+ return;+ }++ update.timeout = setTimeout(+ () => removeOptimisticPostUpdate(token),+ OPTIMISTIC_UPDATE_TTL+ );+ },+ unregister: () => removeOptimisticPostUpdate(token),+ };+}++export function consumeOptimisticPostUpdate(token) {+ if (!token || !pendingOptimisticUpdates.has(token)) {+ return false;+ }++ removeOptimisticPostUpdate(token);+ return true;+}diff --git a/frontend/discourse/app/models/post-stream.js b/frontend/discourse/app/models/post-stream.jsindex b2da640c178..1fa5ae0654f 100644--- a/frontend/discourse/app/models/post-stream.js+++ b/frontend/discourse/app/models/post-stream.js@@ -23,6 +23,25 @@ import { i18n } from "discourse-i18n";let _lastEditNotificationClick = null;+function comparePostTimestamps(candidate, reference) {+ const candidateTime = Date.parse(candidate);+ const referenceTime = Date.parse(reference);+ const candidateIsValid = !Number.isNaN(candidateTime);+ const referenceIsValid = !Number.isNaN(referenceTime);++ if (candidateIsValid && referenceIsValid) {+ return candidateTime - referenceTime;+ }+ if (candidateIsValid) {+ return 1;+ }+ if (referenceIsValid) {+ return -1;+ }++ return candidate === reference ? 0 : 1;+}+export function Placeholder(viewName) {this.viewName = viewName;}@@ -73,6 +92,7 @@ export default class PostStream extends RestModel {@autoTrackedArray userFilters = [];_identityMap = {};+ _pendingPostRefreshes = new Map();@dependentKeyCompatget loading() {@@ -795,7 +815,7 @@ export default class PostStream extends RestModel {const existing = this._identityMap[postId];if (existing) {- return this.triggerChangedPost(postId, new Date());+ return this.refreshPost(postId);}// need to insert into stream@@ -852,40 +872,111 @@ export default class PostStream extends RestModel {}/**- * Updates a post in the stream when it has been changed on the server.+ * Fetches and stores the authoritative state of a loaded post.*- * @param {number} postId - The ID of the post to update- * @param {string} updatedAt - The timestamp when the post was last updated- * @param {Object} opts - Additional options for updating the post+ * @param {number} postId - The ID of the post to refresh+ * @param {Object} opts - Additional options for refreshing the post* @param {boolean} [opts.preserveCooked] - Whether to preserve the cooked HTML content- * @returns {Promise} A promise that resolves when the post has been updated+ * @returns {Promise} A promise that resolves when the post has been refreshed*/- async triggerChangedPost(postId, updatedAt, opts = {}) {+ refreshPost(postId, opts = {}) {opts ||= {};- if (!postId) {+ const existing = this._identityMap[postId];+ if (!existing) {+ return Promise.resolve();+ }+ postId = existing.id;++ let refreshState = this._pendingPostRefreshes.get(postId);+ if (!refreshState) {+ let resolve;+ let reject;+ const reconciled = new Promise((promiseResolve, promiseReject) => {+ resolve = promiseResolve;+ reject = promiseReject;+ });+ refreshState = {+ preserveCooked: true,+ reconciled,+ reject,+ requests: [],+ resolve,+ };+ this._pendingPostRefreshes.set(postId, refreshState);+ }++ refreshState.preserveCooked &&= Boolean(opts.preserveCooked);+ const refresh = { status: "pending" };+ refreshState.requests.push(refresh);++ void ajax(`/posts/${postId}`).then(+ (data) => {+ refresh.data = data;+ refresh.status = "succeeded";+ this._reconcilePostRefresh(postId, refreshState);+ },+ (error) => {+ refresh.error = error;+ refresh.status = "failed";+ this._reconcilePostRefresh(postId, refreshState);+ }+ );++ return refreshState.reconciled;+ }++ _reconcilePostRefresh(postId, refreshState) {+ if (this._pendingPostRefreshes.get(postId) !== refreshState) {return;}- const existing = this._identityMap[postId];+ for (+ let requestIndex = refreshState.requests.length - 1;+ requestIndex >= 0;+ requestIndex--+ ) {+ const refresh = refreshState.requests[requestIndex];+ if (refresh.status === "pending") {+ return;+ }- // Only fetch and update if the post exists and has a different updated timestamp- if (existing && existing.updated_at !== updatedAt) {- // Fetch the latest post data from the server- const updatedData = await ajax(`/posts/${postId}`);+ if (refresh.status === "succeeded") {+ const latest = this._identityMap[postId];+ if (+ latest &&+ comparePostTimestamps(refresh.data.updated_at, latest.updated_at) >= 0+ ) {+ if (refreshState.preserveCooked) {+ refresh.data.cooked = latest.cooked;+ }+ this.storePost(this.store.createRecord("post", refresh.data));+ }- // Preserve the existing cooked HTML content if requested- if (opts.preserveCooked) {- updatedData.cooked = existing.cooked;+ this._pendingPostRefreshes.delete(postId);+ refreshState.resolve();+ return;}+ }- // Create a new post record with updated data and store it in the identity map.- // Creating a new record will update the existing one in the map, which will then- // trigger re-rendering of UI components that use the tracked data that was updated.- const updatedPost = this.store.createRecord("post", updatedData);+ this._pendingPostRefreshes.delete(postId);+ refreshState.reject(refreshState.requests.at(-1).error);+ }++ /**+ * Updates a post in the stream when it has been changed on the server.+ *+ * @param {number} postId - The ID of the post to update+ * @param {string} updatedAt - The time when the change event was published+ * @param {Object} opts - Additional options for updating the post+ * @param {boolean} [opts.preserveCooked] - Whether to preserve the cooked HTML content+ * @returns {Promise} A promise that resolves when the post has been updated+ */+ async triggerChangedPost(postId, updatedAt, opts = {}) {+ const existing = this._identityMap[postId];- // Update the post in the post stream's identity map- this.storePost(updatedPost);+ if (existing && comparePostTimestamps(updatedAt, existing.updated_at) > 0) {+ return this.refreshPost(postId, opts);}}diff --git a/frontend/discourse/tests/unit/controllers/topic-test.js b/frontend/discourse/tests/unit/controllers/topic-test.jsindex afd9f9ab691..c05bfe4c6f1 100644--- a/frontend/discourse/tests/unit/controllers/topic-test.js+++ b/frontend/discourse/tests/unit/controllers/topic-test.js@@ -6,6 +6,7 @@ import { module, test } from "qunit";import sinon from "sinon";import { removeValueFromArray } from "discourse/lib/array-tools";import { forceMobile } from "discourse/lib/mobile";+import { registerOptimisticPostUpdate } from "discourse/lib/optimistic-post-updates";import { withPluginApi } from "discourse/lib/plugin-api";import { Placeholder } from "discourse/models/post-stream";import pretender, { response } from "discourse/tests/helpers/create-pretender";@@ -23,6 +24,37 @@ module("Unit | Controller | topic", function (hooks) {this.store = getOwner(this).lookup("service:store");});+ test("revised messages skip only the originating optimistic refresh", function (assert) {+ const controller = getOwner(this).lookup("controller:topic");+ const model = this.store.createRecord("topic", { id: 1 });+ controller.setProperties({ model });+ const triggerChangedPost = sinon+ .stub(model.postStream, "triggerChangedPost")+ .resolves();+ registerOptimisticPostUpdate("originating-mutation");++ controller.onMessage({+ id: 1,+ preserve_cooked_token: "originating-mutation",+ type: "revised",+ updated_at: "2026-08-31T00:00:00.000Z",+ });+ assert.false(+ triggerChangedPost.called,+ "the originating event preserves the optimistic DOM"+ );++ controller.onMessage({+ id: 1,+ type: "revised",+ updated_at: "2026-08-31T00:00:01.000Z",+ });+ assert.true(+ triggerChangedPost.calledOnceWith(1, "2026-08-31T00:00:01.000Z"),+ "another event refreshes the post"+ );+ });+test("editTopic", function (assert) {const controller = getOwner(this).lookup("controller:topic");const model = this.store.createRecord("topic");diff --git a/frontend/discourse/tests/unit/lib/optimistic-post-updates-test.js b/frontend/discourse/tests/unit/lib/optimistic-post-updates-test.jsnew file mode 100644index 00000000000..87d444edcd7--- /dev/null+++ b/frontend/discourse/tests/unit/lib/optimistic-post-updates-test.js@@ -0,0 +1,59 @@+import { module, test } from "qunit";+import sinon from "sinon";+import {+ consumeOptimisticPostUpdate,+ registerOptimisticPostUpdate,+} from "discourse/lib/optimistic-post-updates";++module("Unit | Lib | optimistic-post-updates", function () {+ test("only the originating event consumes an update", function (assert) {+ registerOptimisticPostUpdate("originating-mutation");++ assert.false(+ consumeOptimisticPostUpdate(),+ "an event without a token is not optimistic"+ );+ assert.false(+ consumeOptimisticPostUpdate("another-mutation"),+ "another client's token is not consumed"+ );+ assert.true(+ consumeOptimisticPostUpdate("originating-mutation"),+ "the originating event consumes the pending update"+ );+ assert.false(+ consumeOptimisticPostUpdate("originating-mutation"),+ "the token cannot be replayed"+ );+ });++ test("unregisters a pending update", function (assert) {+ const { unregister } = registerOptimisticPostUpdate("failed-mutation");++ unregister();++ assert.false(+ consumeOptimisticPostUpdate("failed-mutation"),+ "the mutation is no longer pending"+ );+ });++ test("starts expiration after the mutation request finishes", function (assert) {+ const clock = sinon.useFakeTimers();+ registerOptimisticPostUpdate("in-flight");++ clock.tick(30_000);+ assert.true(+ consumeOptimisticPostUpdate("in-flight"),+ "an in-flight mutation retains its token"+ );++ registerOptimisticPostUpdate("lost-event").startExpiration();+ clock.tick(30_000);+ assert.false(+ consumeOptimisticPostUpdate("lost-event"),+ "a lost event does not retain a completed mutation's token"+ );+ clock.restore();+ });+});diff --git a/frontend/discourse/tests/unit/models/post-stream-test.js b/frontend/discourse/tests/unit/models/post-stream-test.jsindex a61f162ff0b..8a90861a0c8 100644--- a/frontend/discourse/tests/unit/models/post-stream-test.js+++ b/frontend/discourse/tests/unit/models/post-stream-test.js@@ -1,4 +1,5 @@import { getOwner } from "@ember/owner";+import { waitUntil } from "@ember/test-helpers";import { setupTest } from "ember-qunit";import { module, test } from "qunit";import sinon from "sinon";@@ -890,6 +891,302 @@ module("Unit | Model | post-stream", function (hooks) {);});+ test("triggerChangedPost ignores delayed older events", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ const post = store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "first",+ updated_at: "2026-08-28T08:00:02.000Z",+ });+ postStream.appendPost(post);+ let requestCount = 0;++ pretender.get("/posts/1", () => {+ requestCount += 1;+ return response({+ id: 1,+ post_number: 1,+ cooked: "second",+ updated_at: "2026-08-28T08:00:02.000Z",+ });+ });++ await postStream.triggerChangedPost(1, "2026-08-28T08:00:01.000Z");+ assert.strictEqual(requestCount, 0, "an older event causes no refresh");+ assert.strictEqual(+ post.updated_at,+ "2026-08-28T08:00:02.000Z",+ "the loaded timestamp does not regress"+ );++ await postStream.triggerChangedPost(1, "2026-08-28T08:00:03.000Z");+ assert.strictEqual(requestCount, 1, "a newer event refreshes the post");+ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "second",+ "the response is accepted when its persisted timestamp predates the event"+ );+ });++ test("refreshPost accepts an unchanged timestamp", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ postStream.appendPost(+ store.createRecord("post", {+ id: 1,+ post_number: 1,+ version: 2,+ updated_at: "2026-08-28T08:00:01.000Z",+ })+ );++ pretender.get("/posts/1", () => {+ return response({+ id: 1,+ post_number: 1,+ version: 1,+ updated_at: "2026-08-28T08:00:01.000Z",+ });+ });++ await postStream.refreshPost(1);++ assert.strictEqual(+ postStream.findLoadedPost(1).version,+ 1,+ "the authoritative state is stored"+ );+ });++ test("refreshPost ignores responses older than the loaded post", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ const post = store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "first",+ updated_at: "2026-08-28T08:00:01.000Z",+ });+ postStream.appendPost(post);+ let resolveRequest;++ pretender.get("/posts/1", () => {+ return new Promise((resolve) => (resolveRequest = resolve));+ });++ const refresh = postStream.refreshPost(1);+ await waitUntil(() => resolveRequest);+ post.updated_at = "2026-08-28T08:00:03.000Z";+ post.cooked = "third";+ resolveRequest(+ response({+ id: 1,+ post_number: 1,+ cooked: "second",+ updated_at: "2026-08-28T08:00:02.000Z",+ })+ );+ await refresh;++ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "third",+ "the newer loaded state is retained"+ );+ });++ test("refreshPost ignores a timestamp-less response to a timestamped post", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ postStream.appendPost(+ store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "current",+ updated_at: "2026-08-28T08:00:01.000Z",+ })+ );++ pretender.get("/posts/1", () => {+ return response({ id: 1, post_number: 1, cooked: "incomplete" });+ });++ await postStream.refreshPost(1);++ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "current",+ "an incomplete response cannot replace timestamped state"+ );+ });++ test("triggerChangedPost keeps the newest concurrent response", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ postStream.appendPost(+ store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "first",+ updated_at: "2026-08-28T08:00:01.000Z",+ })+ );+ const resolveRequests = [];++ pretender.get("/posts/1", () => {+ return new Promise((resolveRequest) => {+ resolveRequests.push(resolveRequest);+ });+ });++ const olderRequest = postStream.triggerChangedPost(+ 1,+ "2026-08-28T08:00:02.000Z"+ );+ const newerRequest = postStream.triggerChangedPost(+ 1,+ "2026-08-28T08:00:03.000Z"+ );+ await waitUntil(() => resolveRequests.length === 2);++ resolveRequests[1](+ response({+ id: 1,+ post_number: 1,+ cooked: "third",+ updated_at: "2026-08-28T08:00:01.000Z",+ })+ );+ await newerRequest;+ resolveRequests[0](+ response({+ id: 1,+ post_number: 1,+ cooked: "second",+ updated_at: "2026-08-28T08:00:01.000Z",+ })+ );+ await olderRequest;++ const loadedPost = postStream.findLoadedPost(1);+ assert.strictEqual(+ loadedPost.updated_at,+ "2026-08-28T08:00:01.000Z",+ "response ordering does not depend on persisted timestamps"+ );+ assert.strictEqual(+ loadedPost.cooked,+ "third",+ "the cooked HTML stays current"+ );+ });++ test("refreshPost falls back when a newer request fails", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ postStream.appendPost(+ store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "first",+ })+ );+ const resolveRequests = [];++ pretender.get("/posts/1", () => {+ return new Promise((resolveRequest) => {+ resolveRequests.push(resolveRequest);+ });+ });++ const olderRequest = postStream.refreshPost(1);+ const newerRequest = postStream.refreshPost(1);+ await waitUntil(() => resolveRequests.length === 2);++ assert.strictEqual(+ olderRequest,+ newerRequest,+ "concurrent callers share the reconciliation promise"+ );+ resolveRequests[0](response({ id: 1, post_number: 1, cooked: "second" }));+ resolveRequests[1](response(500, { errors: ["failed"] }));+ await newerRequest;+ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "second",+ "the successful older response is used as a fallback"+ );+ });++ test("refreshPost clears a failed batch", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ postStream.appendPost(+ store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "first",+ })+ );++ pretender.get("/posts/1", () => response(500, { errors: ["failed"] }));+ await assert.rejects(postStream.refreshPost(1), "the failed batch rejects");++ pretender.get("/posts/1", () =>+ response({ id: 1, post_number: 1, cooked: "second" })+ );+ await postStream.refreshPost(1);++ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "second",+ "a later refresh can succeed"+ );+ });++ test("refreshPost keeps authoritative cooked content when requests overlap", async function (assert) {+ const postStream = buildStream.call(this, 4567);+ const store = getOwner(this).lookup("service:store");+ postStream.appendPost(+ store.createRecord("post", {+ id: 1,+ post_number: 1,+ cooked: "first",+ })+ );+ const resolveRequests = [];++ pretender.get("/posts/1", () => {+ return new Promise((resolveRequest) => {+ resolveRequests.push(resolveRequest);+ });+ });++ const fullRefresh = postStream.refreshPost(1);+ const preservingRefresh = postStream.refreshPost(1, {+ preserveCooked: true,+ });+ await waitUntil(() => resolveRequests.length === 2);++ resolveRequests[1](response({ id: 1, post_number: 1, cooked: "third" }));+ await preservingRefresh;+ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "third",+ "a full refresh keeps cooked content authoritative for the batch"+ );++ resolveRequests[0](response({ id: 1, post_number: 1, cooked: "second" }));+ await fullRefresh;+ assert.strictEqual(+ postStream.findLoadedPost(1).cooked,+ "third",+ "the older response is ignored"+ );+ });+test("triggerRecoveredPost", async function (assert) {const postStream = buildStream.call(this, 4567);const store = getOwner(this).lookup("service:store");diff --git a/lib/post_revisor.rb b/lib/post_revisor.rbindex a5d618ceeec..6efaeb01a7e 100644--- a/lib/post_revisor.rb+++ b/lib/post_revisor.rb@@ -280,6 +280,8 @@ class PostRevisor# @option opts [Boolean] :skip_staff_log Skip creating an entry in the staff action log# @option opts [Boolean] :silent Don't send notifications to user# @option opts [Boolean] :hidden Force the created revision to be hidden from non-staff users+ # @option opts [String] :expected_raw Reject the revision if the post changed before persistence+ # @option opts [String] :preserve_cooked_token Identifies a client that already rendered the change# @return [Boolean] Returns true if the revision was successful, false otherwisedef revise!(editor, fields, opts = {})@editor = editor@@ -361,6 +363,15 @@ class PostRevisor@should_bump_topic = falsePost.transaction do+ if (expected_raw = @opts[:expected_raw])+ locked_raw = Post.where(id: @post.id).lock("FOR UPDATE").pick(:raw)+ if locked_raw != expected_raw+ @post.errors.add(:base, :edit_conflict, message: I18n.t("edit_conflict"))+ @post_successfully_saved = false+ raise ActiveRecord::Rollback+ end+ end+revise_postyield if block_given?@@ -877,6 +888,10 @@ class PostRevisorDiscourseEvent.trigger(:before_post_publish_changes, post_changes, @topic_changes, options)+ if (token = @opts[:preserve_cooked_token])+ options[:preserve_cooked_token] = token+ end+@post.publish_change_to_clients!(:revised, options)enddiff --git a/plugins/checklist/app/controllers/checklist/checkboxes_controller.rb b/plugins/checklist/app/controllers/checklist/checkboxes_controller.rbnew file mode 100644index 00000000000..24df34e4fc1--- /dev/null+++ b/plugins/checklist/app/controllers/checklist/checkboxes_controller.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++module Checklist+ class CheckboxesController < ::ApplicationController+ MAX_TOGGLE_REQUESTS_PER_MINUTE = 60++ requires_plugin Checklist::PLUGIN_NAME+ requires_login+ before_action :rate_limit_checklist_toggles, only: :toggle++ def toggle+ Checklist::ToggleCheckbox.call(service_params) do+ on_success do |post:, resolved_toggles:|+ revised =+ resolved_toggles.any? { |toggle| toggle.checkbox.checked? != toggle.request[:checked] }+ render json: {+ cooked: post.cooked,+ last_editor_id: post.last_editor_id,+ raw: post.raw,+ revised:,+ updated_at: post.updated_at.iso8601(3),+ version: post.version,+ }+ end+ on_failed_contract do |contract|+ render json: failed_json.merge(errors: contract.errors.full_messages),+ status: :bad_request+ end+ on_model_not_found(:post) { raise Discourse::NotFound }+ on_failed_policy(:can_edit_post) { raise Discourse::InvalidAccess }+ on_failed_policy(:post_unchanged) do |post:, params:|+ render_checklist_conflict(post, retryable: checklist_conflict_retryable?(post, params))+ end+ on_failed_policy(:checkbox_counts_unchanged) { |post:| render_checklist_conflict(post) }+ on_failed_policy(:checkboxes_found) { |post:| render_checklist_conflict(post) }+ on_failed_policy(:checkboxes_toggleable) do+ render json: failed_json.merge(errors: [I18n.t("checklist.checkbox_locked")]),+ status: :unprocessable_entity+ end+ on_failed_step(:revise_post) do |step, post:, params:|+ if step.error == :edit_conflict+ render_checklist_conflict(post, retryable: checklist_conflict_retryable?(post, params))+ else+ render json: failed_json.merge(errors: [I18n.t("checklist.revision_failed")]),+ status: :unprocessable_entity+ end+ end+ on_failure { render json: failed_json, status: :unprocessable_entity }+ end+ end++ private++ def rate_limit_checklist_toggles+ RateLimiter.new(+ current_user,+ "checklist_toggle",+ MAX_TOGGLE_REQUESTS_PER_MINUTE,+ 1.minute,+ ).performed!+ end++ def checklist_conflict_retryable?(post, params)+ Checklist::ToggleCheckbox.retryable_conflict?(post:, expected_raw: params.expected_raw)+ end++ def render_checklist_conflict(post, retryable: false)+ post.reload+ render json:+ failed_json.merge(+ errors: [I18n.t("checklist.checkboxes_changed")],+ raw: post.raw,+ updated_at: post.updated_at.iso8601(3),+ retryable:,+ ),+ status: :conflict+ end+ end+enddiff --git a/plugins/checklist/app/services/checklist/toggle_checkbox.rb b/plugins/checklist/app/services/checklist/toggle_checkbox.rbnew file mode 100644index 00000000000..41a340755d1--- /dev/null+++ b/plugins/checklist/app/services/checklist/toggle_checkbox.rb@@ -0,0 +1,179 @@+# frozen_string_literal: true++module Checklist+ class ToggleCheckbox+ include Service::Base++ MAX_BATCH_SIZE = 50+ INTEGER_TYPE = ActiveModel::Type::Integer.new+ BOOLEAN_TYPE = ActiveModel::Type::Boolean.new+ ResolvedToggle = Data.define(:request, :location, :checkbox)++ params do+ attribute :post_id, :integer+ attribute :toggles, :array+ attribute :expected_raw, :string+ attribute :expected_updated_at, :string+ attribute :mutation_id, :string++ before_validation do+ self.toggles =+ toggles.map do |toggle|+ values = toggle.respond_to?(:to_h) ? toggle.to_h.symbolize_keys : {}+ {+ checkbox_index: INTEGER_TYPE.cast(values[:checkbox_index]),+ checkbox_count: INTEGER_TYPE.cast(values[:checkbox_count]),+ checkbox_source: values[:checkbox_source].presence,+ checked: BOOLEAN_TYPE.cast(values[:checked]),+ }+ end if toggles.is_a?(Array)+ end++ validates :post_id, presence: true+ validates :toggles, presence: true, length: { maximum: MAX_BATCH_SIZE }+ validates :expected_raw,+ presence: true,+ length: {+ maximum: -> { SiteSetting.max_post_length },+ }+ validates :expected_updated_at, presence: true+ validates :mutation_id, presence: true, length: { maximum: 100 }+ validate :toggles_are_valid, if: -> { toggles.present? }+ validate :toggle_targets_are_unique, if: -> { toggles.present? }++ private++ def toggles_are_valid+ toggles.each do |toggle|+ valid_index = toggle[:checkbox_index].is_a?(Integer) && toggle[:checkbox_index] >= 0+ valid_count = toggle[:checkbox_count].is_a?(Integer) && toggle[:checkbox_count] > 0+ valid_source =+ toggle[:checkbox_source].to_s.match?(/\A\d+:\d+\z/) &&+ toggle[:checkbox_source].length <= 30+ valid_checked = [true, false].include?(toggle[:checked])++ valid_target = toggle[:checkbox_source].present? ? valid_source : valid_count+ errors.add(:toggles, :invalid) if !valid_index || !valid_target || !valid_checked+ end+ end++ def toggle_targets_are_unique+ targets =+ toggles.map do |toggle|+ toggle[:checkbox_source].presence || "index:#{toggle[:checkbox_index]}"+ end+ errors.add(:toggles, :taken) if targets.uniq.size != targets.size+ end+ end++ policy :checklist_enabled+ model :post+ policy :can_edit_post+ policy :post_unchanged+ model :resolved_toggles, :resolve_toggles+ policy :checkbox_counts_unchanged+ policy :checkboxes_found+ policy :checkboxes_toggleable++ only_if :checkbox_states_differ do+ step :revise_post+ end++ def self.retryable_conflict?(post:, expected_raw:)+ normalize_checkbox_states(expected_raw) == normalize_checkbox_states(post.reload.raw)+ end++ def self.normalize_checkbox_states(raw)+ raw.gsub(/\[(?: |x)?\]/, "[ ]")+ end+ private_class_method :normalize_checkbox_states++ private++ def checklist_enabled+ SiteSetting.checklist_enabled+ end++ def fetch_post(params:)+ Post.find_by(id: params.post_id)+ end++ def can_edit_post(guardian:, post:)+ guardian.can_edit?(post)+ end++ def post_unchanged(post:, params:)+ expected = Time.iso8601(params.expected_updated_at)+ post.raw == params.expected_raw &&+ (expected.to_r * 1000).floor == (post.updated_at.to_time.to_r * 1000).floor+ rescue ArgumentError, TypeError+ false+ end++ def resolve_toggles(post:, params:)+ targets =+ params.toggles.map do |toggle|+ CheckboxLocator::Target.new(+ index: toggle[:checkbox_index],+ source: toggle[:checkbox_source].presence,+ )+ end+ locations = CheckboxLocator.call_many(post:, targets:)++ params+ .toggles+ .zip(locations)+ .map do |request, location|+ ResolvedToggle.new(request:, location:, checkbox: location.checkbox)+ end+ end++ def checkbox_counts_unchanged(resolved_toggles:)+ resolved_toggles.all? do |toggle|+ toggle.request[:checkbox_source].present? ||+ toggle.location.count == toggle.request[:checkbox_count]+ end+ end++ def checkboxes_found(resolved_toggles:)+ resolved_toggles.all? { |toggle| toggle.checkbox.present? }+ end++ def checkboxes_toggleable(resolved_toggles:)+ resolved_toggles.all? { |toggle| toggle.checkbox.toggleable? }+ end++ def checkbox_states_differ(resolved_toggles:)+ resolved_toggles.any? { |toggle| toggle.checkbox.checked? != toggle.request[:checked] }+ end++ def revise_post(post:, resolved_toggles:, params:, guardian:)+ expected_raw = post.raw+ changed_toggles =+ resolved_toggles.select { |toggle| toggle.checkbox.checked? != toggle.request[:checked] }+ new_raw = expected_raw+ changed_toggles+ .sort_by { |toggle| -toggle.checkbox.offset }+ .each do |toggle|+ new_raw = toggle.checkbox.replace_in(new_raw, checked: toggle.request[:checked])+ end++ revised =+ PostRevisor.new(post).revise!(+ guardian.user,+ { raw: new_raw },+ bypass_bump: true,+ expected_raw:,+ preserve_cooked_token: params.mutation_id,+ )++ if !revised+ if post.errors.details[:base].any? { |error| error[:error] == :edit_conflict }+ fail!(:edit_conflict)+ else+ fail!(:revision_failed)+ end+ end+ end+ end+enddiff --git a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.jsindex a187c8b183f..281e7c5c07f 100644--- a/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js+++ b/plugins/checklist/assets/javascripts/discourse/initializers/checklist.js@@ -1,14 +1,58 @@+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 MAX_CONFLICT_RETRIES = 2;++function timestampIsOlder(candidate, reference) {+ const candidateTime = Date.parse(candidate);+ const referenceTime = Date.parse(reference);+ return (+ !Number.isNaN(candidateTime) &&+ !Number.isNaN(referenceTime) &&+ candidateTime < referenceTime+ );+}++function setCheckboxState(checkbox, checked) {+ checkbox.classList.toggle("checked", checked);+ checkbox.classList.toggle("fa-square-o", !checked);+ checkbox.classList.toggle("fa-square-check-o", checked);+ checkbox.setAttribute("aria-checked", checked.toString());+}++function checkboxLabel(checkbox) {+ const parts = [];+ let sibling = checkbox.nextSibling;++ while (sibling) {+ if (+ sibling.nodeType === Node.ELEMENT_NODE &&+ (sibling.classList.contains("chcklst-box") ||+ sibling.querySelector(".chcklst-box"))+ ) {+ break;+ }++ parts.push(sibling.textContent);+ sibling = sibling.nextSibling;+ }++ const label = parts.join("").replaceAll("\u200b", "").trim();+ return label.slice(0, 200) || i18n("checklist.item");+}+function initializePlugin(api) {const siteSettings = api.container.lookup("service:site-settings");if (siteSettings.checklist_enabled) {- api.decorateCookedElement(checklistSyntax);+ api.decorateCookedElement(checklistSyntax, { onlyStream: true });api.registerRichEditorExtension(richEditorExtension);api.addComposerToolbarPopupMenuOption({@@ -45,8 +89,8 @@ function hasPrecedingContent(node) {}function addUlClasses(boxes) {- boxes.forEach((val) => {- let parent = val.parentElement;+ boxes.forEach((box) => {+ let parent = box.parentElement;if (parent.nodeName === "P" &&parent.parentElement.firstElementChild === parent@@ -57,124 +101,349 @@ function addUlClasses(boxes) {if (parent.nodeName === "LI" &&parent.parentElement.nodeName === "UL" &&- !hasPrecedingContent(val)+ !hasPrecedingContent(box)) {parent.classList.add("has-checkbox");- val.classList.add("list-item-checkbox");- if (!val.nextSibling) {- val.insertAdjacentHTML("afterend", "​"); // Ensure otherwise empty <li> does not collapse height+ box.classList.add("list-item-checkbox");+ if (!box.nextSibling) {+ // Prevent an otherwise empty list item from collapsing.+ box.insertAdjacentHTML("afterend", "​");}}});}-export function checklistSyntax(elem, postDecorator) {- const boxes = [...elem.getElementsByClassName("chcklst-box")];- addUlClasses(boxes);+function configureAccessibility(box, editable) {+ const checked = box.classList.contains("checked");+ const permanent = box.classList.contains("permanent");- const postModel = postDecorator?.getModel();+ box.classList.toggle("is-interactive", editable && !permanent);+ box.setAttribute("role", "checkbox");+ box.setAttribute("aria-checked", checked.toString());+ box.setAttribute("aria-label", checkboxLabel(box));+ box.removeAttribute("aria-disabled");+ box.removeAttribute("aria-readonly");+ box.removeAttribute("tabindex");- if (!postModel?.can_edit) {- return;+ if (permanent) {+ box.setAttribute("aria-disabled", "true");+ } else if (editable) {+ box.setAttribute("tabindex", "0");+ } else {+ box.setAttribute("aria-readonly", "true");}+}- boxes.forEach((val, idx) => {- val.onclick = async (event) => {- const box = event.currentTarget;- const classList = box.classList;+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;- if (classList.contains("permanent") || classList.contains("readonly")) {- return;+ const stopSpinner = (index) => {+ clearTimeout(spinnerStates.get(index)?.timer);+ spinnerStates.delete(index);+ boxes[index].classList.remove("is-saving");+ boxes[index].removeAttribute("aria-disabled");+ };++ const updateBusyState = (index, busy) => {+ const box = boxes[index];++ 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");+ return;+ }- const newValue = classList.contains("checked") ? "[ ]" : "[x]";- const template = document.createElement("template");- template.innerHTML = iconHTML("spinner", {- class: "fa-spin list-item-checkbox",- });- box.insertAdjacentElement("afterend", template.content.firstChild);- box.classList.add("hidden");- boxes.forEach((e) => e.classList.add("readonly"));-- try {- const post = await ajax(`/posts/${postModel.id}`);- const blocks = [];-- // Computing offsets where checkbox are not evaluated (i.e. inside- // code blocks).- [- // inline code- /`[^`\n]*\n?[^`\n]*`/gm,- // multi-line code- /^```[^]*?^```/gm,- // bbcode- /\[code\][^]*?\[\/code\]/gm,- // italic/bold- /_(?=\S).*?\S_/gm,- // strikethrough- /~~(?=\S).*?\S~~/gm,- ].forEach((regex) => {- let match;- while ((match = regex.exec(post.raw)) != null) {- blocks.push([match.index, match.index + match[0].length]);+ box.removeAttribute("aria-busy");+ const spinnerState = spinnerStates.get(index);+ if (!spinnerState) {+ box.classList.remove("is-saving");+ return;+ }++ clearTimeout(spinnerState.timer);+ const elapsed = performance.now() - spinnerState.startedAt;+ const remaining = Math.max(0, MINIMUM_SPINNER_DURATION - elapsed);++ if (remaining === 0) {+ stopSpinner(index);+ } else {+ spinnerState.timer = setTimeout(() => stopSpinner(index), remaining);+ }+ };++ const restoreConfirmedStates = () => {+ boxes.forEach((box, index) => {+ setCheckboxState(box, confirmedStates[index]);+ updateBusyState(index, false);+ });+ };++ const savePendingStates = async () => {+ if (saving) {+ return;+ }++ saving = true;+ let retryBatch;++ 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);}});- [- // italic/bold- /([^\[\n]|^)\*\S.+?\S\*(?=[^\]\n]|$)/gm,- ].forEach((regex) => {- let match;- while ((match = regex.exec(post.raw)) != null) {- // Simulate lookbehind - skip the first character- blocks.push([match.index + 1, match.index + match[0].length]);+ 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);+ break;}++ if (!active) {+ 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,+ };+ 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,+ };- // make the first run go to index = 0- let nth = -1;- let found = false;+ 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;+ }- const newRaw = post.raw.replace(- /\[( |x)?\]/gi,- (match, ignored, off) => {- if (found) {- return match;- }+ if (response.revised) {+ startOptimisticUpdateExpiration();+ } else {+ unregisterOptimisticUpdate();+ }+ unregisterInFlightOptimisticUpdate = undefined;- // skip empty image URLs - ""- if (off > 0 && post.raw[off - 1] === "!") {- return match;+ if (!responseIsStale && (!active || pendingStates.size === 0)) {+ postModel.raw = response.raw;+ if (active) {+ deferredCooked = {+ cooked: response.cooked,+ updatedAt: response.updated_at,+ };+ } else {+ postModel.cooked = response.cooked;}+ }++ if (!active) {+ break;+ }- // skip escaped opening bracket - "\[x]"- if (off > 0 && post.raw[off - 1] === "\\") {- return match;+ batch.states.forEach(([index, desiredState]) => {+ confirmedStates[index] = desiredState;+ if (pendingStates.get(index) === desiredState) {+ pendingStates.delete(index);}+ });+ expectedRaw = response.raw;+ expectedUpdatedAt = response.updated_at;+ } catch (error) {+ unregisterInFlightOptimisticUpdate = undefined;+ unregisterOptimisticUpdate();- nth += blocks.every(- (b) => b[0] >= off + match.length || off > b[1]- );+ if (!active) {+ break;+ }- if (nth === idx) {- found = true; // Do not replace any further matches- return newValue;+ 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;}+ retryBatch = {+ states: batch.states,+ conflictRetries: batch.conflictRetries + 1,+ };+ continue;+ }- return match;+ 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);+ }+ }+ }+ }+ }+ } finally {+ saving = false;+ }+ };++ boxes.forEach((box, index) => {+ if (box.classList.contains("permanent")) {+ return;+ }- await postModel.save({ raw: newRaw });- } catch (e) {- popupAjaxError(e);- } finally {- boxes.forEach((e) => e.classList.remove("readonly"));- box.classList.remove("hidden");- box.parentElement.querySelector(".fa-spin").remove();+ const toggle = () => {+ if (box.classList.contains("is-saving")) {+ return;}++ 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;+ }++ event.preventDefault();+ toggle();+ };++ box.addEventListener("click", onClick);+ box.addEventListener("keydown", onKeyDown);+ cleanups.push(() => {+ box.removeEventListener("click", onClick);+ box.removeEventListener("keydown", onKeyDown);+ });});++ return () => {+ active = false;+ pendingStates.clear();+ unregisterInFlightOptimisticUpdate?.();+ unregisterInFlightOptimisticUpdate = undefined;+ spinnerStates.forEach(({ timer }) => clearTimeout(timer));+ boxes.forEach((box) => {+ box.classList.remove("is-saving");+ 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;+ }+ });+ }+ };+}++export function checklistSyntax(elem, postDecorator) {+ const boxes = [...elem.getElementsByClassName("chcklst-box")];+ addUlClasses(boxes);++ const postModel = postDecorator?.getModel();+ const editable = postModel?.can_edit === true;+ const interactiveBoxes = boxes.filter((box) => !box.closest("aside.quote"));+ const interactiveBoxSet = new Set(interactiveBoxes);++ boxes.forEach((box) =>+ configureAccessibility(box, editable && interactiveBoxSet.has(box))+ );++ if (editable) {+ return addToggleBehavior(interactiveBoxes, postModel);+ }}export default {diff --git a/plugins/checklist/assets/javascripts/lib/discourse-markdown/checklist.js b/plugins/checklist/assets/javascripts/lib/discourse-markdown/checklist.jsindex a2428d390da..3a36b158e51 100644--- a/plugins/checklist/assets/javascripts/lib/discourse-markdown/checklist.js+++ b/plugins/checklist/assets/javascripts/lib/discourse-markdown/checklist.js@@ -1,94 +1,178 @@-const REGEX = /\[( |x)?\]/gi;+const CHECKLIST_HTML_PATTERN = /\bchcklst-box\b|\bdata-chk-src\b/i;++function neutralizeRawChecklistMarkup(state) {+ const neutralize = (token) => {+ if (+ (token.type === "html_inline" || token.type === "html_block") &&+ CHECKLIST_HTML_PATTERN.test(token.content)+ ) {+ token.type = "text";+ token.tag = "";+ token.nesting = 0;+ }+ };++ for (const block of state.tokens) {+ neutralize(block);+ block.children?.forEach(neutralize);+ }+}++function tokenizeChecklistCandidate(state, silent) {+ const candidate = state.src.slice(state.pos, state.pos + 3);+ const marker = candidate.startsWith("[]")+ ? "[]"+ : candidate.match(/^\[[ xX]\]$/)?.[0];+ if (!marker) {+ return false;+ }++ const sourceOffset = state.pos;+ state.pos += marker.length;++ if (!silent) {+ const token = state.push("checklist_candidate", "", 0);+ token.content = marker;+ token.meta = { checklistSourceOffset: sourceOffset };+ }++ return true;+}-function getClasses(str) {- switch (str) {- case "x":+function getClasses(marker) {+ switch (marker) {+ case "[x]":return "checked fa fa-square-check-o";- case "X":+ case "[X]":return "checked permanent fa fa-square-check";default:return "fa fa-square-o";}}-function addCheckbox(result, content, match, state) {- const classes = getClasses(match[1]);+function markerLocations(content, baseLine, lineMarkerCounts) {+ const locations = new Map();+ let line = baseLine;+ let scannedThrough = 0;++ // The ordinal includes markers consumed by other Markdown rules so Ruby can+ // resolve the same physical source position without reimplementing Markdown.+ for (const match of content.matchAll(/\[[ xX]?\]/g)) {+ for (let index = scannedThrough; index < match.index; index += 1) {+ if (content.charCodeAt(index) === 0x0a) {+ line += 1;+ }+ }+ scannedThrough = match.index + match[0].length;- const checkOpenToken = new state.Token("check_open", "span", 1);- checkOpenToken.attrs = [["class", `chcklst-box ${classes}`]];- result.push(checkOpenToken);+ const nth = lineMarkerCounts.get(line) ?? 0;+ lineMarkerCounts.set(line, nth + 1);+ locations.set(match.index, { line, nth, marker: match[0] });+ }- const checkCloseToken = new state.Token("check_close", "span", -1);- result.push(checkCloseToken);+ return locations;}-function applyCheckboxes(content, state) {- let match;- let result = null;- let pos = 0;-- while ((match = REGEX.exec(content))) {- if (match.index > pos) {- result = result || [];- const token = new state.Token("text", "", 0);- token.content = content.slice(pos, match.index);- result.push(token);- }-- pos = match.index + match[0].length;+function processChecklist(state) {+ neutralizeRawChecklistMarkup(state);- result = result || [];- addCheckbox(result, content, match, state);+ if (!state.src.includes("[")) {+ return;}- if (result && pos < content.length) {- const token = new state.Token("text", "", 0);- token.content = content.slice(pos);- result.push(token);- }+ const sourceLines = state.src.split("\n");+ const sourceLineMarkers = new Map();+ const lineMarkerCounts = new Map();+ let tableRowLine;- return result;-}+ const verifiedLocation = (location) => {+ if (!location) {+ return;+ }-function processChecklist(state) {- let i,- j,- l,- tokens,- token,- blockTokens = state.tokens,- nesting = 0;-- for (j = 0, l = blockTokens.length; j < l; j++) {- if (blockTokens[j].type !== "inline") {+ let markers = sourceLineMarkers.get(location.line);+ if (!markers) {+ markers = [+ ...(sourceLines[location.line] ?? "").matchAll(/\[[ xX]?\]/g),+ ].map((match) => match[0]);+ sourceLineMarkers.set(location.line, markers);+ }++ if (markers[location.nth] === location.marker) {+ return location;+ }+ };++ for (const block of state.tokens) {+ if (block.type === "tr_open") {+ tableRowLine = block.map?.[0];continue;}- tokens = blockTokens[j].children;-- // We scan from the end, to keep position when new tags are added.- // Use reversed logic in links start/end match- for (i = tokens.length - 1; i >= 0; i--) {- token = tokens[i];-- nesting += token.nesting;-- if (token.type === "text" && nesting === 0) {- const processed = applyCheckboxes(token.content, state);- if (processed) {- blockTokens[j].children = tokens = state.md.utils.arrayReplaceAt(- tokens,- i,- processed- );+ if (block.type === "tr_close") {+ tableRowLine = undefined;+ continue;+ }+ if (block.type !== "inline") {+ continue;+ }++ const baseLine = block.map?.[0] ?? tableRowLine;+ const locations =+ baseLine === undefined+ ? new Map()+ : markerLocations(block.content, baseLine, lineMarkerCounts);+ const replacements = [];+ let nesting = 0;++ for (let index = 0; index < block.children.length; index += 1) {+ const token = block.children[index];++ if (token.type !== "checklist_candidate") {+ nesting += token.nesting;+ continue;+ }++ if (nesting !== 0) {+ const text = new state.Token("text", "", 0);+ text.content = token.content;+ replacements.push({ index, newTokens: [text] });+ continue;+ }++ const checkbox = new state.Token("check_open", "span", 1);+ checkbox.attrs = [["class", `chcklst-box ${getClasses(token.content)}`]];++ if (baseLine !== undefined && token.content !== "[X]") {+ const location = verifiedLocation(+ locations.get(token.meta.checklistSourceOffset)+ );+ if (location) {+ checkbox.attrs.push([+ "data-chk-src",+ `${location.line}:${location.nth}`,+ ]);}}++ replacements.push({+ index,+ newTokens: [checkbox, new state.Token("check_close", "span", -1)],+ });+ }++ for (let index = replacements.length - 1; index >= 0; index -= 1) {+ block.children = state.md.utils.arrayReplaceAt(+ block.children,+ replacements[index].index,+ replacements[index].newTokens+ );}}}export function setup(helper) {helper.registerOptions((opts, siteSettings) => {- opts.features["checklist"] = !!siteSettings.checklist_enabled;+ opts.features.checklist = !!siteSettings.checklist_enabled;});helper.allowList([@@ -96,9 +180,11 @@ export function setup(helper) {"span.chcklst-box fa fa-square-o","span.chcklst-box checked fa fa-square-check-o","span.chcklst-box checked permanent fa fa-square-check",+ "span[data-chk-src]",]);- helper.registerPlugin((md) =>- md.core.ruler.before("text_join", "checklist", processChecklist)- );+ helper.registerPlugin((md) => {+ md.inline.ruler.push("checklist_candidate", tokenizeChecklistCandidate);+ md.core.ruler.before("text_join", "checklist", processChecklist);+ });}diff --git a/plugins/checklist/assets/stylesheets/checklist.scss b/plugins/checklist/assets/stylesheets/checklist.scssindex edf7dc4c2eb..be99f0dee0d 100644--- a/plugins/checklist/assets/stylesheets/checklist.scss+++ b/plugins/checklist/assets/stylesheets/checklist.scss@@ -17,10 +17,44 @@ span.chcklst-stroked {}span.chcklst-box {- cursor: pointer;display: inline-flex;+ position: relative;vertical-align: -0.125em;+ &.is-interactive {+ 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;+ }+ }++ &:focus-visible {+ outline: 2px solid var(--tertiary);+ outline-offset: 0.2em;+ }+ }++ &.permanent {+ cursor: default;+ }+&:not(.checked) {&.fa-square-o {@include checklist-svg-icon(@@ -46,13 +80,11 @@ span.chcklst-box {);}}+}- &.readonly {- pointer-events: none;- }-- &.hidden {- display: none;+@media (prefers-reduced-motion: reduce) {+ span.chcklst-box.is-interactive .checklist-spinner {+ animation: none;}}@@ -64,24 +96,6 @@ ul li.has-checkbox {}}-.fa-spin {- display: inline-flex;- vertical-align: text-bottom;- animation: fa-spin 2s infinite linear;- width: 1em;- height: 1em;-}--@keyframes fa-spin {- 0% {- transform: rotate(0deg);- }-- 100% {- transform: rotate(1turn);- }-}-.ProseMirror {ul > li.has-checkbox {list-style-type: none;diff --git a/plugins/checklist/config/locales/client.en.yml b/plugins/checklist/config/locales/client.en.ymlindex 4c5f683d2d1..ee780c0f18d 100644--- a/plugins/checklist/config/locales/client.en.yml+++ b/plugins/checklist/config/locales/client.en.yml@@ -1,5 +1,6 @@en:js:checklist:+ item: "Checklist item"composer:checklist: "Check list"diff --git a/plugins/checklist/config/locales/server.en.yml b/plugins/checklist/config/locales/server.en.ymlindex 4e311969614..d8747f9a04d 100644--- a/plugins/checklist/config/locales/server.en.yml+++ b/plugins/checklist/config/locales/server.en.yml@@ -1,3 +1,7 @@en:site_settings:checklist_enabled: "Enable checklist plugin?"+ checklist:+ checkboxes_changed: "This post changed since it was loaded. Refresh and try again."+ checkbox_locked: "This checklist item cannot be changed."+ revision_failed: "The checkbox could not be updated."diff --git a/plugins/checklist/config/routes.rb b/plugins/checklist/config/routes.rbnew file mode 100644index 00000000000..7f065c7f67f--- /dev/null+++ b/plugins/checklist/config/routes.rb@@ -0,0 +1,3 @@+# frozen_string_literal: true++Checklist::Engine.routes.draw { put "/toggle" => "checkboxes#toggle" }diff --git a/plugins/checklist/lib/checklist/checkbox.rb b/plugins/checklist/lib/checklist/checkbox.rbnew file mode 100644index 00000000000..d191115b63d--- /dev/null+++ b/plugins/checklist/lib/checklist/checkbox.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++module Checklist+ class Checkbox+ CHECKED = "[x]"+ UNCHECKED = "[ ]"++ attr_reader :offset, :segment++ def self.permanent+ new(offset: nil, segment: nil, permanent: true)+ end++ def initialize(offset:, segment:, permanent: false)+ @offset = offset+ @segment = segment+ @permanent = permanent+ end++ def permanent?+ @permanent+ end++ def toggleable?+ !permanent? && !offset.nil?+ end++ def checked?+ segment == CHECKED+ end++ def replace_in(raw, checked:)+ raise ArgumentError, "checkbox is not toggleable" if !toggleable?++ raw[0...offset] + (checked ? CHECKED : UNCHECKED) + raw[(offset + segment.length)..]+ end+ end+enddiff --git a/plugins/checklist/lib/checklist/checkbox_locator.rb b/plugins/checklist/lib/checklist/checkbox_locator.rbnew file mode 100644index 00000000000..f3a3009bae3--- /dev/null+++ b/plugins/checklist/lib/checklist/checkbox_locator.rb@@ -0,0 +1,90 @@+# frozen_string_literal: true++module Checklist+ class CheckboxLocator+ Location = Data.define(:count, :checkbox, :needs_recook)+ Target = Data.define(:index, :source)+ SOURCE_PATTERN = /\A(\d+):(\d+)\z/++ def self.call(post:, index:, source: nil)+ call_many(post:, targets: [Target.new(index:, source:)]).first+ end++ def self.call_many(post:, targets:)+ new(post).call_many(targets)+ end++ def initialize(post)+ @post = post+ end++ def call_many(targets)+ locations = build(@post.cooked, targets)+ return locations if locations.none?(&:needs_recook)++ build(@post.cook(@post.raw), targets)+ end++ private++ def build(cooked, targets)+ nodes =+ Nokogiri::HTML5.fragment(cooked).css("span.chcklst-box").reject { |node| quoted?(node) }+ if !source_hints_valid?(nodes)+ return targets.map { Location.new(count: nodes.size, checkbox: nil, needs_recook: true) }+ end++ targets.map { |target| build_location(nodes, target) }+ end++ def build_location(nodes, target)+ node =+ if target.source.present?+ nodes.find { |candidate| candidate["data-chk-src"] == target.source }+ else+ nodes[target.index]+ end+ return Location.new(count: nodes.size, checkbox: nil, needs_recook: false) if node.nil?+ if node.classes.include?("permanent")+ return Location.new(count: nodes.size, checkbox: Checkbox.permanent, needs_recook: false)+ end++ checkbox = checkbox_for(node)+ Location.new(count: nodes.size, checkbox:, needs_recook: checkbox.nil?)+ end++ def quoted?(node)+ node.ancestors.any? do |ancestor|+ ancestor.name == "aside" && ancestor.classes.include?("quote")+ end+ end++ def source_hints_valid?(nodes)+ sources = Set.new++ nodes.each do |node|+ next if node.classes.include?("permanent")++ source = SOURCE_PATTERN.match(node["data-chk-src"].to_s)+ return false if source.nil? || !sources.add?(source[0])+ end++ true+ end++ def checkbox_for(node)+ source = SOURCE_PATTERN.match(node["data-chk-src"].to_s)+ return if source.nil?++ checkbox = source_map.checkbox_at(line: source[1].to_i, nth: source[2].to_i)+ return if checkbox.nil?+ return if checkbox.checked? != node.classes.include?("checked")++ checkbox+ end++ def source_map+ @source_map ||= SourceMap.new(@post.raw)+ end+ end+enddiff --git a/plugins/checklist/lib/checklist/engine.rb b/plugins/checklist/lib/checklist/engine.rbnew file mode 100644index 00000000000..533f99e3df7--- /dev/null+++ b/plugins/checklist/lib/checklist/engine.rb@@ -0,0 +1,8 @@+# frozen_string_literal: true++module Checklist+ class Engine < ::Rails::Engine+ engine_name PLUGIN_NAME+ isolate_namespace Checklist+ end+enddiff --git a/plugins/checklist/lib/checklist/source_map.rb b/plugins/checklist/lib/checklist/source_map.rbnew file mode 100644index 00000000000..1e10dc042ae--- /dev/null+++ b/plugins/checklist/lib/checklist/source_map.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++module Checklist+ class SourceMap+ LINE_ENDING_PATTERN = /\r\n|\r|\n/+ MARKER_PATTERN = /\[[ xX]?\]/+ TOGGLEABLE_SEGMENTS = [Checkbox::UNCHECKED, Checkbox::CHECKED, "[]"].freeze++ def initialize(raw)+ @raw = raw+ end++ def checkbox_at(line:, nth:)+ line_start = line_starts[line]+ return if line_start.nil?++ line_end = line_starts[line + 1] || @raw.length+ line_content = @raw[line_start...line_end]+ # Count marker-shaped text consumed by Markdown too; the tokenizer uses the same physical ordinal.+ match = line_content.to_enum(:scan, MARKER_PATTERN).map { Regexp.last_match }[nth]+ return if match.nil? || TOGGLEABLE_SEGMENTS.exclude?(match[0])++ Checkbox.new(offset: line_start + match.begin(0), segment: match[0])+ end++ private++ def line_starts+ @line_starts ||=+ begin+ starts = [0]+ @raw.scan(LINE_ENDING_PATTERN) { starts << Regexp.last_match.end(0) }+ starts+ end+ end+ end+enddiff --git a/plugins/checklist/plugin.rb b/plugins/checklist/plugin.rbindex 98fecb015a5..a1830b5ffac 100644--- a/plugins/checklist/plugin.rb+++ b/plugins/checklist/plugin.rb@@ -10,4 +10,16 @@enabled_site_setting :checklist_enabledregister_asset "stylesheets/checklist.scss"-register_svg_icon "spinner"++module ::Checklist+ PLUGIN_NAME = "checklist"+end++require_relative "lib/checklist/checkbox"+require_relative "lib/checklist/source_map"+require_relative "lib/checklist/checkbox_locator"+require_relative "lib/checklist/engine"++after_initialize do+ Discourse::Application.routes.append { mount Checklist::Engine, at: "/checklist" }+enddiff --git a/plugins/checklist/spec/lib/checklist/checkbox_locator_spec.rb b/plugins/checklist/spec/lib/checklist/checkbox_locator_spec.rbnew file mode 100644index 00000000000..83a56317f9e--- /dev/null+++ b/plugins/checklist/spec/lib/checklist/checkbox_locator_spec.rb@@ -0,0 +1,171 @@+# frozen_string_literal: true++RSpec.describe Checklist::CheckboxLocator do+ before { SiteSetting.checklist_enabled = true }++ def locate(raw, index, cooked: PrettyText.cook(raw))+ post = Post.new(raw:, cooked:, topic_id: 1)+ described_class.call(post:, index:)+ end++ describe ".call" do+ it "uses source hints from stored cooked without recooking" do+ raw = "- [ ] first\n- [x] second"+ cooked = PrettyText.cook(raw)+ Post.any_instance.expects(:cook).never++ first = locate(raw, 0, cooked:)+ second = locate(raw, 1, cooked:)++ expect([first.count, first.checkbox.offset, first.checkbox.segment]).to eq([2, 2, "[ ]"])+ expect([second.count, second.checkbox.offset, second.checkbox.segment]).to eq([2, 14, "[x]"])+ end++ it "performs one fallback cook for legacy stored HTML" do+ raw = "- [ ] first\n- [x] second"+ cooked = PrettyText.cook(raw)+ legacy_cooked = cooked.gsub(%r{ data-chk-src="[^"]+"}, "")+ Post.any_instance.expects(:cook).once.with(raw).returns(cooked)++ location = locate(raw, 1, cooked: legacy_cooked)++ expect(location.checkbox.replace_in(raw, checked: false)).to eq("- [ ] first\n- [ ] second")+ end++ it "ignores marker-shaped text that Markdown does not render as controls" do+ raw = <<~MARKDOWN+ `[x]`+ *[x]*+ ~~[x]~~+ [x](https://example.com)+ [code][x][/code]+ ```+ [x]+ ```+ [ ] first+ [x] second+ MARKDOWN++ first = locate(raw, 0)+ second = locate(raw, 1)++ expect([first.count, first.checkbox.segment]).to eq([2, "[ ]"])+ expect(first.checkbox.replace_in(raw, checked: true)).to end_with("[x] first\n[x] second\n")+ expect(second.checkbox.replace_in(raw, checked: false)).to end_with("[ ] first\n[ ] second\n")+ end++ it "maps past checkbox-shaped image and link metadata" do+ raw = <<~MARKDOWN+ [x]+ [link](<https://example.test/[x]> "[x]") [ ] visible+ MARKDOWN++ image_line = locate(raw, 0)+ link_line = locate(raw, 1)++ expect(image_line.checkbox.replace_in(raw, checked: false)).to start_with(+ "[ ]",+ )+ expect(link_line.checkbox.replace_in(raw, checked: true)).to end_with(+ '[link](<https://example.test/[x]> "[x]") [x] visible' + "\n",+ )+ end++ it "excludes checkboxes copied into quote asides" do+ raw = <<~MARKDOWN+ [quote="Other user"]+ [ ] quoted+ [/quote]++ [ ] own+ MARKDOWN++ location = locate(raw, 0)++ expect(location.count).to eq(1)+ expect(location.checkbox.replace_in(raw, checked: true)).to end_with("[x] own\n")+ end++ it "maps checkboxes in blockquotes, lists, and table cells" do+ raw = <<~MARKDOWN+ > - [ ] quoted++ | a | b |+ |---|---|+ | [x] no | [ ] go |+ MARKDOWN++ quoted = locate(raw, 0)+ first_cell = locate(raw, 1)+ second_cell = locate(raw, 2)++ expect(quoted.checkbox.replace_in(raw, checked: true)).to include("> - [x] quoted")+ expect(first_cell.checkbox.replace_in(raw, checked: false)).to include("| [ ] no | [ ] go |")+ expect(second_cell.checkbox.replace_in(raw, checked: true)).to include("| [x] no | [x] go |")+ end++ it "handles date-range BBCode before checkboxes" do+ raw = <<~MARKDOWN+ [date-range from=2024-03-22 to=2024-03-23]++ [ ] task 1+ [x] task 2+ MARKDOWN++ expect(locate(raw, 0).checkbox.replace_in(raw, checked: true)).to include("[x] task 1")+ expect(locate(raw, 1).checkbox.replace_in(raw, checked: false)).to include("[ ] task 2")+ end++ it "handles escaped markers, Unicode, legacy markers, and CRLF" do+ raw = "π \\[x] escaped\r\n[] first\r\n[x] second"++ first = locate(raw, 0)+ second = locate(raw, 1)++ expect(first.checkbox.replace_in(raw, checked: true)).to eq(+ "π \\[x] escaped\r\n[x] first\r\n[x] second",+ )+ expect(second.checkbox.replace_in(raw, checked: false)).to eq(+ "π \\[x] escaped\r\n[] first\r\n[ ] second",+ )+ end++ it "identifies permanent checkboxes without a mutable source hint" do+ raw = "[X] permanent\n[x] regular"++ permanent = locate(raw, 0)+ regular = locate(raw, 1)++ expect([permanent.count, permanent.checkbox.permanent?]).to eq([2, true])+ expect([regular.count, regular.checkbox.toggleable?]).to eq([2, true])+ end++ it "returns the rendered count without a checkbox for an invalid index" do+ location = locate("[ ] only", 2)++ expect(location.count).to eq(1)+ expect(location.checkbox).to be_nil+ end++ it "fails closed when a contextual cook cannot produce source hints" do+ raw = "[ ] only"+ hintless_cooked = PrettyText.cook(raw).gsub(%r{ data-chk-src="[^"]+"}, "")+ Post.any_instance.expects(:cook).once.with(raw).returns(hintless_cooked)++ location = locate(raw, 0, cooked: hintless_cooked)++ expect([location.count, location.checkbox]).to eq([1, nil])+ end++ it "fails closed when a source hint does not agree with raw" do+ raw = "[ ] first\n[ ] second"+ fresh_cooked = PrettyText.cook(raw)+ cooked = fresh_cooked.sub('data-chk-src="0:0"', 'data-chk-src="1:0"')+ Post.any_instance.expects(:cook).once.with(raw).returns(fresh_cooked)++ location = locate(raw, 0, cooked:)++ expect(location.checkbox.offset).to eq(0)+ end+ end+enddiff --git a/plugins/checklist/spec/lib/checklist/checkbox_spec.rb b/plugins/checklist/spec/lib/checklist/checkbox_spec.rbnew file mode 100644index 00000000000..1ea1dab293c--- /dev/null+++ b/plugins/checklist/spec/lib/checklist/checkbox_spec.rb@@ -0,0 +1,68 @@+# frozen_string_literal: true++RSpec.describe Checklist::Checkbox do+ describe "#checked?" do+ it "is true for a checked segment" do+ expect(described_class.new(offset: 0, segment: "[x]", permanent: false)).to be_checked+ end++ it "is false for unchecked and legacy empty segments" do+ expect(described_class.new(offset: 0, segment: "[ ]", permanent: false)).not_to be_checked+ expect(described_class.new(offset: 0, segment: "[]", permanent: false)).not_to be_checked+ end+ end++ describe "#permanent?" do+ it "reflects the permanent flag" do+ expect(described_class.new(offset: nil, segment: nil, permanent: true)).to be_permanent+ expect(described_class.new(offset: 0, segment: "[x]", permanent: false)).not_to be_permanent+ end+ end++ describe "#toggleable?" do+ it "is true for a located, non-permanent checkbox" do+ expect(described_class.new(offset: 0, segment: "[ ]", permanent: false)).to be_toggleable+ end++ it "is false for a permanent checkbox" do+ expect(described_class.new(offset: nil, segment: nil, permanent: true)).not_to be_toggleable+ end++ it "is false for a checkbox that could not be located" do+ expect(described_class.new(offset: nil, segment: nil, permanent: false)).not_to be_toggleable+ end+ end++ describe "#replace_in" do+ it "checks an unchecked checkbox" do+ checkbox = described_class.new(offset: 2, segment: "[ ]", permanent: false)++ expect(checkbox.replace_in("- [ ] first", checked: true)).to eq("- [x] first")+ end++ it "unchecks a checked checkbox" do+ checkbox = described_class.new(offset: 0, segment: "[x]", permanent: false)++ expect(checkbox.replace_in("[x] done", checked: false)).to eq("[ ] done")+ end++ it "expands a legacy empty checkbox when checking it" do+ checkbox = described_class.new(offset: 0, segment: "[]", permanent: false)++ expect(checkbox.replace_in("[] first", checked: true)).to eq("[x] first")+ end++ it "rejects replacement for a non-toggleable checkbox" do+ expect { described_class.permanent.replace_in("[X] fixed", checked: false) }.to raise_error(+ ArgumentError,+ "checkbox is not toggleable",+ )+ end++ it "handles multibyte characters before the checkbox" do+ checkbox = described_class.new(offset: 9, segment: "[ ]", permanent: false)++ expect(checkbox.replace_in("π party\n\n[ ] task", checked: true)).to eq("π party\n\n[x] task")+ end+ end+enddiff --git a/plugins/checklist/spec/lib/checklist/source_map_spec.rb b/plugins/checklist/spec/lib/checklist/source_map_spec.rbnew file mode 100644index 00000000000..b24c1f6b114--- /dev/null+++ b/plugins/checklist/spec/lib/checklist/source_map_spec.rb@@ -0,0 +1,26 @@+# frozen_string_literal: true++RSpec.describe Checklist::SourceMap do+ describe "#checkbox_at" do+ it "resolves line ordinals against original CRLF and Unicode raw" do+ raw = "π [ ] visible\r\n[x] second"+ source_map = described_class.new(raw)++ first = source_map.checkbox_at(line: 0, nth: 2)+ second = source_map.checkbox_at(line: 1, nth: 0)++ expect(first.replace_in(raw, checked: true)).to start_with(+ "π [x] visible",+ )+ expect(second.replace_in(raw, checked: false)).to end_with("\r\n[ ] second")+ end++ it "rejects permanent and invalid source locations" do+ source_map = described_class.new("[X] permanent\n[ ] regular")++ expect(source_map.checkbox_at(line: 0, nth: 0)).to be_nil+ expect(source_map.checkbox_at(line: 10, nth: 0)).to be_nil+ expect(source_map.checkbox_at(line: 1, nth: 10)).to be_nil+ end+ end+enddiff --git a/plugins/checklist/spec/pretty_text_spec.rb b/plugins/checklist/spec/pretty_text_spec.rbindex e90ab1f7f63..b4aac4a2f91 100644--- a/plugins/checklist/spec/pretty_text_spec.rb+++ b/plugins/checklist/spec/pretty_text_spec.rb@@ -1,54 +1,108 @@# frozen_string_literal: true-describe PrettyText do- describe "markdown it" do- it "can properly bake boxes" do- md = <<~MD- [],[ ],[x],[X] are all checkboxes- `[ ]` [x](hello) *[ ]* **[ ]** _[ ]_ __[ ]__ ~~[ ]~~ are not checkboxes- MD-- html = <<~HTML- <p><span class="chcklst-box fa fa-square-o"></span>,<span class="chcklst-box fa fa-square-o"></span>,<span class="chcklst-box checked fa fa-square-check-o"></span>,<span class="chcklst-box checked permanent fa fa-square-check"></span> are all checkboxes<br>- <code>[ ]</code> <a>x</a> <em>[ ]</em> <strong>[ ]</strong> <em>[ ]</em> <strong>[ ]</strong> <s>[ ]</s> are not checkboxes</p>- HTML- cooked = PrettyText.cook(md)- expect(cooked).to eq(html.strip)+RSpec.describe PrettyText do+ before { SiteSetting.checklist_enabled = true }++ def checklist_nodes(raw)+ Nokogiri::HTML5.fragment(PrettyText.cook(raw)).css("span.chcklst-box")+ end++ describe "checklist Markdown" do+ it "renders mutable and permanent checkbox variants" do+ raw = "[],[ ],[x],[X] are all checkboxes"+ nodes = checklist_nodes(raw)++ expect(nodes.map { |node| node["data-chk-src"] }).to eq(["0:0", "0:1", "0:2", nil])+ expect(nodes.map { |node| node.classes.include?("checked") }).to eq(+ [false, false, true, true],+ )+ expect(nodes.last.classes).to include("permanent")+ end++ it "does not render markers in code, links, emphasis, or strikethrough" do+ raw = "`[ ]` [x](hello) *[ ]* **[ ]** _[ ]_ __[ ]__ ~~[ ]~~ [ ] real"+ nodes = checklist_nodes(raw)++ expect(nodes.size).to eq(1)+ expect(nodes.first["data-chk-src"]).to eq("0:7")endit "does not treat escaped brackets as checkboxes" do- md = <<~MD+ raw = <<~MARKDOWN\\[x] escaped opening bracket[x\\] escaped closing bracket\\[x\\] both brackets escaped\\[ ] escaped empty checkbox[x] real checkbox- MD-- cooked = PrettyText.cook(md)+ MARKDOWN+ cooked = PrettyText.cook(raw)+ nodes = Nokogiri::HTML5.fragment(cooked).css("span.chcklst-box")- expect(cooked.scan("chcklst-box").count).to eq(1)+ expect(nodes.size).to eq(1)+ expect(nodes.first["data-chk-src"]).to eq("4:0")expect(cooked).to include("[x] escaped opening bracket")expect(cooked).to include("[x] escaped closing bracket")expect(cooked).to include("[x] both brackets escaped")expect(cooked).to include("[ ] escaped empty checkbox")- expect(cooked).to include(- '<span class="chcklst-box checked fa fa-square-check-o"></span> real checkbox',- )end- it "handles escaped checkbox followed by real checkbox" do- md = <<~MD- \\[x] hello [x] world- MD+ it "preserves legacy stroked checklist markup" do+ raw = '<span class="chcklst-stroked">done</span>'++ expect(PrettyText.cook(raw)).to include('<span class="chcklst-stroked">done</span>')+ end++ it "does not allow raw HTML to forge interactive checklist controls" do+ raw = <<~MARKDOWN+ <span class="chcklst-box fa fa-square-o" data-chk-src="1:0"></span>- cooked = PrettyText.cook(md)+ `[ ]` [ ] real+ MARKDOWN+ cooked = PrettyText.cook(raw)+ nodes = Nokogiri::HTML5.fragment(cooked).css("span.chcklst-box")- expect(cooked.scan("chcklst-box").count).to eq(1)- expect(cooked).to include("[x] hello")- expect(cooked).to include(- '<span class="chcklst-box checked fa fa-square-check-o"></span> world',+ expect(nodes.map { |node| node["data-chk-src"] }).to eq(["2:1"])+ expect(cooked).to include("<span")+ end++ it "counts escaped and metadata markers when assigning line ordinals" do+ raw = <<~MARKDOWN+ \\[x] escaped [x] visible+ [x]+ [link](<https://example.test/[x]> "[x]") [ ] visible+ MARKDOWN++ expect(checklist_nodes(raw).map { |node| node["data-chk-src"] }).to eq(%w[0:1 1:2 2:2])+ end++ it "preserves surrounding cooked HTML while adding source hints" do+ raw = "[ ] before `[x]` [x] after"++ expect(PrettyText.cook(raw)).to eq(+ '<p><span class="chcklst-box fa fa-square-o" data-chk-src="0:0"></span> before <code>[x]</code> <span class="chcklst-box checked fa fa-square-check-o" data-chk-src="0:2"></span> after</p>',)end++ it "maps checkboxes in table header cells" do+ raw = <<~MARKDOWN+ | [ ] a | [x] b |+ |---|---|+ | c | d |+ MARKDOWN++ expect(checklist_nodes(raw).map { |node| node["data-chk-src"] }).to eq(%w[0:0 0:1])+ end++ it "maps source lines through blockquotes, lists, and tables" do+ raw = <<~MARKDOWN+ > - [ ] quoted++ | a | b |+ |---|---|+ | [x] no | [ ] go |+ MARKDOWN++ expect(checklist_nodes(raw).map { |node| node["data-chk-src"] }).to eq(%w[0:0 4:0 4:1])+ endendenddiff --git a/plugins/checklist/spec/requests/checklist/checkboxes_controller_spec.rb b/plugins/checklist/spec/requests/checklist/checkboxes_controller_spec.rbnew file mode 100644index 00000000000..38f873e84ba--- /dev/null+++ b/plugins/checklist/spec/requests/checklist/checkboxes_controller_spec.rb@@ -0,0 +1,191 @@+# frozen_string_literal: true++RSpec.describe Checklist::CheckboxesController do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, user: user) }++ fab!(:post) { Fabricate(:post, topic: topic, user: user, raw: "- [ ] first\n- [x] second") }++ before { SiteSetting.checklist_enabled = true }++ describe "#toggle" do+ let(:toggle) { { checkbox_index: 0, checkbox_source: "0:0", checked: true } }+ let(:params) do+ {+ post_id: post.id,+ toggles: [toggle],+ expected_raw: post.raw,+ expected_updated_at: post.updated_at.iso8601(3),+ mutation_id: "mutation-123",+ }+ end++ context "when not logged in" do+ it "returns a 403" do+ put "/checklist/toggle.json", params: params++ expect(response.status).to eq(403)+ end+ end++ context "when logged in as the post author" do+ before { sign_in(user) }++ it "toggles the checkbox" do+ put "/checklist/toggle.json", params: params++ expect(response.status).to eq(200)+ post.reload+ expect(response.parsed_body).to include(+ "cooked" => post.cooked,+ "last_editor_id" => post.last_editor_id,+ "raw" => "- [x] first\n- [x] second",+ "revised" => true,+ "updated_at" => post.updated_at.iso8601(3),+ "version" => post.version,+ )+ expect(post.raw).to eq("- [x] first\n- [x] second")+ end++ it "succeeds without changes when the state already matches" do+ expect {+ put "/checklist/toggle.json",+ params: params.merge(toggles: [toggle.merge(checked: false)])+ }.not_to change { post.reload.raw }++ expect(response.status).to eq(200)+ expect(response.parsed_body["revised"]).to eq(false)+ end++ it "returns a 400 when params are missing" do+ put "/checklist/toggle.json", params: { post_id: post.id }++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "returns a 400 when params are invalid" do+ put "/checklist/toggle.json",+ params: params.merge(toggles: [toggle.merge(checkbox_index: -1)])++ expect(response.status).to eq(400)+ expect(response.parsed_body["errors"]).to be_present+ end++ it "returns a 404 when the post does not exist" do+ put "/checklist/toggle.json", params: params.merge(post_id: -1)++ expect(response.status).to eq(404)+ end++ it "returns a retryable 409 after checklist-only changes" do+ PostRevisor.new(post).revise!(+ user,+ { raw: "- [x] first\n- [x] second" },+ force_new_version: true,+ )+ expected_updated_at = post.reload.updated_at.iso8601(3)+ expected_raw = post.raw+ freeze_time(1.second.from_now) do+ PostRevisor.new(post).revise!(user, { raw: "- [x] first\n- [ ] second" })+ end+ expect(post.reload.revisions.one?).to eq(true)++ put "/checklist/toggle.json", params: params.merge(expected_raw:, expected_updated_at:)++ expect(response.status).to eq(409)+ expect(response.parsed_body).to include(+ "errors" => [I18n.t("checklist.checkboxes_changed")],+ "updated_at" => post.reload.updated_at.iso8601(3),+ "retryable" => true,+ )+ end++ it "returns a retryable 409 for checklist-only grace-period edits" do+ expected_updated_at = post.updated_at.iso8601(3)+ expected_raw = post.raw+ freeze_time(1.second.from_now) do+ PostRevisor.new(post).revise!(user, { raw: "- [x] first\n- [x] second" })+ end+ expect(post.reload.revisions).to be_empty++ put "/checklist/toggle.json", params: params.merge(expected_raw:, expected_updated_at:)++ expect(response.status).to eq(409)+ expect(response.parsed_body).to include(+ "raw" => post.raw,+ "retryable" => true,+ "updated_at" => post.updated_at.iso8601(3),+ )+ end++ it "returns a non-retryable 409 after other post changes" do+ SiteSetting.post_edit_time_limit = 0+ post.update_columns(created_at: 1.day.ago, updated_at: 1.day.ago)+ expected_updated_at = post.reload.updated_at.iso8601(3)+ expected_raw = post.raw+ PostRevisor.new(post).revise!(user, { raw: "intro\n#{post.raw}" }, force_new_version: true)++ put "/checklist/toggle.json", params: params.merge(expected_raw:, expected_updated_at:)++ expect(response.status).to eq(409)+ expect(response.parsed_body).to include(+ "errors" => [I18n.t("checklist.checkboxes_changed")],+ "updated_at" => post.reload.updated_at.iso8601(3),+ "retryable" => false,+ )+ end++ it "returns a 409 when the legacy checkbox count is stale" do+ legacy_toggle = toggle.merge(checkbox_source: nil, checkbox_count: 5)+ put "/checklist/toggle.json", params: params.merge(toggles: [legacy_toggle])++ expect(response.status).to eq(409)+ expect(response.parsed_body).to include(+ "errors" => [I18n.t("checklist.checkboxes_changed")],+ "updated_at" => post.reload.updated_at.iso8601(3),+ "retryable" => false,+ )+ end++ it "returns a 422 when the checkbox is permanent" do+ post.update_columns(raw: "[X] permanent\n[x] not permanent")++ legacy_toggle = toggle.merge(checkbox_source: nil, checkbox_count: 2)+ put "/checklist/toggle.json", params: params.merge(toggles: [legacy_toggle])++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to include(I18n.t("checklist.checkbox_locked"))+ end++ it "returns a 404 when the plugin is disabled" do+ SiteSetting.checklist_enabled = false++ put "/checklist/toggle.json", params: params++ expect(response.status).to eq(404)+ end++ it "returns a 422 with the error when the revision fails" do+ PostRevisor.any_instance.stubs(:revise!).returns(false)++ put "/checklist/toggle.json", params: params++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to include(I18n.t("checklist.revision_failed"))+ end+ end++ context "when logged in as a user who cannot edit the post" do+ fab!(:another_user, :user)++ before { sign_in(another_user) }++ it "returns a 403" do+ put "/checklist/toggle.json", params: params++ expect(response.status).to eq(403)+ end+ end+ end+enddiff --git a/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rb b/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rbnew file mode 100644index 00000000000..cb10563d514--- /dev/null+++ b/plugins/checklist/spec/services/checklist/toggle_checkbox_spec.rb@@ -0,0 +1,267 @@+# frozen_string_literal: true++RSpec.describe Checklist::ToggleCheckbox do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:post_id) }+ it { is_expected.to validate_presence_of(:toggles) }+ it "limits the batch size" do+ toggles =+ Array.new(Checklist::ToggleCheckbox::MAX_BATCH_SIZE + 1) do |index|+ { checkbox_index: index, checkbox_source: "0:#{index}", checked: true }+ end+ contract =+ described_class.new(+ post_id: 1,+ toggles:,+ expected_raw: "[ ] task",+ expected_updated_at: Time.zone.now.iso8601,+ mutation_id: "mutation",+ )++ expect(contract).not_to be_valid+ expect(contract.errors[:toggles]).to be_present+ end+ it { is_expected.to validate_presence_of(:expected_raw) }+ it { is_expected.to validate_length_of(:expected_raw).is_at_most(SiteSetting.max_post_length) }+ it { is_expected.to validate_presence_of(:expected_updated_at) }+ it { is_expected.to validate_presence_of(:mutation_id) }+ it { is_expected.to validate_length_of(:mutation_id).is_at_most(100) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, user: user) }++ fab!(:post) { Fabricate(:post, topic: topic, user: user, raw: "- [ ] first\n- [x] second") }++ let(:params) do+ {+ post_id:,+ toggles: [{ checkbox_index:, checkbox_count:, checkbox_source:, checked: }],+ expected_raw:,+ expected_updated_at:,+ mutation_id:,+ }+ end+ let(:dependencies) { { guardian: user.guardian } }+ let(:post_id) { post.id }+ let(:checkbox_index) { 0 }+ let(:checkbox_count) { 2 }+ let(:checkbox_source) { nil }+ let(:checked) { true }+ let(:expected_raw) { post.raw }+ let(:expected_updated_at) { post.updated_at.iso8601(3) }+ let(:mutation_id) { "mutation-123" }++ context "when the contract is invalid" do+ let(:checkbox_index) { -1 }++ it { is_expected.to fail_a_contract }+ end++ context "when a malformed source is provided with a valid count" do+ let(:checkbox_source) { "invalid" }++ it { is_expected.to fail_a_contract }+ end++ context "when checklist is disabled" do+ before { SiteSetting.checklist_enabled = false }++ it { is_expected.to fail_a_policy(:checklist_enabled) }+ end++ context "when the post does not exist" do+ let(:post_id) { -1 }++ it { is_expected.to fail_to_find_a_model(:post) }+ end++ context "when the user cannot edit the post" do+ fab!(:another_user, :user)++ let(:dependencies) { { guardian: another_user.guardian } }++ it { is_expected.to fail_a_policy(:can_edit_post) }+ end++ context "when the post changed after the client rendered it" do+ let(:expected_updated_at) { 1.minute.ago.iso8601(3) }++ it { is_expected.to fail_a_policy(:post_unchanged) }+ end++ context "when the post has no checkboxes" do+ before { post.update_columns(raw: "no boxes here") }++ let(:checkbox_count) { 1 }++ it { is_expected.to fail_a_policy(:checkbox_counts_unchanged) }+ end++ context "when the client checkbox count is stale" do+ let(:checkbox_count) { 5 }++ it { is_expected.to fail_a_policy(:checkbox_counts_unchanged) }+ end++ context "when the checkbox index is out of bounds" do+ let(:checkbox_index) { 2 }++ it { is_expected.to fail_a_policy(:checkboxes_found) }+ end++ context "when a source hint is provided" do+ let(:checkbox_source) { "1:0" }+ let(:checkbox_count) { 99 }+ let(:checked) { false }++ it "uses the source hint without validating the rendered count" do+ expect { result }.to change { post.reload.raw }.to("- [ ] first\n- [ ] second")+ end+ end++ context "when multiple checkbox changes are batched" do+ before do+ SiteSetting.editing_grace_period = 0+ post.update!(raw: "[ ] first\n[x] second\n[] third")+ end++ let(:params) do+ {+ post_id: post.id,+ toggles: [+ { checkbox_index: 0, checkbox_source: "0:0", checked: true },+ { checkbox_index: 2, checkbox_source: "2:0", checked: true },+ ],+ expected_raw: post.raw,+ expected_updated_at: post.updated_at.iso8601(3),+ mutation_id:,+ }+ end++ it "applies the batch in one revision" do+ expect { result }.to change { PostRevision.count }.by(1)+ expect(post.reload.raw).to eq("[x] first\n[x] second\n[x] third")+ end+ end++ context "when one checkbox in a batch is permanent" do+ before { post.update!(raw: "[ ] first\n[X] permanent") }++ let(:params) do+ {+ post_id: post.id,+ toggles: [+ { checkbox_index: 0, checkbox_source: "0:0", checked: true },+ { checkbox_index: 1, checkbox_count: 2, checked: false },+ ],+ expected_raw: post.raw,+ expected_updated_at: post.updated_at.iso8601(3),+ mutation_id:,+ }+ end++ it { is_expected.to fail_a_policy(:checkboxes_toggleable) }++ it "does not apply the valid part of the batch" do+ expect { result }.not_to change { post.reload.raw }+ end+ end++ context "when the checkbox is permanent" do+ before { post.update_columns(raw: "[X] permanent\n[x] not permanent") }++ it { is_expected.to fail_a_policy(:checkboxes_toggleable) }+ end++ context "when the checkbox is already in the desired state" do+ let(:checked) { false }++ it { is_expected.to run_successfully }++ it "does not change the raw" do+ expect { result }.not_to change { post.reload.raw }+ end++ it "does not create a revision" do+ expect { result }.not_to change { PostRevision.count }+ end+ end++ context "when checking an unchecked checkbox" do+ before { SiteSetting.editing_grace_period = 0 }++ it { is_expected.to run_successfully }++ it "checks the checkbox" do+ expect { result }.to change { post.reload.raw }.to("- [x] first\n- [x] second")+ end++ it "stores source hints for subsequent toggles" do+ result++ expect(post.reload.cooked).to include("data-chk-src")+ end++ it "creates a revision" do+ expect { result }.to change { PostRevision.count }.by(1)+ end++ it "does not bump the topic and preserves the editor's rendered content" do+ messages =+ MessageBus.track_publish("/topic/#{topic.id}") do+ expect { result }.not_to change { topic.reload.bumped_at }+ end+ revised_message = messages.find { |message| message.data[:type] == :revised }++ expect(revised_message.data[:preserve_cooked_token]).to eq(mutation_id)+ end+ end++ context "when unchecking a checked checkbox" do+ let(:checkbox_index) { 1 }+ let(:checked) { false }++ it { is_expected.to run_successfully }++ it "unchecks the checkbox" do+ expect { result }.to change { post.reload.raw }.to("- [ ] first\n- [ ] second")+ end+ end++ context "when the post revision fails" do+ before { PostRevisor.any_instance.stubs(:revise!).returns(false) }++ it { is_expected.to fail_a_step(:revise_post) }++ it "returns a stable failure reason" do+ expect(result["result.step.revise_post"].error).to eq(:revision_failed)+ end+ end++ context "when the raw contains multibyte characters" do+ before { post.update_columns(raw: "π party time\n\n[ ] bring the cake") }++ let(:checkbox_count) { 1 }++ it { is_expected.to run_successfully }++ it "checks the checkbox" do+ expect { result }.to change { post.reload.raw }.to("π party time\n\n[x] bring the cake")+ end+ end++ context "when the post uses legacy empty checkboxes" do+ before { post.update_columns(raw: "[] first thing\n[] second thing") }++ it { is_expected.to run_successfully }++ it "checks the checkbox" do+ expect { result }.to change { post.reload.raw }.to("[x] first thing\n[] second thing")+ end+ end+ end+enddiff --git a/plugins/checklist/spec/system/toggle_checkbox_spec.rb b/plugins/checklist/spec/system/toggle_checkbox_spec.rbnew file mode 100644index 00000000000..9fd1a809b43--- /dev/null+++ b/plugins/checklist/spec/system/toggle_checkbox_spec.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++RSpec.describe "Checklist toggles" do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:topic) { Fabricate(:topic, user:) }+ fab!(:post) { Fabricate(:post, topic:, user:, raw: "- [ ] first") }++ before do+ SiteSetting.checklist_enabled = true+ sign_in(user)+ end++ it "hydrates raw and toggles a checklist from the topic stream" do+ page.visit "/t/#{topic.slug}/#{topic.id}"++ find(".chcklst-box").click++ 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")+ end+enddiff --git a/plugins/checklist/test/javascripts/lib/checklist-test.js b/plugins/checklist/test/javascripts/lib/checklist-test.jsindex e406640e1cf..c23afde6c87 100644--- a/plugins/checklist/test/javascripts/lib/checklist-test.js+++ b/plugins/checklist/test/javascripts/lib/checklist-test.js@@ -1,16 +1,36 @@-import { click } from "@ember/test-helpers";+import {+ click,+ settled,+ triggerKeyEvent,+ waitUntil,+} from "@ember/test-helpers";import { test } from "qunit";import { Promise } from "rsvp";+import { consumeOptimisticPostUpdate } from "discourse/lib/optimistic-post-updates";import { 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";-let currentRaw;--async function prepare(raw) {- currentRaw = raw;+let decoratorCleanup;+let holdRequest;+let hydrationRequests;+let initialRaw;+let postModel;+let releaseRequest;+let requests;+let retryableConflicts;+let respondWithError;+let responseRevised;+let responseSequence;++function nextUpdatedAt() {+ responseSequence += 1;+ return `2026-08-27T08:00:0${responseSequence}.000Z`;+}+async function prepare(raw, { canEdit = true, includeRaw = true } = {}) {+ initialRaw = raw;const cooked = await cook(raw, {siteSettings: {checklist_enabled: true,@@ -18,299 +38,635 @@ async function prepare(raw) {},});- const widget = { attrs: {}, scheduleRerender() {} };- const model = Post.create({ id: 42, can_edit: true });- const decoratorHelper = { widget, getModel: () => model };-+ postModel = Post.create({+ id: 42,+ can_edit: canEdit,+ cooked: cooked.toString(),+ 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();- checklistSyntax(element, decoratorHelper);-+ decoratorCleanup = checklistSyntax(element, decoratorHelper);document.querySelector("#ember-testing").append(element);- const updated = new Promise((resolve) => {- model.save = async (fields) => resolve(fields.raw);- });-- return { updated };+ return [...element.querySelectorAll(".chcklst-box")];}acceptance("checklist", function (needs) {needs.pretender((server, helper) => {- server.get("/posts/42", () => helper.response({ raw: currentRaw }));+ server.get("/posts/42", () => {+ hydrationRequests += 1;+ return helper.response({+ id: 42,+ raw: initialRaw,+ updated_at: "2026-08-27T08:00:00.000Z",+ });+ });++ server.put("/checklist/toggle", (request) => {+ const body = JSON.parse(request.requestBody);+ requests.push(body);++ if (retryableConflicts.length > 0) {+ return helper.response(409, {+ errors: ["The post changed"],+ raw: "server conflict raw",+ retryable: true,+ updated_at: retryableConflicts.shift(),+ });+ }++ if (respondWithError) {+ return helper.response(422, {});+ }++ const updatedAt = nextUpdatedAt();+ const response = {+ cooked: `authoritative cooked ${responseSequence}`,+ last_editor_id: 1,+ raw: `authoritative raw ${responseSequence}`,+ revised: responseRevised,+ updated_at: updatedAt,+ version: responseSequence + 1,+ };+ if (responseRevised) {+ consumeOptimisticPostUpdate(body.mutation_id);+ }+ if (holdRequest) {+ return new Promise((resolve) => {+ releaseRequest = () => resolve(helper.response(response));+ });+ }++ return helper.response(response);+ });+ });++ needs.hooks.beforeEach(function () {+ decoratorCleanup = null;+ holdRequest = false;+ hydrationRequests = 0;+ initialRaw = null;+ postModel = null;+ releaseRequest = null;+ requests = [];+ retryableConflicts = [];+ respondWithError = false;+ responseRevised = true;+ responseSequence = 0;});needs.hooks.afterEach(function () {+ decoratorCleanup?.();+ releaseRequest?.();document.querySelector("#ember-testing").innerHTML = "";});- test("does not clash with date-range bbcode", async function (assert) {- const { updated } = await prepare(`-[date-range from=2024-03-22 to=2024-03-23]--[ ] task 1-[ ] task 2-[x] task 3- `);-- assert.dom(".discourse-local-date").exists({ count: 2 });- assert.dom(".chcklst-box").exists({ count: 3 });- await click(".chcklst-box");+ test("sends the direct source location without a redundant count", async function (assert) {+ const boxes = await prepare(`+\`[x]\`+*[x]*+**[x]**+_[x]_+__[x]__+~~[x]~~- const output = await updated;- assert.true(output.includes("[x] task 1"));- });+[code]+[x]+[ ]+[/code]- test("does not check an image URL", async function (assert) {- const { updated } = await prepare(`-+Actual checkboxes:[] first-[] second- `);-- await click(".chcklst-box");-- const output = await updated;- assert.true(output.includes("[x] first"));- });-- test("make checkboxes readonly while updating", async function (assert) {- const { updated } = await prepare(`-[ ] first[x] second+* test[x]*third*+[x] fourth+[x] fifth`);- const [checkbox1, checkbox2] = [- ...document.querySelectorAll(".chcklst-box"),- ];- checkbox1.click();-- assert.dom(checkbox2).hasClass("readonly");- await click(checkbox2);+ assert.strictEqual(boxes.length, 5, "only rendered checkboxes are counted");++ await click(boxes[3]);++ assert.true(+ /^[0-9a-f-]{36}$/.test(requests[0].mutation_id),+ "the mutation gets a one-time identifier"+ );+ assert.deepEqual(+ requests[0],+ {+ post_id: 42,+ toggles: [+ {+ checkbox_index: 3,+ checkbox_source: boxes[3].dataset.chkSrc,+ checked: false,+ },+ ],+ expected_raw: initialRaw,+ expected_updated_at: "2026-08-27T08:00:00.000Z",+ mutation_id: requests[0].mutation_id,+ },+ "the server receives the checkbox's rendered position and desired state"+ );+ });- const output = await updated;- assert.true(output.includes("[x] first"));- assert.true(output.includes("[x] second"));+ test("defers authoritative cooked content until teardown", async function (assert) {+ const [checkbox] = await prepare("[ ] first");+ const initialCooked = postModel.cooked;++ await click(checkbox);++ assert.strictEqual(+ postModel.last_editor_id,+ 1,+ "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.cooked,+ initialCooked,+ "the visible cooked subtree is not rerendered"+ );+ assert.true(checkbox.isConnected, "the decorated control stays connected");++ decoratorCleanup();+ decoratorCleanup = null;+ await settled();+ assert.strictEqual(+ postModel.cooked,+ "authoritative cooked 1",+ "cooked content is stored for the next render"+ );});- test("checkbox before a code block", async function (assert) {- const { updated } = await prepare(`-[ ] first-[x] actual-\`[x] nope\`- `);+ test("does not apply a response older than the loaded post", 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.cooked = "newer cooked";+ releaseRequest();+ releaseRequest = null;+ await settled();++ assert.strictEqual(postModel.raw, "newer raw", "raw does not regress");+ 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"+ );+ });- assert.dom(".chcklst-box").exists({ count: 2 });+ test("hydrates raw before the first stream toggle", async function (assert) {+ const [checkbox] = await prepare("[ ] first", { includeRaw: false });- await click([...document.querySelectorAll(".chcklst-box")][1]);+ await click(checkbox);- const output = await updated;- assert.true(output.includes("[ ] first"));- assert.true(output.includes("[ ] actual"));- assert.true(output.includes("[x] nope"));+ assert.strictEqual(hydrationRequests, 1, "the missing raw is fetched once");+ assert.strictEqual(+ requests[0].expected_raw,+ "[ ] first",+ "the toggle uses the hydrated baseline"+ );});- test("escaped checkbox syntax is ignored", async function (assert) {- const { updated } = await prepare(`-\\[x] first escaped-\\[ ] second escaped-[ ] actual- `);+ test("sends the checkbox count for legacy cooked HTML", async function (assert) {+ const [checkbox] = await prepare("[ ] first\n[ ] second");+ delete checkbox.dataset.chkSrc;- assert.dom(".chcklst-box").exists({ count: 1 });- await click(".chcklst-box");+ await click(checkbox);- const output = await updated;- assert.true(output.includes("\\[x] first escaped"));- assert.true(output.includes("\\[ ] second escaped"));- assert.true(output.includes("[x] actual"));+ assert.strictEqual(+ requests[0].toggles[0].checkbox_count,+ 2,+ "index lookup includes the rendered count"+ );});- test("permanently checked checkbox", async function (assert) {- const { updated } = await prepare(`-[X] permanent-[x] not permanent- `);+ test("unregisters optimistic tokens when no revision was needed", async function (assert) {+ responseRevised = false;+ const [checkbox] = await prepare("[ ] first");- assert.dom(".chcklst-box").exists({ count: 2 });+ await click(checkbox);- const [checkbox1, checkbox2] = [- ...document.querySelectorAll(".chcklst-box"),- ];+ assert.false(+ consumeOptimisticPostUpdate(requests[0].mutation_id),+ "a no-op response leaves no pending token"+ );+ });- await click(checkbox1);- await click(checkbox2);+ test("updates instantly without hiding or locking the checklist", async function (assert) {+ holdRequest = true;+ const [first, second] = await prepare("[ ] first\n[x] second");- const output = await updated;- assert.true(output.includes("[X] permanent"));- assert.true(output.includes("[ ] not permanent"));- });+ assert+ .dom(".checklist-spinner")+ .doesNotExist("spinners are created lazily");+ first.click();+ await waitUntil(() => requests.length === 1);- test("checkbox before a multiline code block", async function (assert) {- const { updated } = await prepare(`-[ ] first-[x] actual-\`\`\`-[x] nope-[x] neither-\`\`\`- `);+ assert.dom(first).hasClass("checked", "the checkbox changes immediately");+ assert+ .dom(first)+ .hasAttribute("aria-checked", "true", "ARIA state changes immediately");+ assert+ .dom(first)+ .hasAttribute(+ "aria-busy",+ "true",+ "only the pending item is marked busy"+ );+ assert+ .dom(first)+ .hasAttribute(+ "aria-disabled",+ "true",+ "the pending item ignores additional activation"+ );+ assert.dom(first).isVisible("the pending checkbox keeps its layout");+ assert+ .dom(".checklist-spinner", first)+ .isVisible("the familiar spinner is shown immediately");+ assert.strictEqual(+ getComputedStyle(first.querySelector(".checklist-spinner")).animationName,+ "rotate-forever",+ "the pending icon spins in place"+ );+ assert+ .dom(second)+ .doesNotHaveClass("readonly", "other checkboxes remain interactive");- assert.dom(".chcklst-box").exists({ count: 2 });- await click([...document.querySelectorAll(".chcklst-box")][1]);+ releaseRequest();+ await settled();- const output = await updated;- assert.true(output.includes("[ ] first"));- assert.true(output.includes("[ ] actual"));- assert.true(output.includes("[x] nope"));+ assert+ .dom(first)+ .doesNotHaveAttribute("aria-busy", "pending state clears after saving");+ assert+ .dom(first)+ .hasClass("checked", "the optimistic state remains after saving");});- test("checkbox before italic/bold sequence", async function (assert) {- const { updated } = await prepare(` [x] *test*`);-- assert.dom(".chcklst-box").exists({ count: 1 });- await click(".chcklst-box");+ test("shows every spinner for at least 200ms", async function (assert) {+ const [checkbox] = await prepare("[ ] first");+ const startedAt = performance.now();- const output = await updated;- assert.true(output.includes("[ ] *test*"));- });+ checkbox.click();+ await waitUntil(() => requests.length === 1);+ await waitUntil(() => !checkbox.hasAttribute("aria-busy"));- test("checkboxes in an unordered list", async function (assert) {- const { updated } = await prepare(`-* [x] checked-* [] test-* [] two- `);+ assert+ .dom(checkbox)+ .doesNotHaveAttribute(+ "aria-busy",+ "the semantic busy state follows the completed request"+ );+ assert+ .dom(checkbox)+ .hasAttribute(+ "aria-disabled",+ "true",+ "the control stays inactive while its spinner is visible"+ );+ assert+ .dom(".checklist-spinner", checkbox)+ .isVisible("a quick response still shows the spinner");- assert.dom(".chcklst-box").exists({ count: 3 });- await click([...document.querySelectorAll(".chcklst-box")][1]);+ await waitUntil(() => !checkbox.classList.contains("is-saving"));- const output = await updated;- assert.true(output.includes("* [x] checked"));- assert.true(output.includes("* [x] test"));- assert.true(output.includes("* [] two"));+ assert.true(+ performance.now() - startedAt >= 190,+ "the spinner remains visible for approximately 200ms"+ );+ assert+ .dom(".checklist-spinner", checkbox)+ .isNotVisible("the spinner clears after its minimum display time");+ assert+ .dom(checkbox)+ .doesNotHaveAttribute(+ "aria-disabled",+ "the control is interactive again after the spinner clears"+ );});- test("checkboxes in italic/bold-like blocks", async function (assert) {- const { updated } = await prepare(`-*[x-*a [*] x]*-[*x]-~~[*]~~+ test("ignores repeat activation while the spinner is visible", async function (assert) {+ const [checkbox] = await prepare("[ ] first");-* []* 0+ checkbox.click();+ await waitUntil(() => requests.length === 1);+ await waitUntil(() => !checkbox.hasAttribute("aria-busy"));-~~[] ~~ 1+ checkbox.click();-~~ [x]~~ 2+ assert.strictEqual(requests.length, 1, "the extra click sends no request");+ assert+ .dom(checkbox)+ .hasClass("checked", "the optimistic state is unchanged");++ await waitUntil(() => !checkbox.classList.contains("is-saving"));+ checkbox.click();+ await waitUntil(() => requests.length === 2);++ assert.deepEqual(+ requests.flatMap((request) =>+ request.toggles.map((toggle) => toggle.checked)+ ),+ [true, false],+ "the checkbox accepts input again after the spinner clears"+ );+ });-* [x] 3- `);+ test("waits for the active request before sending another checkbox", async function (assert) {+ holdRequest = true;+ const [first, second, third] = await prepare(+ "[ ] first\n[ ] second\n[ ] third"+ );- assert.dom(".chcklst-box").exists({ count: 4 });- await click([...document.querySelectorAll(".chcklst-box")][3]);+ first.click();+ await waitUntil(() => releaseRequest);+ second.click();+ third.click();- const output = await updated;- assert.true(output.includes("* [ ] 3"));+ assert.dom(first).hasClass("checked", "the first change is optimistic");+ assert.dom(second).hasClass("checked", "the second change is optimistic");+ assert.dom(third).hasClass("checked", "the third change is optimistic");+ assert+ .dom(first)+ .hasAttribute(+ "aria-busy",+ "true",+ "the first item remains busy until its request completes"+ );+ assert.strictEqual(+ requests.length,+ 1,+ "the second request waits for the first response"+ );++ holdRequest = false;+ releaseRequest();+ releaseRequest = null;+ await waitUntil(() => requests.length === 2);++ assert.deepEqual(+ requests.map((request) =>+ request.toggles.map((toggle) => toggle.checkbox_index)+ ),+ [[0], [1, 2]],+ "the first change is immediate and the backlog is one batch"+ );+ assert.strictEqual(+ requests[1].expected_raw,+ "authoritative raw 1",+ "the second request uses the first response's raw"+ );+ assert.strictEqual(+ requests[1].expected_updated_at,+ "2026-08-27T08:00:01.000Z",+ "the second request uses the first response's revision token"+ );});- test("correct checkbox is selected", async function (assert) {- const { updated } = await prepare(`-\`[x]\`-*[x]*-**[x]**-_[x]_-__[x]__-~~[x]~~--[code]-[x]-[ ]-[ ]-[x]-[/code]+ test("stops queued work after the decorated content is destroyed", async function (assert) {+ holdRequest = true;+ const [first, second] = await prepare("[ ] first\n[ ] second");++ first.click();+ second.click();+ await waitUntil(() => requests.length === 1);+ decoratorCleanup();+ assert.false(+ consumeOptimisticPostUpdate(requests[0].mutation_id),+ "the detached decoration unregisters its in-flight mutation"+ );+ releaseRequest();+ await settled();++ assert.strictEqual(+ requests.length,+ 1,+ "detached controls do not send stale queued changes"+ );+ assert.strictEqual(+ postModel.raw,+ "authoritative raw 1",+ "the detached model retains the confirmed raw content"+ );+ assert.strictEqual(+ postModel.cooked,+ "authoritative cooked 1",+ "the detached model retains the confirmed cooked content"+ );+ });-\`\`\`-[x]-[ ]-[ ]-[x]-\`\`\`+ test("recovers a stale request without discarding its backlog", async function (assert) {+ retryableConflicts = ["2026-08-27T08:00:10.000Z"];+ const [first, second, third] = await prepare(+ "[ ] first\n[ ] second\n[ ] third"+ );++ first.click();+ second.click();+ third.click();+ await waitUntil(() => requests.length === 3);+ await waitUntil(() =>+ [first, second, third].every(+ (checkbox) => !checkbox.classList.contains("is-saving")+ )+ );++ assert.deepEqual(+ requests.map((request) =>+ request.toggles.map((toggle) => toggle.checkbox_index)+ ),+ [[0], [0], [1, 2]],+ "the failed batch is retried before the accumulated backlog"+ );+ assert.strictEqual(+ requests[1].expected_raw,+ "server conflict raw",+ "the retry uses the server's authoritative raw"+ );+ assert.strictEqual(+ requests[1].expected_updated_at,+ "2026-08-27T08:00:10.000Z",+ "the retry uses the server's authoritative timestamp"+ );+ assert.notStrictEqual(+ requests[1].mutation_id,+ requests[0].mutation_id,+ "the retry receives a new reconciliation token"+ );+ 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(first)+ .doesNotHaveAttribute(+ "aria-busy",+ "the recovered save completes normally"+ );+ });-Actual checkboxes:-[] first-[x] second-* test[x]*third*-[x] fourth-[x] fifth- `);+ test("reverts an unconfirmed optimistic change on error", async function (assert) {+ respondWithError = true;+ const [checkbox] = await prepare("[ ] first");- assert.dom(".chcklst-box").exists({ count: 5 });- await click([...document.querySelectorAll(".chcklst-box")][3]);+ await click(checkbox);- const output = await updated;- assert.true(output.includes("[ ] fourth"));+ assert+ .dom(checkbox)+ .doesNotHaveClass("checked", "the server-confirmed state is restored");+ assert+ .dom(checkbox)+ .doesNotHaveAttribute("aria-busy", "pending state is cleared");});- test("rendering in bullet lists", async function (assert) {- await prepare(`-- [ ] LI 1-- LI 2 [ ] with checkbox in middle-- [ ] LI 3+ test("supports keyboard interaction and exposes checkbox semantics", async function (assert) {+ const [checkbox] = await prepare("[ ] Buy milk");-1. [ ] Ordered LI with checkbox- `);+ assert+ .dom(checkbox)+ .hasAttribute("role", "checkbox", "the control exposes its role");+ assert+ .dom(checkbox)+ .hasAttribute("tabindex", "0", "the control is keyboard focusable");+ assert+ .dom(checkbox)+ .hasAttribute("aria-label", "Buy milk", "the task labels the control");- assert.dom("ul > li").exists({ count: 3 });- const listItems = [...document.querySelectorAll("ul > li")];+ await triggerKeyEvent(checkbox, "keydown", " ");+ assert+ .dom(checkbox)+ .hasAttribute("aria-checked", "true", "Space checks the item");++ await waitUntil(() => !checkbox.classList.contains("is-saving"));+ await triggerKeyEvent(checkbox, "keydown", "Enter");+ assert+ .dom(checkbox)+ .hasAttribute("aria-checked", "false", "Enter unchecks the item");+ });- assert.dom(listItems[0]).hasClass("has-checkbox");- assert.dom(".chcklst-box", listItems[0]).hasClass("list-item-checkbox");+ test("labels multiple controls from their own task text", async function (assert) {+ const [first, second] = await prepare("[ ] Buy milk [ ] Wash car");- assert.dom(listItems[1]).doesNotHaveClass("has-checkbox");assert- .dom(".chcklst-box", listItems[1])- .doesNotHaveClass("list-item-checkbox");+ .dom(first)+ .hasAttribute(+ "aria-label",+ "Buy milk",+ "the first task has its own label"+ );+ assert+ .dom(second)+ .hasAttribute(+ "aria-label",+ "Wash car",+ "the second task has its own label"+ );+ });- assert.dom(listItems[2]).hasClass("has-checkbox");- assert.dom(".chcklst-box", listItems[2]).hasClass("list-item-checkbox");+ test("uses a fallback label for an empty checklist item", async function (assert) {+ const [checkbox] = await prepare("- [ ]");- assert.dom("ol > li").exists({ count: 1 });- assert.dom("ol > li").doesNotHaveClass("has-checkbox");- assert.dom("ol .chcklst-box").doesNotHaveClass("list-item-checkbox");+ assert+ .dom(checkbox)+ .hasAttribute("aria-label", "Checklist item", "the empty item is named");});- test("does not treat escaped brackets as checkboxes", async function (assert) {- const { updated } = await prepare(`-\\[x] escaped opening-[x\\] escaped closing-\\[x\\] both escaped-[ ] real checkbox-[x] another real one- `);+ test("does not make quoted checkboxes interactive", async function (assert) {+ const [quoted, own] = await prepare(+ '[quote="Other user"]\n[ ] quoted task\n[/quote]\n\n[ ] own task'+ );- assert.dom(".chcklst-box").exists({ count: 2 });+ assert+ .dom(quoted)+ .hasAttribute(+ "aria-readonly",+ "true",+ "the quoted checkbox is read-only"+ );+ assert.dom(quoted).doesNotHaveAttribute("tabindex");+ await click(quoted);+ assert.strictEqual(requests.length, 0, "the quote sends no request");++ await click(own);+ assert.strictEqual(requests.length, 1, "the post's own checkbox toggles");+ assert.strictEqual(+ requests[0].toggles[0].checkbox_index,+ 0,+ "quoted checkboxes are excluded from the rendered index"+ );+ });- await click(".chcklst-box");+ test("permanent and read-only checkboxes are not interactive", async function (assert) {+ const [permanent] = await prepare("[X] permanent");- const output = await updated;+ assert+ .dom(permanent)+ .hasAttribute("aria-disabled", "true", "permanent items are disabled");+ assert+ .dom(permanent)+ .doesNotHaveAttribute("tabindex", "permanent items are not focusable");+ await click(permanent);+ assert.strictEqual(requests.length, 0, "permanent items do not save");- assert.true(output.includes("\\[x] escaped opening"));- assert.true(output.includes("[x\\] escaped closing"));- assert.true(output.includes("\\[x\\] both escaped"));+ document.querySelector("#ember-testing").innerHTML = "";+ const [readOnly] = await prepare("[x] completed", { canEdit: false });- assert.true(output.includes("[x] real checkbox"));+ assert+ .dom(readOnly)+ .hasAttribute(+ "aria-readonly",+ "true",+ "non-editors get a read-only state"+ );+ assert+ .dom(readOnly)+ .doesNotHaveAttribute("tabindex", "read-only items are not focusable");+ await click(readOnly);+ assert.strictEqual(requests.length, 0, "read-only items do not save");});- test("handles escaped checkbox followed by real checkbox", async function (assert) {- const { updated } = await prepare(`\\[x] hello [x] world`);-- assert.dom(".chcklst-box").exists({ count: 1 });+ test("preserves checklist list styling", async function (assert) {+ await prepare(`+- [ ] LI 1+- LI 2 [ ] with checkbox in middle+- [ ] LI 3- await click(".chcklst-box");+1. [ ] Ordered LI with checkbox+ `);- const output = await updated;- assert.true(output.includes("\\[x] hello"));- assert.true(output.includes("[ ] world"));+ const listItems = [...document.querySelectorAll("ul > li")];+ assert+ .dom(listItems[0])+ .hasClass("has-checkbox", "a leading checkbox removes the bullet");+ assert+ .dom(listItems[1])+ .doesNotHaveClass("has-checkbox", "an inline checkbox keeps the bullet");+ assert+ .dom(listItems[2])+ .hasClass("has-checkbox", "another leading checkbox removes the bullet");+ assert+ .dom("ol > li")+ .doesNotHaveClass("has-checkbox", "ordered lists keep their numbering");});});diff --git a/spec/lib/post_revisor_spec.rb b/spec/lib/post_revisor_spec.rbindex 2b34e9a707c..95f562166a9 100644--- a/spec/lib/post_revisor_spec.rb+++ b/spec/lib/post_revisor_spec.rb@@ -460,6 +460,29 @@ describe PostRevisor doendend+ it "rejects a stale raw snapshot inside the persistence transaction" do+ expected_raw = post.raw+ Post.where(id: post.id).update_all(+ raw: "a concurrent edit",+ cooked: "<p>a concurrent edit</p>",+ )++ result =+ post_revisor.revise!(post.user, { raw: "a stale replacement" }, expected_raw: expected_raw)++ expect(result).to eq(false)+ expect(post.errors.full_messages).to include(I18n.t("edit_conflict"))+ expect(post.reload.raw).to eq("a concurrent edit")+ end++ it "allows a revision when the expected raw still matches" do+ result =+ post_revisor.revise!(post.user, { raw: "a current replacement" }, expected_raw: post.raw)++ expect(result).to eq(true)+ expect(post.reload.raw).to eq("a current replacement")+ end+it "destroys last revision if edit is undone" doold_raw = post.raw