Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Topic timeline for nested replies view (#40125)

Mark VanLandingham92455224ee72
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index e54b2b5709d..4499a3bf757 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -1,6 +1,7 @@
@import "ac-wrap";
@import "ace-editor";
@import "autocomplete";
+@import "timeline-scrubber";
@import "badges";
@import "banner";
@import "d-breadcrumbs";
diff --git a/app/assets/stylesheets/common/components/timeline-scrubber.scss b/app/assets/stylesheets/common/components/timeline-scrubber.scss
new file mode 100644
index 00000000000..04728738724
--- /dev/null
+++ b/app/assets/stylesheets/common/components/timeline-scrubber.scss
@@ -0,0 +1,70 @@
+.timeline-scrubber {
+ position: relative;
+ touch-action: none;
+ user-select: none;
+
+ --timeline-scroller-height: 50px;
+ border-left: 1px solid var(--topic-timeline-border-color);
+ margin-left: 0.5em;
+
+ &__track {
+ position: absolute;
+ inset: 0;
+ }
+
+ &__scroller {
+ position: absolute;
+ left: 0;
+ right: 0;
+ height: var(--timeline-scroller-height);
+ margin-left: -0.22em;
+ display: flex;
+ align-items: center;
+ cursor: ns-resize;
+ will-change: top;
+ transition: top 0.05s linear;
+
+ // Travel = rail height minus pill height, so progress 0/1 don't overflow.
+ top: calc(
+ var(--scrubber-progress, 0) *
+ (100% - var(--timeline-scroller-height, 50px))
+ );
+ }
+
+ &--dragging &__scroller {
+ transition: none;
+ }
+
+ &__grip {
+ border-radius: 0.8em;
+ width: 0.35em;
+ height: 100%;
+ background-color: var(--topic-timeline-handle-color);
+ flex-shrink: 0;
+ z-index: 1;
+ outline: 1px solid transparent;
+ margin-left: 0.5px;
+ }
+
+ &__scroller-content {
+ box-sizing: border-box;
+ max-width: 100%;
+ overflow: hidden;
+ padding-left: var(--space-4);
+ max-height: 3em;
+ }
+
+ .timeline-replies {
+ overflow: hidden;
+ overflow-wrap: break-word;
+ font-weight: bold;
+ }
+
+ .timeline-ago {
+ color: var(--primary-med-or-secondary-med);
+ max-width: 100%;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+}
diff --git a/app/assets/stylesheets/common/nested-view.scss b/app/assets/stylesheets/common/nested-view.scss
index 0bb78ec80d5..f9fb83ed48e 100644
--- a/app/assets/stylesheets/common/nested-view.scss
+++ b/app/assets/stylesheets/common/nested-view.scss
@@ -1,11 +1,19 @@
@use "lib/viewport";
-// ── Top-level nested view ──────────────────────────────────────────
+.nested-topic-layout {
+ // Read in NestedTopicTimeline to drive matchMedia.
+ --nested-timeline-min-width: 925px;
+ display: grid;
+ grid-template-areas: "content timeline";
+ grid-template-columns: auto auto;
+ margin-bottom: var(--below-topic-margin);
+
+ &__content {
+ grid-area: content;
+ }
+}
+
.nested-view {
- background: var(--secondary);
- margin: 0 auto;
- padding: var(--space-4);
- border-radius: var(--d-border-radius-large);
max-width: calc(
var(--topic-body-width) + (var(--topic-body-width-padding) * 2) +
var(--topic-avatar-width)
@@ -17,6 +25,11 @@
border-bottom: 1px solid var(--primary-low);
}
+ &__loading-previous,
+ &__loading-next {
+ overflow-anchor: none;
+ }
+
&__title {
margin: 0;
font-size: var(--font-up-4);
@@ -1073,3 +1086,49 @@ html.footer-nav-visible {
bottom: calc(var(--footer-nav-height) + env(safe-area-inset-bottom) + 1em);
}
}
+
+.nested-topic-timeline {
+ grid-area: timeline;
+ align-self: start;
+ position: sticky;
+
+ // Matches the sticky offset exactly so the aside doesn't jump between
+ // its natural (scrollY=0) and pinned (scrollY>0) y-positions — the
+ // jump is what made it look like the load-previous spinner was
+ // "pushing" the timeline down.
+ top: calc(var(--header-offset, 60px) + 1.5em);
+ margin-left: 1em;
+ width: 7em;
+ z-index: 50;
+
+ &__endpoint {
+ appearance: none;
+ background: none;
+ border: 0;
+ display: block;
+ font: inherit;
+ color: var(--primary-med-or-secondary-med);
+ padding: 0;
+ margin: 0;
+ cursor: pointer;
+ text-align: left;
+
+ &:hover,
+ &:focus {
+ color: var(--primary);
+ }
+ }
+
+ &__endpoint--start {
+ margin: var(--space-2) 0;
+ }
+
+ &__endpoint--end {
+ margin-top: var(--space-2);
+ }
+
+ &__scrubber {
+ height: 320px;
+ margin-left: var(--space-half);
+ }
+}
diff --git a/app/assets/stylesheets/common/topic-timeline.scss b/app/assets/stylesheets/common/topic-timeline.scss
index bea82d2b327..c8223adfaca 100644
--- a/app/assets/stylesheets/common/topic-timeline.scss
+++ b/app/assets/stylesheets/common/topic-timeline.scss
@@ -152,10 +152,13 @@
border-left: none;
max-width: 120px;
+ // Fullscreen mode renders the rail on the right edge; flip the
+ // pill so the grip sits against it.
.timeline-scroller {
position: relative;
margin-right: -1.5em;
padding-right: 1.5em;
+ flex-direction: row-reverse;
justify-content: flex-end;
.timeline-scroller-content {
@@ -168,17 +171,9 @@
}
.timeline-handle {
- float: none;
width: 11px;
- position: relative;
- right: -6px;
}
}
-
- .timeline-padding {
- margin-left: 0;
- margin-right: -1em;
- }
}
}
@@ -237,79 +232,8 @@
color: var(--primary-med-or-secondary-med);
}
- .timeline-scrollarea {
- margin-top: 0.5em;
- margin-left: 0.5em;
- border-left: 1px solid var(--topic-timeline-border-color);
- position: relative;
- max-width: 100%;
- transform: translateZ(0);
- }
-
- .timeline-padding {
- transition: height 0.15s ease-out;
- cursor: pointer;
-
- // this element has a click event
- // the negative margin lets this element overlap
- // the scrollarea's vertical track and thus it
- // enables taps on the track to work
- margin-left: -1em;
-
- .widget-dragging & {
- transition: none;
- }
-
- .dragging & {
- transition: none;
- }
- }
-
- .timeline-handle {
- border-radius: 0.8em;
- width: 0.35em;
- background-color: var(--topic-timeline-handle-color);
- height: 100%;
- float: left;
- flex-shrink: 0;
- z-index: z("base") + 1;
- outline: 1px solid transparent;
- margin-left: 0.5px;
- }
-
- .timeline-scroller-content {
- box-sizing: border-box;
- max-width: 100%;
- overflow: hidden;
- padding-left: var(--space-4);
- position: absolute; // prevents text length from impacting width
- max-height: 3em; // this hides the date when the count + date would wrap to more than 2 lines
- }
-
- .timeline-ago {
- color: var(--primary-med-or-secondary-med);
- max-width: 100%;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- }
-
- .timeline-scroller {
- @include unselectable;
- margin-left: -0.22em;
- cursor: ns-resize;
- display: flex;
- align-items: center;
-
- .back-button {
- margin-top: var(--space-4);
- }
- }
-
- .timeline-replies {
- overflow: hidden;
- overflow-wrap: break-word;
- font-weight: bold;
+ .topic-timeline-scrubber .back-button {
+ margin-top: var(--space-4);
}
.timeline-last-read {
diff --git a/app/services/nested_topic/list_roots.rb b/app/services/nested_topic/list_roots.rb
index 465031f557c..a191dc6cf4a 100644
--- a/app/services/nested_topic/list_roots.rb
+++ b/app/services/nested_topic/list_roots.rb
@@ -19,6 +19,7 @@ class NestedTopic::ListRoots
step :expand_reply_trees
step :prepare_posts
step :serialize_roots
+ step :attach_root_summary
only_if(:initial_page) { step :enrich_with_topic_metadata }
only_if(:final_page) { step :attach_suggested_and_related }
@@ -55,20 +56,26 @@ class NestedTopic::ListRoots
def load_roots(params:, loader:, topic_view:)
pinned_post_ids = topic_view.topic.nested_topic&.pinned_post_ids.presence
+ context[:all_pinned_post_ids] = pinned_post_ids
scope = loader.root_posts_scope(params.sort)
- scope = scope.where.not(id: pinned_post_ids) if pinned_post_ids.present?
- roots =
- scope.offset(params.page * NestedReplies::TreeLoader::ROOTS_PER_PAGE).limit(
- NestedReplies::TreeLoader::ROOTS_PER_PAGE,
- )
- context[:roots] = loader.load_posts_for_tree(roots).to_a
- context[:has_more_roots] = context[:roots].size == NestedReplies::TreeLoader::ROOTS_PER_PAGE
+
+ # Deleted pinned roots aren't promoted; let them fall through to
+ # render as [deleted] placeholders instead of vanishing.
+ if pinned_post_ids.present?
+ promotable_pinned_ids = loader.promotable_pinned_post_ids(pinned_post_ids)
+ scope = scope.where.not(id: promotable_pinned_ids) if promotable_pinned_ids.present?
+ end
+
+ page_size = NestedReplies::TreeLoader::ROOTS_PER_PAGE
+ roots = scope.offset(params.page * page_size).limit(page_size + 1)
+ roots = loader.load_posts_for_tree(roots).to_a
+ context[:has_more_roots] = roots.size > page_size
+ context[:roots] = roots.first(page_size)
end
- def promote_pinned_roots(loader:, topic_view:, roots:)
- pinned_post_ids = topic_view.topic.nested_topic&.pinned_post_ids.presence
- context[:pinned_post_ids] = pinned_post_ids
- context[:roots] = loader.promote_pinned_roots(roots, pinned_post_ids)
+ def promote_pinned_roots(loader:, all_pinned_post_ids:, roots:)
+ context[:pinned_post_ids] = all_pinned_post_ids
+ context[:roots] = loader.promote_pinned_roots(roots, all_pinned_post_ids)
end
def expand_reply_trees(loader:, params:, roots:)
@@ -128,6 +135,10 @@ class NestedTopic::ListRoots
response[:pinned_post_ids] = pinned_post_ids if pinned_post_ids.present?
end
+ def attach_root_summary(params:, loader:, all_pinned_post_ids:, response:)
+ response[:root_summary] = loader.root_summary(params.sort, pinned_post_ids: all_pinned_post_ids)
+ end
+
def attach_suggested_and_related(serializer:, response:)
response.merge!(serializer.serialize_suggested_and_related)
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 4caff6d11fb..8e3b315ffdc 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -4011,6 +4011,19 @@ en:
category_settings:
default_nested_view: "Use nested view as default for topics in this category"
no_replies: "No replies yet."
+ topic_timeline:
+ aria_label: "Topic timeline"
+ position: "%{current} / %{total}"
+ sort_endpoints:
+ top:
+ start: "Most liked"
+ end: "Least liked"
+ new:
+ start: "Newest"
+ end: "Oldest"
+ old:
+ start: "Oldest"
+ end: "Newest"
deleted_post_placeholder: "[deleted]"
ignored_post_placeholder: "[ignored]"
toggle_ignored_content: "Show ignored content"
diff --git a/frontend/discourse/app/components/nested.gjs b/frontend/discourse/app/components/nested.gjs
index 0ca94996fa1..cc9d0e1fdfc 100644
--- a/frontend/discourse/app/components/nested.gjs
+++ b/frontend/discourse/app/components/nested.gjs
@@ -76,74 +76,79 @@ export default class Nested extends Component {
}}
>
- <NestedHeader
- @topic={{@topic}}
- @editingTopic={{@editingTopic}}
- @buffered={{@buffered}}
- @showCategoryChooser={{@showCategoryChooser}}
- @canEditTags={{@canEditTags}}
- @minimumRequiredTags={{@minimumRequiredTags}}
- @finishedEditingTopic={{@finishedEditingTopic}}
- @cancelEditingTopic={{@cancelEditingTopic}}
- @topicCategoryChanged={{@topicCategoryChanged}}
- @topicTagsChanged={{@topicTagsChanged}}
- @startEditingTopic={{@startEditingTopic}}
- />
-
<PluginOutlet
@name="topic-above-post-stream"
@connectorTagName="div"
@outletArgs={{lazyHash model=@topic}}
/>
- <NestedOp
- @post={{@opPost}}
- @topic={{@topic}}
- @editPost={{@editPost}}
- @showHistory={{@showHistory}}
- @replyToPost={{@replyToPost}}
- @changeNotice={{@changeNotice}}
- @changePostOwner={{@changePostOwner}}
- @grantBadge={{@grantBadge}}
- @lockPost={{@lockPost}}
- @unlockPost={{@unlockPost}}
- @permanentlyDeletePost={{@permanentlyDeletePost}}
- @rebakePost={{@rebakePost}}
- @showPagePublish={{@showPagePublish}}
- @togglePostType={{@togglePostType}}
- @toggleWiki={{@toggleWiki}}
- @unhidePost={{@unhidePost}}
- @showPostMenu={{true}}
- @registerPost={{this.viewportTracker.registerPost}}
- />
+ {{! Site header docks the title once the in-page header is hidden. }}
+ {{#unless @firstLoadedPage}}
+ <NestedHeader
+ @topic={{@topic}}
+ @editingTopic={{@editingTopic}}
+ @buffered={{@buffered}}
+ @showCategoryChooser={{@showCategoryChooser}}
+ @canEditTags={{@canEditTags}}
+ @minimumRequiredTags={{@minimumRequiredTags}}
+ @finishedEditingTopic={{@finishedEditingTopic}}
+ @cancelEditingTopic={{@cancelEditingTopic}}
+ @topicCategoryChanged={{@topicCategoryChanged}}
+ @topicTagsChanged={{@topicTagsChanged}}
+ @startEditingTopic={{@startEditingTopic}}
+ />
- <div class="nested-view__topic-map topic-map">
- <TopicMap
- @model={{@topic}}
- @topicDetails={{@topic.details}}
- @showPMMap={{@topic.isPrivateMessage}}
+ <NestedOp
+ @post={{@opPost}}
+ @topic={{@topic}}
+ @editPost={{@editPost}}
+ @showHistory={{@showHistory}}
+ @replyToPost={{@replyToPost}}
+ @changeNotice={{@changeNotice}}
+ @changePostOwner={{@changePostOwner}}
+ @grantBadge={{@grantBadge}}
+ @lockPost={{@lockPost}}
+ @unlockPost={{@unlockPost}}
+ @permanentlyDeletePost={{@permanentlyDeletePost}}
+ @rebakePost={{@rebakePost}}
+ @showPagePublish={{@showPagePublish}}
+ @togglePostType={{@togglePostType}}
+ @toggleWiki={{@toggleWiki}}
+ @unhidePost={{@unhidePost}}
+ @showPostMenu={{true}}
+ @registerPost={{this.viewportTracker.registerPost}}
/>
- </div>
- <div class="nested-view__controls">
- <NestedSortSelector @current={{@sort}} @onChange={{@changeSort}} />
- <div class="nested-view__controls-right">
- {{#if @topic.has_activity_log}}
- <DButton
- class="btn-flat nested-view__activity-link"
- @action={{@showActivityLog}}
- @label="nested_replies.activity_log.link"
- />
- {{/if}}
- {{#if this.currentUser.can_toggle_nested_mode}}
- <DButton
- class="btn-flat nested-view__flat-link"
- @href={{this.flatViewUrl}}
- @label="nested_replies.view_as_flat"
- />
- {{/if}}
+ <div class="nested-view__topic-map topic-map">
+ <TopicMap
+ @model={{@topic}}
+ @topicDetails={{@topic.details}}
+ @showPMMap={{@topic.isPrivateMessage}}
+ />
</div>
- </div>
+ {{/unless}}
+
+ {{#unless @firstLoadedPage}}
+ <div class="nested-view__controls">
+ <NestedSortSelector @current={{@sort}} @onChange={{@changeSort}} />
+ <div class="nested-view__controls-right">
+ {{#if @topic.has_activity_log}}
+ <DButton
+ class="btn-flat nested-view__activity-link"
+ @action={{@showActivityLog}}
+ @label="nested_replies.activity_log.link"
+ />
+ {{/if}}
+ {{#if this.currentUser.can_toggle_nested_mode}}
+ <DButton
+ class="btn-flat nested-view__flat-link"
+ @href={{this.flatViewUrl}}
+ @label="nested_replies.view_as_flat"
+ />
+ {{/if}}
+ </div>
+ </div>
+ {{/unless}}
{{#if (gt @newRootPostCount 0)}}
<div class="nested-view__new-replies">
@@ -159,6 +164,21 @@ export default class Nested extends Component {
{{/if}}
<div class="nested-view__roots">
+ {{#if @hasMoreRootsBefore}}
+ <DLoadMore
+ @action={{@loadPreviousRoots}}
+ @enabled={{@hasMoreRootsBefore}}
+ @isLoading={{@loadingPreviousRoots}}
+ >
+ {{#if @loadingPreviousRoots}}
+ <DConditionalLoadingSpinner
+ class="nested-view__loading-previous"
+ @condition={{true}}
+ />
+ {{/if}}
+ </DLoadMore>
+ {{/if}}
+
{{#each @rootNodes key="post.id" as |node|}}
<NestedPost
@post={{node.post}}
@@ -200,12 +220,17 @@ export default class Nested extends Component {
{{/each}}
</div>
- <DConditionalLoadingSpinner @condition={{@loadingMore}} />
+ {{#if @loadingNextRoots}}
+ <DConditionalLoadingSpinner
+ class="nested-view__loading-next"
+ @condition={{true}}
+ />
+ {{/if}}
<DLoadMore
@action={{@loadMoreRoots}}
@enabled={{@hasMoreRoots}}
- @isLoading={{@loadingMore}}
+ @isLoading={{@loadingNextRoots}}
/>
<PluginOutlet
diff --git a/frontend/discourse/app/components/nested/header.gjs b/frontend/discourse/app/components/nested/header.gjs
index 969ed81ac18..73c63fb4a7a 100644
--- a/frontend/discourse/app/components/nested/header.gjs
+++ b/frontend/discourse/app/components/nested/header.gjs
@@ -1,4 +1,8 @@
+import Component from "@glimmer/component";
import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
+import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import PluginOutlet from "discourse/components/plugin-outlet";
import TopicCategory from "discourse/components/topic-category";
@@ -7,51 +11,71 @@ import TopicStatus from "discourse/components/topic-status";
import TopicTitleEditor from "discourse/components/topic-title-editor";
import lazyHash from "discourse/helpers/lazy-hash";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dObserveIntersection from "discourse/ui-kit/modifiers/d-observe-intersection";
-<template>
- <div class="nested-view__header">
- {{#if @editingTopic}}
- <div class="edit-topic-title">
- <TopicTitleEditor
- @bufferedTitle={{@buffered.title}}
- @model={{@topic}}
- @buffered={{@buffered}}
- />
+export default class NestedHeader extends Component {
+ @service header;
- <TopicMetadata
- @buffered={{@buffered}}
- @model={{@topic}}
- @showCategoryChooser={{@showCategoryChooser}}
- @canEditTags={{@canEditTags}}
- @minimumRequiredTags={{@minimumRequiredTags}}
- @onSave={{@finishedEditingTopic}}
- @onCancel={{@cancelEditingTopic}}
- @topicCategoryChanged={{@topicCategoryChanged}}
- @topicTagsChanged={{@topicTagsChanged}}
- />
- </div>
- {{else}}
- <h1 class="nested-view__title">
- <TopicStatus @topic={{@topic}} />
- <a
- href={{@topic.url}}
- {{on "click" @startEditingTopic}}
- class="fancy-title"
- >
- {{trustHTML @topic.fancyTitle~}}
- {{~#if @topic.details.can_edit~}}
- <span class="edit-topic__wrapper">
- {{dIcon "pencil" class="edit-topic"}}
- </span>
- {{~/if}}
- </a>
- </h1>
- <TopicCategory @topic={{@topic}} class="topic-category" />
- {{/if}}
- <PluginOutlet
- @name="topic-title"
- @connectorTagName="div"
- @outletArgs={{lazyHash model=@topic}}
- />
- </div>
-</template>
+ @action
+ handleIntersectionChange(entry) {
+ this.header.mainTopicTitleVisible =
+ entry.isIntersecting || entry.boundingClientRect.top > 0;
+ }
+
+ @action
+ handleDestroy() {
+ this.header.mainTopicTitleVisible = false;
+ }
+
+ <template>
+ <div
+ class="nested-view__header"
+ {{dObserveIntersection this.handleIntersectionChange}}
+ {{willDestroy this.handleDestroy}}
+ >
+ {{#if @editingTopic}}
+ <div class="edit-topic-title">
+ <TopicTitleEditor
+ @bufferedTitle={{@buffered.title}}
+ @model={{@topic}}
+ @buffered={{@buffered}}
+ />
+
+ <TopicMetadata
+ @buffered={{@buffered}}
+ @model={{@topic}}
+ @showCategoryChooser={{@showCategoryChooser}}
+ @canEditTags={{@canEditTags}}
+ @minimumRequiredTags={{@minimumRequiredTags}}
+ @onSave={{@finishedEditingTopic}}
+ @onCancel={{@cancelEditingTopic}}
+ @topicCategoryChanged={{@topicCategoryChanged}}
+ @topicTagsChanged={{@topicTagsChanged}}
+ />
+ </div>
+ {{else}}
+ <h1 class="nested-view__title">
+ <TopicStatus @topic={{@topic}} />
+ <a
+ href={{@topic.url}}
+ {{on "click" @startEditingTopic}}
+ class="fancy-title"
+ >
+ {{trustHTML @topic.fancyTitle~}}
+ {{~#if @topic.details.can_edit~}}
+ <span class="edit-topic__wrapper">
+ {{dIcon "pencil" class="edit-topic"}}
+ </span>
+ {{~/if}}
+ </a>
+ </h1>
+ <TopicCategory @topic={{@topic}} class="topic-category" />
+ {{/if}}
+ <PluginOutlet
+ @name="topic-title"
+ @connectorTagName="div"
+ @outletArgs={{lazyHash model=@topic}}
+ />
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/nested/post.gjs b/frontend/discourse/app/components/nested/post.gjs
index b3423678725..986396aec30 100644
--- a/frontend/discourse/app/components/nested/post.gjs
+++ b/frontend/discourse/app/components/nested/post.gjs
@@ -35,6 +35,7 @@ export default class NestedPost extends Component {
@service capabilities;
@service currentUser;
@service modal;
+ @service nestedRootElements;
@service site;
@service siteSettings;
@@ -59,6 +60,15 @@ export default class NestedPost extends Component {
});
});
+ registerRoot = modifier((element) => {
+ if (this.args.depth !== 0) {
+ return;
+ }
+ const postNumber = this.args.post?.post_number;
+ this.nestedRootElements.register(postNumber, element);
+ return () => this.nestedRootElements.unregister(postNumber);
+ });
+
@tracked _childWasCreated = false;
constructor() {
@@ -347,6 +357,7 @@ export default class NestedPost extends Component {
}}
style={{this.cloakingData.style}}
{{this.restoreScroll}}
+ {{this.registerRoot}}
{{! At depth 0, register wrapper with cloaking observer (captures full subtree height).
At deeper depths, register as trackOnly (viewport tracking only, no cloaking). }}
{{@registerPost @post trackOnly=(not this.isRoot)}}
diff --git a/frontend/discourse/app/components/nested/topic-timeline.gjs b/frontend/discourse/app/components/nested/topic-timeline.gjs
new file mode 100644
index 00000000000..cc0b7c1aa54
--- /dev/null
+++ b/frontend/discourse/app/components/nested/topic-timeline.gjs
@@ -0,0 +1,305 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import TimelineScrubber from "discourse/components/timeline-scrubber";
+import { and, gt } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+
+export default class NestedTopicTimeline extends Component {
+ @service header;
+ @service nestedRootElements;
+
+ @tracked activeGlobalIndex = null;
+ @tracked latchedProgress = null;
+ @tracked viewportWide = true;
+
+ trackActiveRoot = modifier(() => {
+ this.#unsubscribeRegistry = this.nestedRootElements.subscribe(
+ this.#handleRegistryChange
+ );
+
+ this.#resizeHandler = () => this.#rebuildObserver();
+ window.addEventListener("resize", this.#resizeHandler, { passive: true });
+
+ this.#rebuildObserver();
+
+ return () => {
+ this.#unsubscribeRegistry?.();
+ this.#unsubscribeRegistry = null;
+ window.removeEventListener("resize", this.#resizeHandler);
+ this.#resizeHandler = null;
+ this.#observer?.disconnect();
+ this.#observer = null;
+ this.#aboveAnchor.clear();
+ };
+ });
+
+ // Post-numbers currently above the anchor line. Updated only when an
+ // IntersectionObserver entry fires — no per-scroll-frame work.
+ #aboveAnchor = new Set();
+ #observer = null;
+ #unsubscribeRegistry = null;
+ #resizeHandler = null;
+ #mediaQuery = null;
+ #onMediaChange = () => (this.viewportWide = this.#mediaQuery.matches);
+ #handleRegistryChange = (type, postNumber, element) => {
+ if (!this.#observer) {
+ return;
+ }
+ if (type === "register") {
+ this.#observer.observe(element);
+ } else {
+ this.#observer.unobserve(element);
+ if (this.#aboveAnchor.delete(postNumber)) {
+ this.#recomputeActive();
+ }
+ }
+ };
+
+ constructor() {
+ super(...arguments);
+ const layout = document.querySelector(".nested-topic-layout");
+ const minWidth =
+ parseInt(
+ layout &&
+ getComputedStyle(layout).getPropertyValue(
+ "--nested-timeline-min-width"
+ ),
+ 10
+ ) || 925;
+ this.#mediaQuery = matchMedia(`(min-width: ${minWidth}px)`);
+ this.viewportWide = this.#mediaQuery.matches;
+ this.#mediaQuery.addEventListener("change", this.#onMediaChange);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#mediaQuery?.removeEventListener("change", this.#onMediaChange);
+ }
+
+ get summary() {
+ return this.args.summary;
+ }
+
+ get total() {
+ return this.summary?.total ?? 0;
+ }
+
+ get pageSize() {
+ return this.summary?.page_size;
+ }
+
+ get pageCount() {
+ return this.summary?.page_count ?? 0;
+ }
+
+ get keyboardStep() {
+ return this.total ? 1 / this.total : 0.05;
+ }
+
+ get ariaValueText() {
+ return this.positionLabelAt(this.effectiveProgress);
+ }
+
+ get sortEndpoints() {
+ const sort = this.args.sort || "top";
+ return {
+ start: i18n(`nested_replies.topic_timeline.sort_endpoints.${sort}.start`),
+ end: i18n(`nested_replies.topic_timeline.sort_endpoints.${sort}.end`),
+ };
+ }
+
+ get scrubProgress() {
+ if (this.activeGlobalIndex == null || this.total <= 1) {
+ return 0;
+ }
+ return Math.min(this.total - 1, this.activeGlobalIndex) / (this.total - 1);
+ }
+
+ // Holds the handle at the just-committed position until jumpToRootPage
+ // resolves and the post-jump scroll has propagated into activeGlobalIndex.
+ // Without this the handle snaps back to the stale scrubProgress for a
+ // visible flash.
+ get effectiveProgress() {
+ return this.latchedProgress ?? this.scrubProgress;
+ }
+
+ @action
+ indexAtProgress(progress) {
+ return Math.min(this.total - 1, Math.floor(progress * this.total));
+ }
+
+ @action
+ positionLabelAt(progress) {
+ return i18n("nested_replies.topic_timeline.position", {
+ current: this.indexAtProgress(progress) + 1,
+ total: this.total,
+ });
+ }
+
+ #rebuildObserver() {
+ this.#observer?.disconnect();
+ this.#aboveAnchor.clear();
+
+ const anchorY = (this.header.headerOffset ?? 0) + 16;
+
+ // rootMargin shrinks the top of the viewport by anchorY, so:
+ // - Threshold 1 fires when the element's top crosses anchorY
+ // (entering/leaving "fully below anchor")
+ // - Threshold 0 fires when the element's bottom crosses anchorY
+ // (entering/leaving "any part below anchor")
+ // We use entry.boundingClientRect.top to determine which side of the
+ // anchor the element is on — no rect read on the scroll path.
+ this.#observer = new IntersectionObserver(
+ (entries) => this.#handleEntries(entries, anchorY),
+ {
+ rootMargin: `-${anchorY}px 0px 0px 0px`,
+ threshold: [0, 1],
+ }
+ );
+
+ for (const el of this.nestedRootElements.elements()) {
+ this.#observer.observe(el);
+ }
+ }
+
+ #handleEntries(entries, anchorY) {
+ let changed = false;
+ for (const entry of entries) {
+ const postNumber = this.nestedRootElements.postNumberFor(entry.target);
+ if (postNumber == null) {
+ continue;
+ }
+ const top = entry.boundingClientRect.top;
+ // top < anchorY means the element's top edge has scrolled past the
+ // anchor line, regardless of whether it's still partly visible.
+ if (top < anchorY) {
+ if (!this.#aboveAnchor.has(postNumber)) {
+ this.#aboveAnchor.add(postNumber);
+ changed = true;
+ }
+ } else if (this.#aboveAnchor.delete(postNumber)) {
+ changed = true;
+ }
+ }
+ if (changed) {
+ this.#recomputeActive();
+ }
+ }
+
+ // The active root is the bottom-most one currently above the anchor line —
+ // i.e. the one the user is most likely reading. With rootNodes already in
+ // DOM order, we iterate from the bottom and stop on the first match.
+ #recomputeActive() {
+ const pageSize = this.summary?.page_size;
+ if (!pageSize) {
+ return;
+ }
+
+ let activeDomIndex = 0;
+ if (this.#aboveAnchor.size > 0) {
+ const rootNodes = this.args.rootNodes ?? [];
+ for (let i = rootNodes.length - 1; i >= 0; i--) {
+ const postNumber = rootNodes[i]?.post?.post_number;
+ if (postNumber != null && this.#aboveAnchor.has(postNumber)) {
+ activeDomIndex = i;
+ break;
+ }
+ }
+ }
+
+ const firstPage = this.args.firstLoadedPage ?? 0;
+ // Pages after 0 contain only unpinned roots; pinned roots sit at the
+ // top of total ordering but aren't re-rendered, so offset for them.
+ const pinnedOffset =
+ firstPage === 0 ? 0 : (this.summary?.pinned_count ?? 0);
+ const globalIndex = pinnedOffset + firstPage * pageSize + activeDomIndex;
+
+ if (globalIndex !== this.activeGlobalIndex) {
+ this.activeGlobalIndex = globalIndex;
+ }
+ }
+
+ @action
+ async onCommit(progress) {
+ const pageSize = this.pageSize;
+ if (!pageSize || this.total === 0 || !this.args.jumpToRootPage) {
+ return;
+ }
+
+ // Page 0 holds pinned + first unpinned page; later pages hold only unpinned.
+ const pinnedCount = this.summary?.pinned_count ?? 0;
+ const targetIndex = this.indexAtProgress(progress);
+ const unpinnedTargetIndex = Math.max(0, targetIndex - pinnedCount);
+ const targetPage = Math.min(
+ this.pageCount - 1,
+ Math.floor(unpinnedTargetIndex / pageSize)
+ );
+ const targetOffset =
+ targetPage === 0 ? targetIndex : unpinnedTargetIndex % pageSize;
+
+ this.latchedProgress = progress;
+ try {
+ await this.args.jumpToRootPage(targetPage, null, targetOffset);
+ await new Promise((r) =>
+ requestAnimationFrame(() => requestAnimationFrame(r))
+ );
+ } finally {
+ this.latchedProgress = null;
+ }
+ }
+
+ @action
+ jumpToStart() {
+ return this.onCommit(0);
+ }
+
+ @action
+ jumpToEnd() {
+ return this.onCommit(1);
+ }
+
+ <template>
+ {{#if (and this.viewportWide (gt this.total 0))}}
+ <aside
+ class="nested-topic-timeline"
+ aria-label={{i18n "nested_replies.topic_timeline.aria_label"}}
+ {{this.trackActiveRoot}}
+ >
+ <button
+ type="button"
+ class="nested-topic-timeline__endpoint nested-topic-timeline__endpoint--start"
+ {{on "click" this.jumpToStart}}
+ >
+ {{this.sortEndpoints.start}}
+ </button>
+
+ <TimelineScrubber
+ class="nested-topic-timeline__scrubber"
+ @progress={{this.effectiveProgress}}
+ @ariaLabel={{i18n "nested_replies.topic_timeline.aria_label"}}
+ @ariaValueText={{this.ariaValueText}}
+ @keyboardStep={{this.keyboardStep}}
+ @onCommit={{this.onCommit}}
+ >
+ <:handle as |progress|>
+ <div class="timeline-replies">
+ {{this.positionLabelAt progress}}
+ </div>
+ </:handle>
+ </TimelineScrubber>
+
+ <button
+ type="button"
+ class="nested-topic-timeline__endpoint nested-topic-timeline__endpoint--end"
+ {{on "click" this.jumpToEnd}}
+ >
+ {{this.sortEndpoints.end}}
+ </button>
+ </aside>
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/app/components/timeline-scrubber.gjs b/frontend/discourse/app/components/timeline-scrubber.gjs
new file mode 100644
index 00000000000..71b223c202e
--- /dev/null
+++ b/frontend/discourse/app/components/timeline-scrubber.gjs
@@ -0,0 +1,200 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { trustHTML } from "@ember/template";
+import { modifier } from "ember-modifier";
+
+export const SCROLLER_HEIGHT = 50;
+
+export default class TimelineScrubber extends Component {
+ @tracked dragging = false;
+ @tracked dragProgress = 0;
+
+ registerRail = modifier((el) => {
+ this.#railEl = el;
+ return () => (this.#railEl = null);
+ });
+
+ registerScroller = modifier((el) => {
+ this.#scrollerEl = el;
+ return () => (this.#scrollerEl = null);
+ });
+
+ #railEl = null;
+ #scrollerEl = null;
+ #dragOffset = 0;
+
+ get progress() {
+ return this.dragging ? this.dragProgress : (this.args.progress ?? 0);
+ }
+
+ get railStyle() {
+ let css = `--scrubber-progress: ${this.progress.toFixed(4)}`;
+ if (this.args.height != null) {
+ css += `; height: ${this.args.height}px`;
+ }
+ return trustHTML(css);
+ }
+
+ get keyboardStep() {
+ return this.args.keyboardStep ?? 0.05;
+ }
+
+ #progressFromClientY(clientY) {
+ if (!this.#railEl) {
+ return 0;
+ }
+ const rect = this.#railEl.getBoundingClientRect();
+ const scrollerHeight =
+ this.#scrollerEl?.getBoundingClientRect().height || SCROLLER_HEIGHT;
+ const travel = Math.max(1, rect.height - scrollerHeight);
+ const desiredScrollerCentre = clientY - this.#dragOffset;
+
+ return Math.min(
+ 1,
+ Math.max(
+ 0,
+ (desiredScrollerCentre - rect.top - scrollerHeight / 2) / travel
+ )
+ );
+ }
+
+ #isInteractiveTarget(target) {
+ return target?.closest?.(
+ "a, button, input, select, textarea, summary, [contenteditable='true'], [data-timeline-scrubber-ignore]"
+ );
+ }
+
+ #commit(progress) {
+ this.args.onCommit?.(Math.min(1, Math.max(0, progress)));
+ }
+
+ @action
+ onPointerDown(event) {
+ if (event.button !== 0 || this.#isInteractiveTarget(event.target)) {
+ return;
+ }
+
+ event.preventDefault();
+ this.dragging = true;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ if (this.#scrollerEl?.contains(event.target)) {
+ const rect = this.#scrollerEl.getBoundingClientRect();
+ this.#dragOffset = event.clientY - (rect.top + rect.height / 2);
+ } else {
+ this.#dragOffset = 0;
+ }
+ this.dragProgress = this.#progressFromClientY(event.clientY);
+ this.args.onDragStart?.();
+ this.args.onDrag?.(this.dragProgress);
+ }
+
+ @action
+ onPointerMove(event) {
+ if (!this.dragging) {
+ return;
+ }
+ this.dragProgress = this.#progressFromClientY(event.clientY);
+ this.args.onDrag?.(this.dragProgress);
+ }
+
+ @action
+ onPointerUp(event) {
+ if (!this.dragging) {
+ return;
+ }
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ const finalProgress = this.dragProgress;
+ this.#dragOffset = 0;
+ this.dragging = false;
+ this.#commit(finalProgress);
+ this.args.onDragEnd?.();
+ }
+
+ @action
+ onPointerCancel(event) {
+ if (!this.dragging) {
+ return;
+ }
+ event.currentTarget.releasePointerCapture?.(event.pointerId);
+ this.#dragOffset = 0;
+ this.dragging = false;
+ this.args.onDragEnd?.();
+ }
+
+ @action
+ onKeyDown(event) {
+ let nextProgress = null;
+
+ switch (event.key) {
+ case "ArrowUp":
+ case "ArrowLeft":
+ nextProgress = this.progress - this.keyboardStep;
+ break;
+ case "ArrowDown":
+ case "ArrowRight":
+ nextProgress = this.progress + this.keyboardStep;
+ break;
+ case "PageUp":
+ nextProgress = this.progress - this.keyboardStep * 5;
+ break;
+ case "PageDown":
+ nextProgress = this.progress + this.keyboardStep * 5;
+ break;
+ case "Home":
+ nextProgress = 0;
+ break;
+ case "End":
+ nextProgress = 1;
+ break;
+ }
+
+ if (nextProgress == null) {
+ return;
+ }
+
+ event.preventDefault();
+ this.#commit(nextProgress);
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}
+ <div
+ role="slider"
+ tabindex="0"
+ aria-orientation="vertical"
+ aria-valuemin="0"
+ aria-valuemax="1"
+ aria-valuenow={{this.progress}}
+ aria-valuetext={{@ariaValueText}}
+ aria-label={{@ariaLabel}}
+ ...attributes
+ class="timeline-scrubber timeline-scrollarea
+ {{if this.dragging 'timeline-scrubber--dragging'}}"
+ style={{this.railStyle}}
+ {{this.registerRail}}
+ {{on "pointerdown" this.onPointerDown}}
+ {{on "pointermove" this.onPointerMove}}
+ {{on "pointerup" this.onPointerUp}}
+ {{on "pointercancel" this.onPointerCancel}}
+ {{on "keydown" this.onKeyDown}}
+ >
+ <div class="timeline-scrubber__track">
+ {{yield this.progress this.dragging to="track"}}
+ </div>
+
+ <div
+ class="timeline-scrubber__scroller timeline-scroller"
+ {{this.registerScroller}}
+ >
+ <div class="timeline-scrubber__grip timeline-handle"></div>
+ <div
+ class="timeline-scrubber__scroller-content timeline-scroller-content"
+ >
+ {{yield this.progress this.dragging to="handle"}}
+ </div>
+ </div>
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/app/components/topic-timeline/container.gjs b/frontend/discourse/app/components/topic-timeline/container.gjs
index 3fa0edd8169..49ec35467b1 100644
--- a/frontend/discourse/app/components/topic-timeline/container.gjs
+++ b/frontend/discourse/app/components/topic-timeline/container.gjs
@@ -3,18 +3,19 @@ import { tracked } from "@glimmer/tracking";
import { fn } from "@ember/helper";
import { on } from "@ember/modifier";
import { action } from "@ember/object";
-import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
import PluginOutlet from "discourse/components/plugin-outlet";
import { actionDescriptionHtml } from "discourse/components/post-action-description";
+import TimelineScrubber, {
+ SCROLLER_HEIGHT,
+} from "discourse/components/timeline-scrubber";
import TopicAdminMenu from "discourse/components/topic-admin-menu";
import TopicLocalizedContentToggle from "discourse/components/topic-localized-content-toggle";
import UserTip from "discourse/components/user-tip";
import lazyHash from "discourse/helpers/lazy-hash";
import topicFeaturedLink from "discourse/helpers/topic-featured-link";
import { bind, debounce } from "discourse/lib/decorators";
-import domUtils from "discourse/lib/dom-utils";
import { headerOffset } from "discourse/lib/offset-calculator";
import TopicNotificationsButton from "discourse/select-kit/components/topic-notifications-button";
import { and, not, or } from "discourse/truth-helpers";
@@ -25,9 +26,7 @@ import dDiscourseTags from "discourse/ui-kit/helpers/d-discourse-tags";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
import BackButton from "./back-button";
-import Scroller from "./scroller";
-export const SCROLLER_HEIGHT = 50;
const DEFAULT_MIN_SCROLLAREA_HEIGHT = 170;
const DEFAULT_MAX_SCROLLAREA_HEIGHT = 300;
const LAST_READ_HEIGHT = 20;
@@ -71,16 +70,9 @@ export default class TopicTimelineScrollArea extends Component {
@tracked lastReadPercentage = null;
@tracked lastRead;
@tracked lastReadTop;
- @tracked before;
- @tracked after;
- @tracked timelineScrollareaStyle;
- @tracked dragging = false;
@tracked excerpt = "";
intersectionObserver = null;
- scrollareaElement = null;
- scrollerElement = null;
- dragOffset = null;
constructor() {
super(...arguments);
@@ -184,18 +176,6 @@ export default class TopicTimelineScrollArea extends Component {
);
}
- get style() {
- return trustHTML(`height: ${this.scrollareaHeight}px`);
- }
-
- get beforePadding() {
- return trustHTML(`height: ${this.before}px`);
- }
-
- get afterPadding() {
- return trustHTML(`height: ${this.after}px`);
- }
-
get showDockedButton() {
return this.site.desktopView && this.hasBackPosition && !this.showButton;
}
@@ -264,16 +244,16 @@ export default class TopicTimelineScrollArea extends Component {
);
}
+ get keyboardStep() {
+ return this.total ? 1 / this.total : 0.05;
+ }
+
get lastReadHeight() {
return Math.round(this.lastReadPercentage * this.scrollareaHeight);
}
@bind
calculatePosition() {
- this.timelineScrollareaStyle = trustHTML(
- `height: ${this.scrollareaHeight}px`
- );
-
const topic = this.args.model;
const postStream = topic.postStream;
this.total = postStream.filteredPostsCount;
@@ -282,30 +262,10 @@ export default class TopicTimelineScrollArea extends Component {
this.clamp(Math.floor(this.total * this.percentage), 0, this.total) + 1;
this.current = this.clamp(this.scrollPosition, 1, this.total);
- const daysAgo = postStream.closestDaysAgoFor(this.current);
-
- let date;
- if (daysAgo === undefined) {
- const post = postStream.posts.find(
- (p) => p.id === postStream.stream[this.current]
- );
-
- if (post) {
- date = new Date(post.created_at);
- }
- } else if (daysAgo !== null) {
- date = new Date();
- date.setDate(date.getDate() - daysAgo || 0);
- } else {
- date = null;
- }
-
- this.date = date;
+ this.date = this.#dateForPostIndex(this.current);
- const lastReadNumber = topic.last_read_post_number;
const lastReadId = topic.last_read_post_id;
-
- if (lastReadId && lastReadNumber) {
+ if (lastReadId && topic.last_read_post_number) {
const idx = postStream.stream.indexOf(lastReadId) + 1;
this.lastRead = idx;
this.lastReadPercentage = this._percentFor(topic, idx);
@@ -316,9 +276,6 @@ export default class TopicTimelineScrollArea extends Component {
this.updateScrollPosition(this.current);
}
- this.before = this.scrollareaRemaining() * this.percentage;
- this.after = this.scrollareaHeight - this.before - SCROLLER_HEIGHT;
-
if (this.percentage === null) {
return;
}
@@ -327,12 +284,31 @@ export default class TopicTimelineScrollArea extends Component {
this.lastReadTop = Math.round(
this.lastReadPercentage * this.scrollareaHeight
);
+ const scrollerTop =
+ this.percentage * (this.scrollareaHeight - SCROLLER_HEIGHT);
this.showButton =
- this.before + SCROLLER_HEIGHT - 5 < this.lastReadTop ||
- this.before > this.lastReadTop + 25;
+ scrollerTop + SCROLLER_HEIGHT - 5 < this.lastReadTop ||
+ scrollerTop > this.lastReadTop + 25;
}
}
+ #dateForPostIndex(index) {
+ const postStream = this.args.model.postStream;
+ const daysAgo = postStream.closestDaysAgoFor(index);
+ if (daysAgo === undefined) {
+ const post = postStream.posts.find(
+ (p) => p.id === postStream.stream[index]
+ );
+ return post ? new Date(post.created_at) : null;
+ }
+ if (daysAgo !== null) {
+ const date = new Date();
+ date.setDate(date.getDate() - daysAgo || 0);
+ return date;
+ }
+ return null;
+ }
+
@debounce(50)
updateScrollPosition(scrollPosition) {
// only ran on mobile
@@ -367,50 +343,8 @@ export default class TopicTimelineScrollArea extends Component {
}
@action
- updatePercentage(e) {
- e.preventDefault();
-
- const currentCursorY = e.pageY || e.touches[0].pageY;
-
- const desiredScrollerCentre = currentCursorY - this.dragOffset;
-
- const areaTop = domUtils.offset(this.scrollareaElement).top;
- const areaHeight = this.scrollareaElement.offsetHeight;
- const scrollerHeight = this.scrollerElement.offsetHeight;
-
- // The range of possible positions for the centre of the scroller
- const scrollableTop = areaTop + scrollerHeight / 2;
- const scrollableHeight = areaHeight - scrollerHeight;
-
- this.percentage = this.clamp(
- parseFloat(desiredScrollerCentre - scrollableTop) / scrollableHeight
- );
- this.commit();
- }
-
- @bind
- didStartDrag(event) {
- const y = event.pageY || event.touches[0].pageY;
-
- const scrollerCentre =
- domUtils.offset(this.scrollerElement).top +
- this.scrollerElement.offsetHeight / 2;
-
- this.dragOffset = y - scrollerCentre;
- this.dragging = true;
- }
-
- @bind
- dragMove(event) {
- event.stopPropagation();
- event.preventDefault();
- this.updatePercentage(event);
- }
-
- @bind
- didEndDrag() {
- this.dragging = false;
- this.dragOffset = null;
+ handleCommit(progress) {
+ this.percentage = this.clamp(progress);
this.commit();
}
@@ -427,6 +361,18 @@ export default class TopicTimelineScrollArea extends Component {
this.args.jumpToIndex(this.lastRead);
}
+ @action
+ jumpToStart(event) {
+ event.preventDefault();
+ this.handleCommit(0);
+ }
+
+ @action
+ jumpToEnd(event) {
+ event.preventDefault();
+ this.handleCommit(1);
+ }
+
dockCheck() {
const timeline = document.querySelector(".timeline-container");
const timelineHeight = (timeline && timeline.offsetHeight) || 400;
@@ -466,12 +412,10 @@ export default class TopicTimelineScrollArea extends Component {
commit() {
this.calculatePosition();
- if (!this.dragging) {
- if (this.current === this.scrollPosition) {
- this.args.jumpToIndex(this.current);
- } else {
- this.args.jumpEnd();
- }
+ if (this.current === this.scrollPosition) {
+ this.args.jumpToIndex(this.current);
+ } else {
+ this.args.jumpEnd();
}
}
@@ -479,10 +423,6 @@ export default class TopicTimelineScrollArea extends Component {
return Math.max(Math.min(p, max), min);
}
- scrollareaRemaining() {
- return this.scrollareaHeight - SCROLLER_HEIGHT;
- }
-
_percentFor(topic, postIndex) {
const total = topic.postStream.filteredPostsCount;
switch (postIndex) {
@@ -499,13 +439,23 @@ export default class TopicTimelineScrollArea extends Component {
}
@action
- registerScrollarea(element) {
- this.scrollareaElement = element;
+ currentAt(progress) {
+ const total = this.total;
+ if (!total) {
+ return 1;
+ }
+ const pos = this.clamp(Math.floor(total * progress), 0, total) + 1;
+ return this.clamp(pos, 1, total);
}
@action
- registerScroller(element) {
- this.scrollerElement = element;
+ dateAt(progress) {
+ return this.#dateForPostIndex(this.currentAt(progress));
+ }
+
+ @action
+ formatTimelineDate(date) {
+ return timelineDate(date);
}
<template>
@@ -591,10 +541,10 @@ export default class TopicTimelineScrollArea extends Component {
<div class="timeline-scrollarea-wrapper">
<div class="timeline-date-wrapper">
<a
- {{on "click" this.updatePercentage}}
href={{@model.firstPostUrl}}
title={{i18n "topic_entrance.jump_top_button_title"}}
class="start-date"
+ {{on "click" this.jumpToStart}}
>
<span>
{{this.startDate}}
@@ -602,51 +552,54 @@ export default class TopicTimelineScrollArea extends Component {
</a>
</div>
- <div
- class="timeline-scrollarea"
- style={{this.timelineScrollareaStyle}}
- {{didInsert this.registerScrollarea}}
+ <TimelineScrubber
+ class="topic-timeline-scrubber"
+ @progress={{this.percentage}}
+ @height={{this.scrollareaHeight}}
+ @ariaLabel={{i18n "topic.progress.title"}}
+ @ariaValueText={{i18n
+ "topic.timeline.replies_short"
+ current=this.current
+ total=this.total
+ }}
+ @keyboardStep={{this.keyboardStep}}
+ @onCommit={{this.handleCommit}}
>
- {{! eslint-disable ember/template-no-invalid-interactive }}
- <div
- {{on "click" this.updatePercentage}}
- style={{this.beforePadding}}
- class="timeline-padding"
- ></div>
-
- <Scroller
- @current={{this.current}}
- @total={{this.total}}
- @onGoBack={{this.onGoBack}}
- @fullscreen={{@fullscreen}}
- @showDockedButton={{this.showDockedButton}}
- @date={{this.date}}
- @didStartDrag={{this.didStartDrag}}
- @dragMove={{this.dragMove}}
- @didEndDrag={{this.didEndDrag}}
- {{didInsert this.registerScroller}}
- />
-
- {{! eslint-disable ember/template-no-invalid-interactive }}
- <div
- {{on "click" this.updatePercentage}}
- style={{this.afterPadding}}
- class="timeline-padding"
- ></div>
-
- {{#if (and this.hasBackPosition this.showButton)}}
- <div class="timeline-last-read" style={{this.lastReadStyle}}>
- {{dIcon "minus" class="progress"}}
- <BackButton @onGoBack={{this.goBack}} />
+ <:track>
+ {{#if (and this.hasBackPosition this.showButton)}}
+ <div class="timeline-last-read" style={{this.lastReadStyle}}>
+ {{dIcon "minus" class="progress"}}
+ <BackButton @onGoBack={{this.goBack}} />
+ </div>
+ {{/if}}
+ </:track>
+ <:handle as |progress dragging|>
+ <div class="timeline-replies">
+ {{i18n
+ "topic.timeline.replies_short"
+ current=(this.currentAt progress)
+ total=this.total
+ }}
</div>
- {{/if}}
- </div>
+ {{#let (this.dateAt progress) as |scrubDate|}}
+ {{#if scrubDate}}
+ <div class="timeline-ago">
+ {{this.formatTimelineDate scrubDate}}
+ </div>
+ {{/if}}
+ {{/let}}
+ {{! Hide while dragging so it doesn't fight the moving handle. }}
+ {{#if (and this.showDockedButton (not dragging))}}
+ <BackButton @onGoBack={{this.goBack}} />
+ {{/if}}
+ </:handle>
+ </TimelineScrubber>
<div class="timeline-date-wrapper">
<a
- {{on "click" this.updatePercentage}}
href={{@model.lastPostUrl}}
class="now-date"
+ {{on "click" this.jumpToEnd}}
>
<span>
{{dAgeWithTooltip this.nowDate this.nowDateOptions}}
diff --git a/frontend/discourse/app/components/topic-timeline/scroller.gjs b/frontend/discourse/app/components/topic-timeline/scroller.gjs
deleted file mode 100644
index 509c454c6df..00000000000
--- a/frontend/discourse/app/components/topic-timeline/scroller.gjs
+++ /dev/null
@@ -1,70 +0,0 @@
-import Component from "@glimmer/component";
-import { trustHTML } from "@ember/template";
-import {
- SCROLLER_HEIGHT,
- timelineDate,
-} from "discourse/components/topic-timeline/container";
-import { and, not } from "discourse/truth-helpers";
-import dDraggable from "discourse/ui-kit/modifiers/d-draggable";
-import { i18n } from "discourse-i18n";
-import BackButton from "./back-button";
-
-export default class TopicTimelineScroller extends Component {
- style = trustHTML(`height: ${SCROLLER_HEIGHT}px`);
-
- get repliesShort() {
- return i18n(`topic.timeline.replies_short`, {
- current: this.args.current,
- total: this.args.total,
- });
- }
-
- get timelineAgo() {
- return timelineDate(this.args.date);
- }
-
- <template>
- <div
- {{dDraggable
- didStartDrag=@didStartDrag
- didEndDrag=@didEndDrag
- dragMove=@dragMove
- }}
- style={{this.style}}
- class="timeline-scroller"
- ...attributes
- >
- {{#if @fullscreen}}
- <div class="timeline-scroller-content">
- <div class="timeline-replies">
- {{this.repliesShort}}
- </div>
- {{#if @date}}
- <div class="timeline-ago">
- {{this.timelineAgo}}
- </div>
- {{/if}}
- {{#if (and @showDockedButton (not @dragging))}}
- <BackButton @onGoBack={{@onGoBack}} />
- {{/if}}
- </div>
- <div class="timeline-handle"></div>
- {{else}}
- <div class="timeline-handle"></div>
- <div class="timeline-scroller-content">
- <div class="timeline-replies">
- {{this.repliesShort}}
- </div>
- {{#if @date}}
- <div class="timeline-ago">
- {{this.timelineAgo}}
- </div>
- {{/if}}
- {{#if (and @showDockedButton (not @dragging))}}
- <BackButton @onGoBack={{@onGoBack}} />
- {{/if}}
- </div>
- {{/if}}
- </div>
- </template>
-}
diff --git a/frontend/discourse/app/controllers/nested.js b/frontend/discourse/app/controllers/nested.js
index b006330fbd2..24a8c4edd54 100644
--- a/frontend/discourse/app/controllers/nested.js
+++ b/frontend/discourse/app/controllers/nested.js
@@ -18,8 +18,10 @@ export default class NestedController extends Controller {
@service store;
@service dialog;
@service currentUser;
+ @service header;
@service messageBus;
@service modal;
+ @service nestedRootElements;
@service nestedViewCache;
@service router;
@service site;
@@ -28,8 +30,11 @@ export default class NestedController extends Controller {
@tracked opPost;
@tracked rootNodes = [];
@tracked page = 0;
+ @tracked firstLoadedPage = 0;
@tracked hasMoreRoots = false;
@tracked loadingMore = false;
+ @tracked loadingPreviousRoots = false;
+ @tracked loadingNextRoots = false;
@tracked sort;
@tracked messageBusLastId;
@tracked postNumber;
@@ -42,6 +47,7 @@ export default class NestedController extends Controller {
@tracked newRootPostIds = [];
@tracked editingTopic = false;
@tracked pinnedPostIds = [];
+ @tracked rootSummary = null;
// Persisted in the URL across in-topic navigation by design — once a
// user lands via a consolidated reply notification, browsing within
// the topic keeps the collapsed view, and the URL is shareable in that
@@ -99,6 +105,168 @@ export default class NestedController extends Controller {
return this.#topicController.minimumRequiredTags;
}
+ get hasMoreRootsBefore() {
+ return this.firstLoadedPage > 0;
+ }
+
+ @action
+ async jumpToRootPage(
+ targetPage,
+ targetPostNumber = null,
+ targetRootOffset = 0
+ ) {
+ if (this.loadingMore) {
+ return;
+ }
+ if (
+ targetPage >= this.firstLoadedPage &&
+ targetPage <= this.page &&
+ this.rootNodes.length > 0
+ ) {
+ const inWindow =
+ targetPostNumber && this.#scrollToLoadedRoot(targetPostNumber);
+ if (!inWindow) {
+ this.#scrollToLoadedRootPage(targetPage, targetRootOffset);
+ }
+ return;
+ }
+
+ this.loadingMore = true;
+ try {
+ const data = await ajax(
+ `/n/${this.topic.slug}/${this.topic.id}.json?page=${targetPage}&sort=${this.sort}`
+ );
+
+ const newNodes = (data.roots || []).map((root) =>
+ this.#processNode(root)
+ );
+
+ const scrollTargetPostNumber =
+ targetPostNumber ??
+ newNodes[targetRootOffset]?.post?.post_number ??
+ newNodes[0]?.post?.post_number ??
+ null;
+
+ this.rootNodes = newNodes;
+ this.firstLoadedPage = data.page;
+ this.page = data.page;
+ this.hasMoreRoots = data.has_more_roots || false;
+ this.rootSummary = data.root_summary ?? this.rootSummary;
+ this.#assignSuggestedAndRelated(data);
+
+ if (scrollTargetPostNumber != null) {
+ const element = await this.nestedRootElements.waitForElement(
+ scrollTargetPostNumber
+ );
+ this.#scrollToRootWrapper(element);
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+
+ #scrollToLoadedRootPage(targetPage, targetRootOffset = 0) {
+ const ordered = this.nestedRootElements.elementsInOrder();
+ if (ordered.length === 0) {
+ return;
+ }
+
+ const pageSize = this.rootSummary?.page_size;
+ if (!pageSize) {
+ this.#scrollToRootWrapper(ordered[0].el);
+ return;
+ }
+
+ let targetIndex =
+ (targetPage - this.firstLoadedPage) * pageSize + targetRootOffset;
+ if (this.firstLoadedPage === 0 && targetPage > 0) {
+ const pinnedIds = new Set(this.pinnedPostIds);
+ targetIndex += this.rootNodes.filter((node) =>
+ pinnedIds.has(node.post.id)
+ ).length;
+ }
+
+ const clamped = Math.max(0, Math.min(targetIndex, ordered.length - 1));
+ this.#scrollToRootWrapper(ordered[clamped].el);
+ }
+
+ @action
+ async loadPreviousRoots() {
+ if (this.loadingMore || !this.hasMoreRootsBefore) {
+ return;
+ }
+
+ // Preserving the first visible root's viewport top keeps the user's
+ // reading position stationary across the prepend.
+ const ordered = this.nestedRootElements.elementsInOrder();
+ const anchor = ordered[0] ?? null;
+ const anchorPostNumber = anchor?.postNumber ?? null;
+ const anchorTopBefore = anchor?.el.getBoundingClientRect().top ?? null;
+
+ this.loadingMore = true;
+ this.loadingPreviousRoots = true;
+ try {
+ const targetPage = this.firstLoadedPage - 1;
+ const data = await ajax(
+ `/n/${this.topic.slug}/${this.topic.id}.json?page=${targetPage}&sort=${this.sort}`
+ );
+
+ const newNodes = (data.roots || []).map((root) =>
+ this.#processNode(root)
+ );
+
+ this.rootNodes = [...newNodes, ...this.rootNodes];
+ this.firstLoadedPage = data.page;
+ this.rootSummary = data.root_summary ?? this.rootSummary;
+ this.#assignSuggestedAndRelated(data);
+
+ const newFirstPostNumber = newNodes[0]?.post?.post_number;
+ if (newFirstPostNumber != null) {
+ await this.nestedRootElements.waitForElement(newFirstPostNumber);
+ }
+
+ if (anchorPostNumber != null && anchorTopBefore != null) {
+ const liveAnchor = this.nestedRootElements.getElement(anchorPostNumber);
+ if (liveAnchor) {
+ const anchorTopAfter = liveAnchor.getBoundingClientRect().top;
+ const delta = anchorTopAfter - anchorTopBefore;
+ if (delta !== 0) {
+ window.scrollBy({ top: delta, behavior: "auto" });
+ }
+ }
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingPreviousRoots = false;
+ this.loadingMore = false;
+ }
+ }
+
+ #scrollToLoadedRoot(postNumber) {
+ if (!postNumber) {
+ return false;
+ }
+ const element = this.nestedRootElements.getElement(postNumber);
+ if (!element) {
+ return false;
+ }
+ this.#scrollToRootWrapper(element);
+ return true;
+ }
+
+ #scrollToRootWrapper(wrapper) {
+ if (!wrapper) {
+ return;
+ }
+ const headerOffset = this.header.headerOffset ?? 0;
+ const top =
+ wrapper.getBoundingClientRect().top + window.scrollY - headerOffset - 8;
+ window.scrollTo({ top, behavior: "auto" });
+ }
+
@action
async loadMoreRoots() {
if (this.loadingMore || !this.hasMoreRoots) {
@@ -106,6 +274,7 @@ export default class NestedController extends Controller {
}
this.loadingMore = true;
+ this.loadingNextRoots = true;
try {
const nextPage = this.page + 1;
const data = await ajax(
@@ -119,10 +288,12 @@ export default class NestedController extends Controller {
this.rootNodes = [...this.rootNodes, ...newNodes];
this.page = data.page;
this.hasMoreRoots = data.has_more_roots || false;
+ this.rootSummary = data.root_summary ?? this.rootSummary;
this.#assignSuggestedAndRelated(data);
} catch (e) {
popupAjaxError(e);
} finally {
+ this.loadingNextRoots = false;
this.loadingMore = false;
}
}
@@ -229,9 +400,14 @@ export default class NestedController extends Controller {
}
);
+ const wasPinned = this.pinnedPostIds.includes(post.id);
this.pinnedPostIds = result.pinned_post_ids || [];
+ const isPinned = this.pinnedPostIds.includes(post.id);
+ if (wasPinned !== isPinned) {
+ this.#updateRootSummary({ pinnedDelta: isPinned ? 1 : -1 });
+ }
- if (this.pinnedPostIds.includes(post.id)) {
+ if (isPinned) {
// Move newly pinned post to front of rootNodes
const idx = this.rootNodes.findIndex((n) => n.post.id === post.id);
if (idx > 0) {
@@ -512,6 +688,7 @@ export default class NestedController extends Controller {
if (isRoot) {
if (data.user_id === this.currentUser?.id) {
+ this.#updateRootSummary({ totalDelta: 1 });
this.rootNodes = [{ post, children: [] }, ...this.rootNodes];
} else {
this.newRootPostIds = [...this.newRootPostIds, data.id];
@@ -587,8 +764,10 @@ export default class NestedController extends Controller {
}
#markPostDeletedLocally(postId) {
+ let deletedPost = null;
for (const post of this.postRegistry.values()) {
if (post.id === postId) {
+ deletedPost = post;
post.set("deleted_at", new Date());
post.set("deleted_post_placeholder", true);
if (!this.currentUser?.staff) {
@@ -597,6 +776,16 @@ export default class NestedController extends Controller {
break;
}
}
+
+ if (
+ deletedPost &&
+ this.pinnedPostIds.includes(postId) &&
+ (!deletedPost.reply_to_post_number ||
+ deletedPost.reply_to_post_number === 1)
+ ) {
+ this.pinnedPostIds = this.pinnedPostIds.filter((id) => id !== postId);
+ this.#updateRootSummary({ pinnedDelta: -1 });
+ }
}
@action
@@ -624,6 +813,7 @@ export default class NestedController extends Controller {
}
if (newNodes.length > 0) {
+ this.#updateRootSummary({ totalDelta: newNodes.length });
this.rootNodes = [...newNodes, ...this.rootNodes];
}
}
@@ -645,6 +835,31 @@ export default class NestedController extends Controller {
return processNode(this.store, this.topic, nodeData);
}
+ #updateRootSummary({ totalDelta = 0, pinnedDelta = 0 } = {}) {
+ if (!this.rootSummary) {
+ return;
+ }
+
+ const total = Math.max(0, (this.rootSummary.total ?? 0) + totalDelta);
+ const pinnedCount = Math.max(
+ 0,
+ Math.min(total, (this.rootSummary.pinned_count ?? 0) + pinnedDelta)
+ );
+ const pageSize = this.rootSummary.page_size;
+ const unpinnedTotal = Math.max(0, total - pinnedCount);
+ const pageCount =
+ total === 0 || !pageSize
+ ? 0
+ : Math.max(1, Math.ceil(unpinnedTotal / pageSize));
+
+ this.rootSummary = {
+ ...this.rootSummary,
+ total,
+ page_count: pageCount,
+ pinned_count: pinnedCount,
+ };
+ }
+
#assignSuggestedAndRelated(data) {
if (!this.topic) {
return;
diff --git a/frontend/discourse/app/routes/nested.js b/frontend/discourse/app/routes/nested.js
index b8dc4080765..0c9582e0827 100644
--- a/frontend/discourse/app/routes/nested.js
+++ b/frontend/discourse/app/routes/nested.js
@@ -1,3 +1,4 @@
+import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
import Route from "@ember/routing/route";
import { service } from "@ember/service";
@@ -10,7 +11,10 @@ import processNode from "../lib/process-node";
export default class NestedRoute extends Route {
@service composer;
+ @service header;
+ @service nestedRootElements;
@service nestedViewCache;
+ @service router;
@service screenTrack;
@service site;
@service siteSettings;
@@ -106,6 +110,8 @@ export default class NestedRoute extends Route {
this.screenTrack.start(model.topic.id, controller);
+ this.header.enterTopic(model.topic, model.firstLoadedPage === 0);
+
if (!isEmpty(model.topic.draft) && !EmbedMode.enabled) {
this.composer.open({
draft: Draft.getLocal(model.topic.draft_key, model.topic.draft),
@@ -117,6 +123,15 @@ export default class NestedRoute extends Route {
}
}
+ @action
+ willTransition(transition) {
+ transition.followRedirects().finally(() => {
+ if (!this.router.currentRouteName?.startsWith("nested")) {
+ this.header.clearTopic();
+ }
+ });
+ }
+
deactivate() {
super.deactivate(...arguments);
@@ -124,6 +139,7 @@ export default class NestedRoute extends Route {
this._saveToCache(controller);
controller.unsubscribe();
+ this.nestedRootElements.clear();
this.screenTrack.stop();
}
@@ -148,6 +164,8 @@ export default class NestedRoute extends Route {
sort: controller.sort,
messageBusLastId: controller.messageBusLastId,
pinnedPostIds: controller.pinnedPostIds,
+ rootSummary: controller.rootSummary,
+ firstLoadedPage: controller.firstLoadedPage,
postNumber: controller.postNumber,
contextMode: controller.contextMode,
contextChain: controller.contextChain,
@@ -228,6 +246,8 @@ export default class NestedRoute extends Route {
sort: data.sort || this.siteSettings.nested_replies_default_sort || "top",
messageBusLastId: data.message_bus_last_id,
pinnedPostIds: data.pinned_post_ids || [],
+ rootSummary: data.root_summary || null,
+ firstLoadedPage: data.page || 0,
postNumber: params.post_number ? Number(params.post_number) : null,
contextMode: false,
contextChain: null,
@@ -288,6 +308,8 @@ export default class NestedRoute extends Route {
opPost,
sort,
pinnedPostIds: [],
+ rootSummary: null,
+ firstLoadedPage: 0,
messageBusLastId: data.message_bus_last_id,
postNumber: Number(params.post_number),
contextMode: true,
diff --git a/frontend/discourse/app/services/nested-root-elements.js b/frontend/discourse/app/services/nested-root-elements.js
new file mode 100644
index 00000000000..5f50768738b
--- /dev/null
+++ b/frontend/discourse/app/services/nested-root-elements.js
@@ -0,0 +1,109 @@
+import Service from "@ember/service";
+
+// Registry of rendered depth-0 root post elements (post_number → element).
+// Populated by <NestedPost> at depth 0 on mount, cleared on teardown.
+export default class NestedRootElementsService extends Service {
+ #elements = new Map();
+ #postNumbers = new WeakMap();
+ #pendingResolvers = new Map();
+ #subscribers = new Set();
+
+ register(postNumber, element) {
+ if (postNumber == null || !element) {
+ return;
+ }
+ this.#elements.set(postNumber, element);
+ this.#postNumbers.set(element, postNumber);
+
+ const resolvers = this.#pendingResolvers.get(postNumber);
+ if (resolvers) {
+ this.#pendingResolvers.delete(postNumber);
+ for (const resolve of resolvers) {
+ resolve(element);
+ }
+ }
+
+ this.#notify("register", postNumber, element);
+ }
+
+ unregister(postNumber) {
+ if (postNumber == null) {
+ return;
+ }
+ const el = this.#elements.get(postNumber);
+ this.#elements.delete(postNumber);
+ if (el) {
+ this.#postNumbers.delete(el);
+ this.#notify("unregister", postNumber, el);
+ }
+ }
+
+ clear() {
+ for (const [postNumber, el] of this.#elements) {
+ this.#postNumbers.delete(el);
+ this.#notify("unregister", postNumber, el);
+ }
+ this.#elements.clear();
+ for (const resolvers of this.#pendingResolvers.values()) {
+ for (const resolve of resolvers) {
+ resolve(null);
+ }
+ }
+ this.#pendingResolvers.clear();
+ }
+
+ getElement(postNumber) {
+ const el = this.#elements.get(postNumber);
+ return el?.isConnected ? el : null;
+ }
+
+ // Sorted by viewport top so prepended pages (loadPreviousRoots) report correctly.
+ elementsInOrder() {
+ const connected = [];
+ for (const [postNumber, el] of this.#elements) {
+ if (el.isConnected) {
+ connected.push({ postNumber, el, top: el.getBoundingClientRect().top });
+ }
+ }
+ connected.sort((a, b) => a.top - b.top);
+ return connected;
+ }
+
+ firstElement() {
+ return this.elementsInOrder()[0]?.el ?? null;
+ }
+
+ waitForElement(postNumber) {
+ const existing = this.getElement(postNumber);
+ if (existing) {
+ return Promise.resolve(existing);
+ }
+ return new Promise((resolve) => {
+ const resolvers = this.#pendingResolvers.get(postNumber) ?? [];
+ resolvers.push(resolve);
+ this.#pendingResolvers.set(postNumber, resolvers);
+ });
+ }
+
+ elements() {
+ return this.#elements.values();
+ }
+
+ postNumberFor(element) {
+ return this.#postNumbers.get(element);
+ }
+
+ // Subscribe to register/unregister events. Returns an unsubscribe function.
+ // Used by NestedTopicTimeline to keep its IntersectionObserver in sync as
+ // roots are paginated in/out without polling the registry every scroll frame.
+ subscribe(fn) {
+ this.#subscribers.add(fn);
+ return () => this.#subscribers.delete(fn);
+ }
+
+ #notify(type, postNumber, element) {
+ for (const fn of this.#subscribers) {
+ fn(type, postNumber, element);
+ }
+ }
+}
diff --git a/frontend/discourse/app/templates/nested.gjs b/frontend/discourse/app/templates/nested.gjs
index a77263e5de2..043eebd6fb0 100644
--- a/frontend/discourse/app/templates/nested.gjs
+++ b/frontend/discourse/app/templates/nested.gjs
@@ -1,6 +1,8 @@
import Nested from "discourse/components/nested";
import NestedContextView from "discourse/components/nested/context-view";
+import NestedTopicTimeline from "discourse/components/nested/topic-timeline";
import PostTextSelection from "discourse/components/post-text-selection";
+import { and, not } from "discourse/truth-helpers";
export default <template>
<PostTextSelection
@@ -11,97 +13,120 @@ export default <template>
@topic={{@controller.topic}}
/>
- {{#if @controller.contextMode}}
- <NestedContextView
- @topic={{@controller.topic}}
- @opPost={{@controller.opPost}}
- @contextChain={{@controller.contextChain}}
- @targetPostNumber={{@controller.targetPostNumber}}
- @contextNoAncestors={{@controller.contextNoAncestors}}
- @ancestorsTruncated={{@controller.ancestorsTruncated}}
- @sort={{@controller.sort}}
- @changeSort={{@controller.changeSort}}
- @viewFullThread={{@controller.viewFullThread}}
- @viewParentContext={{@controller.viewParentContext}}
- @replyToPost={{@controller.replyToPost}}
- @editPost={{@controller.editPost}}
- @deletePost={{@controller.deletePost}}
- @recoverPost={{@controller.recoverPost}}
- @showFlags={{@controller.showFlags}}
- @showHistory={{@controller.showHistory}}
- @changeNotice={{@controller.changeNotice}}
- @changePostOwner={{@controller.changePostOwner}}
- @grantBadge={{@controller.grantBadge}}
- @lockPost={{@controller.lockPost}}
- @unlockPost={{@controller.unlockPost}}
- @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
- @rebakePost={{@controller.rebakePost}}
- @showPagePublish={{@controller.showPagePublish}}
- @togglePostType={{@controller.togglePostType}}
- @toggleWiki={{@controller.toggleWiki}}
- @unhidePost={{@controller.unhidePost}}
- @editingTopic={{@controller.editingTopic}}
- @startEditingTopic={{@controller.startEditingTopic}}
- @cancelEditingTopic={{@controller.cancelEditingTopic}}
- @finishedEditingTopic={{@controller.finishedEditingTopic}}
- @showCategoryChooser={{@controller.showCategoryChooser}}
- @canEditTags={{@controller.canEditTags}}
- @buffered={{@controller.buffered}}
- @topicCategoryChanged={{@controller.topicCategoryChanged}}
- @topicTagsChanged={{@controller.topicTagsChanged}}
- @minimumRequiredTags={{@controller.minimumRequiredTags}}
- @expansionState={{@controller.expansionState}}
- @fetchedChildrenCache={{@controller.fetchedChildrenCache}}
- @scrollAnchor={{@controller.scrollAnchor}}
- @showActivityLog={{@controller.showActivityLog}}
- @collapseReplies={{@controller.collapseReplies}}
- />
- {{else}}
- <Nested
- @topic={{@controller.topic}}
- @opPost={{@controller.opPost}}
- @rootNodes={{@controller.rootNodes}}
- @hasMoreRoots={{@controller.hasMoreRoots}}
- @loadingMore={{@controller.loadingMore}}
- @loadMoreRoots={{@controller.loadMoreRoots}}
- @sort={{@controller.sort}}
- @changeSort={{@controller.changeSort}}
- @replyToPost={{@controller.replyToPost}}
- @editPost={{@controller.editPost}}
- @deletePost={{@controller.deletePost}}
- @recoverPost={{@controller.recoverPost}}
- @showFlags={{@controller.showFlags}}
- @showHistory={{@controller.showHistory}}
- @changeNotice={{@controller.changeNotice}}
- @changePostOwner={{@controller.changePostOwner}}
- @grantBadge={{@controller.grantBadge}}
- @lockPost={{@controller.lockPost}}
- @unlockPost={{@controller.unlockPost}}
- @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
- @rebakePost={{@controller.rebakePost}}
- @showPagePublish={{@controller.showPagePublish}}
- @togglePostType={{@controller.togglePostType}}
- @toggleWiki={{@controller.toggleWiki}}
- @unhidePost={{@controller.unhidePost}}
- @postNumber={{@controller.postNumber}}
- @pinnedPostIds={{@controller.pinnedPostIds}}
- @newRootPostCount={{@controller.newRootPostIds.length}}
- @loadNewRoots={{@controller.loadNewRoots}}
- @editingTopic={{@controller.editingTopic}}
- @startEditingTopic={{@controller.startEditingTopic}}
- @cancelEditingTopic={{@controller.cancelEditingTopic}}
- @finishedEditingTopic={{@controller.finishedEditingTopic}}
- @showCategoryChooser={{@controller.showCategoryChooser}}
- @canEditTags={{@controller.canEditTags}}
- @buffered={{@controller.buffered}}
- @topicCategoryChanged={{@controller.topicCategoryChanged}}
- @topicTagsChanged={{@controller.topicTagsChanged}}
- @minimumRequiredTags={{@controller.minimumRequiredTags}}
- @expansionState={{@controller.expansionState}}
- @fetchedChildrenCache={{@controller.fetchedChildrenCache}}
- @scrollAnchor={{@controller.scrollAnchor}}
- @showActivityLog={{@controller.showActivityLog}}
- @collapseReplies={{@controller.collapseReplies}}
- />
- {{/if}}
+ <div class="nested-topic-layout">
+ <div class="nested-topic-layout__content">
+ {{#if @controller.contextMode}}
+ <NestedContextView
+ @topic={{@controller.topic}}
+ @opPost={{@controller.opPost}}
+ @contextChain={{@controller.contextChain}}
+ @targetPostNumber={{@controller.targetPostNumber}}
+ @contextNoAncestors={{@controller.contextNoAncestors}}
+ @ancestorsTruncated={{@controller.ancestorsTruncated}}
+ @sort={{@controller.sort}}
+ @changeSort={{@controller.changeSort}}
+ @viewFullThread={{@controller.viewFullThread}}
+ @viewParentContext={{@controller.viewParentContext}}
+ @replyToPost={{@controller.replyToPost}}
+ @editPost={{@controller.editPost}}
+ @deletePost={{@controller.deletePost}}
+ @recoverPost={{@controller.recoverPost}}
+ @showFlags={{@controller.showFlags}}
+ @showHistory={{@controller.showHistory}}
+ @changeNotice={{@controller.changeNotice}}
+ @changePostOwner={{@controller.changePostOwner}}
+ @grantBadge={{@controller.grantBadge}}
+ @lockPost={{@controller.lockPost}}
+ @unlockPost={{@controller.unlockPost}}
+ @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
+ @rebakePost={{@controller.rebakePost}}
+ @showPagePublish={{@controller.showPagePublish}}
+ @togglePostType={{@controller.togglePostType}}
+ @toggleWiki={{@controller.toggleWiki}}
+ @unhidePost={{@controller.unhidePost}}
+ @editingTopic={{@controller.editingTopic}}
+ @startEditingTopic={{@controller.startEditingTopic}}
+ @cancelEditingTopic={{@controller.cancelEditingTopic}}
+ @finishedEditingTopic={{@controller.finishedEditingTopic}}
+ @showCategoryChooser={{@controller.showCategoryChooser}}
+ @canEditTags={{@controller.canEditTags}}
+ @buffered={{@controller.buffered}}
+ @topicCategoryChanged={{@controller.topicCategoryChanged}}
+ @topicTagsChanged={{@controller.topicTagsChanged}}
+ @minimumRequiredTags={{@controller.minimumRequiredTags}}
+ @expansionState={{@controller.expansionState}}
+ @fetchedChildrenCache={{@controller.fetchedChildrenCache}}
+ @scrollAnchor={{@controller.scrollAnchor}}
+ @showActivityLog={{@controller.showActivityLog}}
+ @collapseReplies={{@controller.collapseReplies}}
+ />
+ {{else}}
+ <Nested
+ @topic={{@controller.topic}}
+ @opPost={{@controller.opPost}}
+ @rootNodes={{@controller.rootNodes}}
+ @hasMoreRoots={{@controller.hasMoreRoots}}
+ @loadingMore={{@controller.loadingMore}}
+ @loadingPreviousRoots={{@controller.loadingPreviousRoots}}
+ @loadingNextRoots={{@controller.loadingNextRoots}}
+ @loadMoreRoots={{@controller.loadMoreRoots}}
+ @sort={{@controller.sort}}
+ @changeSort={{@controller.changeSort}}
+ @replyToPost={{@controller.replyToPost}}
+ @editPost={{@controller.editPost}}
+ @deletePost={{@controller.deletePost}}
+ @recoverPost={{@controller.recoverPost}}
+ @showFlags={{@controller.showFlags}}
+ @showHistory={{@controller.showHistory}}
+ @changeNotice={{@controller.changeNotice}}
+ @changePostOwner={{@controller.changePostOwner}}
+ @grantBadge={{@controller.grantBadge}}
+ @lockPost={{@controller.lockPost}}
+ @unlockPost={{@controller.unlockPost}}
+ @permanentlyDeletePost={{@controller.permanentlyDeletePost}}
+ @rebakePost={{@controller.rebakePost}}
+ @showPagePublish={{@controller.showPagePublish}}
+ @togglePostType={{@controller.togglePostType}}
+ @toggleWiki={{@controller.toggleWiki}}
+ @unhidePost={{@controller.unhidePost}}
+ @postNumber={{@controller.postNumber}}
+ @pinnedPostIds={{@controller.pinnedPostIds}}
+ @rootSummary={{@controller.rootSummary}}
+ @jumpToRootPage={{@controller.jumpToRootPage}}
+ @firstLoadedPage={{@controller.firstLoadedPage}}
+ @loadPreviousRoots={{@controller.loadPreviousRoots}}
+ @hasMoreRootsBefore={{@controller.hasMoreRootsBefore}}
+ @newRootPostCount={{@controller.newRootPostIds.length}}
+ @loadNewRoots={{@controller.loadNewRoots}}
+ @editingTopic={{@controller.editingTopic}}
+ @startEditingTopic={{@controller.startEditingTopic}}
+ @cancelEditingTopic={{@controller.cancelEditingTopic}}
+ @finishedEditingTopic={{@controller.finishedEditingTopic}}
+ @showCategoryChooser={{@controller.showCategoryChooser}}
+ @canEditTags={{@controller.canEditTags}}
+ @buffered={{@controller.buffered}}
+ @topicCategoryChanged={{@controller.topicCategoryChanged}}
+ @topicTagsChanged={{@controller.topicTagsChanged}}
+ @minimumRequiredTags={{@controller.minimumRequiredTags}}
+ @expansionState={{@controller.expansionState}}
+ @fetchedChildrenCache={{@controller.fetchedChildrenCache}}
+ @scrollAnchor={{@controller.scrollAnchor}}
+ @showActivityLog={{@controller.showActivityLog}}
+ @collapseReplies={{@controller.collapseReplies}}
+ />
+ {{/if}}
+ </div>
+
+ {{#if (and (not @controller.contextMode) @controller.site.desktopView)}}
+ {{#if @controller.rootSummary}}
+ <NestedTopicTimeline
+ @summary={{@controller.rootSummary}}
+ @sort={{@controller.sort}}
+ @jumpToRootPage={{@controller.jumpToRootPage}}
+ @firstLoadedPage={{@controller.firstLoadedPage}}
+ @rootNodes={{@controller.rootNodes}}
+ />
+ {{/if}}
+ {{/if}}
+ </div>
</template>
diff --git a/frontend/discourse/tests/acceptance/topic-timeline-test.js b/frontend/discourse/tests/acceptance/topic-timeline-test.js
index 05afcccb3d8..a16c2677a29 100644
--- a/frontend/discourse/tests/acceptance/topic-timeline-test.js
+++ b/frontend/discourse/tests/acceptance/topic-timeline-test.js
@@ -1,7 +1,29 @@
-import { click, currentURL, visit } from "@ember/test-helpers";
+import { click, currentURL, triggerEvent, visit } from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+async function scrubTimelineTo(progress) {
+ const rail = document.querySelector(".timeline-scrollarea");
+ const rect = rail.getBoundingClientRect();
+ const scroller = rail.querySelector(".timeline-scroller");
+ const scrollerHeight = scroller.getBoundingClientRect().height || 50;
+ const travel = Math.max(1, rect.height - scrollerHeight);
+ const clientY = rect.top + scrollerHeight / 2 + travel * progress;
+
+ await triggerEvent(rail, "pointerdown", {
+ clientY,
+ pointerId: 1,
+ button: 0,
+ buttons: 1,
+ });
+ await triggerEvent(rail, "pointerup", {
+ clientY,
+ pointerId: 1,
+ button: 0,
+ buttons: 0,
+ });
+}
+
acceptance("Glimmer Topic Timeline", function (needs) {
needs.user({
admin: true,
@@ -363,9 +385,11 @@ acceptance("Glimmer Topic Timeline", function (needs) {
assert.dom("[data-post-number='11']").exists();
});
- test("clicking the timeline padding updates the position", async function (assert) {
+ test("clicking the timeline rail updates the position", async function (assert) {
await visit("/t/internationalization-localization/280/2");
- await click(".timeline-scrollarea .timeline-padding");
+ // The rail is now a single pointer surface (no padding divs);
+ // clicking anywhere on it commits a jump.
+ await scrubTimelineTo(0.75);
assert.false(
currentURL().includes("/280/2"),
"The position of the currently viewed post has been updated from it's initial position"
diff --git a/frontend/discourse/tests/integration/components/nested-topic-timeline-test.gjs b/frontend/discourse/tests/integration/components/nested-topic-timeline-test.gjs
new file mode 100644
index 00000000000..570ae1a0667
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/nested-topic-timeline-test.gjs
@@ -0,0 +1,172 @@
+import { click, render, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import NestedTopicTimeline from "discourse/components/nested/topic-timeline";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+async function pointerAt(rail, type, progress) {
+ const rect = rail.getBoundingClientRect();
+ const scroller = rail.querySelector(".timeline-scroller");
+ const scrollerHeight = scroller.getBoundingClientRect().height || 50;
+ const travel = Math.max(1, rect.height - scrollerHeight);
+ const clientY = rect.top + scrollerHeight / 2 + travel * progress;
+
+ await triggerEvent(rail, type, {
+ clientY,
+ pointerId: 1,
+ button: 0,
+ buttons: type === "pointerup" ? 0 : 1,
+ });
+}
+
+module("Integration | Component | nested-topic-timeline", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.clock = sinon.useFakeTimers({ shouldClearNativeTimers: true });
+ this.styleEl = document.createElement("style");
+ this.styleEl.textContent =
+ ".nested-topic-timeline__scrubber { height: 200px; width: 80px; }";
+ document.head.appendChild(this.styleEl);
+ });
+
+ hooks.afterEach(function () {
+ this.clock.restore();
+ this.styleEl.remove();
+ });
+
+ test("commits to a page derived from page_count", async function (assert) {
+ const jumpToRootPage = sinon.spy();
+ this.setProperties({
+ firstLoadedPage: 0,
+ jumpToRootPage,
+ loadedPostNumbers: [10],
+ summary: {
+ total: 100,
+ page_size: 20,
+ page_count: 4,
+ },
+ });
+
+ await render(
+ <template>
+ <div class="nested-view__roots">
+ {{#each this.loadedPostNumbers as |postNumber|}}
+ <div class="nested-post --depth-0">
+ <article data-post-number={{postNumber}}></article>
+ </div>
+ {{/each}}
+ </div>
+
+ <NestedTopicTimeline
+ @summary={{this.summary}}
+ @sort="top"
+ @firstLoadedPage={{this.firstLoadedPage}}
+ @jumpToRootPage={{this.jumpToRootPage}}
+ />
+ </template>
+ );
+
+ const rail = document.querySelector(".nested-topic-timeline__scrubber");
+ await pointerAt(rail, "pointerdown", 0.99);
+ await pointerAt(rail, "pointerup", 0.99);
+
+ assert.deepEqual(
+ jumpToRootPage.lastCall.args,
+ [3, null, 19],
+ "uses page_count and preserves the target offset"
+ );
+ });
+
+ test("accounts for pinned roots when committing to an exact offset", async function (assert) {
+ const jumpToRootPage = sinon.spy();
+ this.setProperties({
+ firstLoadedPage: 0,
+ jumpToRootPage,
+ loadedPostNumbers: [10],
+ summary: {
+ total: 100,
+ page_size: 20,
+ page_count: 5,
+ pinned_count: 10,
+ },
+ });
+
+ await render(
+ <template>
+ <div class="nested-view__roots">
+ {{#each this.loadedPostNumbers as |postNumber|}}
+ <div class="nested-post --depth-0">
+ <article data-post-number={{postNumber}}></article>
+ </div>
+ {{/each}}
+ </div>
+
+ <NestedTopicTimeline
+ @summary={{this.summary}}
+ @sort="top"
+ @firstLoadedPage={{this.firstLoadedPage}}
+ @jumpToRootPage={{this.jumpToRootPage}}
+ />
+ </template>
+ );
+
+ const rail = document.querySelector(".nested-topic-timeline__scrubber");
+ await pointerAt(rail, "pointerdown", 0.75);
+ await pointerAt(rail, "pointerup", 0.75);
+
+ assert.deepEqual(
+ jumpToRootPage.lastCall.args,
+ [3, null, 5],
+ "lands at the target offset within the unpinned page"
+ );
+ });
+
+ test("endpoint labels jump to the start and end", async function (assert) {
+ const jumpToRootPage = sinon.spy();
+ this.setProperties({
+ firstLoadedPage: 0,
+ jumpToRootPage,
+ loadedPostNumbers: [10],
+ summary: {
+ total: 100,
+ page_size: 20,
+ page_count: 5,
+ pinned_count: 10,
+ },
+ });
+
+ await render(
+ <template>
+ <div class="nested-view__roots">
+ {{#each this.loadedPostNumbers as |postNumber|}}
+ <div class="nested-post --depth-0">
+ <article data-post-number={{postNumber}}></article>
+ </div>
+ {{/each}}
+ </div>
+
+ <NestedTopicTimeline
+ @summary={{this.summary}}
+ @sort="top"
+ @firstLoadedPage={{this.firstLoadedPage}}
+ @jumpToRootPage={{this.jumpToRootPage}}
+ />
+ </template>
+ );
+
+ await click(".nested-topic-timeline__endpoint--start");
+ assert.deepEqual(
+ jumpToRootPage.lastCall.args,
+ [0, null, 0],
+ "start label jumps to the first root"
+ );
+
+ await click(".nested-topic-timeline__endpoint--end");
+ assert.deepEqual(
+ jumpToRootPage.lastCall.args,
+ [4, null, 9],
+ "end label jumps to the last root"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/integration/components/timeline-scrubber-test.gjs b/frontend/discourse/tests/integration/components/timeline-scrubber-test.gjs
new file mode 100644
index 00000000000..6a852d583b9
--- /dev/null
+++ b/frontend/discourse/tests/integration/components/timeline-scrubber-test.gjs
@@ -0,0 +1,170 @@
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import {
+ click,
+ render,
+ settled,
+ triggerEvent,
+ triggerKeyEvent,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import TimelineScrubber from "discourse/components/timeline-scrubber";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+
+async function pointerAt(rail, type, progress) {
+ const rect = rail.getBoundingClientRect();
+ const scroller = rail.querySelector(".timeline-scroller");
+ const scrollerHeight = scroller.getBoundingClientRect().height || 50;
+ const travel = Math.max(1, rect.height - scrollerHeight);
+ const clientY = rect.top + scrollerHeight / 2 + travel * progress;
+ await triggerEvent(rail, type, {
+ clientY,
+ pointerId: 1,
+ button: 0,
+ buttons: type === "pointerup" ? 0 : 1,
+ });
+}
+
+function railProgress(rail) {
+ const match = rail
+ .getAttribute("style")
+ ?.match(/--scrubber-progress:\s*([0-9.]+)/);
+ return match ? parseFloat(match[1]) : null;
+}
+
+class Wrapper {
+ @tracked progress = 0.2;
+}
+
+module("Integration | Component | timeline-scrubber", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.styleEl = document.createElement("style");
+ this.styleEl.textContent =
+ ".timeline-scrubber { height: 200px; width: 60px; }";
+ document.head.appendChild(this.styleEl);
+ });
+
+ hooks.afterEach(function () {
+ this.styleEl.remove();
+ });
+
+ test("handle follows @progress when not interacting", async function (assert) {
+ const state = new Wrapper();
+ this.setProperties({ state });
+
+ await render(
+ <template><TimelineScrubber @progress={{state.progress}} /></template>
+ );
+
+ const rail = document.querySelector(".timeline-scrubber");
+ assert.strictEqual(railProgress(rail), 0.2, "starts at @progress");
+
+ state.progress = 0.7;
+ await settled();
+ assert.strictEqual(railProgress(rail), 0.7, "follows @progress updates");
+ });
+
+ test("handle follows the cursor while dragging", async function (assert) {
+ const state = new Wrapper();
+ this.setProperties({ state });
+
+ await render(
+ <template><TimelineScrubber @progress={{state.progress}} /></template>
+ );
+
+ const rail = document.querySelector(".timeline-scrubber");
+ await pointerAt(rail, "pointerdown", 0.5);
+ assert.strictEqual(
+ railProgress(rail),
+ 0.5,
+ "snaps to cursor on pointerdown"
+ );
+
+ await pointerAt(rail, "pointermove", 0.8);
+ assert.strictEqual(
+ railProgress(rail),
+ 0.8,
+ "follows cursor on pointermove"
+ );
+ });
+
+ test("commits the final cursor position on pointer up", async function (assert) {
+ const state = new Wrapper();
+ const onCommit = sinon.spy();
+ this.setProperties({ state, onCommit });
+
+ await render(
+ <template>
+ <TimelineScrubber
+ @progress={{state.progress}}
+ @onCommit={{this.onCommit}}
+ />
+ </template>
+ );
+
+ const rail = document.querySelector(".timeline-scrubber");
+ await pointerAt(rail, "pointerdown", 0.5);
+ await pointerAt(rail, "pointermove", 0.7);
+ await pointerAt(rail, "pointerup", 0.7);
+
+ assert.strictEqual(onCommit.callCount, 1);
+ assert.strictEqual(onCommit.lastCall.args[0], 0.7);
+ });
+
+ test("does not commit when pointerdown lands on an interactive child", async function (assert) {
+ const onCommit = sinon.spy();
+ const onBack = sinon.spy();
+ this.setProperties({ onCommit, onBack });
+
+ await render(
+ <template>
+ <TimelineScrubber
+ @progress={{0.2}}
+ @ariaLabel="Topic timeline"
+ @onCommit={{this.onCommit}}
+ >
+ <:track>
+ <button
+ type="button"
+ class="track-button"
+ {{on "click" this.onBack}}
+ >
+ Back
+ </button>
+ </:track>
+ </TimelineScrubber>
+ </template>
+ );
+
+ await click(".track-button");
+
+ assert.true(onBack.calledOnce, "runs the track control action");
+ assert.true(onCommit.notCalled, "does not commit a scrub");
+ });
+
+ test("keyboard arrows commit a stepped progress", async function (assert) {
+ const onCommit = sinon.spy();
+ this.setProperties({ onCommit });
+
+ await render(
+ <template>
+ <TimelineScrubber
+ @progress={{0.5}}
+ @keyboardStep={{0.1}}
+ @onCommit={{this.onCommit}}
+ />
+ </template>
+ );
+
+ await triggerKeyEvent(".timeline-scrubber", "keydown", "ArrowDown");
+
+ assert.strictEqual(onCommit.callCount, 1);
+ assert.true(
+ Math.abs(onCommit.lastCall.args[0] - 0.6) < 0.0001,
+ `expected ~0.6, got ${onCommit.lastCall.args[0]}`
+ );
+ });
+});
diff --git a/frontend/discourse/tests/unit/controllers/nested-controller-jump-to-root-page-test.js b/frontend/discourse/tests/unit/controllers/nested-controller-jump-to-root-page-test.js
new file mode 100644
index 00000000000..28b695ae6d6
--- /dev/null
+++ b/frontend/discourse/tests/unit/controllers/nested-controller-jump-to-root-page-test.js
@@ -0,0 +1,217 @@
+import { getOwner } from "@ember/owner";
+import { settled } from "@ember/test-helpers";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+
+function fakeTopic() {
+ return {
+ id: 42,
+ slug: "demo-topic",
+ suggested_topics: null,
+ related_topics: null,
+ };
+}
+
+function makeRootNode(postNumber, id = postNumber * 100) {
+ return { post: { id, post_number: postNumber }, children: [] };
+}
+
+function registerStubElement(controller, postNumber, top) {
+ // Stub a DOM element that .getBoundingClientRect returns deterministically,
+ // so the scroll math doesn't depend on real layout in the test runner.
+ const el = {
+ isConnected: true,
+ getBoundingClientRect: () => ({ top, left: 0, right: 0, bottom: top + 10 }),
+ };
+ controller.nestedRootElements.register(postNumber, el);
+ return el;
+}
+
+module("Unit | Controller | nested - jumpToRootPage", function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.controller = getOwner(this).lookup("controller:nested");
+ this.controller.nestedRootElements.clear();
+ this.scrollSpy = sinon.stub(window, "scrollTo");
+ });
+
+ hooks.afterEach(function () {
+ this.scrollSpy.restore();
+ });
+
+ test("in-window jump with target post just scrolls to it", async function (assert) {
+ this.controller.setProperties({
+ topic: fakeTopic(),
+ rootNodes: [makeRootNode(5), makeRootNode(7), makeRootNode(9)],
+ firstLoadedPage: 0,
+ page: 0,
+ rootSummary: { page_size: 3, total: 3 },
+ sort: "top",
+ });
+ registerStubElement(this.controller, 9, 1234);
+
+ await this.controller.jumpToRootPage(0, 9);
+
+ assert.true(
+ this.scrollSpy.called,
+ "scrolls without an ajax fetch when target is in the loaded window"
+ );
+ assert.strictEqual(
+ this.controller.rootNodes.length,
+ 3,
+ "rootNodes unchanged"
+ );
+ });
+
+ test("out-of-window jump replaces rootNodes with the target page", async function (assert) {
+ pretender.get("/n/demo-topic/42.json", (request) => {
+ assert.strictEqual(request.queryParams.page, "3", "fetches target page");
+ return response({
+ roots: [
+ { id: 100, post_number: 50 },
+ { id: 101, post_number: 51 },
+ ],
+ page: 3,
+ has_more_roots: true,
+ });
+ });
+
+ this.controller.setProperties({
+ topic: fakeTopic(),
+ rootNodes: [makeRootNode(5)],
+ firstLoadedPage: 0,
+ page: 0,
+ rootSummary: { page_size: 2, total: 100 },
+ sort: "top",
+ });
+ // Pre-register so waitForElement resolves immediately.
+ registerStubElement(this.controller, 50, 800);
+
+ await this.controller.jumpToRootPage(3, 50);
+ await settled();
+
+ assert.deepEqual(
+ this.controller.rootNodes.map((n) => n.post.post_number),
+ [50, 51],
+ "replaces (not appends) rootNodes with the target page"
+ );
+ assert.strictEqual(this.controller.firstLoadedPage, 3);
+ assert.strictEqual(this.controller.page, 3, "collapses window to one page");
+ assert.true(this.controller.hasMoreRoots);
+ });
+
+ test("uses target offset when no target post is given", async function (assert) {
+ pretender.get("/n/demo-topic/42.json", () =>
+ response({
+ roots: [
+ { id: 200, post_number: 80 },
+ { id: 201, post_number: 81 },
+ ],
+ page: 5,
+ has_more_roots: false,
+ })
+ );
+
+ this.controller.setProperties({
+ topic: fakeTopic(),
+ rootNodes: [makeRootNode(5)],
+ firstLoadedPage: 0,
+ page: 0,
+ rootSummary: { page_size: 2, total: 100 },
+ sort: "top",
+ });
+ registerStubElement(this.controller, 81, 400);
+
+ await this.controller.jumpToRootPage(5, null, 1);
+ await settled();
+
+ assert.true(this.scrollSpy.called, "scrolls to the offset root");
+ });
+
+ test("uses first node post_number when no target is given", async function (assert) {
+ pretender.get("/n/demo-topic/42.json", () =>
+ response({
+ roots: [
+ { id: 200, post_number: 80 },
+ { id: 201, post_number: 81 },
+ ],
+ page: 5,
+ has_more_roots: false,
+ })
+ );
+
+ this.controller.setProperties({
+ topic: fakeTopic(),
+ rootNodes: [makeRootNode(5)],
+ firstLoadedPage: 0,
+ page: 0,
+ rootSummary: { page_size: 2, total: 100 },
+ sort: "top",
+ });
+ registerStubElement(this.controller, 80, 400);
+
+ await this.controller.jumpToRootPage(5);
+ await settled();
+
+ assert.true(this.scrollSpy.called, "scrolls to the first loaded root");
+ });
+
+ test("assigns suggested/related on final-page jump", async function (assert) {
+ pretender.get("/n/demo-topic/42.json", () =>
+ response({
+ roots: [{ id: 300, post_number: 99 }],
+ page: 9,
+ has_more_roots: false,
+ suggested_topics: [{ id: 1 }],
+ related_topics: [{ id: 2 }],
+ })
+ );
+
+ this.controller.setProperties({
+ topic: fakeTopic(),
+ rootNodes: [makeRootNode(5)],
+ firstLoadedPage: 0,
+ page: 0,
+ rootSummary: { page_size: 1, total: 10 },
+ sort: "top",
+ });
+ registerStubElement(this.controller, 99, 200);
+
+ await this.controller.jumpToRootPage(9);
+ await settled();
+
+ assert.deepEqual(
+ this.controller.topic.suggested_topics,
+ [{ id: 1 }],
+ "piggybacked suggested_topics attach to the topic"
+ );
+ assert.deepEqual(this.controller.topic.related_topics, [{ id: 2 }]);
+ });
+
+ test("does nothing while another load is in flight", async function (assert) {
+ this.controller.setProperties({
+ topic: fakeTopic(),
+ rootNodes: [makeRootNode(5)],
+ firstLoadedPage: 0,
+ page: 0,
+ loadingMore: true,
+ sort: "top",
+ });
+
+ let ajaxCalled = false;
+ pretender.get("/n/demo-topic/42.json", () => {
+ ajaxCalled = true;
+ return response({ roots: [], page: 0 });
+ });
+
+ await this.controller.jumpToRootPage(3, 50);
+
+ assert.false(
+ ajaxCalled,
+ "guards against re-entry while loadingMore is true"
+ );
+ });
+});
diff --git a/lib/nested_replies/tree_loader.rb b/lib/nested_replies/tree_loader.rb
index 2c832cf2fe0..ba102a698cb 100644
--- a/lib/nested_replies/tree_loader.rb
+++ b/lib/nested_replies/tree_loader.rb
@@ -46,6 +46,19 @@ module NestedReplies
NestedReplies::Sort.apply(scope, sort)
end
+ def promotable_pinned_post_ids(pinned_post_ids)
+ return [] if pinned_post_ids.blank?
+
+ # apply_visibility unscopes deleted_at, so re-filter after it.
+ apply_visibility(
+ topic
+ .posts
+ .where(id: pinned_post_ids)
+ .where("reply_to_post_number IS NULL OR reply_to_post_number = 1")
+ .where(post_number: 2..),
+ ).where(deleted_at: nil).pluck(:id)
+ end
+
def promote_pinned_roots(roots, pinned_post_ids)
return roots if pinned_post_ids.blank?
@@ -257,6 +270,31 @@ module NestedReplies
.count
end
+ # pinned_count lets the client offset its "position in total"
+ # calculation when firstLoadedPage > 0 — pages after 0 contain only
+ # unpinned roots, but those roots come after N_pinned in the total
+ # ordering.
+ def root_summary(sort, pinned_post_ids: nil)
+ scope = root_posts_scope(sort)
+ total = scope.count
+ unpinned_total =
+ if pinned_post_ids.present?
+ promotable_pinned_ids = promotable_pinned_post_ids(pinned_post_ids)
+ promotable_pinned_ids.present? ? scope.where.not(id: promotable_pinned_ids).count : total
+ else
+ total
+ end
+ page_count = total.zero? ? 0 : [1, (unpinned_total.to_f / ROOTS_PER_PAGE).ceil].max
+ pinned_count = total - unpinned_total
+
+ {
+ total: total,
+ page_size: ROOTS_PER_PAGE,
+ page_count: page_count,
+ pinned_count: pinned_count,
+ }
+ end
+
def total_descendant_counts(post_ids)
return {} if post_ids.empty?
diff --git a/spec/requests/nested_topics_controller_spec.rb b/spec/requests/nested_topics_controller_spec.rb
index 0f825dd0bb3..37951acb722 100644
--- a/spec/requests/nested_topics_controller_spec.rb
+++ b/spec/requests/nested_topics_controller_spec.rb
@@ -269,7 +269,7 @@ RSpec.describe NestedTopicsController, type: :request do
end
it "paginates with has_more_roots" do
- NestedReplies::TreeLoader::ROOTS_PER_PAGE.times do
+ (NestedReplies::TreeLoader::ROOTS_PER_PAGE + 1).times do
Fabricate(:post, topic: topic, user: user, reply_to_post_number: nil)
end
sign_in(user)
diff --git a/spec/services/nested_topic/list_roots_spec.rb b/spec/services/nested_topic/list_roots_spec.rb
index 00765804907..79b0d3f0091 100644
--- a/spec/services/nested_topic/list_roots_spec.rb
+++ b/spec/services/nested_topic/list_roots_spec.rb
@@ -60,6 +60,15 @@ RSpec.describe NestedTopic::ListRoots do
end
end
+ it "marks an exact full root page as the final page" do
+ stub_const(NestedReplies::TreeLoader, :ROOTS_PER_PAGE, 2) do
+ 2.times { Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1) }
+
+ expect(result[:response][:roots].length).to eq(2)
+ expect(result[:response][:has_more_roots]).to eq(false)
+ end
+ end
+
context "when page is greater than 0" do
let(:params) { { sort: "top", page: 1 } }
@@ -94,6 +103,73 @@ RSpec.describe NestedTopic::ListRoots do
end
end
+ context "with root_summary" do
+ it "is included on every page so deep links can render the timeline" do
+ result =
+ described_class.call(
+ params: {
+ sort: "top",
+ page: 1,
+ },
+ guardian: user.guardian,
+ topic_view: topic_view,
+ )
+ expect(result[:response]).to have_key(:root_summary)
+ end
+
+ it "includes page_size so the client can compute target pages" do
+ summary = result[:response][:root_summary]
+ expect(summary[:page_size]).to eq(NestedReplies::TreeLoader::ROOTS_PER_PAGE)
+ end
+
+ it "includes page_count" do
+ summary = result[:response][:root_summary]
+ expect(summary[:page_count]).to eq(0)
+ end
+
+ it "includes pinned_count so the client can offset position math" do
+ root_a = Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+ Fabricate(:nested_topic, topic: topic).update!(pinned_post_ids: [root_a.id])
+
+ summary = result[:response][:root_summary]
+ expect(summary[:pinned_count]).to eq(1)
+ end
+
+ it "reports pinned_count as 0 when nothing is pinned" do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+ summary = result[:response][:root_summary]
+ expect(summary[:pinned_count]).to eq(0)
+ end
+ end
+
+ context "with a deleted pinned root" do
+ fab!(:deleted_pinned) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1, deleted_at: Time.now)
+ end
+
+ before do
+ Fabricate(:nested_topic, topic: topic).update!(pinned_post_ids: [deleted_pinned.id])
+ end
+
+ it "keeps the deleted pinned root in the normal sorted list instead of dropping it" do
+ ids = result[:response][:roots].map { |r| r[:id] }
+ expect(ids).to include(deleted_pinned.id)
+ end
+
+ it "does not count deleted pinned roots as pinned in root_summary" do
+ stub_const(NestedReplies::TreeLoader, :ROOTS_PER_PAGE, 2) do
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+ Fabricate(:post, topic: topic, user: user, reply_to_post_number: 1)
+
+ summary = result[:response][:root_summary]
+ expect(summary[:total]).to eq(3)
+ expect(summary[:pinned_count]).to eq(0)
+ expect(summary[:page_count]).to eq(2)
+ end
+ end
+ end
+
context "when there are pinned roots on page 1" do
let(:params) { { sort: "top", page: 1 } }