A platform for community discussion. Free, open, simple.
FEATURE: j/k navigation for nested posts (#40008)
Mark VanLandingham6d8401d4a161
diff --git a/app/assets/stylesheets/common/components/keyboard_shortcuts.scss b/app/assets/stylesheets/common/components/keyboard_shortcuts.scssindex 646a680167e..ab826a55c34 100644--- a/app/assets/stylesheets/common/components/keyboard_shortcuts.scss+++ b/app/assets/stylesheets/common/components/keyboard_shortcuts.scss@@ -6,7 +6,17 @@}.featured-topic.selected,-.topic-post.selected {+.topic-post.selected,+.nested-view__op-article[data-keyboard-selected],+.nested-post[data-keyboard-selected]+ > .nested-post__main+ > .nested-post__article,+.nested-post[data-keyboard-selected]+ > .nested-post__main+ > .nested-post__collapsed-bar,+.nested-post[data-keyboard-selected]+ > .nested-post__main+ > .nested-post__placeholder {box-shadow: -3px 0 0 var(--d-nav-color--active);}@@ -16,6 +26,8 @@.topic-post,.post-stream--cloaked,.latest-topic-list-item.selected,+.nested-view__op-article[data-keyboard-selected],+.nested-post[data-keyboard-selected],.search-results .fps-result.selected {&:focus-visible {outline: none;diff --git a/frontend/discourse/app/components/nested.gjs b/frontend/discourse/app/components/nested.gjsindex ef6553cad2e..1bc370ce959 100644--- a/frontend/discourse/app/components/nested.gjs+++ b/frontend/discourse/app/components/nested.gjs@@ -21,6 +21,7 @@ import NestedPost from "./nested/post";import NestedSortSelector from "./nested/sort-selector";export default class Nested extends Component {+ @service appEvents;@service currentUser;@service header;@service screenTrack;@@ -29,11 +30,31 @@ export default class Nested extends Component {@tracked cloakBelow = 0;viewportTracker = new PostStreamViewportTracker();+ constructor() {+ super(...arguments);+ this.appEvents.on("keyboard:move-selection", this, this.maybeLoadMoreRoots);+ }+willDestroy() {super.willDestroy(...arguments);+ this.appEvents.off(+ "keyboard:move-selection",+ this,+ this.maybeLoadMoreRoots+ );this.viewportTracker.destroy();}+ @action+ maybeLoadMoreRoots({ selectedArticle, articles }) {+ if (!this.args.hasMoreRoots || this.args.loadingMore) {+ return;+ }+ if (selectedArticle === articles[articles.length - 1]) {+ this.args.loadMoreRoots?.();+ }+ }+get flatViewUrl() {return getURL(`/t/${this.args.topic.slug}/${this.args.topic.id}?flat=1`);}diff --git a/frontend/discourse/app/services/keyboard-shortcuts.js b/frontend/discourse/app/services/keyboard-shortcuts.jsindex 7c0bcf70bd8..f6b0cd7ffbb 100644--- a/frontend/discourse/app/services/keyboard-shortcuts.js+++ b/frontend/discourse/app/services/keyboard-shortcuts.js@@ -51,6 +51,37 @@ export const PLATFORM_KEY_MODIFIER = /Mac|iPod|iPhone|iPad/.test(? "meta": "ctrl";+const NESTED_POST_CONTENT_SELECTOR = [+ ":scope > .nested-post__main > .nested-post__article",+ ":scope > .nested-post__main > .nested-post__collapsed-bar",+ ":scope > .nested-post__main > .nested-post__placeholder",+].join(", ");++const NESTED_POST_SELECTOR = [+ ".nested-view .nested-view__op-article",+ ".nested-view .nested-post",+].join(", ");++const SELECTED_POST_SELECTOR = [+ ".topic-post.selected article[data-post-id]",+ ".nested-view__op-article[data-keyboard-selected][data-post-id]",+ ".nested-post[data-keyboard-selected] > .nested-post__main > .nested-post__article[data-post-id]",+ ".nested-post[data-keyboard-selected] > .nested-post__main > .nested-post__collapsed-bar[data-post-number]",+ ".nested-post[data-keyboard-selected] > .nested-post__main > .nested-post__placeholder[data-post-number]",+].join(", ");++const SELECTED_POST_LIKE_BUTTON_SELECTOR = [+ ".topic-post.selected button.toggle-like",+ ".nested-view__op-article[data-keyboard-selected] button.toggle-like",+ ".nested-post[data-keyboard-selected] > .nested-post__main > .nested-post__article button.toggle-like",+].join(", ");++const SELECTED_POST_DATE_SELECTOR = [+ ".topic-post.selected a.post-date",+ ".nested-view__op-article[data-keyboard-selected] a.post-date",+ ".nested-post[data-keyboard-selected] > .nested-post__main > .nested-post__article a.post-date",+].join(", ");+const DEFAULT_BINDINGS = {"!": { postAction: "showFlags" },"#": { handler: "goToPost", anonymous: true },@@ -94,7 +125,7 @@ const DEFAULT_BINDINGS = {// we use this odd routing here vs a postAction: cause like// has an animation so the widget handles that// TODO: teach controller how to trigger the widget animation- l: { click: ".topic-post.selected button.toggle-like" },+ l: { click: SELECTED_POST_LIKE_BUTTON_SELECTOR },"m m": { handler: "setTrackingToMuted" }, // mark topic as muted"m r": { handler: "setTrackingToRegular" }, // mark topic as regular"m t": { handler: "setTrackingToTracking" }, // mark topic as tracking@@ -113,7 +144,7 @@ const DEFAULT_BINDINGS = {p: { handler: "showCurrentUser" },q: { handler: "quoteReply" },r: { postAction: "replyToPost" },- s: { click: ".topic-post.selected a.post-date", anonymous: true }, // share post+ s: { click: SELECTED_POST_DATE_SELECTOR, anonymous: true }, // share post"shift+j": { handler: "nextSection", anonymous: true },"shift+k": { handler: "prevSection", anonymous: true },"shift+p": { handler: "pinUnpinTopic" },@@ -453,13 +484,128 @@ export default class KeyboardShortcutLib extends Service {}selectDown() {+ if (document.querySelector(".nested-view")) {+ this._moveAmongNestedPosts(1);+ return;+ }this._moveSelection({ direction: 1, scrollWithinPosts: true });}selectUp() {+ if (document.querySelector(".nested-view")) {+ this._moveAmongNestedPosts(-1);+ return;+ }this._moveSelection({ direction: -1, scrollWithinPosts: true });}+ _moveAmongNestedPosts(direction) {+ // Mirrors _moveSelection; nested post wrappers extend through their whole+ // subtrees, so use each wrapper's own content element for height/offset.+ const now = +new Date();+ const fast =+ this._lastMoveTime && now - this._lastMoveTime < 1.5 * animationDuration;+ this._lastMoveTime = now;++ const posts = Array.from(document.querySelectorAll(NESTED_POST_SELECTOR));+ if (!posts.length) {+ return;+ }+ const contentOf = (post) =>+ post.querySelector(NESTED_POST_CONTENT_SELECTOR) || post;++ let selected = posts.find((p) => p.hasAttribute("data-keyboard-selected"));++ if (selected && !fast) {+ const rect = contentOf(selected).getBoundingClientRect();+ if (rect.bottom < headerOffset() || rect.top > window.innerHeight) {+ selected = null;+ }+ }++ if (!selected) {+ const offset = headerOffset();+ selected =+ posts.find((p) => {+ const rect = contentOf(p).getBoundingClientRect();+ return direction > 0 ? rect.top >= offset : rect.bottom >= offset;+ }) || posts[posts.length - 1];+ direction = 0;+ }++ if (!fast && direction !== 0) {+ const selectedContent = contentOf(selected);+ const beginContent = domUtils.offset(selectedContent).top;+ const endContent = beginContent + selectedContent.offsetHeight;+ const beginScreen = window.scrollY;+ const endScreen = beginScreen + window.innerHeight;++ if (direction < 0 && beginScreen > beginContent) {+ return this._scrollTo(+ Math.max(+ beginScreen - window.innerHeight + 3 * headerOffset(),+ beginContent - headerOffset()+ )+ );+ } else if (direction > 0 && endScreen < endContent - headerOffset()) {+ return this._scrollTo(+ Math.min(+ endScreen - 3 * headerOffset(),+ endContent - window.innerHeight+ )+ );+ }+ }++ let next = selected;+ let newIndex = posts.indexOf(selected);+ while (true) {+ newIndex += direction;+ next = posts[newIndex];+ if (!next) {+ return;+ }+ if (contentOf(next).getBoundingClientRect().height > 0) {+ break;+ }+ if (direction === 0) {+ break;+ }+ }++ // Data attribute, not a class — Ember rebuilds .nested-post's class on cloaking/highlight changes and would wipe it.+ for (const p of posts) {+ p.removeAttribute("data-keyboard-selected");+ p.removeAttribute("tabindex");+ }+ next.setAttribute("data-keyboard-selected", "true");+ next.setAttribute("tabindex", "0");+ next.focus({ preventScroll: true });++ // Subscribed by Nested to trigger boundary load-more on last-post selection.+ this.appEvents.trigger("keyboard:move-selection", {+ articles: posts,+ selectedArticle: next,+ });++ const nextContent = contentOf(next);+ const contentTop = domUtils.offset(nextContent).top;+ const contentTopPosition = contentTop - headerOffset();++ // k onto a tall post lands at its bottom page so successive k's scroll up through it.+ if (+ !fast &&+ direction < 0 &&+ nextContent.offsetHeight > window.innerHeight+ ) {+ return this._scrollTo(+ contentTop + nextContent.offsetHeight - window.innerHeight+ );+ }++ this._scrollTo(contentTopPosition);+ }+bulkSelectItem() {const elem = document.querySelector(".selected input.bulk-select, .selected .select-post"@@ -637,19 +783,24 @@ export default class KeyboardShortcutLib extends Service {sendToSelectedPost(action, elem) {// TODO: We should keep track of the post without a CSS class- const selectedPost =- elem || document.querySelector(".topic-post.selected article.boxed");+ const selectedPost = elem || document.querySelector(SELECTED_POST_SELECTOR);let selectedPostId;+ let selectedPostNumber;if (selectedPost) {selectedPostId = parseInt(selectedPost.dataset.postId, 10);+ selectedPostNumber = parseInt(selectedPost.dataset.postNumber, 10);}- if (selectedPostId) {+ if (selectedPostId || selectedPostNumber) {const topicController = getOwner(this).lookup("controller:topic");- const post = topicController- .get("model.postStream.posts")- .find((p) => p.id === selectedPostId);+ const post = topicController.get("model.postStream.posts").find((p) => {+ if (selectedPostId) {+ return p.id === selectedPostId;+ }++ return p.post_number === selectedPostNumber;+ });if (post) {// TODO: Use ember closure actions@@ -946,7 +1097,7 @@ export default class KeyboardShortcutLib extends Service {}_getSelectedPost() {- return document.querySelector(".topic-post.selected article[data-post-id]");+ return document.querySelector(SELECTED_POST_SELECTOR);}_getSelectedTopicListItem() {diff --git a/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.js b/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.jsindex 49ebde832f9..2bf2b66d9cc 100644--- a/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.js+++ b/frontend/discourse/tests/unit/lib/keyboard-shortcuts-test.js@@ -1,7 +1,10 @@+import Controller from "@ember/controller";+import { triggerKeyEvent } from "@ember/test-helpers";import { setupTest } from "ember-qunit";import { module, test } from "qunit";import sinon from "sinon";import DiscourseURL from "discourse/lib/url";+import { logIn } from "discourse/tests/helpers/qunit-helpers";module("Unit | Utility | keyboard-shortcuts", function (hooks) {setupTest(hooks);@@ -167,4 +170,219 @@ module("Unit | Utility | keyboard-shortcuts", function (hooks) {}});});++ module("nested view navigation", function (nestedHooks) {+ function appendPostControls(article) {+ const likeButton = document.createElement("button");+ likeButton.className = "toggle-like";+ article.appendChild(likeButton);++ const postDate = document.createElement("a");+ postDate.className = "post-date";+ postDate.href = "#";+ article.appendChild(postDate);+ }++ function makePostArticle(id, postId, postNumber, op = false) {+ const article = document.createElement("article");+ article.className = op+ ? "nested-view__op-article boxed"+ : "nested-post__article boxed";+ article.id = id;+ article.dataset.postId = postId;+ article.dataset.postNumber = postNumber;+ article.style.height = "20px";+ appendPostControls(article);+ return article;+ }++ function makePost(id, postId, postNumber) {+ const post = document.createElement("div");+ post.className = "nested-post";+ post.id = id;++ const main = document.createElement("div");+ main.className = "nested-post__main";+ main.appendChild(makePostArticle(`${id}-article`, postId, postNumber));+ post.appendChild(main);++ return post;+ }++ function buildNestedView() {+ const view = document.createElement("div");+ view.className = "nested-view";+ view.appendChild(makePostArticle("op", "100", "1", true));++ const roots = document.createElement("div");+ roots.className = "nested-view__roots";+ view.appendChild(roots);++ const r1 = makePost("r1", "101", "2");+ r1.querySelector(".nested-post__main").appendChild(+ makePost("r1-child", "102", "3")+ );+ roots.append(r1, makePost("r2", "103", "4"), makePost("r3", "104", "5"));++ document.body.appendChild(view);+ return view;+ }++ nestedHooks.afterEach(function () {+ document+ .querySelectorAll(".nested-view, .topic-post.selected")+ .forEach((el) => el.remove());+ });++ test("selectDown seeds the OP when nothing is selected", function (assert) {+ buildNestedView();+ const ks = this.owner.lookup("service:keyboard-shortcuts");++ ks.selectDown();++ assert.strictEqual(+ document.querySelector("[data-keyboard-selected]")?.id,+ "op"+ );+ });++ test("selectDown / selectUp walk the OP and every visible post in DOM order regardless of depth", function (assert) {+ buildNestedView();+ const ks = this.owner.lookup("service:keyboard-shortcuts");++ ks.selectDown(); // op+ ks.selectDown(); // r1+ ks.selectDown(); // r1-child+ assert.strictEqual(+ document.querySelector("[data-keyboard-selected]")?.id,+ "r1-child",+ "j descends into r1's child"+ );++ ks.selectDown(); // r2+ ks.selectDown(); // r3+ ks.selectDown(); // no-op past the last post+ assert.strictEqual(+ document.querySelector("[data-keyboard-selected]")?.id,+ "r3",+ "no wrap-around past the last post"+ );++ ks.selectUp(); // r2+ ks.selectUp(); // r1-child+ assert.strictEqual(+ document.querySelector("[data-keyboard-selected]")?.id,+ "r1-child"+ );++ ks.selectUp(); // r1+ ks.selectUp(); // op+ ks.selectUp(); // no-op before the first post+ assert.strictEqual(+ document.querySelector("[data-keyboard-selected]")?.id,+ "op",+ "no wrap-around past the OP"+ );+ });++ test("keyboard:move-selection fires with the selected post and the full post list", function (assert) {+ buildNestedView();+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ const appEvents = this.owner.lookup("service:app-events");++ let payload;+ const handler = (data) => (payload = data);+ appEvents.on("keyboard:move-selection", handler);++ try {+ ks.selectDown(); // op+ assert.strictEqual(payload?.selectedArticle?.id, "op");+ assert.deepEqual(+ payload.articles.map((article) => article.id),+ ["op", "r1", "r1-child", "r2", "r3"],+ "payload mirrors the flat post-stream shape so Nested can detect boundary"+ );+ } finally {+ appEvents.off("keyboard:move-selection", handler);+ }+ });++ test("post actions target the selected OP and nested reply", function (assert) {+ const opPost = { id: 100, post_number: 1 };+ const nestedPost = { id: 101, post_number: 2 };+ let receivedPost;++ this.owner.register(+ "controller:topic",+ class extends Controller {+ model = { postStream: { posts: [opPost, nestedPost] } };+ actions = {+ replyToPost(post) {+ receivedPost = post;+ },+ };+ }+ );++ buildNestedView();+ const ks = this.owner.lookup("service:keyboard-shortcuts");++ ks.selectDown(); // op+ ks.sendToSelectedPost("replyToPost");+ assert.strictEqual(receivedPost, opPost);++ receivedPost = null;+ ks.selectDown(); // r1+ ks.sendToSelectedPost("replyToPost");+ assert.strictEqual(receivedPost, nestedPost);+ });++ test("like and share shortcuts click controls on selected nested articles", async function (assert) {+ const currentUser = logIn(this.owner);+ buildNestedView();+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ ks.currentUser = currentUser;+ ks.bindKey("l");+ let liked = false;+ let shared = false;++ ks.selectDown(); // op+ ks.selectDown(); // r1++ const article = document.querySelector("#r1-article");+ article+ .querySelector(".toggle-like")+ .addEventListener("click", () => (liked = true));+ article.querySelector(".post-date").addEventListener("click", (event) => {+ event.preventDefault();+ shared = true;+ });++ await triggerKeyEvent(document.body, "keypress", "L");+ await triggerKeyEvent(document.body, "keypress", "S");++ assert.true(+ liked,+ "like shortcut clicks the selected nested article's like button"+ );+ assert.true(+ shared,+ "share shortcut clicks the selected nested article's date link"+ );+ });++ test("selectDown outside the nested view delegates to _moveSelection", function (assert) {+ const ks = this.owner.lookup("service:keyboard-shortcuts");+ const stub = sinon.stub(ks, "_moveSelection");+ try {+ ks.selectDown();+ assert.true(+ stub.calledWith({ direction: 1, scrollWithinPosts: true }),+ "falls through to flat-stream selection when .nested-view is absent"+ );+ } finally {+ stub.restore();+ }+ });+ });});