diff --git a/.eslint_todo.ts b/.eslint_todo.ts index 74a5e0058..d512e0153 100644 --- a/.eslint_todo.ts +++ b/.eslint_todo.ts @@ -1,32 +1,29 @@ // This configuration was generated by `exe/eslint_autogen` -// on 2026-11-27 23:20:15 UTC. +// on 2026-11-28 00:43:19 UTC. // The point is for the user to remove these configuration records // one by one as the offenses are removed from the code base. import type {Linter} from "eslint"; const config: Linter.Config[] = [ - // Offense count: 3 + // Offense count: 2 { files: [ - "spec/javascript/controllers/star_toggle_controller_spec.ts", "spec/javascript/helpers/api_spec.ts", ], rules: { "@stylistic/dot-location": "off", }, }, - // Offense count: 78 + // Offense count: 60 { files: [ "app/javascript/controllers/keep_unread_toggle_controller.ts", "app/javascript/controllers/mark_all_as_read_controller.ts", - "app/javascript/controllers/star_toggle_controller.ts", "app/javascript/controllers/unread_count_controller.ts", "app/javascript/helpers/api.ts", "eslint.config.ts", "spec/javascript/controllers/mark_all_as_read_controller_spec.ts", - "spec/javascript/controllers/star_toggle_controller_spec.ts", "spec/javascript/controllers/unread_count_controller_spec.ts", "spec/javascript/helpers/api_spec.ts", "types/eslint-plugin-sort-keys-fix.d.ts", @@ -47,12 +44,10 @@ const config: Linter.Config[] = [ "@stylistic/max-len": "off", }, }, - // Offense count: 11 + // Offense count: 9 { files: [ "app/javascript/controllers/keep_unread_toggle_controller.ts", - "app/javascript/controllers/star_toggle_controller.ts", - "spec/javascript/controllers/star_toggle_controller_spec.ts", "spec/javascript/controllers/unread_count_controller_spec.ts", "spec/javascript/helpers/ensure_spec.ts", "spec/javascript/support/stimulus.ts", diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css index 685b2ce0a..5e35bd575 100644 --- a/app/assets/stylesheets/application.css +++ b/app/assets/stylesheets/application.css @@ -278,11 +278,11 @@ li.story > turbo-frame { display: block; } -.story-refresh-form { +.story-refresh-form, .story-star-form { display: inline; } -.story-refresh { +.story-refresh, .story-starred { padding: 0; color: inherit; background: none; diff --git a/app/components/story.rb b/app/components/story.rb index e53336b6b..63360a06e 100644 --- a/app/components/story.rb +++ b/app/components/story.rb @@ -4,11 +4,11 @@ # 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 refresh form submits inside the story's frame: sample stories skip - # it, and a failed refresh leaves the story as it was. + # 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 = [ "keep-unread-toggle:toggled->story#keepUnreadToggled", - "submit->story#refreshSubmitted", + "submit->story#formSubmitted", "turbo:frame-missing->story#frameMissing" ].join(" ").freeze @@ -31,7 +31,7 @@ def classes def data { - controller: "story star-toggle keep-unread-toggle", + controller: "story keep-unread-toggle", action: ACTIONS, **values, story_list_target: "story", @@ -43,8 +43,7 @@ def values read_state = { is_read: story.is_read, keep_unread: story.keep_unread } { **controller_values("story", **read_state), - **controller_values("keep_unread_toggle", **read_state), - **controller_values("star_toggle", starred: story.is_starred) + **controller_values("keep_unread_toggle", **read_state) } end diff --git a/app/components/story_actions.rb b/app/components/story_actions.rb index 7d97cce54..bfc5ae477 100644 --- a/app/components/story_actions.rb +++ b/app/components/story_actions.rb @@ -16,7 +16,7 @@ def view_template div { span(class: "story-published") { story.pretty_date } } div(class: "story-actions") do keep_unread_button - render(Components::StoryStar.new(story:, hotkey: "s")) + render(Components::StoryStar.new(story:, placement: :actions)) refresh_button permalink_link end diff --git a/app/components/story_frame.rb b/app/components/story_frame.rb index c674c7e9b..cb4c7eafe 100644 --- a/app/components/story_frame.rb +++ b/app/components/story_frame.rb @@ -39,7 +39,7 @@ def preview data = { action: "click->story#previewClicked" } div(class: "row story-preview", data:) do div(class: "col-md-3") do - render(Components::StoryStar.new(story:)) + render(Components::StoryStar.new(story:, placement: :preview)) p(class: "blog-title") { story.source } end div(class: "col-md-9") { details } diff --git a/app/components/story_star.rb b/app/components/story_star.rb index 78f8e145c..a76ecf01f 100644 --- a/app/components/story_star.rb +++ b/app/components/story_star.rb @@ -1,29 +1,45 @@ # frozen_string_literal: true -# A star toggle button for a story. Each story shows two: one in its preview -# row and one in its actions, which also answers the s hotkey. +# A star button for a story. Each story shows two: one in its preview row and +# one in its actions, which also answers the s hotkey. +# +# The button submits a form; the response is a Turbo Stream that replaces both +# buttons (see `Components::StoryStarStream`), so the icon only changes once +# the server has saved the star. class Components::StoryStar < Components::Base - attr_accessor :story, :hotkey + PLACEMENTS = [:preview, :actions].freeze - def initialize(story:, hotkey: nil) + attr_accessor :story, :placement + + def self.dom_id(story, placement) + "story_#{story.id}_star_#{placement}" + end + + def initialize(story:, placement:) super() self.story = story - self.hotkey = hotkey + self.placement = placement end def view_template - div(class: "story-starred", data:) do - icon = story.is_starred ? "fa-star" : "fa-star-o" - i(class: "fa #{icon}", data: { star_toggle_target: "icon" }) + url = "/stories/#{story.id}/star" + id = self.class.dom_id(story, placement) + form_with(url:, method: :patch, class: "story-star-form", id:) do + input(type: "hidden", name: "starred", value: (!story.is_starred).to_s) + star_button end end private - def data - data = { action: "click->star-toggle#toggle:stop" } - return data unless hotkey + def star_button + aria_label = t(story.is_starred ? "stories.unstar" : "stories.star") + button(type: "submit", class: "story-starred", aria_label:, data:) do + i(class: "fa #{story.is_starred ? 'fa-star' : 'fa-star-o'}") + end + end - { **data, hotkeys_target: "click", hotkey: } + def data + placement == :actions ? { hotkeys_target: "click", hotkey: "s" } : {} end end diff --git a/app/components/story_star_stream.rb b/app/components/story_star_stream.rb new file mode 100644 index 000000000..61088fc1a --- /dev/null +++ b/app/components/story_star_stream.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +# The response to starring or unstarring a story: a Turbo Stream that +# replaces both of the story's star buttons with their updated state. +class Components::StoryStarStream < Components::Base + register_element :turbo_stream + + attr_accessor :story + + def initialize(story:) + super() + self.story = story + end + + def view_template + Components::StoryStar::PLACEMENTS.each do |placement| + target = Components::StoryStar.dom_id(story, placement) + turbo_stream(action: "replace", target:) do + template { render(Components::StoryStar.new(story:, placement:)) } + end + end + end +end diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index 5438f4b9d..1c1800c85 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -33,6 +33,18 @@ def refresh render(Components::StoryFrame.new(story:), layout: false, status:) end + # Responds with a Turbo Stream that replaces the story's star buttons. + def star + story = authorization.check(StoryRepository.fetch(params[:id])) + story.update!(is_starred: params[:starred] == "true") + + render( + Components::StoryStarStream.new(story:), + layout: false, + content_type: "text/vnd.turbo-stream.html" + ) + end + def mark_all_as_read stories = authorization.scope(Story.where(id: params[:story_ids])) MarkAllAsRead.call(stories.ids) diff --git a/app/javascript/controllers/index.ts b/app/javascript/controllers/index.ts index e74bc8ca4..47fdc11ad 100644 --- a/app/javascript/controllers/index.ts +++ b/app/javascript/controllers/index.ts @@ -18,9 +18,6 @@ application.register("keep-unread-toggle", KeepUnreadToggleController); import MarkAllAsReadController from "./mark_all_as_read_controller"; application.register("mark-all-as-read", MarkAllAsReadController); -import StarToggleController from "./star_toggle_controller"; -application.register("star-toggle", StarToggleController); - import StoryController from "./story_controller"; application.register("story", StoryController); diff --git a/app/javascript/controllers/star_toggle_controller.ts b/app/javascript/controllers/star_toggle_controller.ts deleted file mode 100644 index 481485967..000000000 --- a/app/javascript/controllers/star_toggle_controller.ts +++ /dev/null @@ -1,34 +0,0 @@ -import {Controller} from "@hotwired/stimulus"; - -import {updateStory} from "helpers/api"; - -export default class extends Controller { - static override values = {id: String, starred: Boolean}; - - static override targets = ["icon"]; - - declare idValue: string; - - declare starredValue: boolean; - - iconTargets!: HTMLElement[]; - - async toggle(): Promise { - const starred = !this.starredValue; - - // eslint-disable-next-line camelcase - const response = await updateStory(this.idValue, {is_starred: starred}); - if (!response.ok) { - throw new Error(`Failed to star story ${this.idValue}`); - } - - this.starredValue = starred; - - let icon = "fa fa-star-o"; - if (starred) { icon = "fa fa-star"; } - - for (const target of this.iconTargets) { - target.className = icon; - } - } -} diff --git a/app/javascript/controllers/story_controller.ts b/app/javascript/controllers/story_controller.ts index 853971e45..d92f67aee 100644 --- a/app/javascript/controllers/story_controller.ts +++ b/app/javascript/controllers/story_controller.ts @@ -52,6 +52,11 @@ export default class extends Controller { } previewClicked(event: MouseEvent): void { + // The preview's star button submits its own form. + if (event.target instanceof Element && event.target.closest("form")) { + return; + } + if (opensInTab(event)) { this.openInBackgroundTab(); return; @@ -89,8 +94,8 @@ export default class extends Controller { this.dispatch("read-changed"); } - // Sample stories have no feed to refresh from, so skip the request. - refreshSubmitted(event: Event): void { + // Sample stories aren't saved, so their star and refresh forms do nothing. + formSubmitted(event: Event): void { if (this.isSample()) { event.preventDefault(); } diff --git a/config/locales/en.yml b/config/locales/en.yml index 3adc10d9c..ffff9e5ab 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -200,6 +200,8 @@ en: stories: keep_unread: Keep unread refresh: Refresh story from feed + star: Star + unstar: Unstar time: formats: default: '%b %d, %H:%M' diff --git a/config/routes.rb b/config/routes.rb index acc232c26..b36e9c981 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -38,5 +38,6 @@ get "/starred", to: "stories#starred" put "/stories/:id", to: "stories#update" post "/stories/:id/refresh", to: "stories#refresh" + patch "/stories/:id/star", to: "stories#star" post "/stories/mark_all_as_read", to: "stories#mark_all_as_read" end diff --git a/spec/components/story_spec.rb b/spec/components/story_spec.rb index 526a4d3b0..91fb2a5be 100644 --- a/spec/components/story_spec.rb +++ b/spec/components/story_spec.rb @@ -14,31 +14,25 @@ def story_li(story) it "sets the Stimulus controllers on the li" do li = story_li(create(:story)) - expect(li["data-controller"]).to eq("story star-toggle keep-unread-toggle") + expect(li["data-controller"]).to eq("story keep-unread-toggle") end def values(element) - names = [ - "story-id", - "story-keep-unread", - "keep-unread-toggle-is-read", - "star-toggle-starred" - ] + names = ["story-id", "story-keep-unread", "keep-unread-toggle-is-read"] names.map { |name| element["data-#{name}-value"] } end it "sets the Stimulus values on the li" do - story = create(:story, keep_unread: true, is_starred: true) + story = create(:story, keep_unread: true) - expect(values(story_li(story))) - .to eq([story.id.to_s, "true", "false", "true"]) + expect(values(story_li(story))).to eq([story.id.to_s, "true", "false"]) end - it "wires the refresh form's submit and missing frame actions" do + it "wires the form submit and missing frame actions" do li = story_li(create(:story)) expect(li["data-action"].split).to include( - "submit->story#refreshSubmitted", + "submit->story#formSubmitted", "turbo:frame-missing->story#frameMissing" ) end diff --git a/spec/components/story_star_spec.rb b/spec/components/story_star_spec.rb new file mode 100644 index 000000000..d9dab5209 --- /dev/null +++ b/spec/components/story_star_spec.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +RSpec.describe Components::StoryStar do + def render_star(story, placement) + html = ApplicationController.render( + described_class.new(story:, placement:), + layout: false + ) + Capybara.string(html) + end + + it "posts to the story's star path with an id for its placement" do + story = create(:story) + form = render_star(story, :preview).find("form") + + expect([form[:action], form[:id]]) + .to eq(["/stories/#{story.id}/star", "story_#{story.id}_star_preview"]) + end + + it "asks to star an unstarred story" do + rendered = render_star(create(:story), :preview) + + expect(rendered).to have_field(name: "starred", type: :hidden, with: "true") + end + + it "asks to unstar a starred story" do + rendered = render_star(create(:story, :starred), :preview) + + expect(rendered) + .to have_field(name: "starred", type: :hidden, with: "false") + end + + it "shows a filled star for a starred story" do + expect(render_star(create(:story, :starred), :preview)) + .to have_css("button.story-starred .fa-star") + end + + it "labels the button with what it will do" do + button = render_star(create(:story, :starred), :preview).find("button") + + expect(button["aria-label"]).to eq("Unstar") + end + + it "answers the s hotkey from the actions row" do + button = render_star(create(:story), :actions).find("button") + + expect([button["data-hotkey"], button["data-hotkeys-target"]]) + .to eq(["s", "click"]) + end + + it "leaves the preview row's star without a hotkey" do + button = render_star(create(:story), :preview).find("button") + + expect(button["data-hotkey"]).to be_nil + end +end diff --git a/spec/javascript/controllers/star_toggle_controller_spec.ts b/spec/javascript/controllers/star_toggle_controller_spec.ts deleted file mode 100644 index 3aacc6c6c..000000000 --- a/spec/javascript/controllers/star_toggle_controller_spec.ts +++ /dev/null @@ -1,114 +0,0 @@ -import type {MockInstance} from "vitest"; -import {bootStimulus, getController} from "support/stimulus"; -import StarToggleController from "controllers/star_toggle_controller"; -import {ensure} from "helpers/ensure"; - -function starClass(starred: boolean): string { - if (starred) { return "fa-star"; } - - return "fa-star-o"; -} - -function setupDOM(starred = false): void { - const cls = starClass(starred); - - // Static test fixture — safe to use innerHTML - document.body.innerHTML = [ - "
  • `, - "
    star-toggle#toggle:stop\">", - ` ", - "
    ", - "
    star-toggle#toggle:stop\">", - ` ", - "
    ", - "
  • ", - ].join("\n"); -} - -async function setupController(starred = false): Promise { - setupDOM(starred); - await bootStimulus("star-toggle", StarToggleController); -} - -const sel = "[data-controller='star-toggle']"; -const iconSel = "[data-star-toggle-target='icon']"; - -function element(): HTMLElement { - return ensure(document.querySelector(sel)); -} - -function controller(): StarToggleController { - return getController(element(), "star-toggle", StarToggleController); -} - -function iconTargets(): HTMLElement[] { - return Array.from(document.querySelectorAll(iconSel)); -} - -function expectIcons(className: string): void { - for (const icon of iconTargets()) { - expect(icon.className).toBe(className); - } -} - -function mockFetch(status = 200): MockInstance { - return vi.spyOn(globalThis, "fetch"). - mockResolvedValue(new Response(null, {status})); -} - -describe("toggle", () => { - // eslint-disable-next-line vitest/no-hooks - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("flips icons from unstarred to starred", async () => { - await setupController(false); - mockFetch(); - - await controller().toggle(); - - expectIcons("fa fa-star"); - }); - - it("flips icons from starred to unstarred", async () => { - await setupController(true); - mockFetch(); - - await controller().toggle(); - - expectIcons("fa fa-star-o"); - }); - - it("does not flip icons when the request fails", async () => { - await setupController(false); - mockFetch(500); - - await expect(controller().toggle()).rejects.toThrow("Failed to star"); - - expectIcons("fa fa-star-o"); - }); - - it("calls fetch with the correct payload", async () => { - await setupController(false); - const fetchSpy = mockFetch(); - - await controller().toggle(); - - expect(fetchSpy).toHaveBeenCalledWith( - "/stories/42", - expect.objectContaining({ - // eslint-disable-next-line camelcase - body: JSON.stringify({is_starred: true}), - method: "PUT", - }), - ); - }); -}); diff --git a/spec/javascript/controllers/story_controller_open_spec.ts b/spec/javascript/controllers/story_controller_open_spec.ts index e6a589a86..ac7bb7df6 100644 --- a/spec/javascript/controllers/story_controller_open_spec.ts +++ b/spec/javascript/controllers/story_controller_open_spec.ts @@ -95,6 +95,18 @@ describe("previewClicked", () => { }); }); +describe("previewClicked on the star button", () => { + it("leaves the story closed", async () => { + await setupController(); + mockFetch(); + const button = ensure(element().querySelector("#star button")); + + button.dispatchEvent(new MouseEvent("click", { bubbles: true })); + + expect(isOpen()).toBe(false); + }); +}); + describe("previewClicked with a modifier", () => { it.each([ ["meta", { metaKey: true }], @@ -140,7 +152,7 @@ describe("frameMissing from outside the story", () => { }); }); -describe("refreshSubmitted", () => { +describe("formSubmitted", () => { function submitRefresh(): SubmitEvent { const form = ensure(element().querySelector("form")); const event = new SubmitEvent("submit", { bubbles: true, cancelable: true }); @@ -148,13 +160,13 @@ describe("refreshSubmitted", () => { return event; } - it("cancels the refresh for sample stories", async () => { + it("cancels form submits for sample stories", async () => { await setupController({ id: "-5" }); expect(submitRefresh().defaultPrevented).toBe(true); }); - it("lets the refresh through for real stories", async () => { + it("lets form submits through for real stories", async () => { await setupController(); const event = submitRefresh(); diff --git a/spec/javascript/support/story_fixture.ts b/spec/javascript/support/story_fixture.ts index f0637da7f..1602da6dd 100644 --- a/spec/javascript/support/story_fixture.ts +++ b/spec/javascript/support/story_fixture.ts @@ -14,13 +14,15 @@ void { "
  • `, "
    ", + " data-action='click->story#previewClicked'>", + "
    ", + " ", " ", "
    ", "
  • ", diff --git a/spec/requests/stories_controller_spec.rb b/spec/requests/stories_controller_spec.rb index bf42f5852..cf079a748 100644 --- a/spec/requests/stories_controller_spec.rb +++ b/spec/requests/stories_controller_spec.rb @@ -232,6 +232,50 @@ def have_story_frame(story, text:) end end + describe "#star" do + def star(story, starred) + patch("/stories/#{story.id}/star", params: { starred: starred.to_s }) + end + + def star_targets(story) + ["preview", "actions"].map { |row| "story_#{story.id}_star_#{row}" } + end + + it "stars the story" do + login_as(default_user) + story = create(:story) + + expect { star(story, true) } + .to change_record(story, :is_starred).from(false).to(true) + end + + it "unstars the story" do + login_as(default_user) + story = create(:story, :starred) + + expect { star(story, false) } + .to change_record(story, :is_starred).from(true).to(false) + end + + it "responds with a Turbo Stream" do + login_as(default_user) + + star(create(:story), true) + + expect(response.media_type).to eq("text/vnd.turbo-stream.html") + end + + it "replaces both of the story's star buttons" do + login_as(default_user) + story = create(:story) + + star(story, true) + + expect(rendered.all("turbo-stream", visible: :all).pluck(:target)) + .to eq(star_targets(story)) + end + end + describe "#mark_all_as_read" do it "marks all unread stories as read and reload the page" do login_as(default_user) diff --git a/spec/system/stories_index_spec.rb b/spec/system/stories_index_spec.rb index c71db71ad..d9d35c85f 100644 --- a/spec/system/stories_index_spec.rb +++ b/spec/system/stories_index_spec.rb @@ -69,6 +69,18 @@ def star_story(story_title) find(".story-actions .story-starred").click end + it "stars from the preview row without opening the story" do + create(:story, title: "My Story") + login_as(default_user) + visit(news_path) + + find(".story-preview .story-starred").click + + expect(page) + .to have_css(".story-starred .fa-star", count: 2, visible: :all) + .and have_no_css("li.story.open") + end + it "allows marking a story as starred" do create(:story, title: "My Story") login_as(default_user)