From a90b12ba8f1b98b52298ae181bc547bc808631f5 Mon Sep 17 00:00:00 2001 From: Robert Fletcher Date: Fri, 27 Nov 2026 19:04:27 -0800 Subject: [PATCH] Imitate story forms on the tutorial page **What** Add a `tutorial-stories` controller around the tutorial's story list. It cancels each story form's submit and makes the change the server's Turbo Stream would have made: it flips the star buttons, swaps in an updated keep unread form, and spins the refresh icon for a moment. Remove `story#formSubmitted`, which tried to skip these submits for sample stories. **Why** The tutorial should behave like the stories page without saving its sample stories, and the shared story controller shouldn't know about the tutorial. **Notes** Each story's Turbo Frame stops the submit event from bubbling, so `formSubmitted` never ran and sample stories' requests reached the server. The new controller listens in the capture phase instead. --- .eslint_todo.ts | 5 +- app/components/story.rb | 8 +- app/javascript/controllers/index.ts | 3 + .../controllers/story_controller.ts | 7 - .../tutorial_stories_controller.ts | 109 +++++++++++++++ app/views/tutorials/index.rb | 16 ++- spec/components/story_spec.rb | 7 +- .../controllers/story_controller_open_spec.ts | 22 --- .../tutorial_stories_controller_spec.ts | 128 ++++++++++++++++++ spec/javascript/support/story_fixture.ts | 3 +- spec/system/tutorial_spec.rb | 22 ++- 11 files changed, 281 insertions(+), 49 deletions(-) create mode 100644 app/javascript/controllers/tutorial_stories_controller.ts create mode 100644 spec/javascript/controllers/tutorial_stories_controller_spec.ts diff --git a/.eslint_todo.ts b/.eslint_todo.ts index b786c984c..0fc1edee8 100644 --- a/.eslint_todo.ts +++ b/.eslint_todo.ts @@ -1,5 +1,5 @@ // This configuration was generated by `exe/eslint_autogen` -// on 2026-11-28 02:17:20 UTC. +// on 2026-11-28 02:54:57 UTC. // The point is for the user to remove these configuration records // one by one as the offenses are removed from the code base. @@ -32,10 +32,9 @@ const config: Linter.Config[] = [ "@stylistic/list-style": "off", }, }, - // Offense count: 3 + // Offense count: 2 { files: [ - "spec/javascript/controllers/story_controller_open_spec.ts", "spec/javascript/setup.ts", "vitest.config.ts", ], diff --git a/app/components/story.rb b/app/components/story.rb index 98abc9358..6a14af4ad 100644 --- a/app/components/story.rb +++ b/app/components/story.rb @@ -4,12 +4,8 @@ # state classes; its contents sit in a Turbo Frame so refreshing the story # from its feed swaps them in place (see `Components::StoryFrame`). class Components::Story < Components::Base - # The star and refresh forms submit inside the story's frame: sample - # stories skip them, and a failed refresh leaves the story as it was. - ACTIONS = [ - "submit->story#formSubmitted", - "turbo:frame-missing->story#frameMissing" - ].join(" ").freeze + # A failed refresh leaves the story as it was. + ACTIONS = "turbo:frame-missing->story#frameMissing" attr_accessor :story diff --git a/app/javascript/controllers/index.ts b/app/javascript/controllers/index.ts index acc7ff93e..8e3475e26 100644 --- a/app/javascript/controllers/index.ts +++ b/app/javascript/controllers/index.ts @@ -27,5 +27,8 @@ application.register("tooltip", TooltipController); import TutorialStartController from "./tutorial_start_controller"; application.register("tutorial-start", TutorialStartController); +import TutorialStoriesController from "./tutorial_stories_controller"; +application.register("tutorial-stories", TutorialStoriesController); + import UnreadCountController from "./unread_count_controller"; application.register("unread-count", UnreadCountController); diff --git a/app/javascript/controllers/story_controller.ts b/app/javascript/controllers/story_controller.ts index 6862cf201..6fb4308f5 100644 --- a/app/javascript/controllers/story_controller.ts +++ b/app/javascript/controllers/story_controller.ts @@ -105,13 +105,6 @@ export default class extends Controller { this.dispatch("read-changed"); } - // Sample stories aren't saved, so their star and refresh forms do nothing. - formSubmitted(event: Event): void { - if (this.isSample()) { - event.preventDefault(); - } - } - /* * A failed refresh can respond without the story's Turbo Frame, e.g. when * the story was deleted. Cancelling the event keeps the story as it was, diff --git a/app/javascript/controllers/tutorial_stories_controller.ts b/app/javascript/controllers/tutorial_stories_controller.ts new file mode 100644 index 000000000..a8a56a23d --- /dev/null +++ b/app/javascript/controllers/tutorial_stories_controller.ts @@ -0,0 +1,109 @@ +import { Controller } from "@hotwired/stimulus"; + +// How long a pretend refresh spins its icon. +const REFRESH_MS = 600; + +function keepUnreadIcon(kept: boolean): string { + if (kept) { + return "fa-check"; + } + + return "fa-square-o"; +} + +function hiddenValue(form: HTMLFormElement, name: string): HTMLInputElement { + const input = form.querySelector(`input[name='${name}']`); + if (!input) { + throw new Error(`Missing ${name} input`); + } + + return input; +} + +function setIcon(form: HTMLFormElement, icon: string): void { + const element = form.querySelector("i"); + if (element) { + element.className = `fa ${icon}`; + } +} + +/* + * Swaps in an updated copy of the keep unread form, like the keep unread + * stream does. The story controller copies the new state onto the story + * when the copy connects. + */ +function keepUnread(form: HTMLFormElement): void { + const kept = hiddenValue(form, "keep_unread").value === "true"; + const copy = form.cloneNode(true); + if (!(copy instanceof HTMLFormElement)) { + return; + } + + copy.dataset.keepUnread = String(kept); + copy.dataset.isRead = String(!kept); + hiddenValue(copy, "keep_unread").value = String(!kept); + setIcon(copy, keepUnreadIcon(kept)); + form.replaceWith(copy); +} + +// Spins the refresh icon for a moment, as a real refresh does. +function refresh(form: HTMLFormElement): void { + form.setAttribute("aria-busy", "true"); + setTimeout(() => { + form.removeAttribute("aria-busy"); + }, REFRESH_MS); +} + +/* + * Imitates the story forms on the tutorial page, whose sample stories have + * nothing to save. It cancels each submit and makes the change the server's + * Turbo Stream response would have made, so the tutorial behaves like the + * real stories page. + */ +export default class extends Controller { + static override values = { starLabel: String, unstarLabel: String }; + + declare starLabelValue: string; + + declare unstarLabelValue: string; + + submitted(event: Event): void { + const form = event.target; + if (!(form instanceof HTMLFormElement)) { + return; + } + + event.preventDefault(); + + if (form.classList.contains("story-star-form")) { + this.star(form); + } else if (form.classList.contains("story-keep-unread-form")) { + keepUnread(form); + } else if (form.classList.contains("story-refresh-form")) { + refresh(form); + } + } + + // Updates both of the story's star buttons, like the star stream does. + private star(form: HTMLFormElement): void { + const starred = hiddenValue(form, "starred").value === "true"; + const story = form.closest("li.story") ?? form; + const forms = story.querySelectorAll(".story-star-form"); + + for (const starForm of forms) { + hiddenValue(starForm, "starred").value = String(!starred); + this.showStar(starForm, starred); + } + } + + private showStar(form: HTMLFormElement, starred: boolean): void { + const button = form.querySelector("button"); + if (starred) { + setIcon(form, "fa-star"); + button?.setAttribute("aria-label", this.unstarLabelValue); + } else { + setIcon(form, "fa-star-o"); + button?.setAttribute("aria-label", this.starLabelValue); + } + } +} diff --git a/app/views/tutorials/index.rb b/app/views/tutorials/index.rb index 0e5d9bfc6..f1eb6ac5e 100644 --- a/app/views/tutorials/index.rb +++ b/app/views/tutorials/index.rb @@ -30,7 +30,9 @@ def view_template render(Components::TutorialActionBar.new(stories:)) end - render(Components::StoryList.new(stories:, title: site_title)) + div(data: stories_data) do + render(Components::StoryList.new(stories:, title: site_title)) + end setup end @@ -83,6 +85,18 @@ def start_button a(**START_BUTTON) { t("tutorial.start") } end + # The sample stories have nothing to save, so tutorial-stories imitates + # their forms instead of submitting them. It listens in the capture phase + # because each story's Turbo Frame stops the submit event from bubbling. + def stories_data + { + controller: "tutorial-stories", + action: "submit->tutorial-stories#submitted:capture", + tutorial_stories_star_label_value: t("stories.star"), + tutorial_stories_unstar_label_value: t("stories.unstar") + } + end + def start_data { controller: "tutorial-start", diff --git a/spec/components/story_spec.rb b/spec/components/story_spec.rb index 2f687dbb3..962483057 100644 --- a/spec/components/story_spec.rb +++ b/spec/components/story_spec.rb @@ -28,13 +28,10 @@ def values(element) expect(values(story_li(story))).to eq([story.id.to_s, "false", "true"]) end - it "wires the form submit and missing frame actions" do + it "keeps the story in place when a refresh fails" do li = story_li(create(:story)) - expect(li["data-action"].split).to include( - "submit->story#formSubmitted", - "turbo:frame-missing->story#frameMissing" - ) + expect(li["data-action"]).to eq("turbo:frame-missing->story#frameMissing") end it "makes the li a story-list and unread-count target", :aggregate_failures do diff --git a/spec/javascript/controllers/story_controller_open_spec.ts b/spec/javascript/controllers/story_controller_open_spec.ts index ac7bb7df6..fcb268c3a 100644 --- a/spec/javascript/controllers/story_controller_open_spec.ts +++ b/spec/javascript/controllers/story_controller_open_spec.ts @@ -151,25 +151,3 @@ describe("frameMissing from outside the story", () => { expect(event.defaultPrevented).toBe(false); }); }); - -describe("formSubmitted", () => { - function submitRefresh(): SubmitEvent { - const form = ensure(element().querySelector("form")); - const event = new SubmitEvent("submit", { bubbles: true, cancelable: true }); - form.dispatchEvent(event); - return event; - } - - it("cancels form submits for sample stories", async () => { - await setupController({ id: "-5" }); - - expect(submitRefresh().defaultPrevented).toBe(true); - }); - - it("lets form submits through for real stories", async () => { - await setupController(); - const event = submitRefresh(); - - expect(event.defaultPrevented).toBe(false); - }); -}); diff --git a/spec/javascript/controllers/tutorial_stories_controller_spec.ts b/spec/javascript/controllers/tutorial_stories_controller_spec.ts new file mode 100644 index 000000000..a3e2f4596 --- /dev/null +++ b/spec/javascript/controllers/tutorial_stories_controller_spec.ts @@ -0,0 +1,128 @@ +import { bootStimulus } from "support/stimulus"; +import TutorialStoriesController from "controllers/tutorial_stories_controller"; +import { ensure } from "helpers/ensure"; + +// An unstarred star form, as the server renders it. +function starForm(id: string): string { + return [ + `
`, + " ", + " ", + "
", + ].join("\n"); +} + +async function setupController(): Promise { + // Static test fixture — safe to use innerHTML + document.body.innerHTML = [ + "
", + "
  • ", + starForm("star-preview"), + starForm("star-actions"), + "
    ", + " ", + " ", + "
    ", + "
    ", + "
  • ", + "
    ", + ].join("\n"); + + await bootStimulus("tutorial-stories", TutorialStoriesController); +} + +function form(selector: string): HTMLFormElement { + return ensure(document.querySelector(selector)); +} + +function submit(selector: string): SubmitEvent { + const event = new SubmitEvent("submit", { bubbles: true, cancelable: true }); + form(selector).dispatchEvent(event); + return event; +} + +function icon(selector: string): string { + return ensure(form(selector).querySelector("i")).className; +} + +describe("submitted", () => { + it("cancels the submit", async () => { + await setupController(); + + expect(submit(".story-refresh-form").defaultPrevented).toBe(true); + }); +}); + +describe("submitted for a star form", () => { + it("stars both of the story's star buttons", async () => { + await setupController(); + + submit("#star-preview"); + + expect([icon("#star-preview"), icon("#star-actions")]) + .toStrictEqual(["fa fa-star", "fa fa-star"]); + }); + + it("asks to unstar next time, with a matching label", async () => { + await setupController(); + + submit("#star-preview"); + + const starred = form("#star-actions"); + expect([ + ensure(starred.querySelector("input")).value, + ensure(starred.querySelector("button")).getAttribute("aria-label"), + ]).toStrictEqual(["false", "Unstar"]); + }); + + it("unstars on a second submit", async () => { + await setupController(); + + submit("#star-preview"); + submit("#star-actions"); + + expect(icon("#star-preview")).toBe("fa fa-star-o"); + }); +}); + +describe("submitted for the keep unread form", () => { + it("swaps in a copy with the kept unread state", async () => { + await setupController(); + const original = form(".story-keep-unread-form"); + + submit(".story-keep-unread-form"); + + const copy = form(".story-keep-unread-form"); + expect([copy === original, copy.dataset.isRead, copy.dataset.keepUnread]) + .toStrictEqual([false, "false", "true"]); + }); + + it("shows a check and asks to stop keeping it unread next", async () => { + await setupController(); + + submit(".story-keep-unread-form"); + + const copy = form(".story-keep-unread-form"); + const input = ensure(copy.querySelector("input")); + expect([icon(".story-keep-unread-form"), input.value]) + .toStrictEqual(["fa fa-check", "false"]); + }); +}); + +describe("submitted for the refresh form", () => { + it("marks the form busy for a moment", async () => { + vi.useFakeTimers(); + await setupController(); + + submit(".story-refresh-form"); + const busy = form(".story-refresh-form").getAttribute("aria-busy"); + vi.runAllTimers(); + + expect([busy, form(".story-refresh-form").hasAttribute("aria-busy")]) + .toStrictEqual(["true", false]); + }); +}); diff --git a/spec/javascript/support/story_fixture.ts b/spec/javascript/support/story_fixture.ts index 18f51752b..713894586 100644 --- a/spec/javascript/support/story_fixture.ts +++ b/spec/javascript/support/story_fixture.ts @@ -25,8 +25,7 @@ void { document.body.innerHTML = [ "
  • `, diff --git a/spec/system/tutorial_spec.rb b/spec/system/tutorial_spec.rb index 909af2ecc..56b73de71 100644 --- a/spec/system/tutorial_spec.rb +++ b/spec/system/tutorial_spec.rb @@ -26,12 +26,28 @@ def open_sample_story(source) find(".story-preview", text: source).click end - it "keeps a sample story in place when refreshed" do + it "pretends to refresh a sample story" do open_sample_story("Darin' Fireballs") find(".story-actions .story-refresh").click - expect(page).to have_current_path(setup_tutorial_path) - .and have_css("li.story.open", text: "Darin' Fireballs") + expect(page).to have_css("li.story.open [aria-busy='true'] .fa-refresh") + .and have_current_path(setup_tutorial_path) + end + + it "stars a sample story without saving it" do + open_sample_story("Darin' Fireballs") + + find(".story-actions .story-starred").click + + expect(page).to have_css("li.story.open .story-starred .fa-star", count: 2) + end + + it "keeps a sample story unread without saving it" do + open_sample_story("Darin' Fireballs") + + find(".story-actions .story-keep-unread").click + + expect(page).to have_css("li.story.open.keepUnread .fa-check") end end